Compare commits

..
3220 Commits
Author SHA1 Message Date
Copilot 7ff4825858 Sync upstream merge cleanup
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-06-24 19:23:19 +08:00
NessZerra c76adee007 Merge pull request #26 from Finesssee/finesssee-fix-open-issues
Merge upstream CLIProxyAPI
2026-06-24 18:48:20 +08:00
Copilot 69cd2a363a Merge upstream CLIProxyAPI
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-06-24 18:44:14 +08:00
Luis Pater 87e6d9cf25 feat(videos): add model binding and propagation for video auth management
- Introduced `model` field in `videoAuthBinding` for model tracking.
- Enhanced binding store with `setWithModel` and `getBinding` methods for binding models.
- Updated handlers to propagate execution models during video processing.
- Added tests to verify model binding, retrieval, and propagation logic.
2026-06-24 16:10:53 +08:00
Luis Pater c20ac28a54 Merge pull request #3981 from sususu98/feat/oauth-model-alias-force-mapping
feat(oauth): add force-mapping for upstream response model rewrite
2026-06-24 15:43:29 +08:00
sususu98 fd93ee035d feat(oauth): add force-mapping for upstream response model rewrite
Add OAuthModelAlias.ForceMapping to rewrite client-visible model fields in non-stream and SSE stream responses while leaving request-log upstream payloads unchanged.

- Wire config, watcher diff, and conductor execute/stream paths
- Rewrite force-mapped responses in Antigravity credits fallback paths
- Prevent buffered SSE chunks from being emitted by line-wise fallback
- Preserve thinking suffixes for same-base force-mapping aliases
- Cover codex, antigravity, kimi, and xai with live-derived fixtures and regression tests
- Document a conservative antigravity-only force-mapping example in config.example.yaml
2026-06-24 14:51:35 +08:00
sususu98 38ed7aefc6 fix(codex): sanitize downstream UA for direct image calls
Direct OpenAI image calls can inherit downstream User-Agent values from the Gin request context, which may trigger upstream Cloudflare 1010 blocks.

Clone inbound Codex headers for direct image requests and remove only User-Agent before applying defaults. This keeps Version, X-Codex-Turn-Metadata, X-Client-Request-Id, and Originator forwarding intact.

Expand direct image regression coverage for downstream identity headers and align edit endpoint expectations with /images/edits.
2026-06-24 14:43:44 +08:00
Luis Pater 3a13865db8 refactor(home): relocate and rename home plugin status reporting logic
- Moved `reportHomePluginStatus` from `cmd/server` to `internal/home` as `ReportPluginStatus`.
- Updated interface and variable names for consistency.
- Adjusted imports and references in `main.go` and test files to align with the changes.
- Improved code structure for better modularity and reuse.
2026-06-23 23:27:11 +08:00
Luis Pater 70053beadb feat(auth): refactor credential kind detection and add dynamic source classification
- Introduced `AuthKind` and `AuthSourceKind` methods for improved credential type and source classification.
- Replaced legacy fallback logic with normalized attribute-based handling in `AuthKind`.
- Consolidated metadata inspection for both API key and OAuth attributes.
- Updated calls to replace direct `AccountInfo` usage with `AuthKind` and `AuthSourceKind`.
- Enhanced unit tests to validate explicit and fallback credential resolution scenarios.
2026-06-23 23:21:33 +08:00
Luis Pater b89c594aac Merge pull request #3973 from router-for-me/home
feat(home): enhance plugin management and synchronization
2026-06-23 21:59:41 +08:00
hkfires e9a11db7b9 feat(home): enhance plugin management and synchronization
- Added NodeID field to HomeConfig for better identification.
- Updated ConfigFromJWT to populate NodeID from claims.
- Introduced new Redis keys for managing plugin status and tasks.
- Implemented RPushPluginStatus and GetPluginTasks methods in the client for handling plugin-related data.
- Enhanced Sync functionality to include detailed reporting on plugin installation and deletion tasks.
- Added error handling and reporting for plugin synchronization failures.
- Created tests for new plugin synchronization and management features.
- Improved the overall structure and readability of the plugin synchronization logic.
2026-06-23 20:42:33 +08:00
sususu98 05d1792d43 feat(xai): replay Grok reasoning for Claude messages (#3962)
Add Grok-native reasoning replay for Claude-sourced xAI Responses requests. Replay state is scoped by model and session, normalized to reasoning/function_call/custom_tool_call items, and injected with the same tool-call alignment semantics used by Codex.

Include the minimal Grok encrypted_content validator needed on upstream/dev so replay cache entries cannot accept Codex/GPT, Gemini, or Claude signature shapes. Cache completed output items from HTTP, streaming, and WebSocket xAI responses.

Cover two-turn Claude replay, tool_result continuity, valid Grok cache storage, and rejection of Codex-shaped encrypted_content.
2026-06-23 14:57:53 +08:00
sususu98 53a21dfb0b [codex] Drop foreign encrypted_content before xAI Grok upstream (#3961)
* Drop foreign encrypted_content before xAI Grok upstream

xAI Grok accepts provider-native encrypted_content as opaque replay state, but GPT/Codex reasoning signatures, Gemini thoughtSignature blobs, and Claude thinking signatures can all travel through OpenAI Responses-style reasoning.encrypted_content while remaining incompatible with xAI. Forwarding those foreign blobs to Grok causes upstream validation failures, especially when the foreign value is high-entropy enough to look ciphertext-like.

Add a Grok encrypted_content transport validator that stays conservative and shape-oriented:

- require unpadded standard base64 with no foreign characters
- reject obvious GPT/Codex gAAAA reasoning signatures before decode
- reject strict Claude thinking signatures in both official E-form and Antigravity R-form
- reject known Gemini thoughtSignature envelopes by reusing the central Gemini validator, covering Gemini 2.5 field-1 and Gemini 3.x field-2 shapes
- require decoded payloads to be long enough and high-entropy enough to look like native Grok ciphertext
- avoid decrypting, protobuf-parsing, or otherwise interpreting native Grok payloads on the hot path

Wire the validator into the xAI Responses request preparation path for reasoning and compaction input items. Invalid encrypted_content fields are deleted before the request is sent upstream, while the surrounding item is preserved and debug logging records only redacted metadata.

Extend coverage with native Grok corpus preservation, Gemini field-1/field-2 rejection, Claude E-form and R-form rejection, invalid-blob sanitizer tests, and compact/websocket replay preservation. The foreign-provider checks are deliberately narrow so high-entropy Grok blobs are not rejected merely because they look random.

* fix(xai): harden encrypted content sanitizer
2026-06-23 14:33:27 +08:00
Luis Pater f1ed8912bb feat(translator): wrap message-level system roles as user-visible reminders
- Added `ClaudeMessageSystemReminderText` to convert system content into user-readable reminder text.
- Updated translators (Antigravity, Gemini, Codex, OpenAI) to wrap `system` roles as reminders with `<system-reminder>` tags.
- Adjusted related test cases to validate reminder wrapping logic.
2026-06-23 13:43:14 +08:00
Luis Pater 7c390a7a2e feat(runtime): add Claude Code session handling with caching and tests
- Introduced `ClaudeCodeSessionID` resolution logic, preferring headers over payload metadata.
- Added `ClaudeCodePromptCache` to map sessions to stable prompt cache keys.
- Refactored existing logic to integrate `ClaudeCodePromptCache` for session-based handling.
- Included extensive unit tests to validate session ID extraction, cache reuse, and header prioritization.
2026-06-23 13:19:13 +08:00
Luis Pater bd646819ed test(translator, runtime): ensure empty text parts are skipped without null values
- Added tests for `ConvertOpenAIRequestToAntigravity` and `ConvertOpenAIRequestToGemini` to verify skipping of empty text parts while maintaining non-null structure.
- Refactored part index logic to correctly handle placement of replay parts in `antigravity_reasoning_replay`.
- Introduced helper functions `antigravityExistingReplayPartPath` and `antigravityReplayPartWritePath` for consistent replay part path management.
2026-06-23 08:07:03 +08:00
Luis Pater 5d9ea1667b Merge pull request #3963 from router-for-me/home
feat(plugins): sync home plugin manifests
2026-06-22 22:39:15 +08:00
hkfires c58da381c7 feat(plugins): sync home plugin manifests 2026-06-22 22:25:44 +08:00
Luis Pater 290f421f9f Merge pull request #3959 from fdreamsu/codex/fix-codex-ws-prefix
Fix Codex WebSocket payload model prefix rewrite / 修复 Codex WebSocket 请求体模型前缀改写
2026-06-22 21:34:12 +08:00
fdreamsu 36ed0e5c9c fix(codex): strip model prefix for websocket payloads
* fix(codex): strip model prefix before sending upstream websocket payloads

* test(codex): assert prefixed downstream models are rewritten for websocket sends
2026-06-22 18:11:06 +08:00
Luis Pater 079ec51f50 feat(cliproxy): optimize API key alias rebuild with deferred execution and caching
- Added `RefreshAPIKeyModelAlias` for explicit alias table rebuilds.
- Introduced deferred rebuild support with `WithDeferredAPIKeyModelAliasRebuild` and context flag validation.
- Implemented `openAICompatibilityRegistrationCache` to streamline OpenAI compatibility model registrations.
- Updated executor and model registration workflows to utilize cached compatibility data, improving efficiency in batch operations.
- Adjusted max worker limits dynamically based on model categories.

Closes: #3953
2026-06-22 08:41:52 +08:00
sususu98 1f2504ebcc fix(claude): bypass signature sanitizer for non-Claude models (#3946)
* fix(claude): bypass signature sanitizer for non-Claude models

* test(claude): use subtests for sanitizer gate model cases
2026-06-21 23:06:38 +08:00
Luis Pater 369e560f1d feat(api): refactor provider key logic for API key usage and add test for compatibility grouping
- Extracted provider key determination into `apiKeyUsageProviderKey` for reuse and better readability.
- Updated `GetAPIKeyUsage` to utilize the new function.
- Added a new test case to validate compatibility grouping logic via `compat_name` attribute.

Closes: #3940 #3941
2026-06-21 11:37:52 +08:00
Luis Pater babef2a1ef feat(cliproxy): add unregisterOpenAICompatExecutor and sync runtime configuration
- Implemented `unregisterOpenAICompatExecutor` to remove OpenAI-compatible executors dynamically.
- Updated `ensureExecutorsForAuth` to unregister incompatible executors while handling plugin candidates.
- Adjusted runtime configuration logic to ensure proper synchronization during updates with `syncPluginModelRuntime`.
2026-06-21 11:21:05 +08:00
Luis Pater 5bc0c68284 feat(pluginhost): improve error handling with HTTP status codes for plugin calls
- Added `rpcPluginError` to encapsulate plugin errors with HTTP status codes.
- Enhanced `decodeEnvelopeResult` to preserve and return detailed plugin errors with status codes.
- Introduced `isPluginErrorEnvelope` to identify plugin error envelopes.
- Updated plugin call logic in Unix and Windows loaders to differentiate plugin errors from system errors.
- Added unit tests to verify error handling and status code preservation.
2026-06-21 10:12:10 +08:00
Luis Pater 31549af180 fix(watcher): update Gemini provider name to "gemini-cli" in file synthesizer logic 2026-06-21 09:38:10 +08:00
Luis Pater 1f21f946ba feat(api): implement support for multi-auth expansion in plugin systems
- Added logic to expand single auth JSON payloads into multiple plugin virtual auth records.
- Updated related API endpoints such as `PatchAuthFileStatus` and `DeleteAuthFile` to handle plugin virtual auths with rollback mechanisms.
- Introduced `NormalizePluginOAuthCallbackProvider` and other normalization functions for better handling of OAuth callbacks.
- Enhanced tests to validate multi-auth parsing, rollback behavior, and API response consistency.
2026-06-21 07:24:29 +08:00
Luis Pater 9a8098d2d5 feat(api): prioritize non-template Codex client models and adjust priority calculation logic
- Added `applyCodexClientNonTemplatePriorities` to assign higher priorities to non-template Codex client models dynamically.
- Implemented `maxCodexClientTemplatePriority` to set base priority for non-template models relative to template models.
- Updated unit tests to validate priority calculation for custom models.
2026-06-21 00:10:03 +08:00
Luis Pater bb414de33f feat(api): add "max" reasoning depth and service_tiers to Codex client models
- Introduced a new "max" level for reasoning depth in Codex client model configuration, providing maximum problem-solving capability.
- Added `service_tiers` field to model responses for better tier categorization.
- Updated unit tests to validate the inclusion and default behavior of `service_tiers` and the new "max" reasoning depth.
2026-06-20 22:49:43 +08:00
Luis Pater eb8d0d0684 Merge pull request #3900 from sususu98/fix/antigravity-replay-fc-order-upstream-dev
fix(antigravity): HOME Gemini replay and functionCall ordering before functionResponse
2026-06-20 14:55:48 +08:00
Luis Pater 35c3d80ab9 feat(translator): add support for handling video URLs in Gemini requests
- Updated `ConvertOpenAIRequestToGemini` to process `video_url` message types, extracting and embedding video metadata (MIME type and base64 data) into Gemini request parts.
- Added corresponding unit tests to validate `video_url` handling, ensuring proper extraction and data preservation.

Closes: #3920
2026-06-20 14:46:39 +08:00
Luis Pater 09179a707f feat(registry): add "max" level and remove deprecated Gemini models
- Added a new "max" level to model `thinking.levels` for enhanced customization.
- Removed deprecated Gemini 3 Pro (High/Low) models and associated fields from the registry.
- Simplified `thinking` attribute structure for `grok-build-0.1` and `grok-composer-2.5-fast` models.

Closes: #3901
2026-06-20 14:22:29 +08:00
Luis Pater 57e1bf97a5 feat(translator): ensure preservation of tool and call IDs in Gemini request and response translations
- Updated `ConvertGeminiRequestToClaude`, `ConvertGeminiRequestToCodex`, and their respective response counterparts to include logic for retaining and using tool/call IDs when present from gateway-provided inputs.
- Enhanced pairing logic between function calls and responses to handle custom and auto-generated IDs consistently.
- Introduced tests validating ID preservation and proper behavior in both streaming and non-streaming flows.

Closes: #3878
2026-06-20 14:12:14 +08:00
Luis Pater 011ffe1dd5 feat(translator): enforce FIFO order in tool call ID consumption for Gemini requests
- Updated `ConvertGeminiRequestToOpenAI` to consume `tool_call_id`s in FIFO order, ensuring consistent mapping between calls and responses.
- Added fallback logic for unmatched or extra function responses to generate unique `tool_call_id`s with a `call_` prefix.
- Introduced comprehensive unit tests to validate order enforcement, distinct ID assignment, and fallback behavior.

Closes: #3874
2026-06-20 14:01:50 +08:00
Luis Pater 5771abbc81 feat(management): add ResetQuota endpoint and auth manager quota reset functionality
- Introduced a new `/reset-quota` API endpoint in the management handler to clear quota and cooldown state for auth records.
- Implemented `ResetQuota` method in the auth manager to handle runtime and registry state resets for affected models.
- Added tests to validate quota reset behavior, including proper state updates and registry consistency.
- Refactored utility functions to support deduplication and registered models handling in quota resets.

Closes: #3866
2026-06-20 13:49:40 +08:00
Luis Pater b4bec344f6 feat(translator): sanitize parametersJsonSchema in OpenAI to Gemini request handling
- Applied `CleanJSONSchemaForGemini` to ensure compatibility by removing unsupported fields and cleaning schema requirements.
- Added test cases to validate schema transformation, ensuring only necessary `required` fields are retained.
- Enhanced both request and response flows to consistently clean and sanitize tool parameter schemas.

Closes: #3863
2026-06-20 13:34:05 +08:00
Luis Pater a79ae80f6e feat(registry): improve model fallback logic and refactor Claude model handling
- Replaced internal model-specific constants with exported defaults (`DefaultClaudeMaxInputTokens`, `DefaultClaudeMaxOutputTokens`).
- Refactored Claude model formatting to centralize schema application in `formatHomeClaudeModel`, with fields like `type`, `display_name`, and token limits.
- Added new unit tests for fallback behavior, metadata fields, and token handling in Claude and Gemini models.
- Removed deprecated test coverage for Amp provider model routes.

Closes: #3833
2026-06-20 13:09:44 +08:00
Luis Pater b0ca3794ad Merge pull request #3834 from dcrdev/main 2026-06-20 12:56:25 +08:00
Luis Pater 790ec307f9 feat(config): add support for rebuild_mid_system_message configuration
- Introduced `RebuildMidSystemMessage` field in config to move system messages into the top-level Claude system field.
- Updated executor to handle mid-system message rebuilding when enabled via config or auth attributes.
- Added unit tests to verify rebuilding behavior and default behavior when disabled.
- Updated configuration example and API handlers to support the new field.

Closes: #3792
2026-06-20 12:15:06 +08:00
Luis Pater f66376f0b9 feat(auth): add per-auth OAuth model alias support
- Introduced `SetOAuthModelAliasesAttribute` and `OAuthModelAliasesFromAttributes` for managing per-auth model aliases.
- Enhanced OAuth model resolution logic to prioritize per-auth aliases over global aliases.
- Updated metadata handling to extract and sanitize per-account model aliases.
- Added tests to validate alias precedence, empty attributes, and conflict scenarios.

Closes: #3764
2026-06-20 11:31:57 +08:00
Luis Pater 379167c992 feat(translator): add benchmarking for convertSystemRoleToDeveloper with large inputs
- Introduced `BenchmarkConvertSystemRoleToDeveloperLargeInput` to evaluate performance on various input sizes and configurations.
- Improved `convertSystemRoleToDeveloper` logic to optimize JSON rebuilding and reduce unnecessary operations.
- Created helper `makeLargeResponsesInputForBenchmark` to generate test data for performance scenarios.

Closes: #3751
2026-06-20 11:10:53 +08:00
Luis Pater 28e2f9798c feat(executor): add session isolation for grok-composer models
- Introduced `xaiRequiresIsolatedConversation` to enforce session ID generation for `grok-composer` models.
- Updated request preparation logic to handle isolated conversations by setting `prompt_cache_key` and `x-grok-conv-id`.
- Added unit tests with coverage for session isolation, stateless models, and explicit `prompt_cache_key` scenarios.

Closes: #3750
2026-06-20 10:54:16 +08:00
Luis Pater bc652c7bf0 feat(translator): add support for text.format conversion in OpenAI to Gemini requests
- Implemented `applyOpenAIResponsesTextFormatToGemini` to handle `json_object` and `json_schema` formats.
- Updated generation config to set appropriate `responseMimeType` and optional `responseJsonSchema`.
- Introduced unit tests to validate correct handling of `text.format` conversion scenarios.

Closes: #3721
2026-06-20 10:14:39 +08:00
Luis Pater 75fa62653f feat(executor): normalize parallel_tool_calls based on tools presence
- Added `normalizeCodexParallelToolCallsForTools` to conditionally remove `parallel_tool_calls` when `tools` are missing or empty.
- Integrated normalization into Codex executor workflows for improved request handling.
- Introduced unit tests to validate behavior across different tool scenarios.

Closes: #3903
2026-06-20 09:47:45 +08:00
Luis Pater 4c78e40da4 feat(auth): unify provider key handling with OpenAI compatibility support
- Replaced direct `strings.ToLower` usage with `util.OpenAICompatibleProviderKey` for generating provider keys.
- Updated auth and executor workflows to use namespaced keys for OpenAI-compatible providers.
- Adjusted tests to validate namespaced key handling, including new test cases for provider registration and execution logic.
- Added `OpenAICompatibleProviderKey` helper in `util` for consistent key transformations.

Closes: #3600
2026-06-20 00:58:20 +08:00
Luis Pater c44d4fcc7c feat(schema): add removal of $comment and enumDescriptions in JSON schema processing
- Updated JSON schema handling to remove `$comment` and `enumDescriptions` fields during schema transformations.
- Adjusted test cases to validate the removal of these fields both at root and nested levels.
- Expanded unsupported schema keywords to include `$comment` and `enumDescriptions` for Gemini compatibility.

Closes: #3512
2026-06-20 00:22:08 +08:00
Luis Pater 34639c3cf9 feat(translator): defer Codex function call starts until function name is available
- Updated `ConvertCodexResponseToClaude` to delay emitting `function_call` start events until the `name` field is resolved.
- Introduced `pendingCodexFunctionCall` for buffering incomplete function calls.
- Added tests to ensure proper behavior for deferred starts, including argument buffering and finalization.

Closes: #3471
2026-06-20 00:11:12 +08:00
Luis Pater 51aa5ba925 feat(translator): preserve input_audio fields in OpenAI request conversions
- Updated `ConvertOpenAIRequestToGemini` and `ConvertOpenAIRequestToCodex` to handle `input_audio`, retaining `data` and `format` fields.
- Added helper `openAIInputAudioMimeType` for determining MIME types from audio formats.
- Introduced unit tests to validate correct preservation of `input_audio` data and format.

Closes: #3447
2026-06-20 00:03:54 +08:00
Luis Pater 1581700646 chore(deps): bump github.com/jackc/pgx/v5 from v5.7.6 to v5.9.2
Closes: #3420
2026-06-19 23:50:48 +08:00
Luis Pater 1b849b6d8f feat(translator): attach reasoning_content to assistant and tool messages in OpenAI response conversion
- Enhanced `ConvertOpenAIResponsesRequestToOpenAIChatCompletions` to include `reasoning_content` in assistant and tool call messages.
- Introduced `collectOpenAIResponsesReasoningContent` for aggregating reasoning summaries.
- Added tests to validate reasoning attachment in various scenarios, including empty reasoning, tool calls, and reasoning followed by user messages.

Closes: #3397
2026-06-19 21:36:55 +08:00
Luis Pater 041a065b2f Merge branch 'remove-gemini-cli' into dev
# Conflicts:
#	internal/api/handlers/management/auth_files.go
#	internal/thinking/provider/geminicli/apply.go
2026-06-19 14:40:29 +08:00
Luis Pater aa2ad995a5 feat(translator): preserve input_image details in OpenAI response conversion
- Updated handling in `ConvertOpenAIResponsesRequestToOpenAIChatCompletions` to retain `input_image` detail fields such as `image_url` and `detail`.
- Added `TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesInputImageDetail` to verify preservation of image details during transformation.

Closes: #3385
2026-06-19 05:56:25 +08:00
Luis Pater aed54adbea feat(translator): preserve structured tool_choice in OpenAI response conversions
- Updated `ConvertOpenAIResponsesRequestToOpenAIChatCompletions` to retain `tool_choice` with raw byte handling.
- Added `TestConvertOpenAIResponsesRequestToOpenAIChatCompletions_PreservesStructuredToolChoice` to ensure function and type fields are preserved in transformations.

Closes: #3384
2026-06-19 05:48:57 +08:00
Luis Pater 07c297a51b feat(auth): add persistent cooldown state management with file-backed store
- Introduced `CooldownStateStore` interface for managing independent cooldown state persistence.
- Implemented `FileCooldownStateStore` for storing cooldown states as per-auth `.cds` files with atomic writes and stale file cleanup.
- Enhanced `Manager` to support restoring state from `CooldownStateStore` and persisting state changes during auth updates.
- Updated tests to validate cooldown state saving, loading, concurrency handling, and error scenarios.

Closes: #3368
2026-06-19 05:34:44 +08:00
Luis Pater d33ac5e1e9 feat(auth): add transient error cooldown configuration and adjust retry logic
- Introduced `SetTransientErrorCooldownSeconds` to enable configurable cooldowns for transient errors (e.g., 408/500/502/503/504).
- Updated retry scheduling logic to use the new `nextTransientErrorRetryAfter` function.
- Modified config parsing to include `transient-error-cooldown-seconds` with support for disabling or defaulting to legacy behavior.
- Expanded tests to validate transient cooldown logic with various configurations and edge cases.

Closes: #3315
2026-06-19 04:26:04 +08:00
Luis Pater 4926630a60 feat(translator): support namespace tools in OpenAI response transformations
- Added `convertResponsesToolToOpenAIChatTools` and helper methods to handle namespace tools during request conversions.
- Enhanced response handling to restore namespace context for function calls using `applyResponsesFunctionCallNamespaceFields` and related utilities.
- Updated tests to validate namespace flattening, function call restoration, and non-stream response handling.

Closes: #3298
2026-06-19 04:12:51 +08:00
Luis Pater 893412e965 feat(translator): normalize service_tier in Codex requests and add tests
- Added `normalizeCodexServiceTier` to standardize `service_tier` values (`fast` to `priority`, omit unsupported tiers).
- Updated `ConvertClaudeRequestToCodex` to apply normalization logic.
- Introduced `TestConvertClaudeRequestToCodex_ServiceTier` to validate behavior across various `service_tier` inputs.

Closes: #3276 #3294
2026-06-19 03:58:55 +08:00
Luis Pater c020e2d03f feat(translator): drop apply_patch custom tool in OpenAI responses
- Added logic in `ConvertOpenAIResponsesRequestToClaude` to exclude `apply_patch` custom tools.
- Introduced `isOpenAIResponsesApplyPatchCustomTool` helper function to identify and filter the tool.
- Added `TestConvertOpenAIResponsesRequestToClaude_DropsApplyPatchCustomTool` to validate the behavior.

Closes: #3243
2026-06-19 03:43:26 +08:00
Luis Pater 1d0551a991 feat(config): improve config reload handling and introduce async management save hook
- Refactored `ConfigReloadHook` to use `reloadConfigFromWatcher` for consistency.
- Added async `reloadConfigAfterManagementSaveAsync` to handle post-save operations.
- Introduced `ReloadConfigIfChanged` in watcher for manual trigger support.
- Enhanced config reload paths to separate auth synthesis from standard updates.
- Updated `applyConfigUpdate` logic to allow more granular reload behaviors.

Closes: #3235
2026-06-19 03:35:09 +08:00
Luis Pater 052f1934b8 fix(auth): classify transport errors as home_unavailable with retryable flag
- Updated error handling in `RPopAuth` to distinguish `auth_not_found` from transport errors.
- Added a new test, `TestPickNextViaHomeClassifiesTransportErrorsAsHomeUnavailable`, to validate correct error classification and retryable property.
2026-06-19 02:54:48 +08:00
Luis Pater ae6c5eaea5 feat(runtime): add support for gpt-image-1.5 and direct image API proxying
- Introduced the `gpt-image-2` model in Codex built-ins and updated visibility logic in the registry.
- Added direct proxy support for OpenAI image generation and editing endpoints.
- Implemented new execution paths for `/images/generations` and `/images/edit`, ensuring seamless handling for both JSON and multipart payloads.
- Expanded test coverage to validate the new model and direct proxy features, including streaming scenarios and error handling.
2026-06-19 00:06:12 +08:00
Luis Pater 41c52b9df6 test(management): add concurrency test for Codex OAuth session handling
- Introduced `TestRequestCodexTokenCompletionKeepsConcurrentSessionPending` to validate proper handling of concurrent OAuth sessions.
- Refactored Codex OAuth logic to use `newCodexOAuthService` for improved testability.

Closes: #3171
2026-06-18 23:15:43 +08:00
Luis Pater c13dbcc24e feat(translator): add test and logic to ensure object schemas include properties field
- Added `TestConvertClaudeRequestToOpenAI_ToolSchemaAddsMissingObjectProperties` to validate automatic addition of missing `properties` in `object` schemas.
- Introduced `normalizeObjectSchemaProperties` to recursively ensure schemas of type `object` include an empty `properties` field if absent.
- Updated `ConvertClaudeRequestToOpenAI` to apply schema normalization for improved compatibility with OpenAI schema expectations.

Closes: #3165
2026-06-18 22:54:20 +08:00
Luis Pater ac8fb9706f feat(thinking): remove thinkingConfig for ModeNone with zero budget and no level
- Updated Gemini, Gemini CLI, and Antigravity logic to delete `thinkingConfig` when `ModeNone` is set, `Budget=0`, and `Level` is empty.
- Adjusted tests to validate this behavior across multiple scenarios and models with zero-allowed configurations.
- Extended test cases for additional coverage of mixed-model behavior.

Closes: #3138
2026-06-18 22:39:02 +08:00
sususu98 ec8c2c2913 test(antigravity): cover invalid-signature replay cache clear
Add executor httptest for upstream 400 clearing HOME reasoning replay
items, and a whitespace call_id matcher regression test for replay
filtering.
2026-06-18 22:31:50 +08:00
sususu98 c55157dc2e fix(antigravity): PR review replay scope, signature merge, and tool keys
- Derive replay session from generateStableSessionID when sessionId is absent
- Merge cached thoughtSignature into existing functionCall by call id
- Allow filter to pass function_call_part when only signature replay is needed
- Include native functionCall id in replay dedupe keys
- Add unit tests for signature merge, stable scope, and parallel tool ids
2026-06-18 20:29:44 +08:00
sususu98 ef19f5fc81 fix(antigravity): address review on replay call_id and args parsing
Trim call_id once for matching-function-response checks; use args.Value()
in synthetic model functionCall insertion; guard functionResponse lookup
when call_id is empty.
2026-06-18 19:52:54 +08:00
sususu98 b17d29ad35 fix(antigravity): insert replayed functionCall before matching functionResponse
When HOME replay restores a cached function_call_part and the request
already contains the matching functionResponse, insert a synthetic
role=model content with functionCall (and thoughtSignature) immediately
before that response content instead of writing into the same index.

Add regression tests for user/model functionResponse shapes.
2026-06-18 19:50:46 +08:00
sususu98 292456a884 feat(antigravity): HOME reasoning replay for Gemini models
Add executor-scoped replay cache aligned with Codex HOME replay:
Scope, observe SSE/non-stream responses, store normalized thought_signature
and function_call_part items, apply on the next streamGenerateContent
request, and invalidate on invalid signature responses.

Gemini/flash/agent models use HOME replay; native per-part signature
replay is not wired on upstream/dev. Wire non-stream and stream paths
in antigravity_executor and purge expired entries from signature_cache.

Includes unit tests and HOME-provider-replay documentation.
2026-06-18 19:50:28 +08:00
sususu98 62c4b377dd Revert "feat(antigravity): HOME reasoning replay for Gemini models"
This reverts commit 365e8fc2ca.
2026-06-18 16:02:50 +08:00
sususu98 365e8fc2ca feat(antigravity): HOME reasoning replay for Gemini models
Add executor-scoped replay cache aligned with Codex HOME replay:
Scope, observe SSE/non-stream responses, store normalized thought_signature
and function_call_part items, apply on the next streamGenerateContent
request, and invalidate on invalid signature responses.

Gemini/flash/agent models use HOME replay; native per-part signature
replay is not wired on upstream/dev. Wire non-stream and stream paths
in antigravity_executor and purge expired entries from signature_cache.

Includes unit tests and HOME-provider-replay documentation.
2026-06-18 14:37:11 +08:00
Luis Pater 78ba8ba731 chore: remove Gemini CLI-related translator packages and logic
- Deleted `geminicli` provider and related `Apply` logic.
- Removed all translator packages specific to Gemini CLI (Claude, Codex integrations).
- Purged associated test files for Gemini CLI translation.
- Removed `GeminiAuthenticator` and all associated authentication logic (OAuth flows, token handling, refresh logic).
- Deleted internal/executor Gemini OAuth support, including bearer token handling and runtime API logic.
- Purged all tests, configs, and command-line flags specific to Gemini OAuth flows.
- Updated documentation and aliases to reflect Gemini removal.
- Renamed `parseRetryDelay` to `ParseRetryDelay` and `deleteJSONField` to `DeleteJSONField`.
- Updated references in `antigravity_executor` and tests to use the new `helps` package.
- Adjusted import paths and test cases to ensure compatibility with the new location.
- Updated README files to reflect changes in the retry logic references.
- Updated `.github/ISSUE_TEMPLATE/bug_report.md` to remove deprecated Gemini CLI mention.
2026-06-18 13:33:10 +08:00
Luis Pater dd49a52003 feat(translator): add tests to validate trailing assistant prefill stripping and sanitize tool call IDs
- Introduced tests for `ConvertOpenAIRequestToGemini`, `ConvertOpenAIResponsesRequestToGemini`, and related Claude functions to ensure trailing model-prefill turns are removed.
- Enhanced tool call ID handling with `util.SanitizeClaudeToolID` to standardize IDs in Claude-related conversions and tests.
- Updated logic in Gemini and Claude translators to handle edge cases for trailing assistant prefill and tool ID sanitization, ensuring compatibility across input variants.

Closes: #3113
2026-06-18 04:13:04 +08:00
Luis Pater cde5081e94 test(translator): add tests to validate omission of top-level output_text in OpenAI responses
- Added `TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_CompletedOmitsTopLevelOutputText` to ensure `output_text` is excluded in streamed responses.
- Added `TestConvertOpenAIChatCompletionsResponseToOpenAIResponses_ToolCallCompletedOmitsTopLevelOutputText` to validate behavior during tool call completions.
- Introduced `TestConvertOpenAIChatCompletionsResponseToOpenAIResponsesNonStream_OmitsTopLevelOutputText` to confirm the omission of `output_text` in non-streamed responses.
- Expanded test coverage to ensure consistency with native OpenAI responses.
2026-06-18 03:43:03 +08:00
Luis Pater acaf250fa8 feat(management): add test to validate priority preservation in auth file uploads
- Implemented `TestUploadAuthFile_PreservesPriorityAttributes` to ensure priority attributes and metadata are preserved during auth file uploads.
- Updated `UploadAuthFile` logic to utilize `SynthesizeAuthFile` for better handling of generated auth attributes and metadata.

Closes: #2924
2026-06-17 21:48:34 +08:00
Luis Pater f23fb122e7 feat(translator): ensure tool uses stay adjacent to tool results in message generation
- Refactored `ConvertOpenAIResponsesRequestToClaude` logic to align tool use with corresponding tool results.
- Introduced helper functions for appending and flushing pending reasoning and tool use messages.
- Expanded tests to validate message order and content consistency when processing tool calls and results.
2026-06-17 13:23:51 +08:00
Luis Pater 644ba74bff feat(videos): implement auth binding for video requests and enhance proxy handling
- Added auth binding logic to tie video requests to specific authentication IDs.
- Enhanced video content handlers to support proxy configuration based on selected auth.
- Introduced helper functions for creating HTTP clients with direct or global proxy fallback.
- Expanded unit tests to validate auth binding, proxy usage, and fallback behavior.
2026-06-17 13:10:07 +08:00
Luis Pater 96a8b0cfe2 feat(executor): normalize reasoning text events and enhance handling logic
- Introduced `xaiNormalizeReasoningSummaryData` and related functions to normalize `reasoning_text` events into `reasoning_summary` shapes for standardization.
- Updated WebSocket and streaming logic to process normalized reasoning summary events correctly.
- Enhanced tests to validate normalization, order of events, and output structure in both stream and non-stream scenarios.
2026-06-17 13:00:00 +08:00
Luis Pater 29f22acd77 Merge pull request #3877 from sususu98/feat/antigravity-cli-ua-upstream-dev
feat(misc): align Antigravity runtime UA with agy CLI version sources
2026-06-17 10:35:31 +08:00
sususu98 c296790801 feat(misc): align Antigravity runtime UA with agy CLI version sources
Use the agy CLI User-Agent family (antigravity/cli/{version} darwin/arm64)
on CPA macOS/arm64 hosts instead of the legacy hub-style antigravity/{version}
string. Resolve the cached version from the CLI auto-updater manifest
(darwin_arm64.json), then the GCS latest pointer, then antigravity-cli GCS
prefix listing, with fallback 1.0.8 when all sources fail.

Update AntigravityUserAgent helpers and executor default UA comment to match.
2026-06-17 10:30:52 +08:00
Luis Pater 0e81dee7e2 Merge pull request #3873 from router-for-me/thinking 2026-06-17 09:16:04 +08:00
hkfires 8c6f279f0a refactor(tests): remove obsolete test files and update reasoning effort logic 2026-06-17 08:11:25 +08:00
Luis Pater b9d024af49 feat(executor): handle usage limit errors and enhance retry logic
- Added `isCodexUsageLimitError` to detect and handle `usage_limit_reached` errors from Codex responses.
- Updated `newCodexStatusErr` to treat usage limit errors as HTTP 429 with proper `RetryAfter` handling.
- Enhanced test coverage to validate usage limit error handling, including reset time parsing and retry behavior.

Closes: #2886
2026-06-17 07:19:02 +08:00
Luis Pater 8d2c00c107 feat(plugin-config): update default plugin Enabled behavior to false and expand test coverage
- Changed default plugin `Enabled` state from `true` to `false` across configurations, runtime logic, and YAML defaults.
- Added helper function `enabledPluginConfigs` for generating plugin configs with `Enabled` set explicitly.
- Expanded unit tests in `pluginhost`, `config`, and `management` to validate behavior changes for disabled plugins, default settings, and skipped load scenarios.
2026-06-17 03:46:30 +08:00
Luis Pater 125c092866 Merge pull request #3872 from router-for-me/codex/pluginhost-async-reload
Fix async plugin reload races
2026-06-17 03:38:42 +08:00
LTbinglingfeng 09596d2f54 Treat loading plugins as busy 2026-06-17 03:19:31 +08:00
LTbinglingfeng a3c87ceeb4 Fix management reload snapshot ordering 2026-06-17 03:17:56 +08:00
LTbinglingfeng 7b16321e50 Stabilize management reload race tests 2026-06-17 02:43:12 +08:00
LTbinglingfeng a4756ab7a9 Use config snapshots for management reload 2026-06-17 02:40:34 +08:00
LTbinglingfeng 7f026e1aab Add runtime config clone 2026-06-17 02:39:04 +08:00
LTbinglingfeng a65ced4a92 fix(management): reload plugins asynchronously after changes 2026-06-17 01:06:57 +08:00
LTbinglingfeng 13f51d96cb fix(pluginhost): avoid holding host lock during plugin lifecycle 2026-06-17 01:05:21 +08:00
Luis Pater a5cb88323d feat(translator): enhance content block handling and add stream-specific test
- Refactored content block start/stop logic into `startCodexTextBlock` and `stopCodexTextBlock` for better readability and reusability.
- Updated logic to ensure proper handling of "output_text" block events to avoid ghost stop emissions.
- Added `TestConvertCodexResponseToClaude_StreamTextBeforeToolCallsDoesNotEmitGhostStop` to validate content block start/stop behavior in streamed responses.
2026-06-17 00:41:08 +08:00
Luis Pater f49d1798d1 feat(translator): add namespace and function call mapping for Claude responses
- Introduced `applyResponsesFunctionCallNamespaceFields` to manage name and namespace settings in response items.
- Added `splitResponsesQualifiedFunctionCallFromRequest` for handling qualified names and matching them with namespaces.
- Updated response generation logic to preserve namespace and function call structure in multiple response pathways.
- Expanded unit tests to validate namespace and function call restoration in both stream and non-stream scenarios.
2026-06-17 00:21:43 +08:00
sususu98 30dc2e7f34 fix(translator): emit Claude server tool blocks for Codex web_search_call streams (#3868)
* fix(translator): emit Claude server tool blocks for Codex web_search_call streams

Map Codex Responses streaming web_search_call events to Claude SSE
server_tool_use and web_search_tool_result blocks, with deduplication
and a focused stream regression test.

* fix(translator): stabilize Codex web_search fallback tool_use IDs

Reuse the active fallback web_search tool_use ID across later stream
events so tool_result blocks stay paired when upstream omits item IDs.
This is defensive hardening; live Codex streams already provide ws_* IDs.

* fix(translator): emit Codex web_search blocks from populated items

Wait for output_item.done before emitting Claude web_search tool_use
and tool_result blocks, and avoid deduping early added/completed events
that arrive before action.query is available. Matches live Responses
stream ordering seen in local tmux verification.

* fix(translator): map Codex web_search_call items in non-stream Claude responses

Emit server_tool_use and web_search_tool_result blocks from completed
response.output web_search_call items, matching the streaming translator.

* fix(translator): keep non-stream web_search on end_turn and dedupe output items

Do not treat server web_search_call items as client tool_use for stop_reason.
Skip duplicate or query-less open_page web_search output items in non-stream
translation, matching spark live behavior.
2026-06-16 23:07:08 +08:00
Luis Pater 2884a67ed0 feat(videos): add support for video_url extraction and validation in handlers
- Updated `openai_videos_handlers` to extract and set `video_url` from payloads when available.
- Enhanced unit tests to validate correct `video_url` extraction and inclusion in responses.
2026-06-16 21:06:27 +08:00
Luis Pater f63cf9820a docs: add CatAPI sponsorship details to README files
- Included CatAPI information in README files (EN, JA, CN) to acknowledge sponsorship.
- Added CatAPI logo and sign-up link with credit claim details.
- Updated project assets to include CatAPI logo.
2026-06-16 20:16:59 +08:00
sususu98 87132e54d7 feat(plugin): add ModelRouter before auth with single-slot routing targets (#3865)
* feat(plugin): add ModelRouter before auth with single-slot routing targets

## Motivation

Plugins that need to change execution based on the **original inbound request**
(protocol format, raw body, headers, query, stream flag, metadata, etc.) often
resorted to virtual/trampoline models or routing inside interceptors. This
commit adds **ModelRouter**: a pluggable layer **before** model-to-provider
resolution and AuthManager credential selection, so plugins can declare who
executes a request without spoofing the client model name.

This is a **new capability**, not a bugfix on the existing chain. With no
ModelRouter plugins loaded, behavior matches upstream.

## Pipeline placement

- `execute`, `stream`, and `count` (and image paths via AuthManager) call
  `applyModelRouter()` before building `coreexecutor.Request`.
- Routing runs **before** the request interceptor (before auth), so routers see
  the client’s original context. After a plugin executor is chosen, the existing
  **after-auth interceptor → response/stream interceptor** chain still applies.
- Internal `ExecuteModel` / `ExecuteModelStream` (host callbacks) support
  `SkipRouterPluginID` so nested calls do not re-enter the same router.

## Routing API (single slot, mutually exclusive)

`ModelRouteResponse` uses **one target slot** to avoid ambiguity when both
`TargetExecutorPluginID` and `TargetProvider` were set and the host ignored one:

| Field | Meaning |
|-------|---------|
| `Handled` | `false`: this router declines; try the next router or default path |
| `TargetKind` | `self` \| `executor` \| `provider` (pick one) |
| `Target` | `self`/`executor`: plugin ID; `provider`: built-in provider key |
| `TargetModel` | Optional on `provider` only; empty keeps client `RequestedModel` |
| `Reason` | Optional diagnostic text |

- **self**: the router plugin’s own executor (`Target` normalized to the router’s plugin ID).
- **executor**: another plugin’s executor; host pre-checks with `executorPluginReady()`
  (executor declared and provider identifier resolvable) to avoid handled routes that 500 at execution.
- **provider**: skip registry model resolution; fixed built-in AuthManager path; optional
  `TargetModel` for execution model only—**does not** change outward requested-model metadata.

Routers run in **descending plugin priority** (tie-break: ascending plugin ID). Panic, error,
invalid target, or unavailable executor/provider → log and **fall through to the next router**;
if none handle, use the original provider+auth flow.

## Context exposed to routers

`ModelRouteRequest` includes:

- `SourceFormat`, `RequestedModel`, `Stream`
- `Headers`, `Query`, `Body` (defensive copies)
- `Metadata` (best-effort read-only context snapshot)
- `AvailableProviders`: built-in provider keys with at least one **non-disabled** auth
  (`AuthManager.AvailableProviders()`). **Does not** reflect per-model cooldown or transient
  unavailability—treat as an optimistic snapshot.

Adds `AuthManager.HasProviderAuth()` and `AvailableProviders()`, excluding `Disabled` and
`StatusDisabled` auths consistently with credential selection.

## Host and RPC

- Go plugins: `pluginapi.ModelRouter` + `RouteModel()`.
- RPC plugins: `pluginabi.MethodModelRoute` (`model.route`), capability flag `model_router`.
- `pluginhost.Host` implements `RouteModel` / `RouteModelExcept`; handlers use
  `SetModelRouterHost` or a `PluginHost` type assertion; **direct executor** paths use
  `ExecutePluginExecutor*` / `CountPluginExecutor`.
- No bundled example ModelRouter plugin; capability is active only when a third-party plugin
  declares `model_router` and loads.

## Plugin RPC schema (policy A, upstream-aligned)

- `pluginabi.SchemaVersion` stays **1**: capability additions (`model_router`, `model.route`)
  do not bump the number; increment only on breaking RPC JSON changes.
- Host sends `schema_version` at register; reject only if the plugin declares a **higher**
  version than the host.
- No unpublished “ModelRouter requires schema ≥ 3” gate (v3 single-slot API was never public).
- Existing plugins and examples without `model_router` (`schema_version: 1`) need no changes.
- RPC ModelRouter: `schema_version: 1` + `model_router: true` + implement `model.route`.

## Path consistency within this commit

- Provider routes reuse image-only model checks (e.g. `gpt-image-2`) on the normalized model,
  same as the default AuthManager path.
- `count` aligned with execute/stream: `SkipRouterPluginID`, query/headers injection,
  interceptor skip semantics.
- Handlers: `modelRoutersEnabled` treats hosts without `HasModelRouters` as disabled
  (same as before ModelRouter existed); `pluginhost.Host` implements the detector.
- API docs: `ModelRouter` explicitly includes built-in **provider** targets (in addition to
  plugin executors and the router’s own executor).

## Testing

go test ./internal/pluginhost ./sdk/api/handlers ./sdk/pluginapi ./sdk/pluginabi ./sdk/cliproxy/auth
go build -o test-output ./cmd/server && rm test-output
go test ./...

* fix(handlers): address ModelRouter review feedback

- Use modelExecutionQuery for plugin executor and AuthManager paths so
  inbound URL query matches router/header behavior
- Guard queryFromContext when gin Request.URL is nil
- Read plugin executor stream chunks via nextStreamChunk to exit on cancel
- Drop redundant clonePluginMetadata on capability record meta

Tests cover query propagation, stream cancel, and nil URL safety.

* feat(plugin): add Claude web search router example

Add a Claude Code web_search ModelRouter example that can route matching Claude requests through Antigravity, Codex, xAI, or Tavily.

The plugin includes executor orchestration, backend fallback/penalty handling, Tavily API key support, Claude-compatible response assembly, stream forwarding, and focused unit coverage for detection, fallback routing, model resolution, penalties, stream forwarding, and Tavily behavior.

Verification: go test -count=1 ./... in examples/plugin/claude-web-search-router/go; go build -buildmode=c-shared for the plugin; go build ./cmd/server; live local CPA curl coverage for plugin load, four explicit routes, fallback, and Codex spark routing.

* fix(pluginhost): validate executor routes before fallback

* fix(pluginhost): skip oauth-only executor routes
2026-06-16 19:15:34 +08:00
sususu98 9f940f162f fix(pluginhost): keep stream callbacks alive until stream close
Keep RPC streaming executor callback scopes alive until async streams close, detach nested host.model.execute_stream contexts from request cancellation, and clean up the stream bridge on stream completion.
2026-06-16 17:31:11 +08:00
Luis Pater 907e3493ee docs: update VisionCoder details in README files
- Added information about exclusive retail availability of Claude Max 200 and GPT Pro 200 premium accounts.
- Enhanced descriptions of VisionCoder's offerings in README files (EN, JA, CN).
2026-06-16 13:52:33 +08:00
Luis Pater 8fad0d0325 feat(config+executor): add global Claude cloak mode toggle and improve credential fallback logic
- Introduced `disable-claude-cloak-mode` configuration to globally disable Claude cloak mode with credential-level overrides.
- Enhanced `getCloakConfigFromAuth` to support fallback to metadata for cloak settings.
- Updated cloak configuration precedence logic, integrating global, credential, and default modes.
- Updated config and watcher diff handling to include `disable-claude-cloak-mode`.

Closes: #2789
2026-06-16 13:03:16 +08:00
Luis Pater 2406daf3ef feat(util): normalize Claude tool_result content and improve Gemini integration
- Added `ConvertClaudeToolResultContent` to standardize Claude tool_result content, preserving JSON structure and splitting out base64-encoded images.
- Updated Gemini and Gemini-CLI translators to use the new utility for generating deterministic function responses and inline image parts.
- Added comprehensive test cases for content types and edge cases, ensuring correct handling of string, JSON, and image blocks.

Closes: #2781
2026-06-16 08:09:30 +08:00
Luis Pater 844b855974 feat(executor): sanitize web search tool domains to meet Anthropic requirements
- Added `sanitizeClaudeWebSearchDomains` to remove empty `allowed_domains` and `blocked_domains` fields for built-in web_search tools, addressing ambiguity errors from Anthropic.
- Integrated domain sanitization into the Claude message preparation pipeline.
- Added test cases to validate correct handling of empty and non-empty domain fields across various tool types.

Closes: #2681
2026-06-16 03:29:44 +08:00
Supra4E8C e40599831a Merge pull request #3850 from router-for-me/feat/log-feat
Feat/log feat
2026-06-15 22:06:38 +08:00
Dominic Robinson 1ed1f7b390 Merge branch 'dev' into main 2026-06-15 14:16:49 +01:00
LTbinglingfeng 0b21b07115 fix log cursor rotation gap 2026-06-15 18:37:21 +08:00
LTbinglingfeng 5036513bf9 Fix ambiguous empty log cursor handling 2026-06-15 16:53:50 +08:00
LTbinglingfeng a47c386319 Avoid counting all logs for tail reads 2026-06-15 15:51:15 +08:00
LTbinglingfeng db3fdea4a1 Disambiguate zero-offset log cursors 2026-06-15 15:50:03 +08:00
LTbinglingfeng 917cec3bf6 Continue log cursors across rotation 2026-06-15 15:46:58 +08:00
LTbinglingfeng 3b0cc913ec feat(plugins): implement asynchronous config reload after plugin deletion 2026-06-15 15:35:55 +08:00
Luis Pater bbef8da454 feat(videos): add video authentication binding and update handler behavior
- Introduced `videoAuthBindingStore` for managing mappings of video IDs to credentials with TTL support.
- Updated video creation and retrieval handlers to bind and utilize credentials for authentication.
- Enhanced response models to include upstream models and adjusted request preparation logic.
- Added test coverage for video auth binding, TTL configuration, and expiration handling.
2026-06-15 13:38:40 +08:00
Luis Pater f85768eef3 feat(auth): add config API key exclusion management with tests
- Implemented helper methods `IsConfigAPIKeyAuth` and `toggleConfigAPIKeyExcludedAll` for managing config API key exclusions.
- Updated API request handling to support enabling/disabling config API key exclusion patterns.
- Added test coverage to validate exclusion toggling logic and persistence behavior.
- Refactored duplicate code for identifying config API key auth entries into reusable utilities.
2026-06-15 11:14:05 +08:00
Luis Pater f33bc56bb9 feat(websockets): add transcript state tracking and compaction trigger support
- Added methods for managing and tracking WebSocket transcript state, including recording, prepending, and replacing transcript inputs.
- Implemented `executeCompactionTriggerFromWebsocketContext` to support compaction triggers using recorded transcript context.
- Enhanced upstream-downstream ID mapping with additional utilities and state synchronization.
- Expanded test coverage to validate transcript state management, compaction payload generation, and WebSocket response handling.
2026-06-15 10:41:35 +08:00
Luis Pater ea90ab6f77 feat(websockets): implement XAIWebsocketsExecutor with enhanced execution and ID mapping
- Developed `XAIWebsocketsExecutor` for handling xAI Responses via WebSocket transport.
- Introduced session and state management with `codexWebsocketSessionStore` and `xaiWebsocketIDStateStore`.
- Added robust ID mapping for upstream and downstream request/response sequences.
- Enhanced error propagation and handling of WebSocket terminal events.
- Included utility methods for WebSocket request preparation, connection management, and state tracking.
- Added foundational support for compact and streamed responses via enhanced session tracking.
2026-06-15 08:22:07 +08:00
Luis Pater 56988aea0f feat(websockets): add Codex websocket passthrough support with tests
- Implemented `websocketDirectCaptureExecutor` for Codex websocket passthrough functionality.
- Added logic to bypass incremental state handling for passthrough models.
- Updated normalization, compaction, and replay handling to support passthrough mode.
- Introduced `responsesWebsocketUsesCodexWebsocketPassthrough` utility for model-specific passthrough determination.
- Expanded test coverage for websocket passthrough scenarios, including compaction and response validation.
2026-06-15 02:31:05 +08:00
LTbinglingfeng d417fa534f Bound management log cursor reads 2026-06-15 02:18:58 +08:00
LTbinglingfeng 0d82daca6b Preserve management log line counts 2026-06-15 02:17:57 +08:00
LTbinglingfeng 331daa24ad Read management logs from cursors 2026-06-15 02:10:25 +08:00
LTbinglingfeng 95a72a47c8 Tail management logs with cursors 2026-06-15 02:08:06 +08:00
LTbinglingfeng c61453a807 Add log cursor helpers 2026-06-15 02:06:25 +08:00
Luis Pater 7de9757c82 feat: add OpenAI video support with improved error handling and response normalization
- Introduced `/openai/v1/videos` endpoint to support OpenAI-specific video generation.
- Added error normalization and handling for OpenAI video resources, including detailed error propagation.
- Enhanced response structure to include OpenAI-specific fields for status, progress, and model mappings.
- Implemented new handlers for video content retrieval and error scenarios.
- Expanded test coverage to validate OpenAI video support, error handling, and backend compatibility.
2026-06-15 01:53:52 +08:00
Supra4E8C ea4e978c60 Merge pull request #3848 from router-for-me/feat/Community_Plugins
Feat/community plugins
2026-06-15 01:22:55 +08:00
LTbinglingfeng 6f3bd7641b feat(pluginstore): improve nil checks in pluginStoreSnapshot function 2026-06-15 01:21:07 +08:00
Luis Pater 3b96119050 feat(websockets): handle terminal events and improve error propagation
- 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.
2026-06-15 01:03:19 +08:00
LTbinglingfeng 239d7ee0b0 feat(pluginstore): refactor plugin store source handling to use string URLs 2026-06-15 00:54:32 +08:00
LTbinglingfeng 303c0f2f53 feat(pluginstore): add support for third-party plugin store sources and enhance plugin management 2026-06-15 00:50:22 +08:00
Luis Pater 529d9e92c9 feat(executor): add support for compact response handling in XAIExecutor
- Introduced `executeCompact` to handle non-streaming compact responses via the `/responses/compact` endpoint.
- Added `executeCompactionTriggerStream` for streaming responses triggered by `compaction_trigger`.
- Enhanced request preparation with `prepareResponsesRequestTo` for dynamic response formats.
- Updated logic to bypass streaming for `/responses/compact` and added fallback behaviors.
- Added comprehensive tests for compact response handling and event streaming validations.
2026-06-15 00:29:38 +08:00
Luis Pater 6f923a28f7 feat(pluginhost): implement host authentication callbacks and add tests
- Introduced `auth_callbacks` for handling host authentication list, get, runtime, and save operations.
- Added extensive unit tests to validate functionality, including disk fallback and runtime-specific cases.
- Created example implementation in Go to demonstrate host callback integrations.
2026-06-14 23:51:40 +08:00
Luis Pater c59eee60b7 Merge pull request #3847 from router-for-me/home
Fix credential handling in home models
2026-06-14 23:47:38 +08:00
hkfires 64a8957e60 fix(auth): map credential errors to unauthorized 2026-06-14 23:02:21 +08:00
hkfires b5da088767 fix(home): forward credentials for home models 2026-06-14 22:09:29 +08:00
Luis Pater 2a050dc95d feat: enhance fault tolerance for kv-based caching and introduce additional tests
- Updated Antigravity Credits fallback to handle KV store unavailability as a service error.
- Enhanced signature caching mechanisms with request-time KV access and sliding expiration.
- Added and improved tests for KV client interactions, including error handling and expiration behaviors.
- Introduced `CacheSignatureBestEffort` for non-critical signature caching and clarified function flows with required context.
- Ensured consistent error reporting for missing or unavailable KV stores in various scenarios.
- Replaced direct `homekv` calls with injectable KV client interfaces for `antigravity` and `codex_reasoning_replay` modules.
- Improved error reporting and handling for KV operations, including `KVGet`, `KVSet`, `KVDel`, and `KVExpire`.
- Introduced dedicated fake KV clients for expanded and granular test coverage.
- Added new unit tests to validate KV client behaviors and error scenarios, ensuring robustness and sliding expiration functionality.
2026-06-14 21:11:35 +08:00
Luis Pater f6aa9a067e Merge pull request #3846 from router-for-me/remove_amp
Remove AMP integration support
2026-06-14 20:57:36 +08:00
hkfires 79db0e54be refactor(api): remove deprecated route module interfaces 2026-06-14 20:45:23 +08:00
hkfires b4054e185e refactor(config): remove legacy migration code 2026-06-14 20:36:54 +08:00
hkfires 8122b9fe4b feat!: remove amp integration support
BREAKING CHANGE: ampcode configuration, management endpoints, provider
routing, and X-Amp-Thread-Id session affinity are no longer supported
2026-06-14 20:31:00 +08:00
Dominic Robinson c354f88f3b feat(api): Route Anthropic /v1/models requests to the Claude format
/v1/models is shared by the OpenAI and Anthropic surfaces and was
dispatched to the Claude format only for claude-cli User-Agents, so
generic Anthropic API clients received the OpenAI format. Distinguish
Anthropic requests by the Anthropic-Version header (sent by every
Anthropic client, never by OpenAI/Codex clients) in addition to the
existing claude-cli check, in both unifiedModelsHandler and
handleHomeModels. Additive and non-breaking for existing clients.
2026-06-14 06:03:58 +01:00
Luis Pater e0cb43f38d Merge pull request #3825 from xiaocoss/add-quotio-desktop
docs: add Quotio Desktop to the projects list
2026-06-14 05:47:03 +08:00
Luis Pater 964e86f612 Merge pull request #3827 from iamkhalidbashir/add-kimi-k2.7-code
feat: add Kimi K2.7 Code model (kimi-k2.7-code)
2026-06-14 05:43:53 +08:00
Luis Pater eebb873b8a Merge pull request #3832 from haowang02/feat/disable-image-generation-passthrough
feat(config): add "passthrough" mode for disable-image-generation
2026-06-14 05:21:44 +08:00
Luis Pater 6d472d7b4f feat(models): increase context_length for Composer 2.5 Fast to 200,000 2026-06-14 02:27:08 +08:00
Dominic Robinson e3301ecc98 fix(registry): Emit Claude model created_at as RFC 3339 string
Anthropic's List Models schema types created_at as an RFC 3339 datetime
string, but the Claude case of convertModelToMap emitted model.Created
as a Unix-timestamp integer. Format it with time.RFC3339 so the listing
matches the documented schema.
2026-06-13 16:15:45 +01:00
Dominic Robinson f5484b0900 fix(registry): Conform Claude models listing to Anthropic API schema
Anthropic's List Models response (GET /v1/models) defines each model object
with id, display_name, max_input_tokens, max_tokens, created_at and type.
The Claude case of convertModelToMap emitted an incomplete object: it dropped
max_input_tokens and max_tokens entirely and omitted display_name whenever it
was unset, so the Anthropic-compatible listing did not match the schema it
emulates.

Emit max_input_tokens from ContextLength and max_tokens from
MaxCompletionTokens (the same registry metadata the Gemini case already
surfaces as inputTokenLimit/outputTokenLimit), with fallbacks, and always
emit display_name, falling back to the model ID.
2026-06-13 16:03:35 +01:00
Hao WangandClaude Opus 4.8 8d4a7f1f2e feat(config): add "passthrough" mode for disable-image-generation
Adds a fourth value for the disable-image-generation setting:

- false:       inject image_generation (unchanged)
- true:        strip everywhere + 404 on /v1/images/* (unchanged)
- chat:        strip on non-images endpoints, keep /v1/images/* (unchanged)
- passthrough: never inject and never strip on non-images endpoints
               (the client payload is forwarded unchanged); behaves like
               "chat" on /v1/images/* endpoints.

image_generation injection (codex executors) is already gated on the Off
mode, and the /v1/images/* 404 gate is already gated on the All mode, so
passthrough only required a change to the payload strip logic in
payload_helpers.go, now expressed via shouldStripImageGeneration().

Closes #3831

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 22:41:15 +08:00
Supra4E8C 83c53d05ee Merge pull request #3830 from router-for-me/codex/add-plugin-delete-api
Codex/add plugin delete api
2026-06-13 21:50:52 +08:00
LTbinglingfeng 9cdb18e1d6 refactor(plugin): remove timeout handling from plugin installation logic 2026-06-13 21:14:06 +08:00
LTbinglingfeng b39ee66250 Add plugin store install timeout 2026-06-13 20:56:49 +08:00
LTbinglingfeng b79647d886 Document plugin delete endpoint 2026-06-13 20:52:30 +08:00
LTbinglingfeng c5cfdb15e5 Add plugin delete management endpoint 2026-06-13 20:52:07 +08:00
Luis Pater d6c4fc2d82 feat(translator): consolidate mid-conversation system messages into initial system content
- Updated `ConvertClaudeRequestToOpenAI` to move mid-conversation `system` messages to the initial system content.
- Added a new test case `TestConvertClaudeRequestToOpenAI_MidConversationSystemMessagesMoveToInitialSystem` to validate functionality.
- Refactored logic for appending system message content for improved readability and maintainability.

Closes: #3815
2026-06-13 16:17:36 +08:00
Khalid Bashir 82235202fb feat: add Kimi K2.7 Code model (kimi-k2.7-code)
Add kimi-k2.7-code to the model registry with:
- 262K context length, 65K max completion tokens
- Thinking support (dynamic, 1024-32000 budget)
- zero_allowed=false (K2.7 Code does not support non-thinking mode)

Closes #3826
2026-06-13 13:14:16 +05:00
lilinho3andClaude Fable 5 57971d7a51 docs: add Quotio Desktop to the projects list
Cross-platform (Tauri) port of Quotio (Windows / macOS / Linux) that manages an AI account pool through CLIProxyAPI. Added to README.md, README_CN.md and README_JA.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-13 15:14:17 +08:00
Luis Pater b94178bfd9 chore(docker): simplify .dockerignore patterns by removing wildcard entries 2026-06-13 14:45:12 +08:00
Luis Pater 94c5a7fd47 Merge pull request #3824 from sususu98/codex/antigravity-websearch-native-minimal
[codex] Bridge Claude WebSearch to Antigravity googleSearch
2026-06-13 13:12:25 +08:00
sususu98 48dcadd9ef feat(antigravity): bridge Claude WebSearch to native googleSearch
Add a native Antigravity WebSearch path for Claude typed WebSearch requests.

Detect Claude Messages requests whose tools are only typed WebSearch tools
(web_search_20250305 / web_search_20260209), and convert them into an
Antigravity requestType=web_search payload instead of sending the request
through the normal tool-calling path.

Preserve the user's requested model. The native path is enabled only when that
Antigravity model is known to support Google Search. Capability data fetched
from Antigravity model info is used only as an enhancement to the local model
registry, not as a replacement for the existing registry fallback behavior.
Unsupported models keep the existing Antigravity request behavior and are not
silently rerouted to another web-search-capable model.

Translate Claude WebSearch request options to the verified Antigravity
googleSearch shape:
- max_uses -> googleSearch.enhancedContent.imageSearch.maxResultCount
- allowed_domains -> googleSearch.includedDomains

Leave blocked_domains and user_location unmapped because the Antigravity
googleSearch request shape has no verified equivalent for them. This avoids
sending speculative fields or pretending unsupported Claude WebSearch options
are enforced upstream.

Translate Antigravity web-search responses back into Claude-compatible output:
server_tool_use blocks, web_search_tool_result blocks, cited text blocks,
grounding URLs, and usage-compatible stream/non-stream responses.

Cover the behavior with tests for request conversion, response conversion,
grounding URL resolution, domain filter mapping, fetched capability hints,
excluded-model handling, and unsupported-model behavior.
2026-06-13 10:07:48 +08:00
Supra4E8C 6a0b198c7e Merge pull request #3823 from router-for-me/fix/cors-expose-plugin-support
fix: expose plugin support header for CORS
2026-06-13 06:10:03 +08:00
LTbinglingfeng 7cd5b15c9b fix: precompute exposed CORS headers 2026-06-13 05:59:18 +08:00
LTbinglingfeng 2659e490a8 fix: expose plugin support header for CORS 2026-06-13 05:53:19 +08:00
Supra4E8C c006e672f8 Merge pull request #3822 from router-for-me/fix/plugin-config-get-endpoint
fix(plugins): expose saved plugin config
2026-06-13 05:09:29 +08:00
LTbinglingfeng b29851d415 docs(plugins): document config get endpoint in Chinese readme 2026-06-13 05:06:03 +08:00
LTbinglingfeng 4f5f1b8f2b fix(plugins): guard config read with mutex 2026-06-13 05:05:49 +08:00
Supra4E8C cbaea358f3 Merge pull request #3821 from router-for-me/feat/plugin-latest-release-check
Feat/plugin latest release check
2026-06-13 04:52:24 +08:00
LTbinglingfeng b60ec43944 fix(plugins): expose saved plugin config 2026-06-13 04:51:07 +08:00
LTbinglingfeng b2b5d10b75 feat(pluginstore): make registry version field optional
The latest release is now the source of truth for plugin versions, so
the registry version only serves as a display fallback. Validate its
format only when present.
2026-06-13 04:10:11 +08:00
LTbinglingfeng 220b4e5bbd feat(management): resolve plugin store versions from latest releases
List entries now show each plugin's latest release version and compute
update availability against it, falling back to the registry version
when the lookup fails. Lookups run concurrently and are cached per
repository with a short failure TTL to respect API rate limits.
2026-06-13 04:05:09 +08:00
LTbinglingfeng 40f4b8b856 feat(pluginstore): fetch and install plugins from latest release
Replace the tag-pinned release lookup with the repository latest
release endpoint. Derive the plugin version from the release tag,
validate it, and attach an optional token to API requests to raise
the rate limit.
2026-06-13 04:00:05 +08:00
Luis Pater b6c22f2d82 chore(plugin/jshandler): remove JS handler plugin implementation and related tests
- Removed the entire `jshandler` plugin implementation, including `abi.go`, `engine.go`, `config.go`, and associated test files.
- Deleted the `scripts` directory containing JavaScript examples.
- Cleaned up the `go.mod` and `go.sum` dependencies related to `jshandler`.
- Ensured redundant code and files associated with the removed plugin are purged from the repository.
2026-06-13 03:57:29 +08:00
Luis Pater 44d3066a9c feat(htmlsanitize): add HTML and JSON sanitization utilities with integration across plugins and APIs
- Introduced `htmlsanitize` package for escaping HTML and handling JSON body sanitization to prevent XSS vulnerabilities.
- Integrated sanitization functions into plugin store, plugin host, and API management handlers to ensure all user-facing content is escaped.
- Added unit tests to verify proper escaping of HTML strings, JSON bodies, and nested data structures.
- Updated existing management and plugin-related tests to validate sanitization implementations.
2026-06-13 01:10:27 +08:00
Luis Pater 60f6a54282 feat(pluginstore, pluginhost): add plugin unload handling and preserve config during plugin updates
- Introduced logic to handle plugin unloading during updates to prevent conflicts with loaded plugins.
- Preserved existing plugin configurations during updates, ensuring seamless transitions and maintaining custom fields.
- Added support for reloading the configuration after management saves changes.
- Enhanced unit tests to validate unloading, configuration preservation, and reloading behaviors.
2026-06-13 00:33:21 +08:00
Luis Pater 049ced5c3f feat(pluginhost, api): add support for "X-CPA-SUPPORT-PLUGIN" header with CGO detection
- Introduced `SupportPluginHeaderValue` to indicate CGO build status (`1` for enabled, `0` for disabled).
- Updated API response headers in `handler.go` to include "X-CPA-SUPPORT-PLUGIN".
- Added unit tests to verify proper header behavior under varying conditions.
2026-06-12 23:54:26 +08:00
Luis Pater 69b7462860 refactor(translator): update test strings to use English for consistency
- Replaced Chinese test strings in `claude_openai-responses_response_test.go` with English equivalents (e.g., "**对比竞品**" -> "**Compare competitors**").
- Updated comments in `config.example.yaml` to English to align with project language standards.
2026-06-12 23:44:57 +08:00
Luis Pater 0626b22e61 Merge pull request #3818 from router-for-me/Plugin-stone
feat(pluginstore): add lightweight plugin store installer APIs
2026-06-12 23:36:44 +08:00
LTbinglingfeng e38ba28db5 feat(pluginstore): add plugin store support 2026-06-12 23:15:00 +08:00
Luis Pater 9dbf4cd07e feat(translator): add usage token details for cache input/output aggregation
- Introduced `claudeResponsesUsageTokens` to manage detailed token statistics, including input, output, cache read, and cache creation tokens.
- Updated aggregation logic to include cached tokens in total usage calculations.
- Refactored usage processing to simplify token merging and ensure consistent handling across streaming and non-streaming responses.
- Added unit tests (`TestConvertClaudeResponseToOpenAIResponses_ReportsCacheTokens`) to verify correct cache token inclusion in usage metrics.

Closes: #3807
2026-06-12 21:03:39 +08:00
Luis Pater 5633c93622 refactor(release): enhance release workflow with changelog generation and improved note handling 2026-06-12 10:37:47 +08:00
Luis Pater ed52c6147c test(websocket, api): add unit tests for response ID injection and handling of pending tool calls
- Introduced test scenarios to validate `previous_response_id` injection during incremental and non-incremental requests.
- Verified behavior for pending tool calls, including proper inclusion or exclusion in websocket requests.
- Updated websocket handling logic to track `lastResponseID` and `pendingToolCallIDs`.
- Added utility functions for pending tool call validation and cleanup.
2026-06-12 04:25:44 +08:00
Luis Pater 538e3416db feat(plugin, api): prevent plugin recursion on host model callbacks, enable targeted interceptor skipping
- Updated host model callback logic to skip originating plugin's interceptors during nested model executions.
- Added `SkipInterceptorPluginID` field to plugin API structs for controlling interceptor bypass behavior.
- Introduced supporting logic in host API handlers, plugin host registry, and callback contexts to identify and skip specific plugins.
- Enhanced unit tests across plugin host, API handlers, and execution paths to verify interceptor skipping behavior and plugin isolation.
- Revised documentation to clarify non-recursive behavior of host model callbacks and the use of `SkipInterceptorPluginID`.
2026-06-12 02:38:51 +08:00
Luis Pater 8e39db2ec7 feat(plugin, api): introduce host model callback support with Go example and API handlers
- Added an example plugin `host-model-callback` in Go to summarize host model callbacks.
- Implemented `cliproxy_plugin_init`, `cliproxyPluginCall`, and other plugin functions for callback handling.
- Introduced API handlers for `ModelExecution` and `ModelExecutionStream` with support for both streaming and non-streaming requests.
- Included unit tests (`model_execution_test.go`) to validate execution logic and streaming responses.
2026-06-12 02:22:23 +08:00
Luis Pater ac4017ea0e Merge branch 'dev' of github.com:router-for-me/CLIProxyAPI into dev 2026-06-11 10:38:16 +08:00
Luis Pater 030c4a9385 Merge pull request #3795 from router-for-me/webui
feat(auto-updater): refactor skip logic and add unit tests for autoUpdateSkipReason
2026-06-11 10:31:58 +08:00
Luis Pater 9985976ebd feat(translator, pluginhost): add stream-specific response transformation support
- Introduced `HasStreamResponseTransformer` and `HasNonStreamResponseTransformer` to handle streaming and non-streaming transformations.
- Updated `executorResponseTranslatorExists` logic to correctly validate stream-specific transformers.
- Enhanced `TranslateStream` to suppress raw fallback when registered native transformers return empty output.
- Added comprehensive tests (`TestHasResponseTransformerChecksConcreteResponseKinds`, `TestHasResponseTransformerIgnoresEmptyRegistration`) for stream and non-stream transformer validation.
2026-06-11 10:16:58 +08:00
hkfires ca1f6271f5 feat(executor): refactor executor registration 2026-06-11 10:15:35 +08:00
hkfires 4cbd50049e feat(service): add XAIExecutor to home executors registration 2026-06-11 09:08:19 +08:00
Luis Pater dc04d8be52 feat(translator): enhance response aggregation and annotation handling
- Implemented logic to aggregate text blocks until `message_stop` for improved consistency.
- Introduced support for message annotations like `citations_delta` in content responses.
- Added methods (`finalizeAssistantMessage`, `appendMessageAnnotation`) to handle message grouping and annotation appending cleanly.
- Updated unit tests to verify message aggregation, annotation handling, and suppression of unwanted native events.

Closes: #3801
2026-06-11 03:14:03 +08:00
Luis Pater 58bf645e66 feat(translator): ensure correct finish_reason handling for all response chunks
- Added tests (`TestCliFinishReasonOnlyOnFinalChunk`, `TestGeminiFinishReasonOnlyOnFinalChunk`) to validate correct `finish_reason` and `native_finish_reason` assignment.
- Refactored Gemini and CLI translators to track `SawToolCall` and `UpstreamFinishReason` for accurate final-chunk determination.
- Improved response parsing logic to align with upstream metadata and provide consistent reasoning on chunk outputs.
2026-06-11 00:17:45 +08:00
Luis Pater 1ca048abdc feat(auth, interceptor, jshandler): add post-auth request interceptors and enhance format handling
- Introduced `applyRequestAfterAuthInterceptor` to modify requests after credential selection and before executor translation.
- Added `InterceptRequestAfterAuth` method across plugin adapters with corresponding tests for context validation.
- Enhanced format resolution logic (`requestToFormat`) to support additional providers and formats.
- Updated JavaScript handler to include a new `on_after_auth_request` hook for post-auth request handling.
- Refactored interceptor methods for clarity and better encapsulation of request/response lifecycles.
2026-06-10 20:58:59 +08:00
hkfires 3c773b6d92 feat(auto-updater): refactor skip logic and add unit tests for autoUpdateSkipReason 2026-06-10 16:15:33 +08:00
Luis Pater 21387f5c71 feat(docs): add Unity2.ai sponsorship details to README
- Updated `README.md`, `README_JA.md`, and `README_CN.md` to include Unity2.ai sponsorship information.
- Highlighted features, benefits, and registration perks offered by Unity2.ai.
- Added Unity2.ai logo (`unity2.jpg`) to the project assets.
2026-06-10 10:27:28 +08:00
Luis Pater 8e52c403f7 feat(auth): deduplicate concurrent refresh token requests with singleflight
- Introduced `singleflight.Group` to prevent redundant token refresh calls across multiple auth implementations (`antigravity`, `kimi`, `xai`, `codex`).
- Added tests to verify shared upstream calls during concurrent refresh requests.
- Refactored token refresh logic to centralize and standardize deduplication mechanisms.
2026-06-10 03:19:26 +08:00
Luis Pater 8caf47464c Merge pull request #3788 from shoucandanghehe/fix/codex-backend-request-id
fix(logging): track Codex backend request IDs
2026-06-10 02:58:36 +08:00
Luis Pater efd69d8ece feat(models): add Claude Fable 5 to registry
- Added new model `Claude Fable 5` to `models.json` with enhanced reasoning and long-horizon capabilities.
- Included detailed parameters such as context length, max completion tokens, and thinking level configurations.
2026-06-10 02:38:04 +08:00
shoucandanghehe dc3152d2e3 fix(logging): tighten Codex backend request ID prefix 2026-06-10 01:29:42 +08:00
shoucandanghehe e1864fbf33 fix(logging): track Codex backend request IDs 2026-06-10 01:05:09 +08:00
Luis Pater 44ea9abced feat(pluginhost): introduce browser-navigable plugin resources in Management API
- Added `resources` field in `management.register` for defining browser-accessible resources.
- Updated examples and documentation to reflect resource-based paths under `/v0/resource/plugins/<pluginID>/...`.
- Replaced legacy `GET` menu routes with resource-based implementations for consistent plugin behavior.
- Enhanced request handling for resource paths, including proper response headers and streamlined test coverage.
2026-06-09 22:46:27 +08:00
Luis Pater 2aeb41cecf feat(pluginhost, jshandler): integrate HostCallbackID with interceptors and JS engine logging
- Added `HostCallbackID` to request, response, and stream chunk interceptors for enhanced context tracking.
- Updated JavaScript engine to support custom console logging with `HostCallbackID` forwarding.
- Introduced tests verifying proper integration of `HostCallbackID` in all interceptor flows and engine logging.
- Enhanced logging and error handling for consistent callback-related logic implementation.
2026-06-09 14:36:42 +08:00
Luis Pater 1d1ee85e37 refactor(auth): simplify plugin scheduler by consolidating strategies and removing RoundRobinSelector
- Removed `pluginDelegateRoundRobin` and related logic to streamline plugin scheduler management.
- Consolidated scheduler strategies under `builtinSchedulerStrategy` with `pickViaBuiltinScheduler`.
- Introduced new methods `pickSingleWithStrategy` and `pickMixedWithStrategy` for strategy-specific behavior.
- Updated tests to reflect changes, including added coverage for round-robin and mixed-provider scenarios.
- Improved maintainability by unifying scheduling logic and reducing redundant structures.
2026-06-09 14:20:24 +08:00
Luis Pater 556f50aa2a feat(interceptor, jshandler): enhance request/response handling with original request support
- Added `opts.OriginalRequest` handling to `applyResponseInterceptors` for improved context passing.
- Introduced new test `TestApplyJSBeforeRequestUsesReturnedCtxBody` to validate JavaScript interceptor behavior.
- Updated JavaScript-based handler to safely rewrite sensitive content and headers in requests.
- Refined interceptor logic to ensure consistent state retention across request processing.
2026-06-09 13:57:38 +08:00
Luis Pater 41a4dba670 feat(auth): enhance plugin scheduler with HasScheduler support and fast-path tests
- Added `pluginSchedulerState` interface with `HasScheduler` method for improved plugin scheduler state checks.
- Updated `Manager.hasPluginScheduler` to handle `HasScheduler` logic.
- Implemented and tested fast-path handling for inactive plugin schedulers, including mixed provider scenarios.
- Expanded unit test coverage to ensure correct behavior in various scheduler states.
2026-06-09 13:57:37 +08:00
Luis Pater 693ce1c55a feat(pluginhost, scheduler): introduce Go-based plugin with scheduler capabilities
- Added a Go scheduler plugin demonstrating CLIProxyAPI capabilities, such as `plugin.register`, `plugin.reconfigure`, and `scheduler.pick`.
- Implemented methods for plugin configuration, built-in scheduler delegation (`fill-first`, `round-robin`), dynamic candidate selection, and error handling.
- Extended `pluginhost` with scheduler handling, candidate normalization, and fallback mechanisms.
- Included examples, tests, and detailed documentation for scheduler usage and implementation.
2026-06-09 13:57:36 +08:00
sususu98 a2db6a6108 Merge pull request #3773 from sususu98/fix/antigravity-version-upstream-dev
fix: update antigravity version lookup
2026-06-09 11:43:59 +08:00
sususu98 9fb9e9154b Merge pull request #3770 from sususu98/fix/codex-claude-stream-error-upstream-dev
fix: translate codex stream errors for claude
2026-06-09 11:43:43 +08:00
sususu98 c7cc3a1a4d fix: update antigravity version lookup 2026-06-09 11:32:57 +08:00
Luis Pater fabf06154f feat(access, pluginhost): add support for exclusive frontend auth providers
- Introduced `FrontendAuthProviderExclusive` capability to restrict authentication to a single selected provider.
- Added `SetExclusiveProvider` and `ClearExclusiveProvider` methods for managing exclusive providers in the access registry.
- Updated `pluginhost` to prioritize and enforce exclusive providers based on plugin priority and ID.
- Enhanced RPC capabilities schema to include `FrontendAuthProviderExclusive` field.
- Added example plugin and tests for exclusive frontend auth behavior.
2026-06-09 10:56:58 +08:00
Luis Pater 583053509d feat(jshandler): add new plugin providing JavaScript-based interceptors and capabilities
- Implemented `RequestInterceptor`, `ResponseInterceptor`, and `StreamChunkInterceptor` using embedded JavaScript.
- Added support for configuring script paths, built-in script resolution, and safe execution.
- Introduced ABI lifecycle management, plugin registration, and execution monitoring.
- Enhanced with extensive test coverage for both plugin behavior and configuration logic.
2026-06-09 08:28:00 +08:00
Luis Pater 5e41e079e5 fix(runtime): update formatting in codex image extraction comment 2026-06-09 02:20:57 +08:00
Luis Pater d128578efa Merge pull request #3771 from Folyd/perf/codex-image-streaming-memory
perf(codex): avoid rebuilding completed JSON when extracting generated images
2026-06-09 01:49:12 +08:00
Luis Pater 1762ee0d2e feat(pluginhost): add support for interceptors and metadata sanitization
- Implemented `RequestInterceptor`, `ResponseInterceptor`, and `StreamChunkInterceptor` capabilities.
- Added `sanitizePluginMetadata` to clean metadata for RPC compatibility.
- Enhanced interceptor chaining, error handling, and test coverage.
- Updated plugin configuration to register and dispatch interceptor methods.
2026-06-09 01:41:46 +08:00
Folyd 2e81766c92 perf(codex): preallocate results and skip empty index sort
Apply review feedback on codexExtractImageResults: preallocate the results
slice to its known maximum capacity to avoid growth reallocations, and guard
the itemsByIndex index-build/sort with a length check so no empty slice is
allocated or sorted when only the fallback items are present.
2026-06-08 15:55:42 +00:00
Folyd 4330b92612 perf(codex): avoid rebuilding completed JSON when extracting generated images
The OpenAI images path (/v1/images/*) previously called patchCodexCompletedOutput
to concatenate collected output_item.done items back into the completed event and
then re-parsed that rebuilt JSON to pull out the image results. For multi-megabyte
base64 image payloads this produced two extra full-size copies per request (the
concatenated output array plus the rebuilt completed event), inflating peak memory
under concurrent image generation.

Add codexExtractImageResults, which extracts image_generation_call results directly
from either the completed event's response.output or the collected items, without
the concatenate-and-reparse step. Semantics are preserved: completed output is
preferred and collected items are used only when it is empty, matching the original
patchCodexCompletedOutput behaviour. patchCodexCompletedOutput remains in use by the
text/responses path, which still forwards the patched event downstream.

Adds unit tests covering the completed-output path, the ordered fallback to
collected items, output preference, fallback list, and the wrong-event-type guard.
2026-06-08 15:47:14 +00:00
sususu98 702295d73a fix: translate codex stream errors for claude 2026-06-08 21:07:21 +08:00
Luis Pater 07c607b709 chore(build): remove checksum generation from release workflows
- Eliminated redundant checksum generation steps in release workflows.
- Updated asset validation checks to exclude checksum files and focus solely on archive assets.
- Simplified workflow logic for packaging and uploading release artifacts.
2026-06-08 12:54:29 +08:00
Luis Pater 856dc81748 feat(safemode): support /management.html route in ExampleAPIKeyWarningHandler
- Added handling for `/management.html` in `ExampleAPIKeyWarningHandler`.
- Updated tests to validate correct behavior for the new route.
2026-06-08 12:41:28 +08:00
Luis Pater 6f38e8488a docs: add RunAPI sponsorship details to README files
- Updated `README.md`, `README_JA.md`, and `README_CN.md` with information about RunAPI as a sponsor.
- Included descriptions of RunAPI's features, benefits, and discounts.
- Added `runapi.png` asset to the project.
2026-06-08 12:25:53 +08:00
Luis Pater d55f215c63 chore(build): include ca-certificates in Docker image for improved HTTPS support 2026-06-08 12:15:30 +08:00
Luis Pater 69d937a8d3 chore(build): add Linux-specific release workflows and update release notes handling
- Introduced `build-linux-glibc` and `build-linux-no-plugin` workflows for creating Linux release assets with and without plugin support.
- Enhanced release workflow with dynamic update of release notes for Linux assets.
- Improved checksum generation and validation for Linux binaries.
- Updated workflow matrix for better platform coverage and asset handling.
2026-06-08 12:04:43 +08:00
Luis Pater ec672446d1 feat(translator): implement signature delta handling and enhance chunk processing in Gemini and Antigravity translators
- Added support for processing `signature-only` chunks without opening empty text blocks.
- Refactored chunk handling logic to include `signature_delta` events for improved fidelity.
- Unified logic for emitting final message states, including `message_delta` and `message_stop`, to ensure consistent behavior across different scenarios.
- Enhanced caching mechanism for thought signatures.
2026-06-08 11:30:17 +08:00
Luis Pater d9a0c9bdc7 chore(build): migrate from Alpine to Debian and update build dependencies
- Updated `Dockerfile` base images from `golang:1.26-alpine` and `alpine:3.23` to `golang:1.26-bookworm` and `debian:bookworm`.
- Replaced `apk` with `apt-get` for dependency installation.
- Added `buildvcs=false` flag to Go build command for enhanced reproducibility.
2026-06-08 11:03:46 +08:00
Luis Pater 365415c87a fix(translator): add fallback for system_instruction key in Gemini request parsing
- Added fallback to handle cases where `system_instruction.parts` is absent by checking for `systemInstruction.parts`.
2026-06-08 08:10:41 +08:00
Luis Pater c989cdd9d7 feat(plugin): add Codex Service Tier request normalizer plugin
- Introduced a Go-based plugin `codex-service-tier` for normalizing requests to Codex.
- Added functionality to set `service_tier` to `priority` for `gpt-5.5` requests when `fast` mode is enabled.
- Enhanced plugin capabilities with lifecycle configuration and request transformation support.
- Updated documentation with configuration examples and usage instructions in multiple languages.
2026-06-07 06:57:19 +08:00
Luis Pater 4f55eccae2 chore(build): refactor FreeBSD build process and optimize workflows
- Removed redundant `vm_arch` matrix configuration.
- Replaced manual FreeBSD VM setup with `go-cross/cgo-actions` for cross-compilation.
- Improved caching for Go modules and build artifacts.
- Simplified metadata generation and environment variable handling.
- Streamlined binary packaging and archive creation steps.
2026-06-07 05:51:32 +08:00
Luis Pater 37df0b8b98 chore(build): update release workflow to include repository reference and fix exit code handling
- Added `GH_REPO` environment variable for repository reference in the workflow.
- Changed exit condition when no release archives are found to avoid workflow failure.
2026-06-07 05:33:10 +08:00
Luis Pater 6d9014b61f chore(build): enhance release workflow with automated asset handling and checksum generation
- Added `prepare-release` job for creating/updating GitHub releases.
- Automated asset checksum generation for hosted and FreeBSD builds.
- Introduced release asset uploads, including archives and checksums.
- Refactored release process to include final checksum publishing.
2026-06-07 05:27:44 +08:00
Luis Pater 43c121464e chore(build): add custom runners and improve Go module handling in FreeBSD release workflow 2026-06-07 05:14:30 +08:00
Luis Pater 4567fd1b06 chore(build): add custom runners and improve Go module handling in FreeBSD release workflow 2026-06-07 05:05:10 +08:00
Luis Pater c75fb2c814 chore(build): add caching for Go dependencies and FreeBSD-specific artifacts in release workflow 2026-06-07 04:53:55 +08:00
Luis Pater 3dedf47839 chore(build): set additional environment variables for FreeBSD builds in release workflow 2026-06-07 04:41:55 +08:00
Luis Pater 9ee64935fb chore(build): remove goreleaser configuration and refactor release workflow
- Deleted `.goreleaser.yml` configuration and migrated functionality to GitHub Actions workflows.
- Replaced `goreleaser` with matrix-based build and archiving process for improved flexibility.
- Enhanced platform and architecture-specific builds, including FreeBSD support and custom runners.
- Streamlined artifact upload, checksum generation, and release publishing.
2026-06-07 04:36:19 +08:00
Luis Pater bc58c21673 chore(build): update dependencies, enhance cross-compilation, and refactor workflows
- Updated `golang.org/x/sys` to v0.38.0 in `go.mod` and replaced `syscall` with `windows` package for memory allocation in `loader_windows.go`.
- Improved cross-compilation in `.goreleaser.yml` using Zig-based toolchains for better platform support.
- Changed GitHub Actions workflow to use macOS runners and added Zig toolchain setup.
2026-06-07 04:13:15 +08:00
Luis Pater 0ed85bb88b feat(pluginhost): refactor and enhance plugin system with new execution and thinking capabilities
- Removed `examples/plugin/main.go` and `internal/pluginhost/loader_plugin.go` after migrating to a more modular system.
- Introduced `streamBridge` in `internal/pluginhost/stream_bridge.go` for efficient stream handling and communication.
- Added examples of `thinking` plugins written in both Rust and Go under `examples/plugin/thinking`.
- Enhanced test coverage for plugin host system changes, including stream chunk translation and thinking logic.
- Improved API compatibility and ensured backward-compatible upgrades for plugin execution.
2026-06-07 03:20:04 +08:00
Luis Pater 3abfc83d96 Merge branch 'dynamic' into dev
# Conflicts:
#	internal/cmd/run.go
2026-06-06 18:41:13 +08:00
Luis Pater d625caddd9 feat(pluginhost): add capabilities for command-line flag handling and plugin execution
- Implemented command-line flag registration and execution for plugins with priority-based conflict resolution.
- Enabled plugin-owned command-line flag execution and persistence of plugin-auth data.
- Added new `Host` methods to support command-line capabilities, including flag normalization, validation, and execution state management.
- Introduced unit tests to ensure coverage for command-line plugin functionality, including auth data persistence.
- Updated configs to normalize plugins during initialization.
2026-06-06 18:35:17 +08:00
Luis Pater fca12a2630 Merge pull request #3735 from router-for-me/safemode
feat(safemode): implement example API key warning server and related functionality
2026-06-06 13:31:37 +08:00
hkfires bc38b68902 feat(safemode): implement example API key warning server and related functionality 2026-06-06 11:42:21 +08:00
Luis Pater 5753d1a089 feat(logging): enable file-backed request/response sources for enhanced API logging
- Introduced support for file-backed logging of API requests and responses to handle large payloads efficiently.
- Refactored `attachWebsocketLogSources` to `attachRequestLogSources` for broader request and response handling.
- Added new methods for appending request/response data to file-backed sources and updated existing logging workflows for compatibility.
- Improved cleanup and merge logic for file-backed sources during request processing.
- Updated tests to cover newly introduced file-backed logging functionality.
2026-06-05 01:48:05 +08:00
Luis Pater 387c783b32 Merge pull request #3649 from intcua/fix/xai-empty-tools-orphan-tool-choice
fix(executor/xai): drop orphaned tool_choice when Claude tools array is empty
2026-06-04 13:11:23 +08:00
Luis Pater 90d46e7749 docs: remove outdated Amp CLI and related tool references
- Removed sections on Amp CLI integration and related management tools from all READMEs (`README.md`, `README_JA.md`, and `README_CN.md`).
- Updated project descriptions for relevance and focus.
2026-06-04 12:58:50 +08:00
Luis Pater bebdaa4d65 Merge pull request #3702 from Villoh/docs/add-tunnel-agent
docs: add Tunnel Agent to community projects
2026-06-04 12:48:11 +08:00
Luis Pater fd30944830 feat(auth): add error event publishing and Redis queue integration
- Introduced `publishErrorEvent` in `Manager` to publish error events to Redis.
- Implemented error event structure to capture authentication errors with detailed metadata.
- Added test cases for error event publishing, subscription, and Redis protocol handling.
- Enhanced error and usage queue handling with `SubscribeErrors` and `EnqueueError`.

Closes: #3701
2026-06-04 00:53:43 +08:00
Mikel Villotaandgemini-code-assist[bot] 46a152a21b docs: use 智能体 for Agent in Chinese translation
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-06-03 18:48:40 +02:00
Villoh 1074507a2f docs: add Tunnel Agent to community projects 2026-06-03 18:34:56 +02:00
Luis Pater 55440f0a39 feat(auth): add runtime auth removal and unscheduling logic
- Introduced `Manager.Remove` to delete runtime auth and unschedule associated tasks.
- Updated handler logic to directly remove auth instead of marking as disabled.
- Added tests to validate removal, unscheduling, and runtime state handling.
- Added a test to validate `skipPersist` behavior during registration.
- Enhanced `Remove` test to verify auto-refresh loop state before and after removal.

Closes: #3690
2026-06-03 11:56:56 +08:00
Luis Pater 9c02454005 Merge pull request #3657 from catoncat/fix/responses-input-id-dedupe-orphaned-output
fix(openai): keep referenced tool call when deduping websocket input IDs
2026-06-03 11:22:00 +08:00
Luis Pater 1c9601ff32 Merge pull request #3689 from sususu98/pr/cloudflare-challenge-retry
fix(auth): retry and backoff cloudflare challenge 403 errors
2026-06-03 11:07:08 +08:00
sususu98 77061aad4b refactor(auth): simplify and narrow cloudflare challenge checks 2026-06-03 10:35:39 +08:00
sususu98andClaude Opus 4.8 45f58d4f91 fix(auth): retry and backoff cloudflare challenge 403 errors
Introduce Cloudflare challenge detection for 403 errors in the Auth
Manager. Apply a progressive rate-limiting cooldown ladder using the
existing BackoffLevel field instead of a hard 30-minute credentials
suspension. This ensures challenged requests fall through to subsequent
credentials and recover exponentially.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-03 10:28:43 +08:00
sususu98 7682accd95 Merge pull request #3688 from sususu98/fix-codex-replay-dev
fix(codex): avoid replaying orphan tool calls
2026-06-03 09:59:44 +08:00
sususu98 17af089189 fix(codex): avoid replaying orphan tool calls 2026-06-03 09:52:17 +08:00
Luis Pater 35ab084fc3 refactor(runtime): enhance NewUtlsHTTPClient with context-based RoundTripper
- Updated `NewUtlsHTTPClient` to support context-aware RoundTrippers for protected hosts (e.g., Cloudflare bypass).
- Replaced `anthropicHosts` with `utlsProtectedHosts` to generalize host handling logic.
- Added unit test to validate context-based RoundTripper behavior.
- Replaced `NewProxyAwareHTTPClient` with `NewUtlsHTTPClient` in relevant executors for improved TLS fingerprinting.

Closes: #3680
2026-06-03 06:58:26 +08:00
Luis Pater 0e3c809ceb fix(codex): handle non-empty reasoning and content items, add test for trailing empty messages
Closes: #3683
2026-06-03 06:28:51 +08:00
Luis Pater 28c7f41cba docs(readme): update project descriptions and add Panopticon link
- Updated links and descriptions for `CPA-Manager-Plus`, replacing outdated `CPA-Manager` references.
- Added `Panopticon`, a multi-agent orchestration tool, to the project list.
2026-06-02 19:42:51 +08:00
Luis Pater d710248407 Merge pull request #3676 from eltmon/add-panopticon-to-users
docs: add Panopticon to "Who is with us?"
2026-06-02 19:35:57 +08:00
Luis Pater 02d0d92a8e Merge pull request #3677 from sususu98/codex/home-auth-loop-upstream-dev
Fix Home auth refresh retry handling
2026-06-02 19:30:14 +08:00
Luis Pater 8306391f91 Merge pull request #3667 from sususu98/feat/codex-reasoning-replay-cache-upstream-dev
feat(codex): cache reasoning replay items
2026-06-02 19:28:55 +08:00
sususu98 4abd59ce1b Merge pull request #3679 from sususu98/codex/system-role-to-user-upstream-dev
fix(translator): normalize message-level system roles for Gemini
2026-06-02 16:56:27 +08:00
sususu98 68282c4aa7 fix(translator): normalize message-level system roles for Gemini 2026-06-02 16:48:58 +08:00
sususu98 603a08fc1a feat(codex): cache reasoning replay items 2026-06-02 16:08:40 +08:00
sususu98 c9dc6bd628 Fix Home auth refresh retry handling
Parse Home refresh auth envelopes so refreshed access tokens are used instead of returning missing access token.

Stop retrying when Home dispatch returns an auth that already failed within the same request.
2026-06-02 13:43:07 +08:00
Edward Becker 7cb466a8e6 docs: add Panopticon to "Who is with us?" 2026-06-02 01:11:03 -04:00
Luis Pater 87d813c56c chore(models): remove legacy GPT 5.2 and GPT 5.3 Codex entries from registry
- Cleaned up outdated GPT 5.2 and GPT 5.3 Codex model configurations from `models.json`.
- Simplified registry by removing unused model references across all tiers (`codex-team`, `codex-plus`, `codex-pro`).
2026-06-02 10:41:12 +08:00
Luis Pater bf04a24221 feat(models): add support for grok-composer-2.5-fast model
- Introduced `grok-composer-2.5-fast` as a new XAI model.
- Updated registry to include display name, description, and configuration details for the new model.
- Enabled support for the model in the Responses API.
2026-06-02 08:50:32 +08:00
Luis Pater f353979e0a feat(watcher, redisqueue): add usage refresh notification support
- Introduced `NotifyUsageRefresh` in `redisqueue` to notify subscribers of usage refresh events.
- Enhanced `Watcher` logic to trigger usage refresh notifications on client changes (add/update/remove).
- Updated tests to validate proper broadcast of usage refresh messages to subscribers.
- Added support for initial `support_refresh` payload upon subscription initialization.
2026-06-02 02:52:27 +08:00
Luis Pater 959067edfb feat(usage): introduce executor type tracking in usage reporting
- Replaced `NewUsageReporter` with `NewExecutorUsageReporter` to include executor type in usage records.
- Updated all executors to use the new reporter implementation.
- Extended `UsageReporter` to track and publish executor type.
- Added tests to validate proper executor type recording and handling.
- Enhanced RedisQueue plugin and payload schema with executor type support.
2026-06-02 00:43:16 +08:00
cat f05d68d4ec refactor(openai): parse dedupe input item metadata in a single pass
Address review feedback: parse each item's type/id/call_id once with
gjson.GetManyBytes and reuse it across the dedupe loops instead of
rescanning every item up to five times. Behavior is unchanged.
2026-06-01 15:01:31 +08:00
cat e7f4dd470d fix(openai): keep referenced tool call when deduping websocket input IDs
The input item ID dedupe added in #3620 keeps only the last occurrence of
each item id. When an upstream reuses the same item id across a re-sent or
repaired tool call (so two function_call items share an id but carry
different call_ids), the last-wins rule can drop the function_call whose
call_id still has a matching function_call_output. The upstream then rejects
the request with HTTP 400 "No tool call found for function call output with
call_id ...", breaking every subsequent turn over the Codex WebSocket path.

Make the dedupe orphan-aware: when several input items share an id, never
replace an item whose call_id is still referenced by a tool-call output with
one that is not. This keeps a single item per id (preserving the original
intent) while ensuring retained tool calls stay paired with their outputs.

Adds a regression test covering two function_call items that share an id
where only the earlier call_id has a surviving output.
2026-06-01 13:10:41 +08:00
Luis Pater 05b972479a feat(executor): refine session and conversation header handling for Codex
- 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.
2026-06-01 11:27:10 +08:00
Luis Pater fb4f39d300 test(models, executor): add XAI video model test and fix Codex User-Agent assertions 2026-06-01 02:59:31 +08:00
Luis Pater ac1360f479 feat(models): add support for grok-imagine-video-1.5-preview model
- Introduced `grok-imagine-video-1.5-preview` as a new XAI video model.
- Updated handlers, registry, and validation logic to include support for the new model.
- Enhanced test coverage to validate integration and functionality of the preview model.
2026-06-01 02:56:15 +08:00
Luis Pater bbcdaab79d feat(executor): enhance Codex identity obfuscation with turn and window metadata handling
- 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.
2026-06-01 00:50:46 +08:00
lamtran 303685c230 fix(executor/xai): drop orphaned tool_choice when Claude tools array is empty
When Claude Code sends a stop-hook evaluator request (or any request
without tools), the payload includes "tools": [] (empty array). The
claude->codex translator unconditionally emits tools: [] + tool_choice:
"auto" + parallel_tool_calls: true into the Codex Responses shape.

When that payload is routed to xAI, the upstream rejects with HTTP 400:
"A tool_choice was set on the request but no tools were specified."

Fix entirely in the xAI executor (translator package is policy-locked):
add normalizeXAIToolChoiceForTools() after normalizeXAITools() to drop
tool_choice and parallel_tool_calls whenever tools end up absent or
empty (covering both the empty-from-source case and the
all-filtered-out case where every tool was an unsupported type such as
tool_search or image_generation).

Per code-review feedback: always remove parallel_tool_calls when tools
are missing (not gated on tool_choice presence) and existence-check
each key before sjson delete to avoid unnecessary JSON parse/copy.

Verification:
- go build -o test-output ./cmd/server
- go test ./internal/runtime/executor/... -count=1
- 5 new regression tests cover empty / missing / present / orphaned
  parallel_tool_calls / no-op-when-both-absent.
2026-05-31 23:13:15 +07:00
Luis Pater 0f24cafbdd feat(executor): implement identity obfuscation for Codex requests and responses
- 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.
2026-05-31 23:31:35 +08:00
Luis Pater 33983b6f3e refactor(executor): consolidate Codex request translation logic
- Introduced `translateCodexRequestPair` to simplify and reuse translation logic for handling original and modified payloads.
- Updated relevant methods to use the new function.
- Added unit tests to cover payload reuse and differentiation scenarios.
2026-05-31 14:38:54 +08:00
Luis Pater 3a54fb7fcf Merge branch 'dev', commit 'refs/pull/3621/head' of github.com:router-for-me/CLIProxyAPI into dev
# Conflicts:
#	internal/translator/gemini/openai/responses/gemini_openai-responses_request_test.go
2026-05-30 20:57:14 +08:00
Luis Pater 430e679e2a fix(auth): strip "generate" from payload during WebSocket HTTP fallback
- Added `sanitizeDownstreamWebsocketFallbackRequest` to clean `generate` from payload for HTTP fallback requests.
- Implemented tests to validate payload handling logic in WebSocket-to-HTTP transitions.

Closes: #3556
2026-05-30 05:14:05 +08:00
Luis Pater 55901f0bda Merge pull request #3620 from iBenzene/fix/responses-input-id-dedupe
fix(openai): dedupe response websocket input item IDs
2026-05-30 03:27:36 +08:00
zzmc 776a9c0049 fix(translator/gemini): support developer role in OpenAI Responses requests 2026-05-29 09:24:48 -07:00
Luis Pater fc0615b171 test(oauth): ensure missing auth directories are created and callback payloads are validated
Closes: #3619
2026-05-29 23:04:35 +08:00
Luis Pater 96b6f7e217 Merge pull request #3612 from router-for-me/log
feat(logging): add request_id handling in HomeAppLogForwarder and tests
2026-05-29 22:10:12 +08:00
Luis Pater 034d2b6bf8 Merge pull request #3615 from sususu98/codex/signature-intercept-on-pr
feat: intercept incompatible signature replay
2026-05-29 22:09:10 +08:00
iBenzene e9dafc7093 fix(openai): dedupe response websocket input item IDs 2026-05-29 17:06:48 +08:00
sususu98 aee7a5fbc5 feat: intercept incompatible signature replay 2026-05-29 15:22:57 +08:00
sususu98 86cb9c150b feat(signature): upgrade provider signature checks 2026-05-29 12:24:18 +08:00
Luis Pater 7d9980e8fa fix(logging): log errors during file-backed source cleanup 2026-05-29 11:24:58 +08:00
hkfires d2c5f279f6 feat(logging): add request_id handling in HomeAppLogForwarder and tests 2026-05-29 10:58:19 +08:00
Luis Pater 4ade13a374 Merge pull request #3605 from router-for-me/log
feat(logging): add HomeAppLogForwarder for application log forwarding
2026-05-29 08:38:40 +08:00
hkfires c4ee063b95 feat(logging): add HomeAppLogForwarder for application log forwarding 2026-05-29 08:12:52 +08:00
Luis Pater f28258de22 Merge pull request #3595 from Progress-infinitely/fix/anthropic-tool-name-reverse-map
fix(amp): restore response tool casing from request
2026-05-29 02:17:27 +08:00
Luis Pater df0176a188 feat(models): add Claude Opus 4.8 model to registry 2026-05-29 01:22:46 +08:00
Luis Pater c65275fd32 Merge pull request #3591 from sususu98/feat/signature-check-extraction
refactor: extract signature validation
2026-05-28 22:17:52 +08:00
Luis Pater 71c185f614 feat(usage): add service tier tracking and defaults in usage reporting
- Introduced `service_tier` metadata key to capture client-requested service tiers.
- Updated usage records, context propagation, and plugins to include service tier data.
- Added default handling logic for cases where `service_tier` is absent.
- Implemented tests for `service_tier` extraction, defaults, and updates across components.
2026-05-28 22:15:54 +08:00
Luis Pater 65e760aa1a feat(usage): include cache tokens in total token calculation and add tests
- Updated `TotalTokens` calculation to account for `CacheReadTokens` and `CacheCreationTokens`.
- Added tests to validate accurate token aggregation and fallback behavior for `CachedTokens`.
2026-05-28 21:34:54 +08:00
Progress-infinitely 01a7cc4a45 fix(amp): restore response tool casing from request 2026-05-28 18:03:15 +08:00
sususu98 b3d6d5d71a refactor: extract signature validation 2026-05-28 15:47:47 +08:00
Luis Pater 2bcc76220c feat(logging): improve file-backed source cleanup and directory recreation logic
- Added `assertFileBodySourceCleaned` helper to streamline cleanup validations in tests.
- Introduced handling to recreate missing directories during file source operations.
- Enhanced tests to verify behavior after manual directory removal, ensuring robustness.
- Fixed edge cases in log file merging when parts are missing.
2026-05-28 10:42:24 +08:00
Luis Pater d9c01a638d chore(models): remove deprecated GPT-5.x models from codex-free catalog 2026-05-28 09:41:51 +08:00
Luis Pater 94c1b25146 feat(executor): add TTFT tracking and reporting for enhanced performance metrics
- Introduced Time-To-First-Token (TTFT) measurement and reporting across major executors.
- Added TTFT calculation to `UsageReporter`, including support for HTTP clients and WebSocket communication.
- Updated tests to validate TTFT tracking in streamed and non-streamed scenarios.
- Ensured integration with `usage` plugin and augmented usage records with TTFT data.
2026-05-28 02:59:24 +08:00
Luis Pater 11f0f906bd feat(logging): add SetTranslatedReasoningEffort to track reasoning levels in usage reporting
- Introduced `SetTranslatedReasoningEffort` method in `UsageReporter` to capture and log reasoning efforts from translated payloads.
- Updated executors to incorporate the new reporting functionality for handling reasoning efforts across various providers.
- Enhanced logging for thinking level extraction with new helper function `ExtractTranslatedReasoningEffort`.
2026-05-28 02:19:45 +08:00
Luis Pater 4b681031bf feat(translator): add reasoning signature handling and tests for Claude-OpenAI conversions
- Introduced support for processing `encrypted_content` reasoning signatures in request and response translations.
- Updated `ConvertOpenAIResponsesRequestToClaude` and `ConvertClaudeResponseToOpenAIResponses` to handle reasoning signatures and summaries.
- Added tests to validate signature preservation and correct reasoning content transformation in both streaming and non-streaming scenarios.
- Refactored processing logic to ensure reasoning content flushing before user messages.
2026-05-27 02:10:58 +08:00
Luis Pater 2cbb8c7b5c fix(translator): correct JSON path for item summary in response event
- Updated `response.output_item.done` to use `item.summary.0.text` instead of `item.summary.text`.
2026-05-27 01:28:04 +08:00
Luis Pater de280d993d feat(websockets): refine incremental repair logic for tool call responses
- Updated WebSocket response repair tests to validate incremental preservation of response calls and outputs.
- Added new test cases for custom tool responses ensuring accurate handling of output cache and call cache.
- Refactored `repairResponsesWebsocketToolCallsWithCaches` to handle orphan outputs more consistently.
- Adjusted input filtering logic for clearer incremental repair behavior.

Closes: #3569
2026-05-27 01:01:57 +08:00
Luis Pater e399edd3cc feat(images): add support for configurable GPT Image 2 base model and improved SSE handling
- Introduced `GPTImage2BaseModel` configuration for hosted image generation tools with validation for "gpt-" prefix.
- Added logic to dynamically resolve and apply the base model in Codex executor workflows.
- Enhanced server-sent events (SSE) implementation with keep-alive tickers and error events for stream reliability.
- Updated configuration file examples and internal documentation.
2026-05-27 00:47:02 +08:00
sususu98 b5959c313d Merge pull request #3554 from sususu98/fix/gemini-cli-request-schema-cleanup
fix: clean Gemini CLI request schemas
2026-05-26 16:37:15 +08:00
sususu98 4a85b6b97e fix: log gemini cli schema cleanup errors 2026-05-26 10:52:53 +08:00
sususu98 70a8cf026f fix: clean gemini cli request schemas 2026-05-26 10:39:37 +08:00
Luis Pater 167edfec6c feat(auth): add support for websockets in auth file parsing and patching
- Introduced parsing logic to handle `websockets` field in auth files.
- Extended `PatchAuthFileFields` to update `websockets` and arbitrary nested metadata fields.
- Added tests to validate `websockets` parsing, updating, and persistence.
2026-05-26 00:49:36 +08:00
Luis Pater a0bb1f3a2b feat(logging): add file-backed sources for request logging
- Introduced `FileBodySource` to support large request log sections stored in temp files.
- Added file-backed support for WebSocket timeline and API WebSocket timeline logging.
- Updated `LogRequest` and middleware to integrate optional file-backed sources.
- Implemented clean-up mechanisms to manage temporary log files after processing.
2026-05-25 21:55:16 +08:00
Luis Pater 412d3442fa feat(logging): add RequestID support in home request logging
- Included `RequestID` field in `homeRequestLogPayload` for better log categorization.
- Updated `forwardRequestLogToHome` and related components to handle `RequestID`.
- Added new test cases to validate `RequestID` propagation in streaming requests.
2026-05-25 20:44:32 +08:00
Luis Pater efa200ec48 feat(cli): add fetch_codex_models command for dynamic Codex model fetching
- Introduced `fetch_codex_models` CLI command to fetch and save Codex model catalogs in JSON format.
- Supports configuration via flags or `config.yaml` for flexible setup.
- Enhanced `fetch_antigravity_models` with `config.yaml` support and improved auth directory resolution logic.
2026-05-25 11:32:49 +08:00
Luis Pater 50d19e204f docs(readme): add APIKEY.FUN sponsorship details to README files
- Acknowledged APIKEY.FUN as a sponsor with details on their services and exclusive project-specific benefits.
- Updated Japanese (README_JA.md), Chinese (README_CN.md), and English (README.md) documentation.
- Added new sponsorship image (`assets/apikey.png`).
2026-05-24 05:19:43 +08:00
Luis Pater aaec9194d5 feat(models): add Grok Build 0.1 to registry
- Registered `grok-build-0.1` model with enhanced context length and agentic engineering support.
- Supports dynamic thinking levels for improved software workflows.
2026-05-23 22:49:36 +08:00
Luis Pater 33f4904b25 fix(translator): handle system role as developer in Claude request conversion
- Updated `ConvertClaudeRequestToGemini` logic to treat `system` role as `developer`.
- Added unit test case to validate the behavior.

Closes: #3510
2026-05-22 12:04:27 +08:00
Luis Pater cecd39317d Merge pull request #3498 from router-for-me/test
fix(auth): update import paths to v7 for registry and executor
2026-05-21 10:50:58 +08:00
hkfires 3c62a9a9b0 fix(auth): update import paths to v7 for registry and executor 2026-05-21 10:00:22 +08:00
Luis Pater 21fad9dbb4 Merge pull request #3477 from router-for-me/cluster
Add cluster-specific docker-compose configuration for CLIProxyAPI
2026-05-21 03:00:50 +08:00
Luis Pater 48a1c88115 Merge pull request #3476 from sususu98/fix/codex-context-length-stream-errors-dev
fix codex context length stream errors
2026-05-21 02:53:54 +08:00
Luis Pater 8b9ecffc2f Merge pull request #3382 from sususu98/dev
fix: scope antigravity credits fallback gate
2026-05-21 02:52:49 +08:00
Luis Pater 42e9605871 Merge pull request #3254 from sususu98/fix/antigravity-project-id-onboard
fix: require antigravity project id
2026-05-21 02:52:32 +08:00
Luis Pater a726e37394 feat(redis): enhance Redis protocol handling with subscription and queue operations
- Added support for advanced RESP commands (`AUTH`, `SUBSCRIBE`, `RPOP`, `LPOP`) with extended functionality.
- Implemented queue operations for usage events via `RPOP` and `LPOP` commands.
- Introduced subscription handling with new Pub/Sub message features and error handling improvements.
- Updated Redis connection logic to enforce authentication requirements and validate inputs.
- Expanded related unit tests to cover new scenarios and edge cases.
2026-05-20 17:20:03 +08:00
Luis Pater f1ee883cd3 Merge pull request #3484 from yavon007/main
Add reasoning_effort to usage event payloads
2026-05-20 12:34:40 +08:00
Luis Pater 1c632d151d fix(translator): skip empty text parts in Claude request conversion
- Updated `ConvertClaudeRequestToGemini` to ignore empty `text` entries during processing.
- Added unit tests to ensure empty `text` parts are skipped correctly.

Closes: #3485
2026-05-20 11:59:31 +08:00
Luis Pater 0ec07e57dd feat(models): add Gemini 3.5 Flash to registry with enhanced thinking capabilities
- Registered `gemini-3.5-flash` model with dynamic thinking levels and extended token limits.
- Supports multiple generation methods, including cached and batch content creation.
2026-05-20 10:53:31 +08:00
Luis Pater fdffe49974 feat(models): register Gemini 3.5 Flash with dynamic thinking levels
- Added new model `gemini-3.5-flash` to the registry with enhanced intelligence and speed capabilities.
- Supports extended thinking levels (`minimal`, `low`, `medium`, `high`) and dynamic adjustments.
- Expanded generation methods, including content creation and token counting.
2026-05-20 10:50:02 +08:00
Luis Pater de0394917a feat(models): expand supported reasoning levels for Codex
- Added new reasoning levels: `none`, `minimal`, and `unsupported` to Codex model configurations.
- Introduced metadata sanitization and normalization for reasoning levels in API response.
- Extended unit tests to cover reasoning levels validation and metadata sanitation logic.
2026-05-20 03:21:46 +08:00
Luis Pater ea25949479 feat(models): add Gemini 3.5 Flash models to registry
- Registered new models: `gemini-3-flash-agent` and `gemini-3.5-flash-low` with detailed specifications.
- Includes support for dynamic thinking levels and extended context capabilities.
2026-05-20 02:17:49 +08:00
Luis Pater 99fa530967 test: remove unused Redis protocol tests and helpers
- Removed obsolete Redis protocol test cases and helper functions that were no longer relevant due to recent architecture changes.
- Streamlined remaining test files to align with updated Redis handling and connection management logic.
2026-05-19 23:12:57 +08:00
Luis Pater b9589e8ed6 Merge pull request #3482 from 9ycrooked/patch-1
Add Codex Switch tool to README
2026-05-19 22:59:28 +08:00
yavon007 0de0ad0d36 Add reasoning effort to usage events 2026-05-19 22:10:48 +08:00
Xinyao Xuandgemini-code-assist[bot] 5ef7693933 Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-05-19 22:05:52 +08:00
Xinyao Xu 7f68fa2414 Add Codex Switch tool to README
Added a new section for Codex Switch tool with details.
2026-05-19 18:00:28 +08:00
Luis Pater bb5ac40a67 feat(client): add timeout handling for Redis operations and subscription failover
- Introduced `homeRedisOperationTimeout` and `homeSubscriptionReceiveTimeout` constants for configurable timeouts.
- Enhanced Redis connection options with operation timeout settings and failover mechanisms.
- Implemented subscription failover logic on heartbeat timeouts to improve resilience.
- Updated message handling to support additional Redis event types, including Pong and Subscription.
2026-05-19 16:44:42 +08:00
hkfires 7efc1629ba feat(docker): add cluster-specific docker-compose configuration for CLIProxyAPI 2026-05-19 16:24:34 +08:00
Luis Pater 67f22514ed style(docs): improve sponsor section clarity in README files
- Updated text formatting with bold emphasis for consistent branding.
- Refined wording for VisionCoder's promotion details in Chinese, Japanese, and English README.
2026-05-19 16:11:48 +08:00
sususu98 ad868308c0 fix codex context length stream errors 2026-05-19 16:05:40 +08:00
Luis Pater bbe30f53b5 feat(server): enhance Home certificate handling with CA fingerprint verification
- Added support for `ClusterID`, `CAFingerprint`, and `EnrollmentSecret` in Home JWT claims.
- Implemented CA fingerprint normalization and verification for PEM and file-based certificates.
- Improved certificate request validation and error handling.
- Updated server-side logic to include `EnrollmentSecret` in certificate requests.
2026-05-19 10:25:57 +08:00
Luis Pater feebe6c7f2 feat(api): add OpenAI compatibility for image models
- Introduced OpenAI-compatible image model support in the API, enabling integration through image generation and editing endpoints.
- Added registry type for OpenAIImageModelType to classify and validate compatibility.
- Implemented request handling for OpenAI-compatible image models, including JSON and multipart formats.
- Enhanced executor methods to support OpenAI-compatible image streaming and non-streaming requests.
- Included tests to validate model registration, streaming behavior, and multipart payload formatting.
2026-05-19 10:13:26 +08:00
sususu98 b67eb6f25d Merge pull request #3470 from sususu98/fix/antigravity-gemini-thought-signatures
Fix Antigravity Gemini thought signatures
2026-05-19 09:48:25 +08:00
sususu98 644823529f Merge pull request #3469 from sususu98/fix/gemini-max-output-token-cap
Cap Gemini max output tokens
2026-05-19 09:48:08 +08:00
Luis Pater bac006e72b feat(thinking): add xAI provider support with reasoning.effort implementation
- Implemented `xAI` provider for thinking configurations with support for reasoning.effort levels.
- Registered `xAI` in available providers and updated relevant APIs for compatibility.
- Added unit tests for `xAI` provider functionality, including fallback logic for unsupported levels.
- Integrated `xAI` with executor handling and ensured conformance with OpenAI-compatible standards.
2026-05-19 03:09:53 +08:00
Luis Pater ad98c9549a feat(runtime): track upstream response headers in logging and usage reporting
- Added APIs to store, retrieve, and clone upstream response headers in context for detailed logging.
- Updated `RecordAPIResponseMetadata`, `RecordAPIWebsocketHandshake`, and related methods to capture response headers.
- Extended `UsageReporter` to include response headers in published usage records.
- Enhanced payload tests to validate response headers' integrity and persistence.
- Refactored `usage.Record` to support optional `ResponseHeaders` field.
2026-05-19 01:29:23 +08:00
Luis Pater 77ba15f71b feat(server): add mTLS certificate bootstrap via JWT for Home connections
- Introduced `-home-jwt` flag and `HOME_JWT` environment variable to provide JWT for mTLS certificate generation.
- Added new APIs to handle certificate requests, validate JWT claims, and manage local certificate files.
- Updated Home TLS configuration to support client certificates, keys, and dynamic server name resolution.
2026-05-19 00:53:40 +08:00
Finesssee a1ce124748 Document OAuth account risk 2026-05-18 19:16:51 +07:00
Finesssee cedb38d1cf Harden management and OAuth surfaces 2026-05-18 19:10:42 +07:00
RCDandCopilot c36e214e2e fix: remove duplicate TUI flag registration
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-18 11:54:34 +00:00
sususu98 32a0d69b17 Fix Antigravity Gemini thought signatures 2026-05-18 19:01:51 +08:00
sususu98 1583cb4ef0 Cap Gemini max output tokens 2026-05-18 18:41:45 +08:00
Luis Pater cc0cb057b3 Merge pull request #3468 from sususu98/fix/claude-codex-call-id-length
Fix Claude-Codex long tool call IDs
2026-05-18 18:04:55 +08:00
Luis Pater 2710f56ae1 Merge pull request #3450 from sususu98/fix/http-connect-proxy-dialer
fix(proxy): support HTTP CONNECT dialer
2026-05-18 18:03:41 +08:00
sususu98 8bc2eff58a fix: shorten claude codex tool call ids 2026-05-18 17:49:42 +08:00
sususu98 ec79951e7f fix(proxy): support HTTP CONNECT dialer 2026-05-18 12:20:41 +08:00
Luis Pater 24602055a8 Merge pull request #2926 from slicenferqin/fix-tool-use-name-loss-and-duplicates
fix(openai→claude): suppress empty/duplicate tool_use content_block_start
2026-05-18 12:11:41 +08:00
Luis Pater 4ad6ffefb7 Merge pull request #3438 from madwiki/fix/strip-claude-code-attribution
fix: strip Claude Code attribution from non-Anthropic translations
2026-05-18 11:25:38 +08:00
slicenfer 1c2153a2cb fix(openai-claude): stabilize streaming tool_use blocks 2026-05-18 11:25:33 +08:00
Luis Pater 64d233fe93 Merge pull request #3448 from LongDinhh/feat/home-env-vars
feat(server): add HOME_ADDR and HOME_PASSWORD env var fallback
2026-05-18 11:20:18 +08:00
Luis Pater 66c5d60b3d refactor(api): remove newTestServerWithOptions and spoofed IP rejection test
- Simplified test server initialization by removing `newTestServerWithOptions`.
- Deleted `TestManagementLocalPasswordRejectsSpoofedForwardedFor` as spoofed IP handling is no longer applicable.
- Removed trusted proxy configuration from Gin engine setup.
2026-05-18 11:01:10 +08:00
Long DinhandClaude Opus 4.7 5f039654f0 refactor: move home env vars after godotenv and use lookupEnv helper
Address review feedback: move HOME_ADDR/HOME_PASSWORD lookup after
godotenv.Load() so .env files work, and use the lookupEnv helper
for case-insensitive key support consistent with PGSTORE_* etc.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 08:52:57 +07:00
Long DinhandClaude Opus 4.7 ed0ac68324 feat(server): add HOME_ADDR and HOME_PASSWORD env var fallback for home flags
Allow configuring the home control plane connection via environment
variables HOME_ADDR and HOME_PASSWORD as an alternative to the --home
and --home-password command-line flags. This enables Docker Swarm stack
deployments without needing docker service update --args.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 03:11:19 +07:00
Luis Pater 605adaa3c2 feat(api): add support for local management password validation and spoofed IP rejection
- Introduced `newTestServerWithOptions` to customize server initialization in tests.
- Added `TestManagementLocalPasswordRejectsSpoofedForwardedFor` to validate security against spoofed `X-Forwarded-For` headers.
- Enabled default WebSocket authentication (`ws-auth`) in `config.example.yaml`.
- Disabled trusted proxy headers in Gin engine with appropriate logging to enhance security.
2026-05-18 01:23:35 +08:00
Luis Pater 9ef99aa766 refactor(runtime): rename FormProtocol to FromProtocol across payload handling logic
- Updated variable, function, and struct names from `FormProtocol` to `FromProtocol` for clarity.
- Adjusted related payload matching and normalization logic.
- Updated tests and examples to align with the new naming convention.
2026-05-17 23:39:07 +08:00
Luis Pater 2007a89594 feat(runtime): enhance payload rule resolution with dynamic path support
- Introduced `resolvePayloadRulePaths` function to dynamically resolve rule paths supporting array queries and complex logic.
- Updated payload processing logic (`apply defaults`, `overrides`, `filters`) to handle resolved paths for better flexibility.
- Added helper functions for path parsing, query matching, and logical resolution to improve modularity and reusability.
- Introduced payload condition match logic, including `match`, `not-match`, `exist`, and `not-exist` rules in `PayloadConfig`.
- Enhanced `payloadModelRulesMatch` function to support conditional checks at various levels.
- Added helper methods for evaluating JSON path conditions and values.
- Updated tests to validate new conditional rules against different payload scenarios.
2026-05-17 23:06:43 +08:00
Luis Pater 26d13af28f feat(runtime): enhance payload rule resolution with dynamic path support
- Introduced `resolvePayloadRulePaths` function to dynamically resolve rule paths supporting array queries and complex logic.
- Updated payload processing logic (`apply defaults`, `overrides`, `filters`) to handle resolved paths for better flexibility.
- Added helper functions for path parsing, query matching, and logical resolution to improve modularity and reusability.
2026-05-17 16:42:35 +08:00
Luis Pater be841b88ee log(registry): replace panic with warning on embedded model parse failure 2026-05-17 15:10:48 +08:00
Luis Pater 4b13f9c255 Merge pull request #3439 from ben-vargas/fix-grok-tool-params
fix(xai): default missing function tool parameters
2026-05-17 15:04:28 +08:00
Luis Pater 74cb53dee1 feat(xai): support namespace tools and enhance tool normalization logic
- Added `namespace` tool type support, enabling nested tools to be normalized and moved to the top level.
- Refactored tool normalization logic into `normalizeXAITool` for reusability and clarity.
- Updated `xai_executor` test cases to validate namespace tool handling and nested tool normalization.
2026-05-17 15:02:36 +08:00
Ben Vargas 2607888a97 fix(xai): default missing function tool parameters 2026-05-16 17:57:40 -06:00
Luis Pater 8b3670b8dd feat(xai): support namespace tools and enhance tool normalization logic
- Added `namespace` tool type support, enabling nested tools to be normalized and moved to the top level.
- Refactored tool normalization logic into `normalizeXAITool` for reusability and clarity.
- Updated `xai_executor` test cases to validate namespace tool handling and nested tool normalization.
2026-05-17 05:22:57 +08:00
Luis Pater 96754f5a33 refactor(api): move Codex client model handling to registry package
- Relocated Codex client model JSON and related logic from `openai` package to `registry` for better modularity.
- Updated references to use `registry.GetCodexClientModelsJSON()` in loading logic.
- Extended test cases to cover additional field removals (`upgrade`, `availability_nux`).
2026-05-17 05:11:41 +08:00
Luis Pater ddd10539ad feat(xai): normalize xAI input reasoning items and enhance test cases
- Added `normalizeXAIInputReasoningItems` to clean up `input` reasoning items, removing null `content` and `encrypted_content` fields.
- Updated `xai_executor` test cases to validate input normalization and reasoning item handling.
2026-05-17 04:51:17 +08:00
Luis Pater 088ab33df8 feat(api): add Codex client models support for OpenAI API
- Introduced Codex client models framework in `openai` package.
- Added JSON-based model definitions (`codex_client_models.json`) for Codex, including metadata, reasoning levels, and configuration options.
- Implemented handlers to load, clone, and build Codex client models with support for visibility overrides and metadata application.
- Enabled sorting and prioritization of models based on configuration or runtime criteria.
- Added utility functions for managing and validating model attributes.
2026-05-17 04:48:34 +08:00
Mad Wiki d606faa99c fix: strip Claude Code attribution from non-Anthropic translations 2026-05-17 04:21:53 +08:00
Luis Pater 53d1fd6c5c feat(api, xai): add xAI Grok video model support with API integration
- Introduced new xAI `grok-imagine-video` model for video generation with configurable options (e.g., duration, size, resolution).
- Implemented video-specific API endpoints (`/v1/videos`, `/v1/videos/generations`, `/v1/videos/edits`, `/v1/videos/extensions`), including request validation and model handling.
- Enhanced model registry with `xaiBuiltinVideoModelID` and metadata for video capabilities.
- Added unit tests to validate video model support, request structures, and API response handling.
- Extended `XAIExecutor` to integrate video generation and retrieval via runtime requests.
2026-05-17 02:53:50 +08:00
Luis Pater 2ff9e33e26 feat(api, xai): integrate xAI Grok image models and extend API endpoints for image support
- Added new xAI Grok image models (`grok-imagine-image`, `grok-imagine-image-quality`) with high-fidelity and aspect ratio configurations.
- Extended `isSupportedImagesModel` logic to validate xAI models.
- Implemented API request builders for image generation/editing with customizable options (e.g., resolution, aspect ratio, response format).
- Enhanced `/v1/images` endpoints to handle xAI model capabilities, including response normalization and model-specific handlers.
- Updated unit tests to validate xAI model validation, request structure, and API integration.
2026-05-17 01:30:23 +08:00
Luis Pater e4c957078c feat(auth): add OAuth2 support for xAI with PKCE and token persistence
- Implemented xAI OAuth2 integration with PKCE (Proof Key for Code Exchange) support.
- Added logic for token exchange, refresh, and persistent storage in JSON format.
- Created `xai` package with helpers for OAuth discovery, API token handling, and URL building.
- Introduced `XAIExecutor` for integrating xAI credentials into runtime HTTP requests.
- Added unit tests to validate OAuth flow, token persistence, and endpoint validation.
2026-05-17 01:02:35 +08:00
Luis Pater cd0cea393c refactor(server): consolidate home_flag logic into main.go for better maintainability and simplicity 2026-05-16 22:48:10 +08:00
Luis Pater c66fa37665 feat(home): add cluster nodes payload parsing and Redis channel handling
- Added `parseClusterNodesPayload` for streamlined cluster node parsing.
- Introduced `handleSubscriptionPayload` to handle Redis channel payloads, including updates for the new `cluster` channel.
- Updated subscription logic to process and apply cluster node updates seamlessly.
2026-05-16 22:10:38 +08:00
Luis Pater f4c6c41f0b Merge pull request #3430 from router-for-me/home
Implement Redis integration with TLS support and cluster discovery option
2026-05-16 20:44:20 +08:00
hkfires 644d5ea618 feat(home): add support for disabling cluster discovery in Redis configuration 2026-05-16 20:25:29 +08:00
hkfires 48104abf51 feat(home): implement home control plane integration with Redis and TLS support 2026-05-16 19:57:19 +08:00
Luis Pater 7a1a3408bf fix(home): use net.JoinHostPort for consistent host:port formatting 2026-05-16 16:11:38 +08:00
Luis Pater 82c9e0de58 feat(api, watcher): add zstd decoding for request logs and payload diff support
- Added `zstd` decoding support in request logging, including helper functions to process `Content-Encoding` headers.
- Enhanced config diff logic to compare payload-specific rules and track changes in payload configurations.
- Added tests to validate `zstd` decoding and payload diff behavior.
2026-05-16 13:00:32 +08:00
Luis Pater e7a185962d feat(api): add request body decoding with Content-Encoding support
- Introduced `ReadRequestBody` helper function to support decoding request bodies based on "Content-Encoding" (e.g., `zstd`).
- Replaced `c.GetRawData()` with `ReadRequestBody` across handlers to enable decoding.
- Added test case to validate `zstd` decoding for compact responses.
2026-05-16 12:19:32 +08:00
Luis Pater 30a8824b64 fix(gitstore): adjust garbage collection to run after push operation
- Updated `maybeRunGC` to accept `repoDir` instead of `repo`.
- Moved garbage collection trigger to occur after the push step for improved reliability.
- Added a test to validate the sequence of push and GC operations.

Closes: #3373
2026-05-16 04:55:44 +08:00
Luis Pater 9d01c80d33 feat(redis): implement Pub/Sub support for usage tracking
- Added Redis Pub/Sub capability to broadcast usage updates to subscribed clients.
- Enhanced `redisqueue` with subscriber management and message broadcasting.
- Updated tests to validate Pub/Sub message handling, subscription behavior, and fallback to the queue after unsubscribing.
- Integrated `project_id` parsing into auth-files logic to include project identifiers in metadata.

Closes: #3027
2026-05-16 00:38:43 +08:00
Luis Pater 1d529c3ce4 feat(redis): implement Pub/Sub support for usage tracking
- Added Redis Pub/Sub capability to broadcast usage updates to subscribed clients.
- Enhanced `redisqueue` with subscriber management and message broadcasting.
- Updated tests to validate Pub/Sub message handling, subscription behavior, and fallback to the queue after unsubscribing.
- Integrated `project_id` parsing into auth-files logic to include project identifiers in metadata.
2026-05-15 21:59:43 +08:00
Luis Pater 229d03a690 feat(auth): add support for disabling auth via metadata
- Added logic to set `auth.Disabled` and update `auth.Status` to `StatusDisabled` when `disabled` metadata is provided and true.
- Updated `objectstore`, `gitstore`, and `postgresstore` implementations to handle the new metadata attribute.

Closes: #2651
2026-05-15 03:59:25 +08:00
Luis Pater 3a9fb3780e fix(home): implement home dispatch headers and enhance Gemini model handling 2026-05-14 03:01:55 +08:00
Luis Pater 437aa87c9b feat(api): add dynamic handler for Gemini models with home integration
- Introduced `geminiModelsHandler` to dynamically route Gemini model requests based on home configuration.
- Added `handleHomeGeminiModels` and `loadHomeModelEntries` to support home-specific Gemini model handling.
- Refactored and centralized error handling logic for improved maintainability.
- Enhanced response formatting with `formatHomeGeminiModels` for consistent output structure.
2026-05-14 02:27:23 +08:00
Luis Pater bcbb94906c feat(client): add cluster node failover and improve reconnection handling
- Introduced cluster node management with `clusterNode` and `clusterNodesEnvelope` types.
- Added failover handling for reconnection failures with configurable threshold (`homeReconnectFailoverThreshold`).
- Implemented node switching and dynamic cluster target updates.
- Enhanced Redis client management with centralized locking for concurrency safety.
- Updated configuration refresh logic to prioritize the best cluster node.
- Improved debug logging for reconnect failures and node switching.
2026-05-14 00:21:31 +08:00
sususu98 bfdc0b3989 fix: scope antigravity credits fallback gate 2026-05-13 18:17:22 +08:00
Luis Pater 6bfcb0ce79 feat(auth): improve unauthorized error handling for refresh and auto-refresh
- Added `isUnauthorizedError` and `hasUnauthorizedAuthFailure` to classify and handle unauthorized errors.
- Introduced `refreshErrorFromError` to map errors to standardized unauthorized responses.
- Modified refresh logic to stop auto-refresh retries for unauthorized errors.
- Updated tests to verify unauthorized error handling and refresh retry prevention.
2026-05-13 02:59:46 +08:00
Finesssee c26de75913 Harden PR and release workflows 2026-05-12 18:42:12 +07:00
Luis Pater bd8c05a830 feat(usage): add support for detailed token breakdown in usage tracking
- Introduced `CacheReadTokens` and `CacheCreationTokens` to enhance token breakdown.
- Refactored `parseClaudeUsageNode` for cleaner and reusable logic.
- Adjusted helpers and updated token calculations to align with the new fields.
2026-05-12 11:59:07 +08:00
RCD bd3901ca29 chore: merge upstream CLIProxyAPI v7.0.2
# Conflicts:
#	internal/translator/openai/openai/responses/openai_openai-responses_request_test.go
2026-05-11 07:53:17 +00:00
RCDandCopilot 3636be31d6 fix: make Kiro auth fallback safe and document Claude limits
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-11 07:51:59 +00:00
Luis Pater 041ccf0195 Merge pull request #3303 from lihan3238/fix-3267
fix(api): prevent idle TCP connections from blocking the accept loop
2026-05-11 08:43:00 +08:00
Luis Pater 1fca942b9c Merge remote-tracking branch 'origin/pr/3239' 2026-05-10 20:43:35 +08:00
RCDandCopilot 18d9369ce4 chore: merge upstream CLIProxyAPI v7.0.1
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-10 07:47:19 +00:00
lihan3238andClaude Opus 4.7 c5596e0925 fix(api): clear sniff deadline before entering Redis handler
Clear the 10s read deadline before calling handleRedisConnection so
that authenticated Redis clients are not disconnected by an i/o timeout
after 10 seconds of idle time. HTTP paths already clear the deadline
after routing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 15:43:58 +08:00
Luis Pater 5e5b1bce35 feat(config): add detailed logging for home config changes
- Introduced `logHomeConfigChanges` to compare old and new configs, logging detected differences.
- Leveraged `diff.BuildConfigChangeDetails` for structured change detection.
- Adjusted logging behavior to enable debug-level logs dynamically when required.
2026-05-10 15:28:49 +08:00
Luis Pater 15ac7fb932 refactor(auth): simplify home auth session management and remove ref counting
- Consolidated `homeRuntimeAuths` to store a map of session-scoped auth maps, replacing `homeRuntimeAuthSessions` and `homeRuntimeAuthRefs`.
- Adjusted session cleanup logic to directly remove session-scoped auths without reference counting.
- Added `GetExecutionSessionAuthByID` to retrieve auths scoped to a specific execution session.
- Updated tests to reflect the new session-scoped caching behavior.
2026-05-10 15:21:33 +08:00
Luis Pater 8300ee8bbe feat(auth): enhance home auth session reuse with scoped caching and ref counting
- Added `homeRuntimeAuthSessions` and `homeRuntimeAuthRefs` for scoped caching of home auths per session.
- Updated `pickNextViaHome` to prevent reuse of already-tried pinned auths during session retries.
- Implemented reference counting for shared auths across multiple sessions to improve memory management.
- Enhanced session cleanup logic to clear cached auths only when all referencing sessions are closed.
- Added unit tests to validate scoped caching, retry logic, and session cleanup behavior.
2026-05-10 14:00:13 +08:00
Luis Pater dc1cc7f115 feat(auth): add websocket session reuse for home auths with caching support
- Introduced `homeRuntimeAuths` to cache home auths for websocket session reuse.
- Updated `pickNextViaHome` to prioritize cached auths for pinned websocket sessions.
- Implemented automatic clearing of cached home auths when home mode is disabled.
- Added unit tests to validate caching behavior, clearing logic, and fallback scenarios.
2026-05-10 13:39:14 +08:00
lihan3238 28dfcae350 fix(api): prevent idle TCP connections from blocking the accept loop
Move per-connection protocol detection (TLS handshake, reader.Peek) out
of the accept loop and into a per-connection goroutine. An idle TCP
connection that never sends bytes would previously block Peek(1)
indefinitely, preventing all subsequent connections from being accepted
and making the management/API server unresponsive.

Closes #3267
2026-05-10 03:23:29 +08:00
Luis Pater a44e5eb1ab Merge branch 'v7' into dev 2026-05-10 02:33:42 +08:00
Luis Pater 67fb4eb98e feat(auth): add shouldReturnLastErrorOnPickFailure helper and improve error handling in home mode
- Introduced `shouldReturnLastErrorOnPickFailure` to streamline error return logic during provider selection.
- Added `isHomeRequestRetryExceededError` for better home-specific error classification.
- Updated fallback conditions to enhance error handling clarity in `pickNextMixed`.
2026-05-10 02:09:53 +08:00
Luis Pater 66c3dae06b feat(home): implement count for home auth dispatch requests and enable usage statistics
- Added `count` attribute to `homeAuthCount` requests to improve home message batching.
- Enabled usage statistics for home mode by default and added config-level enforcement.
- Adjusted failure logging to include detailed metadata in `UsageReporter`.
- Updated multiple executors to pass error details to `PublishFailure` for better debugging.
- Enhanced unit tests to validate `count` behavior and usage statistics enforcement across components.
2026-05-10 01:30:43 +08:00
Luis Pater 1abf8625d8 feat(logging): add home request-log forwarding support
- Introduced `SetHomeEnabled` to enable/disable request-log forwarding to the home control plane.
- Implemented `forwardRequestLogToHome` for non-streaming logs and `homeStreamingLogWriter` for real-time streaming logs.
- Enhanced `FileRequestLogger` to bypass local logging when home forwarding is enabled.
- Updated server configuration to dynamically toggle home request-log forwarding based on changes.
- Added corresponding unit tests to ensure correct forwarding behavior and fallback mechanisms.
2026-05-09 23:39:59 +08:00
Luis Pater 3cbd587b2c Merge pull request #3283 from wuchulonly/fix/responses-ws-tool-output-context
Fix Responses WebSocket tool output context repair
2026-05-09 21:08:43 +08:00
Luis Pater 41f4ee7c7d feat(auth): enhance auth index generation with improved file path handling
- Updated `EnsureIndex` logic to incorporate absolute and cleaned file paths when generating auth indexes.
- Refined metadata handling to include OAuth type in auth index seed.
- Improved compatibility for `json` file paths as sources in auth attributes.
- Added unit tests to validate correct auth index behavior for various path and type scenarios.
2026-05-09 21:03:11 +08:00
Luis Pater c69ff49758 feat(auth): add support for persisting disabled flag in token storage
- Updated `FileTokenStore` and related stores (`objectstore`, `gitstore`, `postgresstore`) to include the `disabled` flag in metadata for token storage.
- Adjusted `Auth` metadata handling to initialize empty maps when absent.
- Refined logic in `auto_refresh_loop` and `conductor` to exclude `disabled` tokens from refresh checks.
- Added comprehensive unit tests to verify proper handling of the `disabled` flag in storage and retrieval operations.
2026-05-09 19:48:42 +08:00
Luis Pater 68fddaa319 Merge pull request #3292 from lihan3238/fix-3272
fix: apply default auth-dir when config value is empty
2026-05-09 17:34:05 +08:00
Luis Pater 09ac8a1165 Merge pull request #3221 from mochenya/main
fix(executor): ignore null OpenAI stream usage chunks
2026-05-09 11:53:26 +08:00
Luis Pater 0dcb8bd714 refactor(cliproxy): remove ClaudeCodeSessionAffinity support and simplify session affinity logic 2026-05-09 10:51:49 +08:00
Luis Pater 0f0fcd2304 feat(config): add per-auth disable_cooling override support
- Introduced `disable_cooling` metadata field for fine-grained control over cooldown scheduling.
- Updated `Auth` object to include `Metadata` with conditional logic for handling empty states.
- Added YAML configuration support for `disable_cooling` in API key definitions across providers.
- Enhanced unit tests to validate `disable_cooling` behavior in various scenarios.
2026-05-09 10:51:27 +08:00
Luis Pater c67096b687 feat(server): add support for loading configuration from a remote home control plane
- Introduced `-home` and `-home-password` flags for specifying home control plane address and authentication.
- Implemented fetching and parsing configuration from the home control plane when `-home` is used.
- Adjusted server configuration handling to bypass local config files when loading from home.
- Ensured compatibility with cloud deploy mode and validation of home configurations.
2026-05-09 07:14:44 +08:00
Luis Pater 1721994111 feat(management): expose additional OAuth and configuration helpers
- Added new helper methods for OAuth session management (`RegisterOAuthSession`, `CompleteOAuthSession`, etc.).
- Introduced `WriteConfig` for persisting management configurations.
- Exported `Handler` type and `NewHandler` constructors for SDK consumers.
2026-05-09 00:23:45 +08:00
lihan3238 4cbe172934 refactor: extract DefaultAuthDir constant per review feedback 2026-05-08 22:28:38 +08:00
lihan3238 4071fdef84 fix: apply default auth-dir when config value is empty
When auth-dir is not specified in config.yaml, ResolveAuthDir returns
an empty string which causes os.MkdirAll to fail with no path. Use
the documented default ~/.cli-proxy-api instead.

Fixes #3272
2026-05-08 21:47:41 +08:00
Codex c883114a4d fix responses websocket tool output context 2026-05-08 05:12:30 +00:00
Luis Pater e50cabac4b chore: upgrade CLIProxyAPI dependency to v7 across the project
- 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.
2026-05-08 11:46:46 +08:00
sususu98 809feb1e86 fix(antigravity): mask project_id in logs 2026-05-07 16:28:53 +08:00
sususu98 33130f18d2 fix: require antigravity project id 2026-05-07 12:55:31 +08:00
Luis Pater 785b00c312 Merge pull request #3237 from seakee/docs/add-cpa-manager-usage-statistics
docs: add CPA-Manager to usage statistics recommendations
2026-05-07 09:32:32 +08:00
Luis Pater a034cf8b8d Merge pull request #3247 from edlsh/fix/amp-thread-actors-route
fix(amp): proxy thread actors route
2026-05-07 09:31:16 +08:00
edlsh 01171742a6 fix(amp): proxy thread actors route 2026-05-06 13:12:35 -04:00
Luis Pater fb08b92402 feat(executor): add upstream disconnect handling for Codex WebSocket sessions
- 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.
2026-05-06 22:09:33 +08:00
AhDEV a09a16e8f6 Merge branch 'router-for-me:main' into my-fix 2026-05-06 16:41:14 +08:00
RCDandCopilot 68b97075af chore: merge upstream CLIProxyAPI v6.10.8
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-05-06 08:10:59 +00:00
seakee ad3f4f2ce5 📝 docs(readme): add CPA-Manager usage statistics recommendation
Add CPA-Manager to the Usage Statistics recommendations across English, Chinese, and Japanese READMEs.

Highlight request-level monitoring, cost estimation, LiteLLM price sync, SQLite persistence, and Codex account-pool operations for multi-account maintenance.
2026-05-06 15:49:57 +08:00
songyu 17a1f53c47 fix:openai 2 kimi error Continuous function_call
连续的function_call 转换 tool_calls
2026-05-06 14:37:18 +08:00
Luis Pater ed1458aa6d chore(docs): update sponsor details in README
- Replaced sponsor `z.ai` with `PackyCode` and updated related descriptions, images, and links in `README.md`, `README_CN.md`, and `README_JA.md`.
- Removed outdated sponsor entries for `Poixe AI` in all README files.
- Added new image assets for PackyCode (`packycode-cn.png` and `packycode-en.png`).
2026-05-06 00:41:50 +08:00
mochenya 99dfbaef61 fix(executor): ignore null OpenAI stream usage chunks
- Added validation so OpenAI-style usage parsing only accepts object payloads with token fields.
- Prevented streaming usage:null chunks from publishing zero-token records before the final usage chunk arrives.
- Reused the shared OpenAI-style parser for stream usage to support both chat completions and responses token field names.
- Added tests covering null usage chunks and input/output token usage fields in streaming responses.
2026-05-05 12:31:33 +08:00
Luis Pater da6c599efd refactor(management): rename GetUsage to GetUsageQueue and update routes/tests
- Renamed handler and test methods for better clarity on functionality.
- Updated route from `/v0/management/usage` to `/v0/management/usage-queue`.
- Adjusted integration and unit tests to reflect new naming and routes.
2026-05-05 03:02:25 +08:00
Luis Pater 61b39d49bd feat(management): add usage record retrieval endpoint
- Implemented `/v0/management/usage` endpoint for fetching queued usage records from Redis.
- Included validation for `count` parameter to ensure positive integers.
- Added unit tests for queue retrieval and validation, with authentication validation in integration tests.
- Updated management routing to include the new endpoint.
2026-05-05 02:53:04 +08:00
Luis Pater ba5d8ca733 feat(usage): add support for requested model alias handling
- Introduced methods for setting and retrieving model aliases in execution and usage contexts.
- Enhanced `UsageReporter` and related structures to include client-requested aliases.
- Updated tests to validate alias propagation and ensure correct usage reporting.
- Adjusted metadata handling in CLIProxyAPI executors to address alias integration.
2026-05-05 01:47:53 +08:00
Luis Pater 28b4b19e7e Merge pull request #3208 from kdcokenny/codex-websocket-protocol-parity
Align Codex websocket protocol semantics
2026-05-05 01:29:19 +08:00
Luis Pater bdc424007e Merge pull request #2896 from edlsh/fix/oauth-tool-rename-per-request-map
fix(amp): smart-mode tool name fixes + deep-mode response repair
2026-05-05 00:58:39 +08:00
Luis Pater e4a93c02c5 fix(executor): enhance parsing of OpenAI stream data lines
- Added trimming for stream input lines to prevent processing of unnecessary whitespace.
- Improved handling of unsupported prefixes and malformed JSON responses, ensuring errors are recorded and propagated appropriately.

Fixed: #2690
2026-05-04 23:42:26 +08:00
Luis Pater 8262a03f29 Merge PR #2568: fix Claude refresh backoff 2026-05-04 21:44:11 +08:00
Luis Pater ecf1c2590c fix: preserve Antigravity cancellation errors 2026-05-04 21:18:18 +08:00
Luis Pater 162897e02a Merge remote-tracking branch 'origin/pr/3205' into dev 2026-05-04 21:17:01 +08:00
Luis Pater c1caa454b3 fix(translator): handle empty tool function names in OpenAI Claude responses
- Added check to prevent processing of empty `function.name` values, ensuring valid data is handled.

Fixed: #2557
2026-05-04 21:00:33 +08:00
Luis Pater bf6fa402e2 fix(executor): strip Vertex OpenAI response tool call IDs for consistency
- Integrated `StripVertexOpenAIResponsesToolCallIDs` to remove tool call ID data from request bodies and translated requests.
- Ensures uniformity and avoids unnecessary payload data propagation.

Fixed: #2549
2026-05-04 17:54:16 +08:00
Luis Pater 85c0150653 feat(translator): add token usage tracking and improve usage handling
- Introduced `claudeUsageTokens` struct for detailed token usage tracking.
- Replaced `calculateClaudeUsageTokens` with `Merge` and `OpenAIUsage` methods for better modularity.
- Enhanced integration of usage tokens into response processing, enabling more accurate reporting of token details.

Fixed: #2419
2026-05-04 16:57:50 +08:00
Luis Pater 89d80bfff4 fix(executor): adjust ApplyThinking order and add payload override test
- Moved `ApplyThinking` logic earlier in `openai_compat_executor` to align with configuration application sequence.
- Added test to verify payload override precedence over Thinking suffix configuration.
2026-05-04 16:45:25 +08:00
Luis Pater a1eba112f3 Merge pull request #2416 from kslamph/fix/gemini-cli-projectid
fix(gemini-cli): use backend project ID from onboarding response
2026-05-04 16:08:31 +08:00
Kenny 6b4bc0a9a8 Align Codex default identity and docs 2026-05-03 21:13:37 -07:00
Kenny 08b0fe6816 Fix Codex websocket retry metadata 2026-05-03 19:01:44 -07:00
Kenny c19ae1d5be Align Codex websocket protocol semantics 2026-05-03 15:56:39 -07:00
Luis Pater 17be6442a8 fix(translator): improve tool response handling for non-string content
- Added `setToolCallOutputContent` to process various content types, including arrays and fallback cases.
- Implemented robust handling for specific tool output types like text, image URLs, and files, ensuring proper serialization.
- Improved fallback logic to handle unexpected or missing data.

Fixed: #2313
Closes: #2349
2026-05-04 05:50:01 +08:00
Luis Pater 38dad2afdf chore(docker): upgrade base image to alpine 3.23
Fixed: #2265
2026-05-04 05:36:09 +08:00
Luis Pater 8e6ef3fa64 fix(websocket): ensure state consistency on auth errors in streaming
- Added logic to reset `pinnedAuthID` and replay transcript on unauthorized, forbidden, or throttling errors.
- Enhanced error handling in `forwardResponsesWebsocket` with detailed status inspection.
- Introduced `shouldReleaseResponsesWebsocketPinnedAuth` to determine auth reset conditions.
- Updated state management to preserve prior request and response data during forced replay.

Fixed: #2230
2026-05-04 05:23:23 +08:00
Luis Pater a1487b0958 fix(translator): handle non-string types in tools result processing
- Skip setting values for non-string `type` fields to prevent runtime errors.

Closes: #2226
2026-05-04 05:08:31 +08:00
Luis Pater 82ebe24b9e Merge pull request #2266 from DragonFSKY/fix/ws-compact-tool-output-mismatch
fix(websocket): skip stale state merge after client-side compact
2026-05-04 04:40:43 +08:00
Luis Pater 2753d9fb71 feat: add validation for Claude streaming responses
- Implemented `validateClaudeStreamingResponse` to ensure upstream streaming data integrity.
- Added new tests to verify response validation, including empty streams, error events, incomplete streams, and valid streams.
- Integrated validation logic into the Claude executor's streaming handler, returning detailed errors for malformed upstream data.

Fixed: #2193
2026-05-04 03:37:31 +08:00
1137043480 bf0e5c23f7 fix: prevent goroutine leaks in streaming executors via context-aware channel sends
All streaming executors use bare channel sends (out <- chunk) inside goroutines
that process upstream SSE responses. When the downstream consumer disconnects
(client timeout, network drop, etc.), these sends block indefinitely, causing
the goroutine and all associated resources (HTTP response body, scanner buffers,
translation state) to leak permanently.

Over time, leaked goroutines accumulate monotonically, leading to RSS growth
from ~30MB to 3.7GB+ and eventual OOM kills on resource-constrained VPS hosts.

Fix: Replace all bare 'out <- ...' sends with:
  select {
  case out <- ...:
  case <-ctx.Done():
    return
  }

This ensures goroutines terminate promptly when the request context is canceled,
allowing GC to reclaim all associated resources.

Affected executors (9 files, 36+ send sites):
- antigravity_executor.go (5 sites)
- gemini_cli_executor.go (6 sites)
- gemini_vertex_executor.go (6 sites)
- aistudio_executor.go (4 sites)
- gemini_executor.go (3 sites)
- openai_compat_executor.go (3 sites)
- claude_executor.go (4 sites)
- codex_executor.go (2 sites)
- kimi_executor.go (3 sites)
2026-05-03 11:25:04 -04:00
Luis Pater 672fdd14ed feat: filter and drop empty assistant messages in Kimi executor
- Added `filterKimiEmptyAssistantMessages` to identify and remove empty assistant messages with no content, tool links, or reasoning.
- Integrated logging to track the number of dropped messages.
- Updated tests to validate the filtering logic for both empty and valid assistant messages.

Fixed: #1730
2026-05-03 22:40:42 +08:00
Luis Pater af65908cb0 feat: enhance tool mapping with namespace and web search support
- Added functions to handle tool conversion, including namespace-based tools and web search tools.
- Improved parameter normalization and tool input schema standardization.
- Integrated logic to handle qualified tool names and map override functionality.
- Refactored existing tool processing for better extensibility and maintainability.

Fixed: #3199
2026-05-03 22:26:23 +08:00
Luis Pater 756b600b7a Merge pull request #3204 from zhanglunet/add-usage-dashboard-link
Add CLIProxyAPI Usage Dashboard to usage statistics docs
2026-05-03 21:38:45 +08:00
Luis Pater 054d0dee1d Merge pull request #3201 from murasame612/docs/add-cliproxy-pool-watch
docs: add CLIProxy Pool Watch project
2026-05-03 21:37:36 +08:00
zhangluandgemini-code-assist[bot] d2386a3114 Update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-05-03 20:38:51 +08:00
zhangluandgemini-code-assist[bot] 7972130513 Update README_CN.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-05-03 20:38:25 +08:00
John 81db7fdc1e Add CLIProxyAPI Usage Dashboard to statistics docs 2026-05-03 20:23:23 +08:00
ziwu 5fc6f662e1 docs: add CLIProxy Pool Watch project 2026-05-03 18:25:11 +08:00
Luis Pater 593995a404 Merge pull request #3197 from VjayC/dev
docs: update Subtitle Translator project description
2026-05-03 14:23:44 +08:00
Vijay Chimmi 101b59cfe8 docs: update Subtitle Translator project description 2026-05-02 17:37:38 -07:00
Luis Pater 56df36895a feat: add configurable retention period for Redis usage queue
- Introduced `redis-usage-queue-retention-seconds` config parameter with a default of 60 seconds and a max of 3600 seconds.
- Updated logic in `redisqueue` to honor configurable retention periods for enqueued usage data.
- Modified config validation and initialization to support and enforce retention limits.
- Enhanced change tracking in `config_diff` to detect updates to this parameter.
2026-05-02 20:43:16 +08:00
Luis Pater 85124f098b Merge pull request #3194 from daishuge/codex/add-daishuge-cpa-port-20260502
docs: add Playful Proxy API Panel
2026-05-02 17:43:02 +08:00
daishuge 2efa56dbb8 docs: add Playful Proxy API Panel 2026-05-02 17:03:11 +08:00
Luis Pater 79579c34bf docs: update README to consolidate and clarify CPA Usage Keeper details
- Moved CPA Usage Keeper from "CLI tools" to a dedicated "Usage Statistics" section.
- Added details on its functionality, periodic data sync, SQLite storage, and built-in dashboard.
- Applied updates across English, Chinese, and Japanese README files for consistency.
2026-05-02 13:37:42 +08:00
Luis Pater 18bb9c315f chore: remove usage tracking and logging functionality
- Deleted the `LoggerPlugin` along with associated usage tracking and in-memory statistics logic.
- Removed all related tests (`logger_plugin_test.go`, `usage_tab_test.go`) and external-facing handler (`usage.go`) for usage statistics export/import.
- Cleaned up TUI integration by deleting `usage_tab.go`.
2026-05-02 04:50:58 +08:00
Luis Pater b8bba053fc feat: add tracking for auth request success and failure counts
- Introduced `Success` and `Failed` fields in auth records to track request outcomes.
- Updated `/v0/management/auth-files` and `/v0/management/api-key-usage` responses to include success and failure counts.
- Enhanced tests to validate tracking logic and API responses.
2026-05-02 03:40:00 +08:00
Luis Pater 8c2f1a80d3 feat: enhance API key usage grouping with base URL inclusion
- Updated `GetAPIKeyUsage` to group API key usage by "base_url|api_key" composite keys.
- Adjusted logic to handle `base_url` extraction from auth attributes.
- Revised unit tests to validate "base_url|api_key" grouping behavior.
2026-05-02 02:20:49 +08:00
Luis Pater e37f3be0bf chore: update .goreleaser.yml to include custom archive naming with arch override logic 2026-05-02 00:09:08 +08:00
Luis Pater b0dc9df887 feat: add API key usage endpoint with provider and key grouping
- Implemented `GetAPIKeyUsage` to expose recent request data grouped by provider and API key.
- Added supporting function `mergeRecentRequestBuckets` for bucket aggregation.
- Registered new endpoint `/v0/management/api-key-usage` in the management API.
- Included extensive unit tests for provider and key-based grouping validation.
- Updated `formatRecentRequestBucketLabel` to support configurable bucket duration.
2026-05-01 23:34:18 +08:00
Luis Pater 6187919000 feat: add support for recent request tracking in auth records
- Implemented `RecentRequestsSnapshot` in `Auth` to capture bucketed recent request data.
- Added new fields and methods to `Auth` for tracking request success and failure counts over time.
- Updated `/v0/management/auth-files` response to include recent request data for each auth record.
- Introduced unit tests to validate request tracking and snapshot generation logic.
2026-05-01 22:55:22 +08:00
Luis Pater 4035abc0cd refactor(logging): replace gin-specific context handling with generic context-based request metadata utilities
- Introduced reusable utilities in `requestmeta` to manage endpoint and response status in request contexts.
- Refactored plugins and handlers to use context-based metadata, removing direct dependency on `gin`.
- Updated tests to validate new context utilities and replaced `gin`-based context handling.

Fixed: #3166
2026-04-30 23:36:07 +08:00
RCDandCopilot 101099ca3a chore: merge upstream CLIProxyAPI v6.9.45
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-30 13:35:28 +00:00
Luis Pater 8b286e8fb3 Merge pull request #3163 from C4AL/docs/add-codexclipplus-ecosystem
docs: add CodexCliPlus to README ecosystem list
2026-04-30 20:42:32 +08:00
C4AL aa70d13f60 docs: add CodexCliPlus to README ecosystem list 2026-04-30 20:36:37 +08:00
songyu 05ecfb6241 feat: add local Docker build script and update compose configuration
- Introduced a new script `docker-build-local.sh` to build a local Docker image and start services using Docker Compose.
- Updated `docker-compose.yml` to allow dynamic pull policy configuration via the `CLI_PROXY_PULL_POLICY` environment variable.
- Modified `Dockerfile` to support build arguments for Go module proxy settings during the `go mod download` step.
2026-04-30 14:01:56 +08:00
songyu 243c582159 feat: add unit tests for OpenAI responses request conversion
- Introduced a new test file for validating the conversion of OpenAI responses to chat completions.
- Implemented tests to ensure correct merging of consecutive function calls and proper handling of interrupted function calls.
- Enhanced the main conversion function to buffer consecutive function calls and emit them as a single assistant message.
2026-04-30 13:33:40 +08:00
Luis Pater 6ba7c810a7 feat: apply image_generation filtering before payload rules
- Updated `ApplyPayloadConfigWithRoot` to prioritize `disable-image-generation` filtering before applying payload rules.
- Ensured payload overrides can explicitly re-enable `image_generation` when required.
- Added unit tests to validate `image_generation` restoration through overrides.
2026-04-30 12:42:08 +08:00
Luis Pater f56a19e5b8 feat: add tri-state support for disable-image-generation configuration
- Introduced `DisableImageGenerationMode` with support for `false`, `true`, and `chat` values.
- Updated payload handling to preserve `image_generation` on images endpoints when `chat` mode is enabled.
- Modified OpenAI image handlers (`ImagesGenerations`, `ImagesEdits`) to respect tri-state logic.
- Added unit tests for `DisableImageGenerationMode` behavior and endpoint-specific handling.
- Enhanced configuration diff logging to support `DisableImageGenerationMode`.
2026-04-30 12:10:27 +08:00
Luis Pater 46018417ad feat: remove tool_choice for image_generation when disabled
- Added logic to remove `tool_choice` entries of type `image_generation` from payloads when `disable-image-generation` is enabled.
- Updated `ApplyPayloadConfigWithRoot` to handle new removal logic.
- Added unit tests to verify `tool_choice` removal behavior.
2026-04-30 08:24:14 +08:00
RCDandCopilot dbf432c3e7 chore: merge upstream CLIProxyAPI v6.9.43
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-29 23:41:52 +00:00
Luis Pater e3e60f914b feat: support disabling image generation globally
- Added `disable-image-generation` configuration flag to disable the `image_generation` tool globally.
- Updated payload handling to remove `image_generation` tools from request payload arrays when the flag is enabled.
- Modified OpenAI image handlers (`ImagesGenerations`, `ImagesEdits`) to return 404 when the feature is disabled.
- Enhanced configuration diff logging to track changes for the `disable-image-generation` flag.
- Added accompanying unit tests for the new feature in payload helpers and image handler logic.
2026-04-30 03:42:27 +08:00
RCDandCopilot 270e273254 chore: merge upstream CLIProxyAPI v6.9.42
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-29 15:38:08 +00:00
Luis Pater 359ec30d0c chore(docs): remove LingtrueAPI sponsorship section from README files 2026-04-29 23:13:12 +08:00
Luis Pater a1f0ed9575 Merge pull request #3071 from sususu98/fix/antigravity-credits-log
Mark Antigravity credits requests in access logs
2026-04-29 22:56:41 +08:00
Luis Pater b3b92f334e Merge pull request #3125 from sususu98/fix/gemini-cli-usage-metadata-variants
fix: parse gemini cli usage metadata variants
2026-04-29 22:56:14 +08:00
Luis Pater 2c1539ead7 Merge pull request #3133 from sususu98/optimize/claude-codex-translator
fix: align claude codex translation
2026-04-29 22:55:37 +08:00
sususu98 0d107dd566 fix: respect declared claude web search tool names 2026-04-29 19:24:53 +08:00
sususu98 1c0c426b85 fix: align claude codex translation 2026-04-29 18:47:03 +08:00
sususu98 4982512da2 fix: parse gemini cli usage metadata variants 2026-04-29 13:10:53 +08:00
Luis Pater 2ea8f77efb feat(models): add GPT-5.5 to the registry with support for advanced tasks 2026-04-29 09:49:26 +08:00
Luis Pater f95ab4cdf1 Merge pull request #3089 from XYenon/feat/session-affinity
feat: support Codex/PI session headers for session affinity
2026-04-28 23:54:16 +08:00
sususu98 c4965befe7 Merge pull request #3117 from sususu98/fix/restore-antigravity-ua-handling
fix: restore Antigravity user agent handling
2026-04-28 19:07:05 +08:00
sususu98 0e1235122e fix antigravity client agent headers 2026-04-28 19:04:40 +08:00
sususu98 e78d45acc9 fix antigravity user agent handling 2026-04-28 19:04:40 +08:00
sususu98 b34f3be13e Merge pull request #3114 from Xbang0222/fix/antigravity-credits-ua
fix(antigravity): 使用真实 antigravity UA 查询积分余额
2026-04-28 19:03:21 +08:00
Luis Pater 9fb6a49260 test(api): add validation for unsupported models in OpenAI image handlers
- Introduced tests to ensure unsupported models are rejected in `/images/generations` and `/images/edits`.
- Added `isSupportedImagesModel` and `rejectUnsupportedImagesModel` functions for consistent model validation.
- Enhanced image handler logic to apply validation checks for model compatibility.
2026-04-28 17:19:12 +08:00
xbang a992dee4e8 fix(antigravity): use real antigravity UA when polling credits balance
The loadCodeAssist polling call hardcoded the User-Agent to
google-api-nodejs-client/9.15.1. Google Cloud Code returns the
paidTier object WITHOUT the availableCredits array for that UA,
so updateAntigravityCreditsBalance always saw "no credits", set the
hint to Available=false for every Google One AI Ultra account, and
the conductor-level credits fallback could never find a candidate.

Switching to resolveUserAgent(auth) (the same UA used for
streamGenerateContent / generateContent) makes the response include
availableCredits, so the credits hint is populated correctly and the
fallback can actually inject enabledCreditTypes:["GOOGLE_ONE_AI"]
when free tier is exhausted.
2026-04-28 16:21:15 +08:00
XYenonandAmp 3ac39dcc7d feat: support Codex/PI session headers for session affinity
Amp-Thread-ID: https://ampcode.com/threads/T-019dce25-c070-773a-ac52-11c541220b30
Co-authored-by: Amp <amp@ampcode.com>
2026-04-27 17:10:50 +08:00
Luis Pater 34027da7f1 Merge pull request #3088 from sususu98/codex-claude-reasoning-signature
Preserve Codex reasoning signatures for Claude
2026-04-27 16:59:11 +08:00
sususu c523101439 Preserve Codex reasoning signatures for Claude 2026-04-27 16:51:35 +08:00
Luis Pater d85e13b044 fix(codex): include content field in reasoning item initialization 2026-04-27 16:41:23 +08:00
Luis Pater 01e16a8509 feat(codex): handle thinking-signature conversion for reasoning content
- Implemented `appendReasoningContent` to support processing of `thinking` signature and text as reasoning input.
- Added test cases to validate reasoning content conversion with and without text.
2026-04-27 16:31:26 +08:00
Luis Pater 04a336f7df fix(usage_helpers): skip zero-token usage in additional model records
- Added `buildAdditionalModelRecord` to filter out zero-token usage details.
- Introduced `hasNonZeroTokenUsage` helper function for token usage validation.
- Updated tests to cover scenarios for zero and non-zero token usage.
2026-04-27 10:56:22 +08:00
Luis Pater a325533f20 Merge pull request #2972 from XYenon/feat/amp-thread-id
feat: support X-Amp-Thread-Id for session affinity
2026-04-26 23:30:12 +08:00
sususu98 6fc23568df logging: mark antigravity credits requests 2026-04-26 23:04:27 +08:00
Luis Pater 736ae61e4a Merge pull request #3051 from philipbankier/fix/gpt55-free-tier-test
fix(test): remove free tier from GPT-5.5 inclusion test
2026-04-26 22:35:59 +08:00
Luis Pater c5bea6f6f8 Merge pull request #3020 from Matthias319/fix/codex-error-classification
fix(codex): classify context, thinking-signature, previous-response, and auth failures
2026-04-26 22:26:40 +08:00
Luis Pater c7b28ba058 feat(executor): add support for Codex image generation tool usage tracking
- Introduced `publishCodexImageToolUsage` to report image generation tool metrics.
- Updated executor logic to handle image generation tool events and defaults.
- Added parsing logic for `image_gen` tool usage details in `helps/usage_helpers.go`.
- Updated `UsageReporter` for additional model-specific usage publishing.
- Refactored usage detail normalizations.

Closes: #3063
2026-04-26 22:19:03 +08:00
Luis Pater 38573050aa feat(config): add support for disabling OpenAI compatibility providers
- Introduced a `Disabled` flag to OpenAI compatibility configurations.
- Updated routing, auth selection, and API handling logic to respect the `Disabled` state.
- Extended relevant APIs, YAML configurations, and data structures to include the `Disabled` field.
- Adjusted all relevant loops and filters to skip disabled providers.

Closes: #3060 #3059 #2977
2026-04-26 21:49:36 +08:00
RCDandCopilot 153d8c160f chore: merge upstream CLIProxyAPI v6.9.38
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-26 08:51:31 +00:00
philipbankier 32ef1588e8 fix(test): remove free tier from GPT-5.5 inclusion test
GPT-5.5 was correctly removed from codex-free tier in 7b89583c
(since free accounts cannot access it), but the test was not updated
to reflect this. This caused TestCodexStaticModelsIncludeGPT55 to
fail on the free subtest.

Changes:
- Remove free tier from GPT-5.5 inclusion test
- Add new TestCodexFreeModelsExcludeGPT55 to explicitly verify
  that free tier does NOT include GPT-5.5
2026-04-25 22:11:08 -04:00
edlsh 80eb03709a fix(openai): preserve multiline repaired SSE data 2026-04-25 18:12:27 -04:00
edlsh d36e70e9dc fix(openai): preserve unindexed response output items 2026-04-25 18:06:00 -04:00
edlsh fd45dece7f fix(openai): repair empty responses stream output 2026-04-25 17:46:44 -04:00
edlsh 95318ad46d fix(amp): preserve lowercase glob tool name 2026-04-25 17:46:44 -04:00
Enzo Lucchesi fc1ddf365f fix(claude): centralize oauth tool-name transform flow 2026-04-25 17:45:03 -04:00
edlsh 03ea4e569f perf(claude): pre-allocate reverseMap capacity
Address Gemini code review suggestion: the reverseMap can contain at
most len(oauthToolRenameMap) entries, so pre-allocating avoids
reallocations as entries are added.
2026-04-25 17:45:03 -04:00
Enzo Lucchesi e707cf7d46 fix(claude): only reverse-remap OAuth tool names that were forward-renamed
remapOAuthToolNames renames lowercase client-sent tools (e.g. `glob` →
`Glob`) to Claude Code equivalents on OAuth requests to avoid tool-name
fingerprinting. The reverse pass previously ran against a *global*
reverse map and rewrote every tool_use block whose name matched any
value in oauthToolRenameMap — regardless of what the client actually
sent.

For clients that send mixed casing (notably Amp CLI — `Bash`, `Read`,
`Grep`, `Task` alongside `glob`, `skill`, etc.) this corrupted the
response. Any forward rename in the request set the "renamed" flag,
which then unconditionally lowercased every `Bash` in the response to
`bash`. Amp's tool registry has `Bash`, not `bash`, so it rejected the
tool_use with `tool "bash" is not allowed for smart mode` and tool
execution failed.

Fix: `remapOAuthToolNames` now returns a per-request map keyed on the
upstream (TitleCase) name valued with the original client-sent name.
The reverse functions take this map and only touch entries in it.
Names the client sent in TitleCase pass through untouched in both
directions.

- Change remapOAuthToolNames signature from `([]byte, bool)` to
  `([]byte, map[string]string)`; populate at every rename site
  (tools[], tool_choice.name, message tool_use, tool_reference,
  nested tool_reference inside tool_result).
- Change reverseRemapOAuthToolNames and
  reverseRemapOAuthToolNamesFromStreamLine to accept and consume the
  per-request map; remove the global oauthToolRenameReverseMap.
- Update all three executor call sites (Execute, ExecuteStream direct
  passthrough, ExecuteStream translated) + count_tokens.
- Add regression tests for the mixed-case scenario in both the
  non-streaming and SSE code paths.
2026-04-25 17:45:03 -04:00
Luis Pater 0a7c6b0a4a feat(api): enhance model assignment logic in image handlers
- Updated `buildImagesResponsesRequest` to derive `model` dynamically based on `toolJSON`.
- Adjusted streaming execution to handle dynamic model resolution across multiple contexts.

Closes: #2965
2026-04-26 03:24:43 +08:00
Luis Pater ea670ef8c0 feat(models): add Codex Auto Review model entry to registry JSON
Closes: #2995
2026-04-26 03:09:06 +08:00
Luis Pater 2c626efc59 feat(security): implement IP ban for repeated management key and Redis AUTH failures
- Added IP ban logic to `AuthenticateManagementKey` and Redis protocol handlers, blocking requests after multiple failed attempts.
- Introduced unit tests to validate IP ban behavior across localhost and remote clients.
- Synchronized Redis protocol's authentication policy with management key validation.
2026-04-25 21:39:58 +08:00
Luis Pater 28d78273e4 feat(api): implement protocol multiplexer and Redis queue for usage integration
- Added `protocol_multiplexer.go`, enabling support for both HTTP and Redis protocols on a single listener.
- Introduced `redis_queue_protocol.go` to handle Redis-compatible RESP commands for queue management.
- Integrated `redisqueue` package, supporting in-memory queuing with expiration pruning.
- Updated server initialization to manage a shared listener and multiplex connections.
- Adjusted `Handler` to adopt `AuthenticateManagementKey` for modular key validation, supporting both HTTP and Redis flows.
2026-04-25 18:52:24 +08:00
Luis Pater be0fe6fab3 Merge pull request #3022 from Willxup/main
docs: add CPA Usage Keeper to ecosystem list
2026-04-25 11:44:49 +08:00
Will cf043f6c07 docs:Add CPA Usage Keeper to README ecosystem list 2026-04-24 23:54:09 +08:00
Will faad8e30dd Add CPA Usage Keeper to README ecosystem list 2026-04-24 23:28:44 +08:00
Luis Pater a7e92e2639 feat(auth): disallow free-tier Codex auth during selection process
- Introduced `disallowFreeAuthFromMetadata` and `isFreeCodexAuth` to enforce skipping free-tier credentials.
- Modified scheduler logic to honor `DisallowFreeAuthMetadataKey` during auth selection.
- Updated `ensureImageGenerationTool` to skip tool injection for free-tier Codex auth.
- Added context utility `WithDisallowFreeAuth` and integrated with image handlers.
- Augmented relevant tests to cover free-tier exclusion scenarios.
2026-04-24 23:18:56 +08:00
Matthias319 4056c2590b fix(codex): classify known upstream failures
Normalize Codex context, thinking-signature, previous-response, and auth failures to explicit error codes: context_too_large, thinking_signature_invalid, previous_response_not_found, auth_unavailable.

Refs #2596.
2026-04-24 17:13:23 +02:00
sususu98 36cc762fc9 Merge pull request #3007 from sususu98/fix-antigravity-credits-stream-fallback
fix(antigravity): trigger credits fallback for streaming
2026-04-24 17:28:47 +08:00
sususu98 5f5d5936fa fix antigravity credits stream fallback 2026-04-24 15:47:18 +08:00
RCD 35a58873b0 chore: merge upstream CLIProxyAPI v6.9.36 2026-04-24 04:25:06 +00:00
Luis Pater f1ba6151a9 feat(codex): pass base model to enable conditional image_generation tool injection
- Modified `ensureImageGenerationTool` to accept `baseModel` for conditional logic.
- Ensured `gpt-5.3-codex-spark` models bypass image_generation tool injection.
- Updated relevant tests and executor logic to reflect changes.
2026-04-24 07:21:03 +08:00
Luis Pater 7b89583cf8 chore(models): remove GPT-5.5 model entry from registry JSON 2026-04-24 05:07:03 +08:00
Luis Pater 1576d14137 Merge pull request #2989 from ben-vargas/gpt-5-5-support
Align GPT-5.5 Codex metadata with runtime cache
2026-04-24 04:24:58 +08:00
Ben Vargas 736018a0b0 Add GPT-5.5 Codex model support 2026-04-23 13:43:02 -06:00
Luis Pater 7d5f6d9382 feat(models): add GPT-5.5 model entry to registry JSON 2026-04-24 02:43:12 +08:00
sususu98 12195a276e Merge pull request #2971 from sususu98/feat/antigravity-credits-fallback
feat(antigravity): conductor-level credits fallback for Claude models
2026-04-24 00:15:23 +08:00
Luis Pater 25137b1984 feat(logging): add AI API path support for image routes
- Included `/v1/images` in AI API path prefixes.
- Introduced tests to validate `/v1/images/generations` and `/v1/images/edits` as AI API paths.
2026-04-24 00:11:42 +08:00
sususu98 7ad1900041 perf(antigravity): async credits hint refresh for warm tokens 2026-04-23 23:58:10 +08:00
Luis Pater 8eb56e5602 Merge pull request #2962 from MoYeRanqianzhi/feat/codex-image-generation-tool-injection
feat(codex): inject image_generation tool + route aliases for Codex CLI image generation
2026-04-23 23:48:31 +08:00
sususu98 f130846ec1 fix(auth): break credits cold-start deadlock by keeping unknown-hint auths as fallback candidates
Replace antigravityCreditsAvailableForModel with inline known/unknown
split. Auths whose credit hints are not yet populated are kept as
lower-priority candidates instead of being rejected, breaking the
chicken-and-egg deadlock at cold start.
2026-04-23 22:47:51 +08:00
sususu98 920b6efffa refactor(logging): strip unrelated deferred body changes, keep credits-only logging
Remove deferred body optimization and maxErrorLog constants that were
unrelated to credits fallback. Keep only MarkCreditsUsed/CreditsUsed
helpers for flagging requests that consumed AI credits.
2026-04-23 17:41:54 +08:00
sususu98 e75daa299b fix(antigravity): respect pinned auth in credits fallback, release deferred body on success
- findAllAntigravityCreditsCandidateAuths now filters by PinnedAuthMetadataKey
  to prevent credential isolation violations during credits fallback
- Release deferredBody reference on success path to avoid holding large
  payloads in memory for the lifetime of the gin context
2026-04-23 17:38:02 +08:00
XYenon 8e49c795f5 fix: forward HTTP headers to executor Options so session affinity can read X-Amp-Thread-Id 2026-04-23 15:34:31 +08:00
sususu98 4de5c29f86 fix(antigravity): remove credits fallback from CountTokens, fix gofmt
CountTokens upstream API does not support enabledCreditTypes, so
remove the dead credits fallback path from ExecuteCount and delete
the unused tryAntigravityCreditsExecuteCount method. Fix gofmt on
credits test file.
2026-04-23 15:17:00 +08:00
XYenon 4d6457e6ec feat: support extracting X-Amp-Thread-Id header as session id for session affinity 2026-04-23 13:49:00 +08:00
sususu98 14d46a0a5d feat(antigravity): conductor-level credits fallback for Claude models
Move credits handling from executor-level retry to conductor-level
orchestration. When all free-tier auths are exhausted (429/503), the
conductor discovers auths with available Google One AI credits and
retries with enabledCreditTypes injected via context flag.

Key changes:
- Add AntigravityCreditsHint system for tracking per-auth credits state
- Conductor tries credits fallback after all auths fail (Execute/Stream/Count)
- Executor injects enabledCreditTypes only when conductor sets context flag
- Credits fallback respects provider scope (requires antigravity in providers)
- Add context cancellation check in credits fallback to avoid wasted requests
- Remove executor-level attemptCreditsFallback and preferCredits machinery
- Restructure 429 decision logic (parse details first, keyword fallback)
- Expand shouldAbort to cover INVALID_ARGUMENT/FAILED_PRECONDITION/500+UNKNOWN
- Support human-readable retry delay parsing (e.g. "1h43m56s")
2026-04-23 13:44:20 +08:00
MoYeRanQianZhi 31934ae04c feat(codex): enable image generation for all Codex upstream requests
Codex CLI gates the built-in image_generation tool behind
AuthMode::Chatgpt (OAuth only). When clients connect via API key
auth through CPA, the tool is absent from requests, making image
generation unavailable through the reverse proxy.

Changes:

1. Inject image_generation tool (codex_executor.go):
   Add ensureImageGenerationTool() that appends
   {"type":"image_generation","output_format":"png"} to the tools
   array if not already present. Applied to all three execution
   paths: Execute, executeCompact, and ExecuteStream.

2. Route aliases for Codex CLI direct access (server.go):
   Add /backend-api/codex/responses routes that map to the same
   OpenAI Responses API handlers as /v1/responses. This allows
   Codex CLI to connect via chatgpt_base_url config while keeping
   AuthMode::Chatgpt, which enables the built-in image_generation
   tool on the client side.

3. Unit tests (codex_executor_imagegen_test.go):
   Cover no-tools, existing tools, already-present, empty array,
   and mixed built-in tool scenarios.
2026-04-23 01:24:40 +08:00
Luis Pater a188159632 fix(handlers): remove references to unsupported n parameter in OpenAI image handlers 2026-04-22 21:28:17 +08:00
Luis Pater fd71960c3e fix(handlers): remove handling of unsupported n parameter in OpenAI image handlers 2026-04-22 21:12:50 +08:00
Luis Pater e935196df4 feat(models): add hardcoded GPT-Image-2 model support in Codex
- Added `GPT-Image-2` as a built-in model to avoid dependency on remote updates for Codex.
- Updated model tier functions (`CodexFree`, `CodexTeam`, etc.) to include built-in models via `WithCodexBuiltins`.
- Introduced new handlers for image generation and edit operations under `OpenAIAPIHandler`.
- Extended tests to validate 503 response for unsupported image model requests.
2026-04-22 20:51:13 +08:00
Luis Pater 4fc2c619fb feat(models): add Kimi K2.6 model entry to registry JSON 2026-04-21 20:53:03 +08:00
Luis Pater 8ced7a548f Merge pull request #2834 from muzhi1991/fix/openai-compat-host-header
fix(util): forward custom Host header to upstream
2026-04-21 20:29:14 +08:00
Luis Pater 3444820958 Merge pull request #2939 from stringer07/fix/codex-stream-output-backfill
fix(codex): backfill streaming response output
2026-04-21 20:18:57 +08:00
Luis Pater 1716a845eb feat(api): add support for HEAD requests to /healthz endpoint
- Refactored `/healthz` handler to support `HEAD` requests alongside `GET`.
- Updated tests to include validation for `HEAD` requests with expected status and empty body.

Closes: #2929
2026-04-21 20:16:18 +08:00
stringer07 b6781d69be perf(codex): avoid repeated output patch writes 2026-04-21 16:29:54 +08:00
stringer07 bb8408cef5 fix(codex): backfill streaming response output 2026-04-21 16:03:56 +08:00
Luis Pater e6866ff19c feat(auth): add refresh backoff for ineffective token updates
- Introduced `refreshIneffectiveBackoff` to prevent tight-looping in auto-refresh when token refresh fails to update expiry.
- Adjusted refresh logic to apply backoff when `shouldRefresh` evaluates true.

Closes: #2830
2026-04-20 15:40:43 +08:00
RCD 2ebbb59670 chore: merge upstream CLIProxyAPI v6.9.30
# Conflicts:
#	README.md
#	README_CN.md
#	README_JA.md
2026-04-20 12:48:28 +07:00
Luis Pater 8f4a4eabfc feat(docs): add VisionCoder sponsorship details and optimize external links
- Added VisionCoder sponsorship information to `README.md`, `README_CN.md`, and `README_JA.md`.
- Updated external links to include `target="_blank"` for improved user experience.
- Added new logo asset `visioncoder.png` for README use.
2026-04-19 23:00:09 +08:00
Luis Pater e05abec01f Merge pull request #2898 from octo-patch/fix/issue-2866-remove-obsolete-1m-beta-header
fix(executor): drop obsolete context-1m-2025-08-07 beta header
2026-04-19 11:46:21 +08:00
octo-patch f4eb16102b fix(executor): drop obsolete context-1m-2025-08-07 beta header (fixes #2866)
Anthropic has moved the 1M-context-window feature to General Availability,
so the context-1m-2025-08-07 beta flag is no longer accepted and now causes
400 Bad Request errors when forwarded upstream.

Remove the X-CPA-CLAUDE-1M detection and the corresponding injection of the
now-invalid beta header.  Also drop the unused net/textproto import that was
only needed for the header-key lookup.
2026-04-19 10:38:16 +08:00
Luis Pater 86c856f56f feat(translator): add partial and full image generation support in Codex-GPT and Codex-Gemini flows
- Introduced `LastImageHashByItemID` in Codex-GPT and `LastImageHashByID` in Codex-Gemini for deduplication of generated images.
- Added support for handling `partial_image` and `image_generation_call` types, with inline data embedding for Gemini and URL payload conversion for GPT.
- Extended unit tests to verify image handling in both streaming and non-streaming modes.
2026-04-19 03:21:59 +08:00
RCD 2221b8e557 chore: merge upstream CLIProxyAPI v6.9.29 2026-04-18 23:28:27 +07:00
Supra4E8C c6baa64b4e Merge pull request #2892 from router-for-me/fix-provider
feat(api): integrate auth index into key retrieval endpoints for Gemi…
2026-04-18 17:24:43 +08:00
Supra4E8C a64141a9a6 fix(tests): remove obsolete config_auth_index_test file 2026-04-18 17:22:16 +08:00
Supra4E8C c26936e2e6 fix(management): stabilize auth-index mapping 2026-04-18 17:12:14 +08:00
Supra4E8C 894baad829 feat(api): integrate auth index into key retrieval endpoints for Gemini, Claude, Codex, OpenAI, and Vertex 2026-04-18 16:44:33 +08:00
muzhi1991 eba561bf6f fix(util): also keep Host in header map for synthetic requests
Addressing the P1 note from the Codex reviewer: applyCustomHeaders is
also called with a synthetic &http.Request{Header: ...} from the
websockets executors (aistudio_executor.go, codex_websockets_executor.go),
which forward only the header map. The previous continue meant a custom
Host was dropped from that map, regressing virtual-host overrides on
those flows. Mirror the value to both r.Host (for real net/http) and
r.Header (for header-map-only consumers).
2026-04-17 09:28:59 +08:00
hkfires da43f63735 fix(tests): update Gemini family test case numbers for consistency 2026-04-17 08:43:19 +08:00
hkfires d9a3b3e5f3 fix(tests): update model lookup references and enhance Claude executor tests 2026-04-17 08:32:07 +08:00
RCD 7ec328f952 chore: merge upstream CLIProxyAPI v6.9.28 2026-04-17 07:04:22 +07:00
Luis Pater 5dcca69e8c feat(models): add Claude Opus 4.7 model entry to registry JSON 2026-04-17 01:08:19 +08:00
Luis Pater f5dc6483d5 chore: remove iFlow-related modules and dependencies
- Deleted `iflow` provider implementation, including thinking configuration (`apply.go`) and authentication modules.
- Removed iFlow-specific tests, executors, and helpers across SDK and internal components.
- Updated all references to exclude iFlow functionality.
2026-04-17 01:07:12 +08:00
Luis Pater d949921143 feat(auth): add proxy URL override support to auth constructors and executors
- Introduced `WithProxyURL` variants for `CodexAuth`, `ClaudeAuth`, `IFlowAuth`, and `DeviceFlowClient`.
- Updated executors to use proxy-aware constructors for improved configurability.
- Added unit tests to validate proxy override precedence and functionality.

Closes: #2823
2026-04-16 22:11:39 +08:00
Luis Pater 7b03f04670 fix(handlers): include execution session metadata and skip idempotency key when absent
- Refactored `requestExecutionMetadata` to handle empty `Idempotency-Key` gracefully.
- Added test to validate metadata inclusion of execution session without idempotency key.
2026-04-16 21:44:32 +08:00
muzhi1991 8f9e6622b0 fix(util): forward custom Host header to upstream
Custom headers configured under openai-compatibility (and any other
provider passing through applyCustomHeaders) were silently dropped for
the Host key, because Go's net/http reads the wire Host from
req.Host, not req.Header["Host"]. As a result, virtual-host routed
upstreams (e.g. LiteLLM behind an ingress) saw the base-url's host
instead of the user-configured override and returned 404.

Detect the Host key with http.CanonicalHeaderKey and assign it to
req.Host so it is actually written on the wire. Other headers continue
to use Header.Set as before.

Fixes #2833
2026-04-16 20:45:37 +08:00
RCD 71be5e897b chore: merge upstream CLIProxyAPI v6.9.27 2026-04-16 09:00:13 +07:00
hkfires 1267fddf61 fix(docker-build): improve argument handling and error messaging for usage option 2026-04-16 09:19:03 +08:00
Luis Pater ba454dbfbf Merge pull request #2817 from sususu98/fix/antigravity-strip-billing-header
fix(antigravity): strip billing header from system instruction before upstream call
2026-04-16 02:46:05 +08:00
Luis Pater d1508ca030 Merge pull request #2816 from sususu98/feat/session-affinity
feat(session-affinity): add session-sticky routing for multi-account load balancing
2026-04-16 02:45:31 +08:00
sususu98 d4a6a5ae15 fix(antigravity): strip billing header from system instruction before upstream call
The x-anthropic-billing-header block in the Claude system array is
client-internal metadata and should not be forwarded to the Gemini
upstream as part of systemInstruction.parts.
2026-04-16 00:19:01 +08:00
sususu98 7c24d54ca8 feat(session-affinity): add session-sticky routing for multi-account load balancing
When multiple auth credentials are configured, requests from the same
session are now routed to the same credential, improving upstream prompt
cache hit rates and maintaining context continuity.

Core components:
- SessionAffinitySelector: wraps RoundRobin/FillFirst selectors with
  session-to-auth binding; automatic failover when bound auth is
  unavailable, re-binding via the fallback selector for even distribution
- SessionCache: TTL-based in-memory cache with background cleanup
  goroutine, supporting per-session and per-auth invalidation
- StoppableSelector interface: lifecycle hook for selectors holding
  resources, called during Manager.StopAutoRefresh()

Session ID extraction priority (extractSessionIDs):
1. metadata.user_id with Claude Code session format (old
   user_{hash}_session_{uuid} and new JSON {session_id} format)
2. X-Session-ID header (generic client support)
3. metadata.user_id (non-Claude format, used as-is)
4. conversation_id field
5. Stable FNV hash from system prompt + first user/assistant messages
   (fallback for clients with no explicit session ID); returns both a
   full hash (primaryID) and a short hash without assistant content
   (fallbackID) to inherit bindings from the first turn

Multi-format message hash covers OpenAI messages, Claude system array,
Gemini contents/systemInstruction, and OpenAI Responses API input items
(including inline messages with role but no type field).

Configuration (config.yaml routing section):
- session-affinity: bool (default false)
- session-affinity-ttl: duration string (default "1h")
- claude-code-session-affinity: bool (deprecated, alias for above)
All three fields trigger selector rebuild on config hot reload.

Side effect: Idempotency-Key header is no longer auto-generated with a
random UUID when absent — only forwarded when explicitly provided by the
client, to avoid polluting session hash extraction.
2026-04-16 00:18:47 +08:00
Luis Pater a4c1e32ff6 chore(models): remove outdated GPT-5 and related model entries from registry JSON 2026-04-15 20:37:32 +08:00
Luis Pater f56cf42461 Merge pull request #2800 from sususu98/fix/antigravity-max-output-tokens-cap
fix(antigravity): cap maxOutputTokens using registry max_completion_tokens
2026-04-15 20:35:11 +08:00
Luis Pater 3dea1da249 Merge pull request #2782 from sususu98/fix/strip-invalid-signature-thinking-blocks
fix(antigravity): use E-prefixed fake signature in strict bypass test
2026-04-15 20:34:32 +08:00
Luis Pater 8fac29631d chore: remove Qwen support from SDK and internal components
- Deleted `QwenAuthenticator`, internal `qwen_auth`, and `qwen_executor` implementations.
- Removed all Qwen-related OAuth flows, token handling, and execution logic.
- Cleaned up dependencies and references to Qwen across the codebase.
2026-04-15 12:16:08 +08:00
sususu98 8fecd625d2 fix(antigravity): cap maxOutputTokens using registry max_completion_tokens
Claude models on antigravity have a 64000 token output limit but
max_tokens from downstream requests was passed through uncapped,
causing 400 INVALID_ARGUMENT from Google when clients sent 128000.
2026-04-15 11:57:55 +08:00
sususu98 10b55b5ddd fix(antigravity): use E-prefixed fake signature in strict bypass test
The strict bypass test used testGeminiSignaturePayload() which produces
a base64 string starting with 'C'. Since StripInvalidSignatureThinkingBlocks
now strips all non-E/R signatures unconditionally, the test payload was
stripped before reaching ValidateClaudeBypassSignatures, causing the test
to pass the request through instead of rejecting it with 400.

Replace with testFakeClaudeSignature() which produces a base64 string
starting with 'E' (valid at the lightweight check) but with invalid
protobuf content (no valid field 2), so strict mode correctly rejects
it at the deep validation layer.
2026-04-14 15:46:02 +08:00
sususu98 41ae2c81e7 fix(antigravity): discard thinking blocks with non-Claude-format signatures
Proxy-generated thinking blocks may carry hex hashes or other non-Claude
signatures (e.g. "d5cb9cd0823142109f451861") from Gemini responses. These
are now discarded alongside empty-signature blocks during the strip phase,
before validation runs. Valid Claude signatures always start with 'E' or 'R'
(after stripping any cache prefix).
2026-04-14 15:14:48 +08:00
sususu98 278a89824c fix(antigravity): strip thinking blocks with empty signatures instead of rejecting
Thinking blocks with empty signatures come from proxy-generated
responses (Antigravity/Gemini routed as Claude). These should be
silently dropped from the request payload before forwarding, not
rejected with 400. Fixes 10 "missing thinking signature" errors.
2026-04-14 15:14:48 +08:00
RCD 06c3e95454 chore: update upstream markers for v6.9.24 2026-04-13 05:29:08 +07:00
RCD a6cc1a2e71 Merge tag 'v6.9.24' into sync-upstream-v6.9.23-to-v6.9.24 2026-04-13 05:28:14 +07:00
sususu98 c4459c4346 Merge pull request #2724 from sususu98/fix/skip-schema-cleanup-empty-tools
fix(antigravity): skip full schema cleanup for empty tool requests
2026-04-12 14:05:47 +08:00
sususu98 61e0447f92 Merge pull request #2723 from sususu98/fix/drop-redacted-thinking-blocks
fix(antigravity): drop redacted thinking blocks with empty text
2026-04-12 14:05:41 +08:00
sususu98 1dc3018fd6 Merge pull request #2716 from sususu98/pr/antigravity-bypass-log-noise
fix(antigravity): reduce bypass mode log noise
2026-04-12 14:05:34 +08:00
sususu98 26fd3eff03 Merge pull request #2715 from sususu98/pr/antigravity-32mb-bypass-signatures
fix(antigravity): allow 32MB bypass signatures
2026-04-12 14:05:27 +08:00
Luis Pater 5bfaf8086b feat(auth): add configurable worker pool size for auto-refresh loop
- Introduced `auth-auto-refresh-workers` config option to override default concurrency.
- Updated `authAutoRefreshLoop` to support customizable worker counts.
- Enhanced token refresh scheduling flexibility by aligning worker pool with runtime configurations.
2026-04-12 13:56:05 +08:00
Luis Pater 6c0a1efd71 refactor(auth): simplify auth directory scanning and improve JSON processing logic
- Replaced `filepath.Walk` with `os.ReadDir` for cleaner directory traversal.
- Fixed `isAuthJSON` check to use `filepath.Dir` for directory comparison.
- Updated auth hash cache generation and file synthesis to improve readability and maintainability.
2026-04-12 13:32:03 +08:00
sususu98andSisyphus f5ed5c7453 fix(antigravity): skip full schema cleanup for empty tool requests
Avoid whole-payload schema sanitization when translated Antigravity requests have no actual tool schemas, including missing and empty tools arrays. Add regression coverage so image-heavy no-tool requests keep bypassing the old memory amplification path.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-12 12:51:42 +08:00
sususu98 65158cce46 fix(antigravity): drop redacted thinking blocks with empty text
Antigravity wraps empty thinking text into a prompt-caching-scope
object that omits the required inner "thinking" field, causing 400
"messages.N.content.0.thinking.thinking: Field required" when Claude
Max requests are routed through Antigravity in bypass mode.
2026-04-12 12:30:43 +08:00
RCD 9cc006c941 chore: merge upstream CLIProxyAPI v6.9.23 2026-04-12 02:15:21 +07:00
Luis Pater a583463d60 feat(auth): implement auto-refresh loop for managing auth token schedule
- Introduced `authAutoRefreshLoop` to handle token refresh scheduling.
- Replaced semaphore-based refresh logic in `Manager` with the new loop.
- Added unit tests to verify refresh schedule logic and edge cases.
2026-04-12 02:06:40 +08:00
sususu98andSisyphus 8ed290c1c4 fix(antigravity): reduce bypass mode log noise
Keep cache-disable visibility at info level while suppressing duplicate state-change logs and moving strict-mode chatter down to debug.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-12 00:52:41 +08:00
sususu98andSisyphus 727221df2e fix(antigravity): allow 32MB bypass signatures
Raise the local bypass-signature ceiling so long Claude thinking signatures are not rejected before request translation, and keep the oversized-signature test cheap to execute.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-12 00:51:53 +08:00
Luis Pater 0ab1f5412f fix(executor): handle 429 Retry-After header and default retry logic for quota exhaustion
- Added proper parsing of `Retry-After` headers for 429 responses.
- Set default retry duration when "disable cooling" is active on quota exhaustion.
- Updated tests to verify `Retry-After` handling and default behavior.
2026-04-11 21:04:55 +08:00
Luis Pater 9ded75d335 Merge pull request #2702 from AllenReder/docs/add-quota-inspector
docs(README): add CLIproxyAPI Quota Inspector to community projects list
2026-04-11 16:42:02 +08:00
Allen Yi f135fdf7fc docs: clarify codex quota window wording in README locales 2026-04-11 16:39:32 +08:00
Luis Pater 828df80088 refactor(executor): remove immediate retry with token refresh on 429 for Qwen and update tests accordingly 2026-04-11 16:35:18 +08:00
Allen Yi c585caa0ce docs: fix CLIProxyAPI Quota Inspector naming and link casing 2026-04-11 16:22:45 +08:00
Allen Yi 5bb69fa4ab docs: refine CLIproxyAPI Quota Inspector description in all README locales 2026-04-11 15:22:27 +08:00
RCD 85267e7379 fix: resolve v6.9.22 cache metric cycles 2026-04-11 00:10:43 +07:00
RCD 45dc09d487 chore: merge upstream CLIProxyAPI v6.9.22 2026-04-11 00:06:28 +07:00
Luis Pater 5ab9afac83 fix(executor): handle OAuth tool name remapping with rename detection and add tests
Closes: #2656
2026-04-10 21:54:59 +08:00
Luis Pater 65ce86338b fix(executor): implement immediate retry with token refresh on 429 for Qwen and add associated tests
Closes: #2661
2026-04-10 21:12:03 +08:00
Chén Mù 2a97037d7b Merge pull request #2670 from sususu98/feat/antigravity-prefer-prod-url
feat(antigravity): prefer prod URL as first priority
2026-04-10 19:43:27 +08:00
sususu98 d801393841 feat(antigravity): prefer prod URL as first priority
Promote cloudcode-pa.googleapis.com to the first position in the
fallback order, with daily and sandbox URLs as fallbacks.
2026-04-10 19:37:56 +08:00
Luis Pater b2c0cdfc88 Merge pull request #2621 from wykk-12138/fix/oauth-extra-usage-detection
fix(claude): prevent OAuth extra-usage billing via tool name fingerprinting and system prompt cloaking
2026-04-10 10:29:27 +08:00
Luis Pater f32c8c9620 fix(handlers): update listener to bind on all interfaces instead of localhost
Fixed: #2640
2026-04-10 07:24:34 +08:00
wykk-12138andSisyphus 0f45d89255 fix(claude): address PR review feedback for OAuth cloaking
- Use buildTextBlock for billing header to avoid raw JSON string interpolation
- Fix empty array edge case in prependToFirstUserMessage
- Allow remapOAuthToolNames to process messages even without tools array
- Move claude_system_prompt.go to helps/ per repo convention
- Export prompt constants (ClaudeCode* prefix) for cross-package access

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-10 00:07:11 +08:00
wykk-12138 96056d0137 Merge remote-tracking branch 'upstream/main' into fix/oauth-extra-usage-detection 2026-04-09 22:59:31 +08:00
wykk-12138andSisyphus f780c289e8 fix(claude): map question/skill to TitleCase instead of removing them
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-09 22:28:00 +08:00
wykk-12138andSisyphus ac36119a02 fix(claude): preserve OAuth tool renames when filtering tools
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-09 22:20:15 +08:00
Luis Pater 39dc4557c1 Merge pull request #2412 from sususu98/feat/signature-cache-toggle
feat: configurable signature cache toggle for Antigravity/Claude thinking blocks
2026-04-09 21:54:47 +08:00
ZTXBOSS666 30e94b6792 fix(antigravity): refine 429 handling and credits fallback
Includes: restore SDK docs under docs/; update antigravity executor credits tests; gofmt.
2026-04-09 21:48:32 +08:00
sususu98 38f0ae5970 docs(antigravity): document signature validation spec alignment
Add package-level comment documenting the protobuf tree structure,
base64 encoding equivalence proof, output dimensions, and spec
section references. Remove unreachable legacy_vertex_group dead code.
2026-04-09 21:12:40 +08:00
sususu98 cf249586a9 feat(antigravity): configurable signature cache with bypass-mode validation
Antigravity 的 Claude thinking signature 处理新增 cache/bypass 双模式,
并为 bypass 模式实现按 SIGNATURE-CHANNEL-SPEC.md 的签名校验。

新增 antigravity-signature-cache-enabled 配置项(默认 true):
- cache mode(true):使用服务端缓存的签名,行为与原有逻辑完全一致
- bypass mode(false):直接使用客户端提供的签名,经过校验和归一化

支持配置热重载,运行时可切换模式。

校验流程:
1. 剥离历史 cache-mode 的 'modelGroup#' 前缀(如 claude#Exxxx → Exxxx)
2. 首字符必须为 'E'(单层编码)或 'R'(双层编码),否则拒绝
3. R 开头:base64 解码 → 内层必须以 'E' 开头 → 继续单层校验
4. E 开头:base64 解码 → 首字节必须为 0x12(Claude protobuf 标识)
5. 所有合法签名归一化为 R 形式(双层 base64)发往 Antigravity 后端

非法签名处理策略:
- 非严格模式(默认):translator 静默丢弃无签名的 thinking block
- 严格模式(antigravity-signature-bypass-strict: true):
  executor 层在请求发往上游前直接返回 HTTP 400

按 SIGNATURE-CHANNEL-SPEC.md 解析 Claude 签名的完整 protobuf 结构:
- Top-level Field 2(容器)→ Field 1(渠道块)
- 渠道块提取:channel_id (Field 1)、infrastructure (Field 2)、
  model_text (Field 6)、field7 (Field 7)
- 计算 routing_class、infrastructure_class、schema_features
- 使用 google.golang.org/protobuf/encoding/protowire 解析

- resolveThinkingSignature 拆分为 resolveCacheModeSignature / resolveBypassModeSignature
- hasResolvedThinkingSignature:mode-aware 签名有效性判断
  (cache: len>=50 via HasValidSignature,bypass: non-empty)
- validateAntigravityRequestSignatures:executor 预检,
  仅在 bypass + strict 模式下拦截非法签名返回 400
- 响应侧签名缓存逻辑与 cache mode 集成
- Cache mode 行为完全保留:无 '#' 前缀的原生签名静默丢弃
2026-04-09 21:12:40 +08:00
Luis Pater 1dba2d0f81 fix(handlers): add base URL validation and improve API key deletion tests 2026-04-09 20:51:54 +08:00
Luis Pater 730809d8ea fix(auth): preserve and restore ready view cursors during index rebuilds 2026-04-09 20:26:16 +08:00
wykk-12138 e8d1b79cb3 fix(claude): remap OAuth tool names to Claude Code style to avoid third-party fingerprint detection
A/B testing confirmed that Anthropic uses tool name fingerprinting to detect
third-party clients on OAuth traffic. OpenCode-style lowercase names like
'bash', 'read', 'todowrite' trigger extra-usage billing, while Claude Code
TitleCase names like 'Bash', 'Read', 'TodoWrite' pass through normally.

Changes:
- Add oauthToolRenameMap: maps lowercase tool names to Claude Code equivalents
- Add oauthToolsToRemove: removes 'question' and 'skill' (no Claude Code counterpart)
- remapOAuthToolNames: renames tools, removes blacklisted ones, updates tool_choice and messages
- reverseRemapOAuthToolNames/reverseRemapOAuthToolNamesFromStreamLine: reverse map for responses
- Apply in Execute(), ExecuteStream(), and CountTokens() for OAuth token requests
2026-04-09 20:15:16 +08:00
Luis Pater 5e81b65f2f fix(auth, executor): normalize Qwen base URL, adjust RefreshLead duration, and add tests 2026-04-09 18:07:07 +08:00
github-actions[bot] 5775476bc0 chore: sync CLIProxyAPI v6.9.15-v6.9.18 2026-04-09 09:15:47 +00:00
wykk-12138andSisyphus 7e8e2226a6 fix(claude): reduce forwarded OAuth prompt to minimal tool reminder
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-09 17:12:07 +08:00
wykk-12138andSisyphus f0c20e852f fix(claude): remove invalid cache_control scope from static system block
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-09 17:00:04 +08:00
wykk-12138 7cdf8e9872 fix(claude): sanitize forwarded third-party prompts for OAuth cloaking
Only for Claude OAuth requests, sanitize forwarded system-prompt context before
it is prepended into the first user message. This preserves neutral task/tool
instructions while removing OpenCode branding, docs links, environment banners,
and product-specific workflow sections that still triggered Anthropic extra-usage
classification after top-level system[] cloaking.
2026-04-09 16:45:29 +08:00
wykk-12138 e2e3c7dde0 fix: remove invalid org scope and match Claude Code block layout 2026-04-09 14:09:52 +08:00
wykk-12138 9e0ab4d116 fix: build cache_control JSON manually to avoid sjson map marshaling 2026-04-09 14:03:23 +08:00
wykk-12138 8783caf313 fix: buildTextBlock cache_control sjson path issue
sjson treats 'cache_control.type' as nested path, creating
{ephemeral: {scope: org}} instead of {type: ephemeral, scope: org}.
Pass the whole map to sjson.SetBytes as a single value.
2026-04-09 13:58:04 +08:00
wykk-12138 f6f4640c5e fix: use sjson to build system blocks, avoid raw newlines in JSON
The previous commit used fmt.Sprintf with %s to insert multi-line string
constants into JSON strings. Go raw string literals contain actual newline
bytes, which produce invalid JSON (control characters in string values).

Replace with buildTextBlock() helper that uses sjson.SetBytes to properly
escape text content for JSON serialization.
2026-04-09 13:50:49 +08:00
wykk-12138 613fe6768d fix(executor): inject full Claude Code system prompt blocks with proper cache scopes
Previous fix only injected billing header + agent identifier (2 blocks).
Anthropic's updated detection now validates system prompt content depth:
- Block count (needs 4-6 blocks, not 2)
- Cache control scopes (org for agent, global for core prompt)
- Presence of known Claude Code instruction sections

Changes:
- Add claude_system_prompt.go with extracted Claude Code v2.1.63 system prompt
  sections (intro, system instructions, doing tasks, tone & style, output efficiency)
- Rewrite checkSystemInstructionsWithSigningMode to build 5 system blocks:
  [0] billing header (no cache_control)
  [1] agent identifier (cache_control: ephemeral, scope=org)
  [2] core intro prompt (cache_control: ephemeral, scope=global)
  [3] system instructions (no cache_control)
  [4] doing tasks (no cache_control)
- Third-party client system instructions still moved to first user message

Follow-up to 69b950db4c
2026-04-09 12:58:50 +08:00
Luis Pater ad8e3964ff fix(auth): add retry logic for 429 status with Retry-After and improve testing 2026-04-09 07:07:19 +08:00
Luis Pater 941334da79 fix(auth): handle OAuth model alias in retry logic and refine Qwen quota handling 2026-04-09 03:44:19 +08:00
Luis Pater d54f816363 fix(executor): update Qwen user agent and enhance header configuration 2026-04-09 01:45:52 +08:00
wykk-12138 69b950db4c fix(executor): fix OAuth extra usage detection by Anthropic API
Three changes to avoid Anthropic's content-based system prompt validation:

1. Fix identity prefix: Use 'You are Claude Code, Anthropic's official CLI
   for Claude.' instead of the SDK agent prefix, matching real Claude Code.

2. Move user system instructions to user message: Only keep billing header +
   identity prefix in system[] array. User system instructions are prepended
   to the first user message as <system-reminder> blocks.

3. Enable cch signing for OAuth tokens by default: The xxHash64 cch integrity
   check was previously gated behind experimentalCCHSigning config flag.
   Now automatically enabled when using OAuth tokens.

Related: router-for-me/CLIProxyAPI#2599
2026-04-09 00:06:38 +08:00
hkfires 343a2fc2f7 docs: update AGENTS.md for improved clarity and detail in commands and architecture 2026-04-08 12:33:16 +08:00
Luis Pater 12b967118b Merge pull request #2592 from router-for-me/tests
fix(tests): update test cases
2026-04-08 11:57:15 +08:00
Luis Pater 70efd4e016 chore: add workflow to retarget main PRs to dev automatically 2026-04-08 10:35:49 +08:00
Luis Pater f5aa68ecda chore: add workflow to prevent AGENTS.md modifications in pull requests 2026-04-08 10:12:51 +08:00
hkfires d390b95b76 fix(tests): update test cases 2026-04-08 08:53:50 +08:00
Luis Pater d1f6224b70 Merge pull request #2569 from LucasInsight/fix/record-zero-usage
fix: record zero usage
2026-04-08 08:13:11 +08:00
Luis Pater fcc59d606d fix(translator): add unit tests to validate output_item.done fallback logic for Gemini and Claude 2026-04-08 03:54:15 +08:00
Luis Pater 91e7591955 fix(executor): add transient 429 resource exhausted handling with retry logic 2026-04-08 02:48:53 +08:00
Luis Pater c8b7e2b8d6 fix(executor): ensure empty stream completions use output_item.done as fallback
Fixed: #2583
2026-04-07 18:21:12 +08:00
DragonFSKY 4ca00f7983 fix(websocket): gate compact replay by downstream support 2026-04-07 14:25:05 +08:00
DragonFSKY d2d0e6f6a1 fix(websocket): narrow compact replay detection 2026-04-07 14:23:44 +08:00
DragonFSKY a0fe273081 fix(websocket): skip stale state merge after client-side compact
After a Codex CLI compact, the client sends a full conversation
transcript (with compaction items or assistant messages) as input.
Previously, normalizeResponseSubsequentRequest() unconditionally
merged this with stale lastRequest/lastResponseOutput, breaking
function_call/function_call_output pairings and causing 400 errors
("No tool output found for function call").

Add inputContainsFullTranscript() heuristic that detects compaction
items (type=compaction/compaction_summary) or assistant messages in
the input array, and bypasses the merge when a full transcript is
present.

Fixes #2207
2026-04-07 14:22:53 +08:00
Luis Pater cad45ffa33 Merge pull request #2578 from LemonZuo/feat_socks5h
feat: support socks5h scheme for proxy settings
2026-04-07 09:57:18 +08:00
Luis Pater 6a27bceec0 Merge pull request #2576 from zilianpn/fix/disable-cooling-auth-errors
fix(auth): honor disable-cooling and enrich no-auth errors
2026-04-07 09:56:25 +08:00
Lemon 163d68318f feat: support socks5h scheme for proxy settings 2026-04-07 07:46:11 +08:00
zilianpn 0ea768011b fix(auth): honor disable-cooling and enrich no-auth errors 2026-04-07 01:12:13 +08:00
Michael 8b9dbe10f0 fix: record zero usage 2026-04-06 20:19:42 +08:00
Code_GandSisyphus 29e32aaab9 fix(executor): route Claude refresh through retry-aware auth
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-06 17:16:42 +09:00
Code_GandSisyphus 6431cec7d3 fix(claude-auth): dedupe OAuth refresh and honor 429 backoff
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-04-06 17:16:15 +09:00
Luis Pater 9f5bdfaa31 Merge pull request #2531 from jamestut/openai-vertex-token-usage-fix
Fix missing `response.completed.usage` for late-usage OpenAI-compatible streams
2026-04-06 09:30:49 +08:00
Luis Pater 9eabdd09db Merge pull request #2522 from aikins01/fix/strip-tool-use-signature
fix(amp): strip signature from tool_use blocks before forwarding to Claude
2026-04-06 09:30:14 +08:00
Luis Pater c3f8dc362e Merge pull request #2491 from mpfo0106/feature/claude-code-safe-alignment-sentinels
test(claude): add compatibility sentinels and centralize builtin fallback handling
2026-04-06 09:27:08 +08:00
Luis Pater b85120873b Merge pull request #2332 from RaviTharuma/fix/claude-thinking-signature
fix: preserve Claude thinking signatures in Codex translator
2026-04-06 09:25:06 +08:00
Luis Pater 6f58518c69 docs(readme): remove redundant GITSTORE_GIT_BRANCH description in README files 2026-04-06 09:23:04 +08:00
Luis Pater 000fcb15fa Merge pull request #2298 from snoyiatk/feat/add-gitstore-branch
feat(gitstore): add support for specifying git branch (via GITSTORE_G…
2026-04-06 09:21:03 +08:00
Luis Pater ea43361492 Merge pull request #2121 from destinoantagonista-wq/main
Reconcile registry model states on auth changes
2026-04-06 09:13:27 +08:00
Luis Pater c1818f197b Merge pull request #1940 from Blue-B/fix/claude-interleaved-thinking-amp-gzip-budget
fix(claude): enable interleaved-thinking beta, decode AMP error gzip, fix budget 400
2026-04-06 09:08:23 +08:00
Aikins Laryea b0653cec7b fix(amp): strip signature from tool_use blocks before forwarding to Claude
ensureAmpSignature injects signature:"" into tool_use blocks so the
Amp TUI does not crash on P.signature.length. when Amp sends the
conversation back, Claude rejects the extra field with 400:
  tool_use.signature: Extra inputs are not permitted

strip the proxy-injected signature from tool_use blocks in
SanitizeAmpRequestBody before forwarding to the upstream API.
2026-04-05 12:26:24 +00:00
Luis Pater 22a1a24cf5 feat(executor): add tests for preserving key order in cache control functions
Added comprehensive tests to ensure key order is maintained when modifying payloads in `normalizeCacheControlTTL` and `enforceCacheControlLimit` functions. Removed unused helper functions and refactored implementations for better readability and efficiency.
2026-04-05 17:58:13 +08:00
RCD e040fdb330 chore: merge upstream CLIProxyAPI v6.9.15
# Conflicts:
#	.gitignore
#	README.md
#	README_CN.md
#	README_JA.md
#	cmd/server/main.go
2026-04-05 13:55:36 +07:00
Luis Pater ada8e2905e feat(api): enhance proxy resolution for API key-based auth
Added comprehensive support for resolving proxy URLs from configuration based on API key and provider attributes. Introduced new helper functions and extended the test suite to validate fallback mechanisms and compatibility cases.
2026-04-05 01:56:34 +08:00
Luis Pater 4ba10531da feat(docs): add Poixe AI sponsorship details to README files
Added Poixe AI sponsorship information, including referral bonuses and platform capabilities, to README files in English, Japanese, and Chinese. Updated assets to include Poixe AI logo.
2026-04-05 01:20:50 +08:00
RCD 81929c06da fix(security): remove unverified management asset fallback (#12) 2026-04-04 21:25:56 +07:00
Luis Pater 3774b56e9f feat(misc): add background updater for Antigravity version caching
Introduce `StartAntigravityVersionUpdater` to periodically refresh the cached Antigravity version using a non-blocking background process. Updated main server flow to initialize the updater.
2026-04-04 22:09:11 +08:00
Luis Pater c2d4137fb9 feat(executor): enhance Qwen system message handling with strict injection and merging rules
Closes: #2537
2026-04-04 21:51:02 +08:00
Luis Pater 2ee938acaf Merge pull request #2535 from rensumo/main
feat: 动态获取 Antigravity User-Agent 版本号
2026-04-04 21:00:47 +08:00
rensumo 8d5e470e1f feat: dynamically fetch antigravity UA version from releases API
Fetch the latest version from the antigravity auto-updater releases
endpoint and cache it for 6 hours. Falls back to 1.21.9 if the API
is unreachable or returns unexpected data.
2026-04-04 14:52:59 +08:00
James 65e9e892a4 Fix missing response.completed.usage for late-usage OpenAI-compatible streams 2026-04-04 05:58:04 +00:00
Luis Pater 8430b28cfa Merge pull request #2526 from rensumo/main
feat: 升级反重力 (antigravity) UA 版本为 1.21.9
2026-04-04 11:32:16 +08:00
rensumo f3ab8f4bc5 chore: update antigravity UA version to 1.21.9 2026-04-04 07:35:08 +08:00
Luis Pater 0e4f189c2e Merge pull request #1302 from dinhkarate/feat(vertex)/add-prefix-field
Feat(vertex): add prefix field
2026-04-04 04:17:12 +08:00
Luis Pater 754b126944 fix(executor): remove commented-out code in QwenExecutor 2026-04-04 02:14:48 +08:00
Luis Pater ae37ccffbf Merge pull request #2520 from Arronlong/main
fix:qwen invalid_parameter_error
2026-04-04 02:13:09 +08:00
RCD d548446ce8 docs(readme): document default config bootstrap 2026-04-04 00:32:55 +07:00
RCD 852642d5ee fix(startup): bootstrap packaged default config 2026-04-04 00:32:36 +07:00
RCD 371bfc3528 docs: record upstream v6.9.12 sync 2026-04-04 00:22:10 +07:00
RCD 9cf230cc40 chore: merge upstream CLIProxyAPI v6.9.12 2026-04-04 00:21:26 +07:00
Luis Pater 42c062bb5b Merge pull request #2509 from adamhelfgott/fix-claude-thinking-temperature
Normalize Claude temperature when thinking is enabled
2026-04-03 23:55:50 +08:00
Luis Pater f389667ec3 Merge pull request #2513 from lonr-6/codex/fix-ws-custom-tool-repair-v2
fix: repair responses websocket custom tool call pairing
2026-04-03 23:45:38 +08:00
Arronlong 29dba0399b Comment out system message check in Qwen executor
fix qwen invalid_parameter_error
2026-04-03 23:07:33 +08:00
Luis Pater a824e7cd0b feat(models): add GPT-5.3, GPT-5.4, and GPT-5.4-mini with enhanced "thinking" levels 2026-04-03 23:05:10 +08:00
Luis Pater adb580b344 feat(security): add configuration to toggle Gemini CLI endpoint access
Closes: #2445
2026-04-03 21:46:49 +08:00
Luis Pater 06405f2129 fix(security): enforce stricter localhost validation for GeminiCLIAPIHandler
Closes: #2445
2026-04-03 21:22:03 +08:00
Kai Wang d1fd2c4ad4 fix: repair websocket custom tool calls 2026-04-03 17:11:44 +08:00
Kai Wang b6c6379bfa fix: repair websocket custom tool calls 2026-04-03 17:11:42 +08:00
Kai Wang 8f0e66b72e fix: repair websocket custom tool calls 2026-04-03 17:11:41 +08:00
Adam Helfgott f63cf6ff7a Normalize Claude temperature for thinking 2026-04-03 03:45:51 -04:00
RCD de8d8cc432 chore: restore executor compatibility wrappers 2026-04-03 13:16:37 +07:00
RCD 3d853cb295 chore: merge upstream CLIProxyAPI v6.9.10 2026-04-03 13:13:41 +07:00
Luis Pater d2419ed49d feat(executor): ensure default system message in QwenExecutor payload 2026-04-03 11:18:48 +08:00
mpfo0106 9b5ce8c64f Keep Claude builtin helpers aligned with the shared helper layout
The review asked for the builtin tool registry helper to live with the rest
of executor support utilities. This moves the registry code into the helps
package, exports the minimal surface executor needs, and keeps behavior tests
with the executor while leaving registry-focused checks with the helper.

Constraint: Requested layout keeps executor helper utilities centralized under internal/runtime/executor/helps
Rejected: Keep the files in executor and reply with rationale | conflicts with requested package organization
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep executor behavior tests near applyClaudeToolPrefix and keep pure registry tests in helps
Tested: go test ./internal/runtime/executor/helps ./internal/runtime/executor -run 'Claude|Builtin|Tool'; go test ./test/...; go test ./...
Not-tested: End-to-end Claude Code direct-connect/session runtime behavior
2026-04-03 00:13:02 +09:00
Duong M. CUONG 058793c73a feat(gitstore): honor configured branch and follow live remote default 2026-04-02 14:44:44 +00:00
Luis Pater ab9ebea592 Merge PR #2474
# Conflicts:
#	internal/api/modules/amp/response_rewriter.go
#	internal/api/modules/amp/response_rewriter_test.go
2026-04-02 22:31:12 +08:00
Luis Pater 7ee37ee4b9 feat: add /healthz endpoint and test coverage for health check
Closes: #2493
2026-04-02 21:56:27 +08:00
Luis Pater 3171d524f0 docs: fix duplicated ProxyPal entry in README files 2026-04-02 21:22:40 +08:00
Luis Pater 3e78a8d500 Merge branch 'main' into dev 2026-04-02 21:21:26 +08:00
Luis Pater fcba912cc4 Merge pull request #2492 from davidwushi1145/main
fix(responses): reassemble split SSE event/data frames before streaming
2026-04-02 21:20:31 +08:00
Luis Pater 7170eeea5f Merge pull request #2454 from buddingnewinsights/add-proxypal-to-readme
docs: add ProxyPal to "Who is with us?" section
2026-04-02 21:18:22 +08:00
Luis Pater e3eb048c7a Merge pull request #2489 from Soein/upstream-pr
fix: 增强 Claude 反代检测对抗能力
2026-04-02 21:16:58 +08:00
Luis Pater a59e92435b Merge pull request #2490 from router-for-me/logs
Refactor websocket logging and error handling
2026-04-02 20:47:31 +08:00
davidwushi1145 108895fc04 Harden Responses SSE framing against partial chunk boundaries
Follow-up review found two real framing hazards in the handler-layer
framer: it could flush a partial `data:` payload before the JSON was
complete, and it could inject an extra newline before chunks that
already began with `\n`/`\r\n`. This commit tightens the framer so it
only emits undelimited events when the buffered `data:` payload is
already valid JSON (or `[DONE]`), skips newline injection for chunks
that already start with a line break, and avoids the heavier
`bytes.Split` path while scanning SSE fields.

The regression suite now covers split `data:` payload chunks,
newline-prefixed chunks, and dropping incomplete trailing data on
flush, so the original Responses fix remains intact while the review
concerns are explicitly locked down.

Constraint: Keep the follow-up limited to handler-layer framing and tests
Rejected: Ignore the review and rely on current executor chunk shapes | leaves partial data payload corruption possible
Rejected: Build a fully generic SSE parser | wider change than needed for the identified risks
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Do not emit undelimited Responses SSE events unless buffered `data:` content is already complete and valid
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers/openai -count=1
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers -count=1
Tested: /tmp/go1.26.1/go/bin/go vet ./sdk/api/handlers/...
Not-tested: Full repository test suite outside sdk/api/handlers packages
2026-04-02 20:39:49 +08:00
davidwushi1145 abc293c642 Prevent malformed Responses SSE frames from breaking stream clients
Line-oriented upstream executors can emit `event:` and `data:` as
separate chunks, but the Responses handler had started terminating
each incoming chunk as a full SSE event. That split `response.created`
into an empty event plus a later data block, which broke downstream
clients like OpenClaw.

This keeps the fix in the handler layer: a small stateful framer now
buffers standalone `event:` lines until the matching `data:` arrives,
preserves already-framed events, and ignores delimiter-only leftovers.
The regression suite now covers split event/data framing, full-event
passthrough, terminal errors, and the bootstrap path that forwards
line-oriented openai-response streams from non-Codex executors too.

Constraint: Keep the fix localized to Responses handler framing instead of patching every executor
Rejected: Revert to v6.9.7 chunk writing | would reintroduce data-only framing regressions
Rejected: Patch each line-oriented executor separately | duplicates fragile SSE assembly logic
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Do not assume incoming Responses stream chunks are already complete SSE events; preserve handler-layer reassembly for split `event:`/`data:` inputs
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers/openai -count=1
Tested: /tmp/go1.26.1/go/bin/go test ./sdk/api/handlers -count=1
Tested: /tmp/go1.26.1/go test ./sdk/api/handlers/... -count=1
Tested: /tmp/go1.26.1/go/bin/go vet ./sdk/api/handlers/...
Tested: Temporary patched server on 127.0.0.1:18317 -> /v1/models 200, /v1/responses non-stream 200, /v1/responses stream emitted combined `event:` + `data:` frames
Not-tested: Full repository test suite outside sdk/api/handlers packages
2026-04-02 20:26:42 +08:00
mpfo0106 da3a498a28 Keep Claude Code compatibility work low-risk and reviewable
This change stops short of broader Claude Code runtime alignment and instead
hardens two safe edges: builtin tool prefix handling and source-informed
sentinel coverage for future drift checks.

Constraint: Must preserve existing default behavior for current users
Rejected: Implement control-plane/session alignment now | too much runtime risk for a first slice
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Treat the new fixtures as compatibility sentinels, not a full Claude Code schema contract
Tested: go test ./test/...; go test ./sdk/translator/...; go test ./internal/runtime/executor -run 'Claude|Builtin|Tool'; go test ./...
Not-tested: End-to-end Claude Code direct-connect/session runtime behavior
2026-04-02 20:35:39 +09:00
pzy bb44671845 fix: 修复反代检测对抗的 3 个问题
- computeFingerprint 使用 rune 索引替代字节索引,修复多字节字符指纹不匹配
- utls Chrome TLS 指纹仅对 Anthropic 官方域名生效,自定义 base_url 走标准 transport
- IPv6 地址使用 net.JoinHostPort 正确拼接端口
2026-04-02 19:12:55 +08:00
Luis Pater 09e480036a feat(auth): add support for managing custom headers in auth files
Closes #2457
2026-04-02 19:11:09 +08:00
pzy 249f969110 fix: Claude API 请求使用 utls Chrome TLS 指纹
Claude executor 的 API 请求之前使用 Go 标准库 crypto/tls,JA3 指纹
与真实 Claude Code(Bun/BoringSSL)不匹配,可被 Cloudflare 识别。

- 新增 helps/utls_client.go,封装 utls Chrome 指纹 + HTTP/2 + 代理支持
- Claude executor 的 4 处 NewProxyAwareHTTPClient 替换为 NewUtlsHTTPClient
- 其他 executor(Gemini/Codex/iFlow 等)不受影响,仍用标准 TLS
- 非 HTTPS 请求自动回退到标准 transport
2026-04-02 19:09:56 +08:00
hkfires 4f8acec2d8 refactor(logging): centralize websocket handshake recording 2026-04-02 18:39:32 +08:00
hkfires 34339f61ee Refactor websocket logging and error handling
- Introduced new logging functions for websocket requests, handshakes, errors, and responses in `logging_helpers.go`.
- Updated `CodexWebsocketsExecutor` to utilize the new logging functions for improved clarity and consistency in websocket operations.
- Modified the handling of websocket upgrade rejections to log relevant metadata.
- Changed the request body key to a timeline body key in `openai_responses_websocket.go` to better reflect its purpose.
- Enhanced tests to verify the correct logging of websocket events and responses, including disconnect events and error handling scenarios.
2026-04-02 17:30:51 +08:00
pzy 4045378cb4 fix: 增强 Claude 反代检测对抗能力
基于 Claude Code v2.1.88 源码分析,修复多个可被 Anthropic 检测的差距:

- 实现消息指纹算法(SHA256 盐值 + 字符索引),替代随机 buildHash
- billing header cc_version 从设备 profile 动态取版本号,不再硬编码
- billing header cc_entrypoint 从客户端 UA 解析,支持 cli/vscode/local-agent
- billing header 新增 cc_workload 支持(通过 X-CPA-Claude-Workload 头传入)
- 新增 X-Claude-Code-Session-Id 头(每 apiKey 缓存 UUID,TTL=1h)
- 新增 x-client-request-id 头(仅 api.anthropic.com,每请求 UUID)
- 补全 4 个缺失的 beta flags(structured-outputs/fast-mode/redact-thinking/token-efficient-tools)
- OAuth scope 对齐 Claude Code 2.1.88(移除 org:create_api_key,添加 sessions/mcp/file_upload)
- Anthropic-Dangerous-Direct-Browser-Access 仅在 API key 模式发送
- 响应头网关指纹清洗(剥离 litellm/helicone/portkey/cloudflare/kong/braintrust 前缀头)
2026-04-02 15:55:22 +08:00
Luis Pater 4f99bc54f1 test: update codex header expectations 2026-04-02 11:19:37 +08:00
Luis Pater 913f4a9c5f test: fix executor tests after helpers refactor 2026-04-02 11:12:30 +08:00
Luis Pater 25d1c18a3f fix: scope experimental cch signing to billing header 2026-04-02 11:03:11 +08:00
Luis Pater d09dd4d0b2 Merge commit '15c2f274ea690c9a7c9db22f9f454af869db5375' into dev 2026-04-02 10:59:54 +08:00
Luis Pater 474fb042da Merge pull request #2476 from router-for-me/cherry-pick/pr-2438-to-dev
Cherry-pick PR #2438 onto dev
2026-04-02 10:36:50 +08:00
Michael 8435c3d7be feat(tui): show time in usage details 2026-04-02 10:35:13 +08:00
Luis Pater e783d0a62e Merge pull request #2441 from MonsterQiu/issue-2421-alias-before-suspension
fix(auth): resolve oauth aliases before suspension checks
2026-04-02 10:27:39 +08:00
Luis Pater b05f575e9b Merge pull request #2444 from 0oAstro/fix/codex-nonstream-finish-reason-tool-calls
fix(codex): set finish_reason to "tool_calls" in non-streaming response when tool calls are present
2026-04-02 10:01:25 +08:00
Aikins Laryea f5e9f01811 test(amp): update tests to expect thinking blocks to pass through during streaming 2026-04-01 20:35:23 +00:00
Aikins Laryea ff7dbb5867 test(amp): update tests to expect thinking blocks to pass through during streaming 2026-04-01 20:21:39 +00:00
Aikins Laryea e34b2b4f1d fix(gemini): clean tool schemas and eager_input_streaming
delegate schema sanitization to util.CleanJSONSchemaForGemini and drop the top-level eager_input_streaming key to prevent validation errors when sending claude tools to the gemini api
2026-04-01 19:49:38 +00:00
edlsh 15c2f274ea fix: preserve cloak config defaults when mode omitted 2026-04-01 13:20:11 -04:00
edlsh 37249339ac feat: add opt-in experimental Claude cch signing 2026-04-01 13:03:17 -04:00
Luis Pater c422d16beb Merge pull request #2398 from 7RPH/fix/responses-sse-framing
fix: preserve SSE event boundaries for Responses streams
2026-04-02 00:46:51 +08:00
Luis Pater 66cd50f603 Merge pull request #2468 from router-for-me/ip
fix(openai): improve client IP retrieval in websocket handler
2026-04-02 00:03:35 +08:00
hkfires caa529c282 fix(openai): improve client IP retrieval in websocket handler 2026-04-01 20:16:01 +08:00
hkfires 51a4379bf4 refactor(openai): remove websocket body log truncation limit 2026-04-01 18:11:43 +08:00
Luis Pater acf98ed10e fix(openai): add session reference counter and cache lifecycle management for websocket tools 2026-04-01 17:28:50 +08:00
Luis Pater d1c07a091e fix(openai): add websocket tool call repair with caching and tests to improve transcript consistency 2026-04-01 17:16:49 +08:00
Luis Pater 105a21548f fix(codex): centralize session management with global store and add tests for executor session lifecycle 2026-04-01 13:17:10 +08:00
Luis Pater 1734aa1664 fix(codex): prioritize websocket-enabled credentials across priority tiers in scheduler logic 2026-04-01 12:51:12 +08:00
Luis Pater ca11b236a7 refactor(runtime, openai): simplify header management and remove redundant websocket logging logic 2026-04-01 11:57:31 +08:00
huynhgiabuu 6fdff8227d docs: add ProxyPal to 'Who is with us?' section
Add ProxyPal (https://github.com/buddingnewinsights/proxypal) to the
community projects list in all three README files (EN, CN, JA).
Placed after CCS, restoring its original position.

ProxyPal is a cross-platform desktop app (macOS, Windows, Linux) that
wraps CLIProxyAPI with a native GUI, supporting multiple AI providers,
usage analytics, request monitoring, and auto-configuration for popular
coding tools.

Closes #2420
2026-04-01 10:23:22 +07:00
Luis Pater 330e12d3c2 fix(codex): conditionally set Session_id header for Mac OS user agents and clean up redundant logic 2026-04-01 11:11:45 +08:00
RCD 8fc58e0806 chore: merge upstream CLIProxyAPI v6.9.7 2026-04-01 03:36:56 +07:00
Luis Pater b468ca79c3 Merge branch 'dev' of github.com:router-for-me/CLIProxyAPI into dev 2026-04-01 03:09:03 +08:00
Luis Pater d2c7e4e96a refactor(runtime): move executor utilities to helps package and update references 2026-04-01 03:08:20 +08:00
Luis Pater 1c7003ff68 Merge pull request #2452 from Lucaszmv/fix-qwen-cli-v0.13.2
fix(qwen): update CLI simulation to v0.13.2 and adjust header casing
2026-04-01 02:44:27 +08:00
Lucaszmv 1b44364e78 fix(qwen): update CLI simulation to v0.13.2 2026-03-31 15:19:07 -03:00
0oAstro ec77f4a4f5 fix(codex): set finish_reason to tool_calls in non-streaming response when tool calls are present 2026-03-31 14:12:15 +05:30
MonsterQiu f611dd6e96 refactor(auth): dedupe route-aware model support checks 2026-03-31 15:42:25 +08:00
MonsterQiu 07b7c1a1e0 fix(auth): resolve oauth aliases before suspension checks 2026-03-31 14:27:14 +08:00
Luis Pater 51fd58d74f fix(codex): use normalizeCodexInstructions to set default instructions 2026-03-31 12:16:57 +08:00
Luis Pater faae9c2f7c Merge pull request #2422 from MonsterQiu/fix/codex-compact-instructions
fix(codex): add default instructions for /responses/compact
2026-03-31 12:14:20 +08:00
Luis Pater bc3a6e4646 Merge pull request #2434 from MonsterQiu/fix/codex-responses-null-instructions
fix(codex): normalize null instructions for /responses requests
2026-03-31 12:01:21 +08:00
Luis Pater b09b03e35e Merge pull request #2424 from possible055/fix/websocket-transcript-replacement
fix(openai): handle transcript replacement after websocket v2 compaction
2026-03-31 11:00:33 +08:00
Luis Pater 16231947e7 Merge pull request #2426 from xixiwenxuanhe/feature/antigravity-credits
feat(antigravity): add AI credits quota fallback
2026-03-31 10:51:40 +08:00
MonsterQiu 39b9a38fbc fix(codex): normalize null instructions across responses paths 2026-03-31 10:32:39 +08:00
MonsterQiu bd855abec9 fix(codex): normalize null instructions for responses requests 2026-03-31 10:29:02 +08:00
Luis Pater 7c3c2e9f64 Merge pull request #2417 from CharTyr/fix/amp-streaming-thinking-regression
fix(amp): 修复流式响应中 thinking block 被错误抑制导致的 TUI 空白回复
2026-03-31 10:12:13 +08:00
Luis Pater c10f8ae2e2 Fixed: #2420
docs(readme): remove ProxyPal section from all README translations
2026-03-31 07:23:02 +08:00
xixiwenxuanhe a0bf33eca6 fix(antigravity): preserve fallback and honor config gate 2026-03-31 00:14:05 +08:00
xixiwenxuanhe 88dd9c715d feat(antigravity): add AI credits quota fallback 2026-03-30 23:58:12 +08:00
apparition a3e21df814 fix(openai): avoid developer transcript resets
- Narrow websocket transcript replacement detection to assistant outputs and function calls
- Preserve existing merge behavior for follow-up developer messages without previous_response_id
- Add a regression test covering mid-session developer message updates
2026-03-30 23:33:16 +08:00
MonsterQiu d3b94c9241 fix(codex): normalize null instructions for compact requests 2026-03-30 22:58:05 +08:00
apparition c1d7599829 fix(openai): handle transcript replacement after websocket compaction
- Add shouldReplaceWebsocketTranscript() to detect historical model output in input
- Add normalizeResponseTranscriptReplacement() for full transcript reset handling
- Prevent duplicate stale turn-state when clients replace local history post-compaction
- Avoid orphaned function_call items from incremental append on compact transcripts
- Add unit tests for transcript replacement detection and state reset behavior
2026-03-30 22:44:58 +08:00
MonsterQiu d11936f292 fix(codex): add default instructions for /responses/compact 2026-03-30 22:44:46 +08:00
Luis Pater 17363edf25 fix(auth): skip downtime for request-scoped 404 errors in model state management 2026-03-30 22:22:42 +08:00
CharTyr 279cbbbb8a fix(amp): don't suppress thinking blocks in streaming mode
Reverts the streaming thinking suppression introduced in b15453c.
rewriteStreamEvent should only inject signatures and rewrite model
names — suppressing thinking blocks in streaming mode breaks SSE
index alignment and causes the Amp TUI to render empty responses
on the second message onward (especially with model-mapped
non-Claude providers like GPT-5.4).

Non-streaming responses still suppress thinking when tool_use is
present via rewriteModelInResponse.
2026-03-30 20:09:32 +08:00
daniel 91387ca247 refactor(gemini-cli): simplify redundant if/else in project ID assignment
Both branches assign finalProjectID = responseProjectID, so move the
assignment outside the conditional and keep only the logging inside.
2026-03-30 20:07:02 +08:00
Luis Pater 486cd4c343 Merge pull request #2409 from sususu98/fix/tool-use-pairing-break
fix(antigravity): reorder model parts to prevent tool_use↔tool_result pairing breakage
2026-03-30 16:59:46 +08:00
sususu98 25feceb783 fix(antigravity): reorder model parts to prevent tool_use↔tool_result pairing breakage
When a Claude assistant message contains [text, tool_use, text], the
Antigravity API internally splits the model message at functionCall
boundaries, creating an extra assistant turn between tool_use and the
following tool_result. Claude then rejects with:

  tool_use ids were found without tool_result blocks immediately after

Fix: extend the existing 2-way part reordering (thinking-first) to a
3-way partition: thinking → regular → functionCall. This ensures
functionCall parts are always last, so Antigravity's split cannot
insert an extra assistant turn before the user's tool_result.

Fixes #989
2026-03-30 15:09:33 +08:00
Luis Pater d26752250d Merge pull request #2403 from CharTyr/clean-pr
fix(amp): 修复Amp CLI 集成 缺失/无效 signature 导致的 TUI 崩溃与上游 400 问题
2026-03-30 12:54:15 +08:00
CharTyr b15453c369 fix(amp): address PR review - stream thinking suppression, SSE detection, test init
- Call suppressAmpThinking in rewriteStreamEvent for streaming path
- Handle nil return from suppressAmpThinking to skip suppressed events
- Narrow looksLikeSSEChunk to line-prefix detection (HasPrefix vs Contains)
- Initialize suppressedContentBlock map in test
2026-03-30 00:42:04 -04:00
CharTyr 04ba8c8bc3 feat(amp): sanitize signatures and handle stream suppression for Amp compatibility 2026-03-29 22:23:18 -04:00
danielandClaude Sonnet 4.6 fccfb162b4 fix(gemini-cli): use backend project ID from onboarding response
- Simplify project ID selection to always use the backend project ID returned by Gemini onboarding
- Update Gemini CLI version from 0.31.0 to 0.34.0
- Add 'terminal' to User-Agent string for better client identification

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-29 23:52:01 +08:00
Luis Pater 6570692291 Merge pull request #2400 from router-for-me/revert-2374-codex-cache-clean
Revert "fix(codex): restore prompt cache continuity for Codex requests"
2026-03-29 22:19:39 +08:00
trph f73d55ddaa fix: simplify responses SSE suffix handling 2026-03-29 22:19:25 +08:00
Luis Pater 13aa5b3375 Revert "fix(codex): restore prompt cache continuity for Codex requests" 2026-03-29 22:18:14 +08:00
trph 0fcc02fbea fix: tighten responses SSE review follow-up 2026-03-29 22:10:28 +08:00
trph c03883ccf0 fix: address responses SSE review feedback 2026-03-29 22:00:46 +08:00
trph 134a9eac9d fix: preserve SSE event boundaries for Responses streams 2026-03-29 17:23:16 +08:00
RCD 1e4ba8f4c7 ci: normalize dev installer version metadata 2026-03-29 15:04:22 +07:00
RCD 950e484af6 ci: allow dev versions in Windows installer builds 2026-03-29 15:01:07 +07:00
RCD 9167f0a416 ci: fix Windows release workflow 2026-03-29 14:57:15 +07:00
RCD 3af8992d23 chore: merge upstream CLIProxyAPI v6.9.5 sync into main 2026-03-29 14:41:08 +07:00
RCD 9332a5eac8 chore: finalize upstream CLIProxyAPI v6.9.5 sync 2026-03-29 14:33:20 +07:00
RCD 9fddf15d2a chore: merge upstream CLIProxyAPI v6.9.5
# Conflicts:
#	README.md
#	README_CN.md
#	README_JA.md
2026-03-29 13:59:33 +07:00
RCD f793af5a12 chore: merge upstream CLIProxyAPI v6.9.4
# Conflicts:
#	README.md
#	README_CN.md
#	README_JA.md
2026-03-29 13:57:29 +07:00
RCD 1436721c3e chore: merge upstream CLIProxyAPI v6.9.3
# Conflicts:
#	README_CN.md
2026-03-29 13:56:38 +07:00
RCD 5f48b13144 chore: merge upstream CLIProxyAPI v6.9.2
# Conflicts:
#	README_JA.md
#	internal/api/handlers/management/auth_files.go
2026-03-29 13:55:37 +07:00
Luis Pater 6d8de0ade4 feat(auth): implement weighted provider rotation for improved scheduling fairness 2026-03-29 13:49:01 +08:00
Luis Pater 1587ff5e74 Merge pull request #2389 from router-for-me/claude
fix(claude): add default max_tokens for models
2026-03-29 13:03:20 +08:00
hkfires f033d3a6df fix(claude): enhance ensureModelMaxTokens to use registered max_completion_tokens and fallback to default 2026-03-29 13:00:43 +08:00
hkfires 145e0e0b5d fix(claude): add default max_tokens for models 2026-03-29 12:46:00 +08:00
Luis Pater 9b7d7021af docs(readme): update LingtrueAPI link in all README translations 2026-03-29 12:30:24 +08:00
Luis Pater e41c22ef44 docs(readme): add LingtrueAPI sponsorship details to all README translations 2026-03-29 12:23:37 +08:00
Ravi Tharuma 5fc2bd393e fix: retain codex thinking signature until item done 2026-03-28 14:41:25 +01:00
Luis Pater 55271403fb Merge pull request #2374 from VooDisss/codex-cache-clean
fix(codex): restore prompt cache continuity for Codex requests
2026-03-28 21:16:51 +08:00
Luis Pater 36fba66619 Merge pull request #2371 from RaviTharuma/docs/provider-specific-routes
docs: clarify provider-specific routing for aliased models
2026-03-28 21:11:29 +08:00
Ravi Tharuma 66eb12294a fix: clear stale thinking signature when no block is open 2026-03-28 14:08:31 +01:00
Ravi Tharuma 73b22ec29b fix: omit empty signature field from thinking blocks
Emit signature only when non-empty in both streaming content_block_start
and non-streaming thinking blocks. Avoids turning 'missing signature'
into 'empty/invalid signature' which Claude clients may reject.
2026-03-28 14:08:31 +01:00
Ravi Tharuma c31ae2f3b5 fix: retain previously captured thinking signature on new summary part 2026-03-28 14:08:31 +01:00
Ravi Tharuma 76b53d6b5b fix: finalize pending thinking block before next summary part 2026-03-28 14:08:31 +01:00
Ravi Tharuma a34dfed378 fix: preserve Claude thinking signatures in Codex translator 2026-03-28 14:08:31 +01:00
Luis Pater b9b127a7ea Merge pull request #2347 from edlsh/fix/codex-strip-stream-options
fix(codex): strip stream_options from Responses API requests
2026-03-28 21:03:01 +08:00
Luis Pater 2741e7b7b3 Merge pull request #2346 from pjpjq/codex/fix-codex-capacity-retry
fix(codex): Treat Codex capacity errors as retryable
2026-03-28 21:00:50 +08:00
Luis Pater 1767a56d4f Merge pull request #2343 from kongkk233/fix/proxy-transport-defaults
Preserve default transport settings for proxy clients
2026-03-28 20:58:24 +08:00
Luis Pater 779e6c2d2f Merge pull request #2231 from 7RPH/fix/responses-stream-multi-tool-calls
fix: preserve separate streamed tool calls in Responses API
2026-03-28 20:53:19 +08:00
Luis Pater 73c831747b Merge pull request #2133 from DragonFSKY/fix/2061-stale-modelstates
fix(auth): prevent stale runtime state inheritance from disabled auth entries
2026-03-28 20:50:57 +08:00
Luis Pater 10b824fcac fix(security): validate auth file names to prevent unsafe input 2026-03-28 04:48:23 +08:00
VooDisss e5d3541b5a refactor(codex): remove stale affinity cleanup leftovers
Drop the last affinity-related executor artifacts so the PR stays focused on the minimal Codex continuity fix set: stable prompt cache identity, stable session_id, and the executor-only behavior that was validated to restore cache reads.
2026-03-27 20:40:26 +02:00
VooDisss 79755e76ea refactor(pr): remove forbidden translator changes
Drop the chat-completions translator edits from this PR so the branch complies with the repository policy that forbids pull-request changes under internal/translator. The remaining PR stays focused on the executor-level Codex continuity fix that was validated to restore cache reuse.
2026-03-27 19:34:13 +02:00
VooDisss 35f158d526 refactor(pr): narrow Codex cache fix scope
Remove the experimental auth-affinity routing changes from this PR so it stays focused on the validated Codex continuity fix. This keeps the prompt-cache repair while avoiding unrelated routing-policy concerns such as provider/model affinity scope, lifecycle cleanup, and hard-pin fallback semantics.
2026-03-27 19:06:34 +02:00
VooDisss 6962e09dd9 fix(auth): scope affinity by provider
Keep sticky auth affinity limited to matching providers and stop persisting execution-session IDs as long-lived affinity keys so provider switching and normal streaming traffic do not create incorrect pins or stale affinity state.
2026-03-27 18:52:58 +02:00
VooDisss 4c4cbd44da fix(auth): avoid leaking or over-persisting affinity keys
Stop using one-shot idempotency keys as long-lived auth-affinity identifiers and remove raw affinity-key values from debug logs so sticky routing keeps its continuity benefits without creating avoidable memory growth or credential exposure risks.
2026-03-27 18:34:51 +02:00
VooDisss 26eca8b6ba fix(codex): preserve continuity and safe affinity fallback
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.
2026-03-27 18:27:33 +02:00
VooDisss 62b17f40a1 refactor(codex): align continuity helpers with review feedback
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.
2026-03-27 18:11:57 +02:00
VooDisss 511b8a992e fix(codex): restore prompt cache continuity for Codex requests
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.
2026-03-27 17:49:29 +02:00
Luis Pater 7dccc7ba2f docs(readme): remove redundant whitespace in BmoPlus sponsorship section of Chinese README 2026-03-27 20:52:14 +08:00
Luis Pater 70c90687fd docs(readme): fix formatting in BmoPlus sponsorship section of Chinese README 2026-03-27 20:49:43 +08:00
Luis Pater 8144ffd5c8 Merge pull request #2370 from B3o/add-bmoplus-sponsor
docs: add BmoPlus sponsorship banners to READMEs
2026-03-27 20:48:22 +08:00
Ravi Tharuma 0ab977c236 docs: clarify provider path limitations 2026-03-27 11:13:08 +01:00
Ravi Tharuma 224f0de353 docs: neutralize provider-specific path wording 2026-03-27 11:11:06 +01:00
B3o 6b45d311ec add BmoPlus sponsorship banners to READMEs 2026-03-27 18:01:35 +08:00
Ravi Tharuma d54de441d3 docs: clarify provider-specific routing for aliased models 2026-03-27 10:53:09 +01:00
白金 1821bf7051 docs: add BmoPlus sponsorship banners to READMEs 2026-03-27 17:39:29 +08:00
Luis Pater d42b5d4e78 docs(readme): update QQ group information in Chinese README 2026-03-27 11:46:21 +08:00
edlsh 754f3bcbc3 fix(codex): strip stream_options from Responses API requests
The Codex/OpenAI Responses API does not support the stream_options
parameter. When clients (e.g. Amp CLI) include stream_options in their
requests, CLIProxyAPI forwards it as-is, causing a 400 error:

  {"detail":"Unsupported parameter: stream_options"}

Strip stream_options alongside the other unsupported parameters
(previous_response_id, prompt_cache_retention, safety_identifier)
in Execute, ExecuteStream, and CountTokens.
2026-03-25 11:58:36 -04:00
pjpj 36973d4a6f Handle Codex capacity errors as retryable 2026-03-25 23:25:31 +08:00
kwz c89d19b300 Preserve default transport settings for proxy clients 2026-03-25 15:33:09 +08:00
RCD fc9616026b chore: merge upstream CLIProxyAPI v6.9.2 2026-03-25 09:38:44 +07:00
Luis Pater 1e6bc81cfd refactor(config): replace auto-update-panel with disable-auto-update-panel for clarity 2026-03-25 10:31:44 +08:00
Luis Pater 1a149475e0 Merge pull request #2293 from Xvvln/fix/management-asset-security
fix(security): harden management panel asset updater
2026-03-25 10:22:49 +08:00
Luis Pater e5166841db Merge pull request #2310 from shellus/fix/claude-openai-system-top-level
fix: preserve OpenAI system messages as Claude top-level system
2026-03-25 10:21:18 +08:00
Luis Pater bb9b2d1758 Merge pull request #2320 from cikichen/build/freebsd-support
build: add freebsd support for releases
2026-03-25 10:12:35 +08:00
Luis Pater 76c064c729 Merge pull request #2335 from router-for-me/auth
Support batch upload and delete for auth files
2026-03-25 09:34:44 +08:00
Luis Pater d2f652f436 Merge pull request #2333 from router-for-me/codex
feat(codex): pass through codex client identity headers
2026-03-25 09:34:09 +08:00
Luis Pater 6a452a54d5 Merge pull request #2316 from router-for-me/openai
Add per-model thinking support for OpenAI compatibility
2026-03-25 09:31:28 +08:00
hkfires 9e5693e74f feat(api): support batch auth file upload and delete 2026-03-25 09:20:17 +08:00
hkfires 528b1a2307 feat(codex): pass through codex client identity headers 2026-03-25 08:48:18 +08:00
Luis Pater 0cc978ec1d Merge pull request #2297 from router-for-me/readme
docs(readme): update japanese documentation links
2026-03-25 03:11:24 +08:00
simon d312422ab4 build: add freebsd support to releases 2026-03-24 16:49:04 +08:00
hkfires fee736933b feat(openai-compat): add per-model thinking support 2026-03-24 14:21:12 +08:00
GeJiaXiang 09c92aa0b5 fix: keep a fallback turn for system-only Claude inputs 2026-03-24 13:54:25 +08:00
GeJiaXiang 8c67b3ae64 test: verify remaining user message after system merge 2026-03-24 13:47:52 +08:00
GeJiaXiang 000e4ceb4e fix: map OpenAI system messages to Claude top-level system 2026-03-24 13:42:33 +08:00
RCD a2a4fba626 chore: merge upstream CLIProxyAPI v6.9.1 2026-03-24 09:41:49 +07:00
hkfires 5c99846ecf docs(readme): update japanese documentation links 2026-03-24 09:47:01 +08:00
trph cc32f5ff61 fix: unify Responses output indexes for streamed items 2026-03-24 08:59:09 +08:00
trph fbff68b9e0 fix: preserve choice-aware output indexes for streamed tool calls 2026-03-24 08:54:43 +08:00
trph 7e1a543b79 fix: preserve separate streamed tool calls in Responses API 2026-03-24 08:51:15 +08:00
Luis Pater d475aaba96 Fixed: #2274
fix(translator): omit null content fields in Codex OpenAI tool call responses
2026-03-24 01:00:57 +08:00
Luis Pater 96f55570f7 Merge pull request #2282 from eltociear/add-ja-doc
docs: add Japanese README
2026-03-24 00:40:58 +08:00
Luis Pater 0906aeca87 Merge pull request #2254 from clcc2019/main
refactor: streamline usage reporting by consolidating record publishi…
2026-03-24 00:39:31 +08:00
Xvvln 7333619f15 fix: reject oversized downloads instead of truncating; warn on unverified fallback
- Read maxAssetDownloadSize+1 bytes and error if exceeded, preventing
  silent truncation that could write a broken management.html to disk
- Log explicit warning when fallback URL is used without digest
  verification, so users are aware of the reduced security guarantee
2026-03-24 00:27:44 +08:00
Luis Pater 97c0487add Merge pull request #2223 from cnrpman/fix/codex-responses-web-search-preview-compat
fix: normalize web_search_preview for codex responses
2026-03-24 00:25:37 +08:00
DragonFSKY 74b862d8b8 test(cliproxy): cover delete re-add stale state flow 2026-03-24 00:21:04 +08:00
Xvvln 2db8df8e38 fix(security): harden management panel asset updater
- Abort update when SHA256 digest mismatch is detected instead of
  logging a warning and proceeding (prevents MITM asset replacement)
- Cap asset download size to 10 MB via io.LimitReader (defense-in-depth
  against OOM from oversized responses)
- Add `auto-update-panel` config option (default: false) to make the
  periodic background updater opt-in; the panel is still downloaded
  on first access when missing, but no longer silently auto-updated
  every 3 hours unless explicitly enabled
2026-03-24 00:10:04 +08:00
Luis Pater a576088d5f Merge pull request #2222 from kaitranntt/kai/fix/758-openai-proxy-alternating-model-support
fix: fall back on model support errors during auth rotation
2026-03-24 00:03:28 +08:00
Luis Pater 66ff916838 Merge pull request #2220 from xulongwu4/main
fix: normalize model name in TranslateRequest fallback to prevent prefix leak
2026-03-23 23:56:15 +08:00
Luis Pater 7b0453074e Merge pull request #2219 from beck-8/fix/context-done-race
fix: avoid data race when watching request cancellation
2026-03-23 22:57:21 +08:00
Luis Pater a000eb523d Merge pull request #2213 from TTTPOB/ua-fix
feat(claude): stabilize device fingerprint across mixed Claude Code and cloaked clients
2026-03-23 22:53:51 +08:00
Luis Pater 18a4fedc7f Merge pull request #2126 from ailuntz/fix/watcher-auth-cache-memory
perf(watcher): reduce auth cache memory
2026-03-23 22:47:34 +08:00
Luis Pater 5d6cdccda0 Merge pull request #2268 from sususu98/fix/sanitize-tool-names
fix(translator): sanitize tool names for Gemini function_declarations compatibility
2026-03-23 21:42:22 +08:00
Luis Pater 1b7f4ac3e1 Merge pull request #2252 from sususu98/fix/antigravity-empty-thought-text
fix(antigravity): always include text field in thought parts to prevent Google 500
2026-03-23 21:41:25 +08:00
Luis Pater afc1a5b814 Fixed: #2281
refactor(claude): centralize usage token calculation logic and add tests for cached token handling
2026-03-23 21:30:03 +08:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 7ed38db54f docs: update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:43 +09:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 28c10f4e69 docs: update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:32 +09:00
Ikko Eltociear Ashimineandgemini-code-assist[bot] 6e12441a3b Update README_JA.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-03-23 16:57:19 +09:00
Ikko Ashimine 65c439c18d docs: add Japanese README 2026-03-23 15:23:18 +09:00
dslife2025 0ed2d16596 Merge branch 'router-for-me:main' into main 2026-03-23 09:50:43 +08:00
Supra4E8C db335ac616 Merge pull request #2269 from router-for-me/auth-fix
fix(auth): ensure absolute paths for auth file handling
2026-03-22 22:53:44 +08:00
sususu98 e8bb350467 fix: extend tool name sanitization to all remaining Gemini-bound translators
Apply SanitizeFunctionName on request and RestoreSanitizedToolName on
response for: gemini/claude, gemini/openai/chat-completions,
gemini/openai/responses, antigravity/openai/chat-completions,
gemini-cli/openai/chat-completions.

Also update SanitizedToolNameMap to handle OpenAI format
(tools[].function.name) in addition to Claude format (tools[].name).
2026-03-22 14:06:46 +08:00
Supra4E8C 5331d51f27 fix(auth): ensure absolute paths for auth file handling 2026-03-22 13:58:16 +08:00
sususu98 755ca75879 fix: address review feedback - init ToolNameMap eagerly, log collisions, add collision test 2026-03-22 13:24:03 +08:00
sususu98 2398ebad55 fix(translator): sanitize tool names for Gemini function_declarations compatibility
Claude Code and MCP clients may send tool names containing characters
invalid for Gemini's function_declarations (e.g. '/', '@', spaces).
Sanitize on request via SanitizeFunctionName and restore original names
on response for both antigravity/claude and gemini-cli/claude translators.
2026-03-22 13:10:53 +08:00
clcc2019 c1bf298216 refactor: streamline usage reporting by consolidating record publishing logic
- Introduced a new method `buildRecord` in `usageReporter` to encapsulate record creation, improving code readability and maintainability.
- Added latency tracking to usage records, ensuring accurate reporting of request latencies.
- Updated tests to validate the inclusion of latency in usage records and ensure proper functionality of the new reporting structure.
2026-03-20 19:44:26 +08:00
sususu e005208d76 fix(antigravity): always include text field in thought parts to prevent Google 500
When Claude sends redacted thinking with empty text, the translator
was omitting the "text" field from thought parts. Google Antigravity
API requires this field, causing 500 "Unknown Error" responses.

Verified: 129/129 error logs with empty thought → 500, 0/97 success
logs had empty thought. After fix: 0 new "Unknown Error" 500s.
2026-03-20 18:59:25 +08:00
Junyi Du d1df70d02f chore: add codex builtin tool normalization logging 2026-03-20 14:08:37 +08:00
Luis Pater f81acd0760 Merge pull request #2243 from router-for-me/oauth
Improve OAuth callback handling with async prompts
2026-03-20 12:35:44 +08:00
hkfires 636da4c932 refactor(auth): replace manual input handling with AsyncPrompt for callback URLs 2026-03-20 12:24:27 +08:00
hkfires cccb77b552 fix(auth): avoid blocking oauth callback wait on prompt 2026-03-20 11:48:30 +08:00
Luis Pater 2bd646ad70 refactor: replace sjson.Set usage with sjson.SetBytes to optimize mutable JSON transformations 2026-03-19 17:58:54 +08:00
tpob 52c1fa025e fix(claude): learn official fingerprints after custom baselines 2026-03-19 13:59:41 +08:00
tpob 680105f84d fix(claude): refresh cached fingerprint after baseline upgrades 2026-03-19 13:28:58 +08:00
tpob f7069e9548 fix(claude): pin stabilized OS arch to baseline 2026-03-19 13:07:16 +08:00
Junyi Du 793840cdb4 fix: cover dated and nested codex web search aliases 2026-03-19 03:41:12 +08:00
Junyi Du 8f421de532 fix: handle sjson errors in codex tool normalization 2026-03-19 03:36:06 +08:00
Junyi Du be2dd60ee7 fix: normalize web_search_preview for codex responses 2026-03-19 03:23:14 +08:00
Tam Nhu Tran ea3e0b713e fix: harden pooled model-support fallback state 2026-03-18 13:19:20 -04:00
tpob 8179d5a8a4 fix(claude): avoid racy fingerprint downgrades 2026-03-19 01:03:41 +08:00
tpob 6fa7abe434 fix(claude): keep configured baseline above older fingerprints 2026-03-19 01:02:04 +08:00
Tam Nhu Tran 5135c22cd6 fix: fall back on model support errors during auth rotation 2026-03-18 12:43:45 -04:00
Longwu Ou 1e27990561 address PR review: log sjson error and add unit tests
- Log a warning instead of silently ignoring sjson.SetBytes errors in the TranslateRequest fallback path
  - Add registry_test.go with tests covering the fallback model normalization and verifying registered transforms take precedence
2026-03-18 12:43:40 -04:00
Longwu Ou e1e9fc43c1 fix: normalize model name in TranslateRequest fallback to prevent prefix leak
When no request translator is registered for a format pair (e.g.
        openai-response → openai-response), TranslateRequest returned the raw
        payload unchanged. This caused client-side model prefixes (e.g.
        "copilot/gpt-5-mini") to leak into upstream requests, resulting in
        "The requested model is not supported" errors from providers.

        The fallback path now updates the "model" field in the payload to
        match the resolved model name before returning.
2026-03-18 12:30:22 -04:00
beck-8 b2921518ac fix: avoid data race when watching request cancellation 2026-03-19 00:15:52 +08:00
tpob dd64adbeeb fix(claude): preserve legacy user agent overrides 2026-03-19 00:03:09 +08:00
tpob 616d41c06a fix(claude): restore legacy runtime OS arch fallback 2026-03-19 00:01:50 +08:00
tpob e0e337aeb9 feat(claude): add switch for device profile stabilization 2026-03-18 19:31:59 +08:00
tpob d52839fced fix: stabilize claude device fingerprint 2026-03-18 18:46:54 +08:00
Luis Pater 56073ded69 Merge pull request #2200 from sususu98/feat/local-model-flag
feat: add -local-model flag to skip remote model catalog fetching
2026-03-18 10:58:07 +08:00
sususu98 9738a53f49 feat: add -local-model flag to skip remote model catalog fetching
When enabled, the server uses only the embedded models.json loaded at
init() and skips registry.StartModelsUpdater(), disabling the initial
remote fetch and 3-hour periodic refresh. The management panel
auto-updater (managementasset.StartAutoUpdater) is unaffected.
2026-03-18 10:48:03 +08:00
Luis Pater be3f8dbf7e Merge pull request #2187 from Darley-Wey/fix/claude-disable-parallel-tool-calls
fix(claude): honor disable_parallel_tool_use
2026-03-17 21:06:08 +08:00
Darley 9c6c3612a8 fix(claude): read disable_parallel_tool_use from tool_choice 2026-03-17 19:35:41 +08:00
Darley 19e1a4447a fix(claude): honor disable_parallel_tool_use 2026-03-17 19:17:41 +08:00
dinhkarateandClaude Opus 4.6 36efcc6e28 fix(vertex): include prefix in auth filename and validate at import
Address two blocking issues from PR review:
- Auth file now named vertex-{prefix}-{project}.json so importing the
  same project with different prefixes no longer overwrites credentials
- Prefix containing "/" is rejected at import time instead of being
  silently ignored at runtime
- Add prefix to in-memory metadata map for consistency

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 15:06:04 +07:00
Pham Quang Dinh a337ecf35c Merge branch 'router-for-me:main' into feat(vertex)/add-prefix-field 2026-03-17 11:48:40 +07:00
RCD 3595d47a9d docs: record v0.3.0-dev-0.43 release 2026-03-17 02:29:57 +07:00
RCD 82a00093b6 chore: merge upstream CLIProxyAPI v6.8.55 2026-03-17 02:25:21 +07:00
Luis Pater fb95813fbf Merge pull request #2142 from Muran-prog/fix/strip-uniqueItems-gemini-2123
fix: strip uniqueItems from Gemini function_declarations (#2123)
2026-03-16 20:34:28 +08:00
Luis Pater db63f9b5d6 Merge pull request #2162 from enieuwy/fix/responses-api-json-valid-check
fix: validate JSON before raw-embedding function call outputs in Responses API
2026-03-16 18:42:31 +08:00
Luis Pater 25f6c4a250 Merge pull request #2158 from sususu98/fix/antigravity-functionresponse-name
fix(antigravity): resolve empty functionResponse.name for toolu_* tool_use_id format
2026-03-16 18:39:40 +08:00
enieuwy b24ae74216 fix: validate JSON before raw-embedding function call outputs in Responses API
gjson.Parse() marks any string starting with { or [ as gjson.JSON type,
even when the content is not valid JSON (e.g. macOS plist format, truncated
tool results). This caused sjson.SetRaw to embed non-JSON content directly
into the Gemini API request payload, producing 400 errors.

Add json.Valid() check before using SetRaw to ensure only actually valid
JSON is embedded raw. Non-JSON content now falls through to sjson.Set
which properly escapes it as a JSON string.

Fixes #2161
2026-03-16 15:29:18 +08:00
Luis Pater 59ad8f40dc Merge pull request #2124 from RGBadmin/feat/auth-list-priority-note
feat(api): expose priority and note in GET /auth-files response
2026-03-16 12:31:11 +08:00
sususu98 ff03dc6a2c fix(antigravity): resolve empty functionResponse.name for toolu_* tool_use_id format
The Claude-to-Gemini translator derived function names by splitting
tool_use_id on "-", which produced empty strings for IDs with exactly
2 segments (e.g. toolu_tool-<uuid>). Replace the string-splitting
heuristic with a lookup map built from tool_use blocks during the
main processing loop, with fallback to the raw ID on miss.
2026-03-16 11:18:29 +08:00
Luis Pater dc7187ca5b fix(websocket): pin only websocket-capable auth IDs and add corresponding test 2026-03-16 09:57:38 +08:00
Luis Pater b1dcff778c Merge pull request #2141 from Muran-prog/fix/tool-calling-translation-2132
fix: skip empty assistant message in tool call translation (#2132)
2026-03-16 01:42:27 +08:00
Luis Pater 198b3f4a40 chore(ci): update build metadata to use GITHUB_REF_NAME in workflows 2026-03-16 00:30:44 +08:00
Luis Pater 9fee7f488e chore(ci): update GoReleaser config and release workflow to skip validation step 2026-03-16 00:16:25 +08:00
RGBadminandClaude Opus 4.6 c1241a98e2 fix(api): restrict fallback note to string-typed JSON values
Only emit note in listAuthFilesFromDisk when the JSON value is actually
a string (gjson.String), matching the synthesizer/buildAuthFileEntry
behavior. Non-string values like numbers or booleans are now ignored
instead of being coerced via gjson.String().

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 23:00:17 +08:00
RGBadminandClaude Opus 4.6 8d8f5970ee fix(api): fallback to Metadata for priority/note on uploaded auths
buildAuthFileEntry now falls back to reading priority/note from
auth.Metadata when Attributes lacks them. This covers auths registered
via UploadAuthFile which bypass the synthesizer and only populate
Metadata from the raw JSON.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 17:36:11 +08:00
RGBadminandClaude Opus 4.6 f90120f846 fix(api): propagate note to Gemini virtual auths and align priority parsing
- Read note from Attributes (consistent with priority) in buildAuthFileEntry,
  fixing missing note on Gemini multi-project virtual auth cards.
- Propagate note from primary to virtual auths in SynthesizeGeminiVirtualAuths,
  mirroring existing priority propagation.
- Sync note/priority writes to both Metadata and Attributes in PatchAuthFileFields,
  with refactored nil-check to reduce duplication (review feedback).
- Validate priority type in fallback disk-read path instead of coercing all values
  to 0 via gjson.Int(), aligning with the auth-manager code path.
- Add regression tests for note synthesis, virtual-auth note propagation, and
  end-to-end multi-project Gemini note inheritance.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-15 16:47:01 +08:00
Muran-prog 0b94d36c4a test: use exact match for tool name assertion
Address review feedback - drop function.name fallback and
strings.Contains in favor of direct == comparison.
2026-03-14 21:45:28 +02:00
Muran-prog 152c310bb7 test: add uniqueItems stripping test
Covers the fix from the previous commit — verifies uniqueItems is
removed from the schema and moved to the description hint.
2026-03-14 21:22:14 +02:00
Muran-prog f6bbca35ab fix: strip uniqueItems from Gemini function_declarations (#2123)
Gemini API rejects uniqueItems in tool schemas with 400. Add it to
unsupportedConstraints alongside minItems/maxItems where it belongs.

Same class of fix as #1424 and #1531.
2026-03-14 21:18:06 +02:00
Muran-prog c8cee6a209 fix: skip empty assistant message in tool call translation (#2132)
When assistant has tool_calls but no text content, the translator
emitted an empty message into the Responses API input array before
function_call items. The API then couldn't match function_call_output
to its function_call by call_id, returning:

  No tool output found for function call ...

Only emit assistant messages that have content parts. Tool-call-only
messages now produce function_call items directly.

Added 9 tests for tool calling translation covering single/parallel
calls, multi-turn conversations, name shortening, empty content
edge cases, and call_id integrity.
2026-03-14 21:01:01 +02:00
Luis Pater b5701f416b Fixed: #2102
fix(auth): ensure unique auth index for shared API keys across providers and credential identities
2026-03-15 02:48:54 +08:00
Luis Pater 4b1a404fcb Fixed: #1936
feat(translator): add image type handling in ConvertClaudeRequestToGemini
2026-03-15 02:18:28 +08:00
Luis Pater 67669196ed Merge pull request #2131 from HEUDavid/docs/add-who-is-with-us
docs: Add Shadow AI to 'Who is with us?' section
2026-03-15 01:44:46 +08:00
DragonFSKY 5c817a9b42 fix(auth): prevent stale ModelStates inheritance from disabled auth entries
When an auth file is deleted and re-created with the same path/ID, the
new auth could inherit stale ModelStates (cooldown/backoff) from the
previously disabled entry, preventing it from being routed.

Gate runtime state inheritance (ModelStates, LastRefreshedAt,
NextRefreshAfter) on both existing and incoming auth being non-disabled
in Manager.Update and Service.applyCoreAuthAddOrUpdate.

Closes #2061
2026-03-14 23:46:23 +08:00
destinoantagonista-wq e08f68ed7c chore(auth): drop reconcile test file from pr 2026-03-14 14:41:26 +00:00
destinoantagonista-wq f09ed25fd3 fix(auth): tighten registry model reconciliation 2026-03-14 14:40:06 +00:00
hkfires 58fd9bf964 fix(codex): add 'go' plan_type in registerModelsForAuth 2026-03-14 22:09:14 +08:00
HEUDavid 7b3dfc67bc docs: Add Shadow AI to 'Who is with us?' section 2026-03-14 21:01:07 +08:00
HEUDavid cdd24052d3 docs: Add Shadow AI to 'Who is with us?' section 2026-03-14 20:53:43 +08:00
Luis Pater 733fd8edab Merge pull request #2111 from qzydustin/main
Fix missing streaming usage tracking for OpenAI-compatible providers
2026-03-14 18:17:08 +08:00
Luis Pater af27f2b8bc Merge pull request #2110 from router-for-me/codex
feat(service): extend model registration for team and business types
2026-03-14 18:10:01 +08:00
Luis Pater 2e1925d762 Merge pull request #2108 from sususu98/fix/gemini-cli-tool-schema-and-empty-parts
fix(gemini-cli): sanitize tool schemas and filter empty parts
2026-03-14 18:02:52 +08:00
Luis Pater 77254bd074 Merge pull request #2116 from router-for-me/vertex
fix(config): allow vertex keys without base-url
2026-03-14 17:27:48 +08:00
RGBadminandClaude Opus 4.6 5b6342e6ac feat(api): expose priority and note fields in GET /auth-files list response
The list endpoint previously omitted priority and note, which are stored
inside each auth file's JSON content. This adds them to both the normal
(auth-manager) and fallback (disk-read) code paths, and extends
PATCH /auth-files/fields to support writing the note field.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-14 14:47:31 +08:00
destinoantagonista-wq e166e56249 Reconcile registry model states on auth changes
Add Manager.ReconcileRegistryModelStates to clear stale per-model runtime failures for models currently registered in the global model registry. The method finds models supported for an auth, resets non-clean ModelState entries, updates aggregated availability, persists changes, and pushes a snapshot to the scheduler. Introduce modelStateIsClean helper to determine when a model state needs resetting. Call ReconcileRegistryModelStates from Service paths that register/refresh models (applyCoreAuthAddOrUpdate and refreshModelRegistrationForAuth) to keep the scheduler and global registry aligned after model re-registration.
2026-03-13 19:41:49 +00:00
hkfires 560c020477 fix(config): allow vertex keys without base-url 2026-03-13 19:09:26 +08:00
Zhenyu Qi aec65e3be3 fix(openai_compat): add stream_options.include_usage for streaming usage tracking 2026-03-13 00:48:17 -07:00
hkfires f44f0702f8 feat(service): extend model registration for team and business types 2026-03-13 14:12:19 +08:00
sususu98 b76b79068f fix(gemini-cli): sanitize tool schemas and filter empty parts
1. Claude translator: add CleanJSONSchemaForGemini() to sanitize tool
   input schemas (removes $schema, anyOf, const, format, etc.) and
   delete eager_input_streaming from tool declarations. Remove fragile
   bytes.Replace for format:"uri" now covered by schema cleaner.

2. Gemini native translator: filter out content entries with empty or
   missing parts arrays to prevent Gemini API 400 error "required
   oneof field 'data' must have one initialized field".

Both fixes align gemini-cli with protections already present in the
antigravity translator.
2026-03-13 12:37:37 +08:00
Luis Pater 1db23979e8 Merge pull request #2106 from router-for-me/model
feat(model_registry): enhance model registration and refresh mechanisms
2026-03-13 11:18:51 +08:00
hkfires c3d5dbe96f feat(model_registry): enhance model registration and refresh mechanisms 2026-03-13 10:56:39 +08:00
RCD 3a828bb14c docs: record maintenance fix rollout 2026-03-12 12:55:04 +07:00
RCD c93f57a02a fix(translator): align tool and gemini semantics 2026-03-12 12:54:50 +07:00
RCD dd0d99e64b fix(management): harden handler state and paths 2026-03-12 12:54:33 +07:00
RCD 96f28fc5d5 fix(auth): harden token persistence and refresh 2026-03-12 12:54:14 +07:00
RCD 85f6a29477 docs: record maintenance review findings 2026-03-12 12:02:21 +07:00
RCD 13a1fbe946 fix(auth): resolve nested filestore deletes 2026-03-12 11:20:51 +07:00
RCD 1f82eedbef chore: switch releases to manual publishing 2026-03-12 11:07:03 +07:00
RCD d9e5506949 docs: track CLIProxyAPI v6.8.51 sync 2026-03-12 11:00:53 +07:00
RCD 6628e20d8c fix(cmd): align model listing with codex tiers 2026-03-12 11:00:16 +07:00
RCD 64e2a43259 chore: merge upstream CLIProxyAPI v6.8.51 2026-03-12 10:58:52 +07:00
RCD febd409cca Merge tag 'v6.8.50' 2026-03-12 10:53:58 +07:00
Luis Pater 5484489406 chore(ci): update model catalog fetch method in workflows 2026-03-12 11:19:24 +08:00
Luis Pater 0ac52da460 chore(ci): update model catalog fetch method in release workflow 2026-03-12 10:50:46 +08:00
Luis Pater 817cebb321 Merge pull request #2082 from router-for-me/antigravity
Refactor Antigravity model handling and improve logging
2026-03-12 10:39:13 +08:00
Luis Pater 683f3709d6 Merge pull request #2076 from aikins01/fix/backfill-empty-function-response-names
fix: backfill empty functionResponse.name from preceding functionCall
2026-03-12 10:35:44 +08:00
hkfires dbd42a42b2 fix(model_updater): clarify log message for model refresh failure 2026-03-12 10:32:04 +08:00
hkfires ec24baf757 feat(fetch_antigravity_models): add command to fetch and save Antigravity model list 2026-03-12 10:21:09 +08:00
hkfires dea3e74d35 feat(antigravity): refactor model handling and remove unused code 2026-03-12 09:24:45 +08:00
Aikins Laryea a6c3042e34 refactor: remove redundant bounds checks per code review 2026-03-12 00:12:43 +00:00
Aikins Laryea 861537c9bd fix: backfill empty functionResponse.name from preceding functionCall
when Amp or Claude Code sends functionResponse with an empty name in Gemini
conversation history, the Gemini API rejects the request with 400
"Name cannot be empty". this fix backfills empty names from the
corresponding preceding functionCall parts using positional matching.

covers all three Gemini translator paths:
- gemini/gemini (direct API key)
- antigravity/gemini (OAuth)
- gemini-cli/gemini (Gemini CLI)

also switches fixCLIToolResponse pending group matching from LIFO to
FIFO to correctly handle multiple sequential tool call groups.

fixes #1903
2026-03-12 00:00:38 +00:00
Luis Pater 8c92cb0883 Merge pull request #2056 from lang-911/codex/custom-useragent-request
feat(config/codex): Add Codex header defaults (`user-agent`: override; `beta-features`: default)
2026-03-11 22:56:36 +08:00
Luis Pater 89d7be9525 Merge branch 'dev' into codex/custom-useragent-request 2026-03-11 22:55:50 +08:00
lang-911 2b79d7f22f fix: restore double quotes style in config.example.yaml for consistency and readability 2026-03-11 06:59:26 -07:00
lang-911 163fe287ce fix: codex header defaults example 2026-03-11 06:55:03 -07:00
lang-911 70988d387b Add Codex websocket header defaults 2026-03-11 00:34:57 -07:00
Luis Pater ddaa9d2436 Fixed: #2034
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.
2026-03-11 11:08:02 +08:00
Luis Pater 7b7b258c38 Fixed: #2022
test(translator): add tests for handling Claude system messages as string and array
2026-03-11 10:47:33 +08:00
Luis Pater cf74ed2f0c Merge pull request #2013 from router-for-me/model
Fetch model catalog from network
2026-03-10 19:07:23 +08:00
ailuntz c3762328a5 perf(watcher): reduce auth cache memory 2026-03-10 16:27:10 +08:00
hkfires e333fbea3d feat(updater): update StartModelsUpdater to block until models refresh completes 2026-03-10 14:41:58 +08:00
hkfires efbe36d1d4 feat(updater): change models refresh to one-time fetch on startup 2026-03-10 14:18:54 +08:00
hkfires 8553cfa40e feat(workflows): refresh models catalog in workflows 2026-03-10 14:03:31 +08:00
hkfires 30d5c95b26 feat(registry): refresh model catalog from network 2026-03-10 14:02:54 +08:00
hkfires d1e3195e6f feat(codex): register models by plan tier 2026-03-10 11:20:37 +08:00
Luis Pater ce53d3a287 Fixed: #1997
test(auth-scheduler): add benchmarks and priority-based scheduling improvements

- Added `BenchmarkManagerPickNextMixedPriority500` for mixed-priority performance assessment.
- Updated `pickNextMixed` to prioritize highest ready priority tiers.
- Introduced `highestReadyPriorityLocked` and `pickReadyAtPriorityLocked` for better scheduling logic.
- Added unit test to validate selection of highest priority tiers in mixed provider scenarios.
2026-03-09 22:27:15 +08:00
Blue-B 5f58248016 fix(claude): clamp max_tokens to model limit in normalizeClaudeBudget
When adjustedBudget < minBudget, the previous fix blindly set
max_tokens = budgetTokens+1 which could exceed MaxCompletionTokens.

Now: cap max_tokens at MaxCompletionTokens, recalculate budget, and
disable thinking entirely if constraints are unsatisfiable.

Add unit tests covering raise, clamp, disable, and no-op scenarios.
2026-03-09 22:10:30 +09:00
Luis Pater 4cc99e7449 Merge pull request #1992 from dcrdev/main
System prompt silently dropped when sent as a string
2026-03-09 21:03:15 +08:00
Luis Pater 71773fe032 Merge pull request #1996 from router-for-me/codex/fix-unbounded-websocket-log-buffering
fix: cap websocket body log growth in responses handler
2026-03-09 20:50:38 +08:00
Dominic Robinson a1e0fa0f39 test(executor): cover string system prompt handling in checkSystemInstructionsWithMode 2026-03-09 12:40:27 +00:00
Supra4E8C fc2f0b6983 fix: cap websocket body log growth 2026-03-09 17:48:30 +08:00
Dominic Robinson 5c9997cdac fix: Preserve system prompt when sent as a string instead of content block array 2026-03-09 07:38:11 +00:00
RCD 23e9dda036 docs: track CLIProxyAPI v6.8.49 sync 2026-03-09 09:05:54 +07:00
RCD af4affc150 fix(update): point release checks at ProxyPilot 2026-03-09 09:05:44 +07:00
RCD bd11f5372d chore: merge upstream CLIProxyAPI v6.8.49
# Conflicts:
#	README.md
#	README_CN.md
2026-03-09 09:02:25 +07:00
RCD 98247b0b8d chore: merge upstream CLIProxyAPI v6.8.48 2026-03-09 09:01:45 +07:00
RCD 691aeb78fe chore: merge upstream CLIProxyAPI v6.8.47 2026-03-09 09:01:41 +07:00
Luis Pater f5941a411c test(auth): cover scheduler refresh regression paths 2026-03-09 09:27:56 +08:00
Luis Pater ba672bbd07 Merge PR #1969 into dev 2026-03-09 09:25:06 +08:00
Luis Pater d9c6627a53 Merge pull request #1963 from qixing-jk/docs/add-all-api-hub-showcase
docs: add All API Hub to related projects list
2026-03-09 09:16:41 +08:00
Luis Pater 2e9907c3ac Merge pull request #1959 from thebtf/fix/system-instruction-camelcase
fix: use camelCase systemInstruction in OpenAI-to-Gemini translators
2026-03-09 09:09:03 +08:00
DragonFSKY 90afb9cb73 fix(auth): new OAuth accounts invisible to scheduler after dynamic registration
When new OAuth auth files are added while the service is running,
`applyCoreAuthAddOrUpdate` calls `coreManager.Register()` (which upserts
into the scheduler) BEFORE `registerModelsForAuth()`. At upsert time,
`buildScheduledAuthMeta` snapshots `supportedModelSetForAuth` from the
global model registry — but models haven't been registered yet, so the
set is empty. With an empty `supportedModelSet`, `supportsModel()`
always returns false and the new auth is never added to any model shard.

Additionally, when all existing accounts are in cooldown, the scheduler
returns `modelCooldownError`, but `shouldRetrySchedulerPick` only
handles `*Error` types — so the `syncScheduler` safety-net rebuild
never triggers and the new accounts remain invisible.

Fix:
1. Add `RefreshSchedulerEntry()` to re-upsert a single auth after its
   models are registered, rebuilding `supportedModelSet` from the
   now-populated registry.
2. Call it from `applyCoreAuthAddOrUpdate` after `registerModelsForAuth`.
3. Make `shouldRetrySchedulerPick` also match `*modelCooldownError` so
   the full scheduler rebuild triggers when all credentials are cooling
   down — catching any similar stale-snapshot edge cases.
2026-03-09 03:11:47 +08:00
anime d0cc0cd9a5 docs: add All API Hub to related projects list
- Update README.md with All API Hub entry in English
- Update README_CN.md with All API Hub entry in Chinese
2026-03-09 02:00:16 +08:00
Kirill Turanskiy 338321e553 fix: use camelCase systemInstruction in OpenAI-to-Gemini translators
The Gemini v1internal (cloudcode-pa) and Antigravity Manager endpoints
require camelCase "systemInstruction" in request JSON. The current
snake_case "system_instruction" causes system prompts to be silently
ignored when routing through these endpoints.

Replace all "system_instruction" JSON keys with "systemInstruction" in
chat-completions and responses request translators.
2026-03-08 15:59:13 +03:00
Luis Pater 4f48e5254a Merge pull request #1957 from router-for-me/thinking
fix(translator): pass through adaptive thinking effort
2026-03-08 20:46:58 +08:00
Luis Pater 15dd5db1d7 Merge pull request #1956 from router-for-me/vertex
fix(executor): use aiplatform base url for vertex api key calls
2026-03-08 20:46:28 +08:00
hkfires 424711b718 fix(executor): use aiplatform base url for vertex api key calls 2026-03-08 20:13:12 +08:00
Luis Pater 2b134fc378 test(auth-scheduler): add unit tests and scheduler implementation
- Added comprehensive unit tests for `authScheduler` and related components.
- Implemented `authScheduler` with support for Round Robin, Fill First, and custom selector strategies.
- Improved tracking of auth states, cooldowns, and recovery logic in scheduler.
2026-03-08 05:52:55 +08:00
Luis Pater b9153719b0 Merge pull request #1925 from shenshuoyaoyouguang/pr/openai-compat-pool-thinking
fix(openai-compat): improve pool fallback and preserve adaptive thinking
2026-03-08 01:05:05 +08:00
Luis Pater 631e5c8331 Merge pull request #1922 from shenshuoyaoyouguang/pr/model-registry-safety
fix(registry): clone model snapshots and invalidate available-model cache
2026-03-07 23:01:42 +08:00
Luis Pater e9c60a0a67 Merge pull request #1910 from thebtf/fix/gemini-oauth-error-messages
fix: surface upstream error details in Gemini CLI OAuth onboarding UI
2026-03-07 22:25:18 +08:00
Luis Pater 98a1bb5a7f Merge pull request #1900 from rex-zsd/feature/add-gemini-3.1-flash-image-preview
feat(registry): add gemini-3.1-flash-image-preview model definition
2026-03-07 22:17:10 +08:00
Luis Pater ca90487a8c Merge branch 'main' into feature/add-gemini-3.1-flash-image-preview 2026-03-07 22:16:09 +08:00
Luis Pater 1042489f85 Merge pull request #1893 from thebtf/fix/normalize-ttl-byte-preservation-mainline
fix: preserve original JSON bytes in normalizeCacheControlTTL
2026-03-07 22:14:13 +08:00
Luis Pater 38277c1ea6 Merge pull request #1875 from woqiqishi/fix/tool-use-id-sanitize
fix: sanitize tool_use.id to comply with Claude API regex ^[a-zA-Z0-9_-]+$
2026-03-07 22:06:36 +08:00
Blue-B 07d6689d87 fix(claude): add interleaved-thinking beta header, AMP gzip error decoding, normalizeClaudeBudget max_tokens
1. Always include interleaved-thinking-2025-05-14 beta header so that
   thinking blocks are returned correctly for all Claude models.

2. Remove status-code guard in AMP reverse proxy ModifyResponse so that
   error responses (4xx/5xx) with hidden gzip encoding are decoded
   properly — prevents garbled error messages reaching the client.

3. In normalizeClaudeBudget, when the adjusted budget falls below the
   model minimum, set max_tokens = budgetTokens+1 instead of leaving
   the request unchanged (which causes a 400 from the API).
2026-03-07 21:31:10 +09:00
RCD cc0156f28c Merge pull request #8 from Finesssee/sync-upstream-v6.8.40-to-v6.8.46
chore: sync CLIProxyAPI v6.8.40-v6.8.46
2026-03-07 19:11:59 +07:00
RCD 6d89800038 docs: track CLIProxyAPI v6.8.46 sync 2026-03-07 19:08:42 +07:00
RCD 165de06c69 chore: merge upstream CLIProxyAPI v6.8.46 2026-03-07 19:07:10 +07:00
RCD b402506252 chore: merge upstream CLIProxyAPI v6.8.45 2026-03-07 19:06:38 +07:00
RCD 4a13c2e269 chore: merge upstream CLIProxyAPI v6.8.44 2026-03-07 19:06:18 +07:00
RCD 8ad863a4a2 chore: merge upstream CLIProxyAPI v6.8.43 2026-03-07 19:05:56 +07:00
RCD 08fb275fb6 chore: merge upstream CLIProxyAPI v6.8.42 2026-03-07 19:05:11 +07:00
RCD a445780e43 chore: merge upstream CLIProxyAPI v6.8.41 2026-03-07 19:04:31 +07:00
RCD 3d26dbadb0 Merge upstream CLIProxyAPI v6.8.40 2026-03-07 19:03:29 +07:00
chujian 3a18f6fcca fix(registry): clone slice fields in model map output 2026-03-07 18:53:56 +08:00
chujian 099e734a02 fix(registry): always clone available model snapshots 2026-03-07 18:40:02 +08:00
chujian a52da26b5d fix(auth): stop draining stream pool goroutines after context cancellation 2026-03-07 18:30:33 +08:00
chujian 522a68a4ea fix(openai-compat): retry empty bootstrap streams 2026-03-07 18:08:13 +08:00
chujian a02eda54d0 fix(openai-compat): address review feedback 2026-03-07 17:39:42 +08:00
chujian 97ef633c57 fix(registry): address review feedback 2026-03-07 17:36:57 +08:00
chujian dae8463ba1 fix(registry): clone model snapshots and invalidate available-model cache 2026-03-07 16:59:23 +08:00
chujian 7c1299922e fix(openai-compat): improve pool fallback and preserve adaptive thinking 2026-03-07 16:54:28 +08:00
Luis Pater ddcf1f279d Fixed: #1901
test(websocket): add tests for incremental input and prewarm handling logic

- Added test cases for incremental input support based on upstream capabilities.
- Introduced validation for prewarm handling of `response.create` messages locally.
- Enhanced test coverage for websocket executor behavior, including payload forwarding checks.
- Updated websocket implementation with prewarm and incremental input logic for better testability.
2026-03-07 13:11:28 +08:00
Luis Pater 7e6bb8fdc5 Merge origin/dev into pr-1774-review and resolve watcher conflicts 2026-03-07 11:12:42 +08:00
Luis Pater 9cee8ef87b Merge pull request #1684 from alexey-yanchenko/fix/input-audio-from-openai-to-antigravity
fix: preserve input_audio content parts when proxying to Antigravity
2026-03-07 10:12:28 +08:00
Luis Pater 93fb841bcb Fixed: #1670
test(translator): add unit tests for OpenAI to Claude requests and tool result handling

- Introduced tests for converting OpenAI requests to Claude with text, base64 images, and URL images in tool results.
- Refactored `convertClaudeToolResultContent` and related functionality to properly handle raw content with images and text.
- Updated conversion logic to streamline image handling for both base64 and URL formats.
2026-03-07 09:25:22 +08:00
Luis Pater 5ebc58fab4 refactor(executor): remove legacy connCreateSent logic and standardize response.create usage for all websocket events
- 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.
2026-03-07 09:07:23 +08:00
Luis Pater 2b609dd891 Merge pull request #1912 from FradSer/main
feat(registry): add gemini 3.1 flash lite preview
2026-03-07 05:41:31 +08:00
Frad LEEandClaude Sonnet 4.6 a8cbc68c3e feat(registry): add gemini 3.1 flash lite preview
- Add model to GetGeminiModels()
- Add model to GetGeminiVertexModels()
- Add model to GetGeminiCLIModels()
- Add model to GetAIStudioModels()
- Add to AntigravityModelConfig with thinking levels
- Update gemini-3-flash-preview description

Registers the new lightweight Gemini model across all provider
endpoints for cost-effective high-volume usage scenarios.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 20:52:28 +08:00
Kirill Turanskiy 11a795a01c fix: surface upstream error details in Gemini CLI OAuth onboarding UI
SetOAuthSessionError previously sent generic messages to the management
panel (e.g. "Failed to complete Gemini CLI onboarding"), hiding the
actual error returned by Google APIs. The specific error was only
written to the server log via log.Errorf, which is often inaccessible
in headless/Docker deployments.

Include the upstream error in all 8 OAuth error paths so the
management panel shows actionable messages like "no Google Cloud
projects available for this account" instead of a generic failure.
2026-03-06 13:06:37 +03:00
Luis Pater 2695a99623 fix(translator): conditionally remove service_tier from OpenAI response processing 2026-03-06 11:07:22 +08:00
zhongnan.rex 242aecd924 feat(registry): add gemini-3.1-flash-image-preview model definition 2026-03-06 10:50:04 +08:00
KT-lcz 8e1acbf5d0 Update dashboard URL in README 2026-03-06 09:32:20 +08:00
hkfires ce8cc1ba33 fix(translator): pass through adaptive thinking effort 2026-03-06 09:13:32 +08:00
Kirill Turanskiy 97fdd2e088 fix: preserve original JSON bytes in normalizeCacheControlTTL when no TTL change needed
normalizeCacheControlTTL unconditionally re-serializes the entire request
body through json.Unmarshal/json.Marshal even when no TTL normalization
is needed. Go's json.Marshal randomizes map key order and HTML-escapes
<, >, & characters (to \u003c, \u003e, \u0026), producing different raw
bytes on every call.

Anthropic's prompt caching uses byte-prefix matching, so any byte-level
difference causes a cache miss. This means the ~119K system prompt and
tools are re-processed on every request when routed through CPA.

The fix adds a bool return to normalizeTTLForBlock to indicate whether
it actually modified anything, and skips the marshal step in
normalizeCacheControlTTL when no blocks were changed.
2026-03-05 22:28:01 +03:00
Luis Pater 9397f7049f fix(registry): simplify GPT 5.4 model description in static data 2026-03-06 02:32:56 +08:00
Luis Pater 8822f20d17 feat(registry): add GPT 5.4 model definition to static data 2026-03-06 02:23:53 +08:00
Xu Hong 553d6f50ea fix: sanitize tool_use.id to comply with Claude API regex ^[a-zA-Z0-9_-]+$
Add util.SanitizeClaudeToolID() to replace non-conforming characters in
tool_use.id fields across all five response translators (gemini, codex,
openai, antigravity, gemini-cli).

Upstream tool names may contain dots or other special characters
(e.g. "fs.readFile") that violate Claude's ID validation regex.
The sanitizer replaces such characters with underscores and provides
a generated fallback for empty IDs.

Fixes #1872, Fixes #1849

Made-with: Cursor
2026-03-06 00:10:09 +08:00
Luis Pater f0e5a5a367 test(watcher): add unit test for server update timer cancellation and immediate reload logic
- Add `TestTriggerServerUpdateCancelsPendingTimerOnImmediate` to verify proper handling of server update debounce and timer cancellation.
- Fix logic in `triggerServerUpdate` to prevent duplicate timers and ensure proper cleanup of pending state.
2026-03-05 23:48:50 +08:00
Luis Pater f6dfea9357 Merge pull request #1874 from constansino/fix/watcher-auth-event-storm-debounce
fix(watcher): 合并 auth 事件风暴下的回调触发,降低高 CPU
2026-03-05 23:29:56 +08:00
Luis Pater cc8dc7f62c Merge branch 'main' into dev 2026-03-05 23:13:21 +08:00
Luis Pater a3846ea513 Merge pull request #1870 from sususu98/fix/remove-instructions-restore
cleanup(translator): remove leftover instructions restore in codex responses
2026-03-05 23:12:31 +08:00
Luis Pater 8d44be858e Merge pull request #1834 from DragonFSKY/fix/sse-streaming-accept-encoding
fix(claude): extend gzip fix to SSE success path and header-absent compression (#1763)
2026-03-05 22:57:27 +08:00
Luis Pater 0e6bb076e9 fix(translator): comment out service_tier removal from OpenAI response processing 2026-03-05 22:49:38 +08:00
Luis Pater ac135fc7cb Fixed: #1815
**test(executor): add unit tests for prompt cache key generation in OpenAI `cacheHelper`**
2026-03-05 22:49:23 +08:00
Luis Pater 4e1d09809d Fixed: #1741
fix(translator): handle tool name mappings and improve tool call handling in OpenAI and Claude integrations
2026-03-05 22:24:50 +08:00
constansino ac95e92829 fix(watcher): guard debounced callback after Stop 2026-03-05 19:25:57 +08:00
constansino 8526c2da25 fix(watcher): debounce auth event callback storms 2026-03-05 19:12:57 +08:00
sususu98 68a6cabf8b style: blank unused params in codex responses translator 2026-03-05 16:42:48 +08:00
sususu98 ac0e387da1 cleanup(translator): remove leftover instructions restore in codex responses
The instructions restore logic was originally needed when the proxy
injected custom instructions (per-model system prompts) into requests.
Since ac802a46 removed the injection system, the proxy no longer
modifies instructions before forwarding. The upstream response's
instructions field now matches the client's original value, making
the restore a no-op.

Also removes unused sjson import.

Closes router-for-me/CLIProxyAPI#1868
2026-03-05 16:34:55 +08:00
Luis Pater 5850492a93 Fixed: #1548
test(translator): add unit tests for fallback logic in `ConvertCodexResponseToOpenAI` model assignment
2026-03-05 12:11:54 +08:00
Luis Pater fdbd4041ca Fixed: #1531
fix(gemini): add `deprecated` to unsupported schema keywords

Add `deprecated` to the list of unsupported schema metadata fields in Gemini and update tests to verify its removal.
2026-03-05 11:48:15 +08:00
Luis Pater ebef1fae2a Merge pull request #1511 from stondy0103/fix/responses-nullable-type-array
fix(translator): fix nullable type arrays breaking Gemini/Antigravity API
2026-03-05 11:30:09 +08:00
DragonFSKY 419bf784ab fix(claude): prevent compressed SSE streams and add magic-byte decompression fallback
- Set Accept-Encoding: identity for SSE streams; upstream must not compress
  line-delimited SSE bodies that bufio.Scanner reads directly
- Re-enforce identity after ApplyCustomHeadersFromAttrs to prevent auth
  attribute injection from re-enabling compression on the stream path
- Add peekableBody type wrapping bufio.Reader for non-consuming magic-byte
  inspection of the first 4 bytes without affecting downstream readers
- Detect gzip (0x1f 0x8b) and zstd (0x28 0xb5 0x2f 0xfd) by magic bytes
  when Content-Encoding header is absent, covering misbehaving upstreams
- Remove if-Content-Encoding guard on all three error paths (Execute,
  ExecuteStream, CountTokens); unconditionally delegate to decodeResponseBody
  so magic-byte detection applies consistently to all response paths
- Add 10 tests covering stream identity enforcement, compressed success bodies,
  magic-byte detection without headers, error path decoding, and
  auth attribute override prevention
2026-03-05 06:38:38 +08:00
FSOS a0b068756c fix: remove duplicate 'tui' flag definition causing startup panic
Fixes #5 - The 'tui' flag was registered twice via flag.BoolVar(),
causing a 'panic: flag redefined: tui' crash on startup.
Removed the duplicate at line 208, keeping the original at line 181.
2026-03-05 05:03:16 +07:00
Luis Pater 4bbeb92e9a Fixed: #1135
**test(translator): add tests for `tool_choice` handling in Claude request conversions**
2026-03-04 22:28:26 +08:00
Luis Pater b436dad8bc Merge pull request #1822 from sususu98/fix/strip-defer-loading
fix(translator): strip defer_loading from Claude tool declarations in Codex and Gemini translators
2026-03-04 20:49:48 +08:00
Luis Pater 6ae15d6c44 Merge pull request #1816 from sususu98/fix/antigravity-adaptive-effort
fix(antigravity): pass through adaptive thinking effort level instead of always mapping to high
2026-03-04 20:48:38 +08:00
Luis Pater 0468bde0d6 Merge branch 'dev' into fix/antigravity-adaptive-effort 2026-03-04 20:48:26 +08:00
Luis Pater 1d7329e797 Merge pull request #1825 from router-for-me/vertex
feat(config): support excluded vertex models in config
2026-03-04 20:44:41 +08:00
hkfires 48ffc4dee7 feat(config): support excluded vertex models in config 2026-03-04 18:47:42 +08:00
Luis Pater b680c146c1 chore(docs): update sponsor image links in README files 2026-03-04 18:29:23 +08:00
sususu98 d26ad8224d fix(translator): strip defer_loading from Claude tool declarations in Codex and Gemini translators
Claude's Tool Search feature (advanced-tool-use-2025-11-20 beta) adds
defer_loading field to tool definitions. When proxying Claude requests
to Codex or Gemini, this unknown field causes 400 errors upstream.

Strip defer_loading (and cache_control where missing) in all three
Claude-to-upstream translation paths:
- codex/claude: defer_loading + cache_control
- gemini-cli/claude: defer_loading
- gemini/claude: defer_loading

Fixes #1725, Fixes #1375
2026-03-04 14:21:30 +08:00
hkfires 5c84d69d42 feat(translator): map output_config.effort to adaptive thinking level in antigravity 2026-03-04 13:11:07 +08:00
sususu98 527e4b7f26 fix(antigravity): pass through adaptive thinking effort level instead of always mapping to high 2026-03-04 10:12:45 +08:00
Luis Pater b48485b42b Fixed: #822
**fix(auth): normalize ID casing on Windows to prevent duplicate entries due to case-insensitive paths**
2026-03-04 02:31:20 +08:00
Luis Pater 79009bb3d4 Fixed: #797
**test(auth): add test for preserving ModelStates during auth updates**
2026-03-04 02:06:24 +08:00
Luis Pater 9f95b31158 **fix(translator): enhance handling of mixed output content in Claude requests** 2026-03-03 21:49:41 +08:00
Luis Pater 5da07eae4c Merge pull request #1805 from router-for-me/thinking
Add adaptive thinking support for Claude models
2026-03-03 20:31:31 +08:00
hkfires 835ae178d4 feat(thinking): rename isBudgetBasedProvider to isBudgetCapableProvider and update logic for provider checks 2026-03-03 19:49:51 +08:00
hkfires c80ab8bf0d feat(thinking): improve provider family checks and clamp unsupported levels 2026-03-03 19:05:15 +08:00
hkfires ce87714ef1 feat(thinking): normalize effort levels in adaptive thinking requests to prevent validation errors 2026-03-03 15:10:47 +08:00
hkfires 0452b869e8 feat(thinking): add HasLevel and MapToClaudeEffort functions for adaptive thinking support 2026-03-03 14:16:36 +08:00
hkfires d2e5857b82 feat(thinking): enhance adaptive thinking support across models and update test cases 2026-03-03 13:00:24 +08:00
Luis Pater f9b005f21f Fixed: #1799
**test(auth): add tests for auth file deletion logic with manager and fallback scenarios**
2026-03-03 09:37:24 +08:00
hkfires 532107b4fa test(auth): add global model registry usage to conductor override tests 2026-03-03 09:18:56 +08:00
hkfires c44793789b feat(thinking): add adaptive thinking support for Claude models
Add support for Claude's "adaptive" and "auto" thinking modes using `output_config.effort`. Introduce support for new effort level "max" in adaptive thinking. Update thinking logic, validate model capabilities, and extend converters and handling to ensure compatibility with adaptive modes. Adjust static model data with supported levels and refine handling across translators and executors.
2026-03-03 09:05:31 +08:00
RCD 960422f715 Merge upstream CLIProxyAPI v6.8.38–v6.8.39
Upstream changes:
- Antigravity v1.19.5→1.19.6: Claude 4-6 migration, new models, image_gen payload
- Comprehensive browser fingerprint and proxy tracing header scrubbing
- Whitelist-based header filtering (replaces blacklist approach)
- Singleton HTTP transport to prevent OOM from connection pool leaks
- Disable HTTP/2 ALPN in Antigravity client (fixes connection resets)
- Gemini: route gemini-3.1-flash-image, custom generationConfig passthrough
- GeminiCLI versioning and User-Agent streamlining
- Model registry: input/output modalities, token limits, generation methods
- Removed oauth-model-alias migration logic

Fork resolution:
- Keep both SupportedEndpoints (fork) and modality fields (upstream) in ModelInfo
- Keep our README, delete README_CN.md
2026-03-02 19:51:13 +07:00
Luis Pater 09fec34e1c chore(docs): update sponsor info and GLM model details in README files 2026-03-02 20:30:07 +08:00
hkfires 9229708b6c revert(executor): re-apply PR #1735 antigravity changes with cleanup 2026-03-02 19:30:32 +08:00
hkfires 914db94e79 refactor(headers): streamline User-Agent handling and introduce GeminiCLI versioning 2026-03-02 13:04:30 +08:00
hkfires 660bd7eff5 refactor(config): remove oauth-model-alias migration logic and related tests 2026-03-02 13:02:15 +08:00
hkfires b907d21851 revert(executor): revert antigravity_executor.go changes from PR #1735 2026-03-02 12:54:15 +08:00
lyd123qw2008 dd44413ba5 refactor(watcher): make authSliceToMap always return map 2026-03-02 10:09:56 +08:00
lyd123qw2008 10fa0f2062 refactor(watcher): dedupe auth map conversion in incremental flow 2026-03-02 10:03:42 +08:00
Luis Pater d6cc976d1f chore(executor): remove unused header scrubbing function 2026-03-02 03:40:54 +08:00
Luis Pater 8aa2cce8c5 Merge PR #1735 into dev with conflict resolution and fixes 2026-03-02 03:22:51 +08:00
RCD 6d47c30305 Merge upstream CLIProxyAPI v6.8.33–v6.8.37
Upstream changes:
- Claude Code 2.1.63 fingerprint cloaking alignment
- X-CPA-CLAUDE-1M header handling and beta merging logic
- Claude cache-control guardrails and gzip error decoding
- Antigravity model updates and thinkingBudget default 64000
- Thinking type "auto" support (Amp client → adaptive translation)
- Kimi thinking provider improvements
- .idea directory gitignore

Fork resolution:
- Update SetRetryConfig calls (new maxRetryCredentials param)
- Update retrySettings() destructuring (now returns 3 values)
2026-03-02 02:10:16 +07:00
RCD dfd2e09898 Merge remote-tracking branch 'upstream/main' 2026-03-02 02:08:44 +07:00
Luis Pater 77b42c6165 fix(claude): handle X-CPA-CLAUDE-1M header and ensure proper beta merging logic 2026-03-01 21:39:33 +08:00
Luis Pater 1cbc4834e1 Merge pull request #1771 from edlsh/fix/claude-cache-control-1769
Fix Claude OAuth cache_control regressions and gzip error decoding
2026-03-01 20:17:22 +08:00
lyd123qw2008 30338ecec4 perf(watcher): remove redundant auth clones in incremental path 2026-03-01 14:05:11 +08:00
lyd123qw2008 9a37defed3 test(watcher): restore main test names and max-retry callback coverage 2026-03-01 13:54:03 +08:00
lyd123qw2008 c83a057996 refactor(watcher): make auth file events fully incremental 2026-03-01 13:42:42 +08:00
hkfires a8a5d03c33 chore: ignore .idea directory in git and docker builds 2026-03-01 12:42:59 +08:00
edlsh 76aa917882 Optimize cache-control JSON mutations in Claude executor 2026-02-28 22:47:04 -05:00
edlsh 6ac9b31e4e Handle compressed error decode failures safely 2026-02-28 22:43:46 -05:00
edlsh 0ad3e8457f Clarify cloaking system block cache-control comments 2026-02-28 22:34:14 -05:00
edlsh 444a47ae63 Fix Claude cache-control guardrails and gzip error decoding 2026-02-28 22:32:33 -05:00
Luis Pater 725f4fdff4 Merge pull request #1768 from router-for-me/claude
fix(translator): handle Claude thinking type "auto" like adaptive
2026-03-01 11:03:13 +08:00
Luis Pater c23e46f45d Merge pull request #1767 from router-for-me/antigravity
fix(antigravity): update model configurations and add new models for Antigravity
2026-03-01 11:02:20 +08:00
hkfires b148820c35 fix(translator): handle Claude thinking type "auto" like adaptive 2026-03-01 10:30:19 +08:00
hkfires 134f41496d fix(antigravity): update model configurations and add new models for Antigravity 2026-03-01 10:05:29 +08:00
Luis Pater 1ae994b4aa fix(antigravity): adjust thinkingBudget default to 64000 and update model definitions for Claude 2026-03-01 09:39:39 +08:00
Luis Pater cc1d8f6629 Fixed: #1747
feat(auth): add configurable max-retry-credentials for finer control over cross-credential retries
2026-03-01 02:42:36 +08:00
Luis Pater 5446cd2b02 Merge pull request #1761 from margbug01/fix/thinking-chain-display
fix: support thinking.type=auto from Amp client and decouple thinking translation from unsigned history
2026-03-01 02:30:42 +08:00
margbug01andAmp 8de0885b7d fix: support thinking.type="auto" from Amp client for Antigravity Claude models
## Problem

When using Antigravity Claude models through CLIProxyAPI, the thinking
chain (reasoning content) does not display in the Amp client.

## Root Cause

The Amp client sends `thinking: {"type": "auto"}` in its requests,
but `ConvertClaudeRequestToAntigravity` only handled `"enabled"` and
`"adaptive"` types in its switch statement. The `"auto"` type was
silently ignored, resulting in no `thinkingConfig` being set in the
translated Gemini request. Without `thinkingConfig`, the Antigravity
API returns responses without any thinking content.

Additionally, the Antigravity API for Claude models does not support
`thinkingBudget: -1` (auto mode sentinel). It requires a concrete
positive budget value. The fix uses 128000 as the budget for "auto"
mode, which `ApplyThinking` will then normalize to stay within the
model's actual limits (e.g., capped to `maxOutputTokens - 1`).

## Changes

### internal/translator/antigravity/claude/antigravity_claude_request.go

1. **Add "auto" case** to the thinking type switch statement.
   Sets `thinkingBudget: 128000` and `includeThoughts: true`.
   The budget is subsequently normalized by `ApplyThinking` based
   on model-specific limits.

2. **Add "auto" to hasThinking check** so that interleaved thinking
   hints are injected for tool-use scenarios when Amp sends
   `thinking.type="auto"`.

### internal/registry/model_definitions_static_data.go

3. **Add Thinking configuration** for `claude-sonnet-4-6`,
   `claude-sonnet-4-5`, and `claude-opus-4-6` in
   `GetAntigravityModelConfig()` -- these were previously missing,
   causing `ApplyThinking` to skip thinking config entirely.

## Testing

- Deployed to Railway test instance (cpa-thinking-test)
- Verified via debug logging that:
  - Amp sends `thinking: {"type": "auto"}`
  - CPA now translates this to `thinkingConfig: {thinkingBudget: 128000, includeThoughts: true}`
  - `ApplyThinking` normalizes the budget to model-specific limits
  - Antigravity API receives the correct thinkingConfig

Amp-Thread-ID: https://ampcode.com/threads/T-019ca511-710d-776d-a07c-4b750f871a93
Co-authored-by: Amp <amp@ampcode.com>
2026-03-01 02:18:43 +08:00
Luis Pater a6ce5f36e6 Fixed: #1758
fix(codex): filter billing headers from system result text and update template logic
2026-03-01 01:45:35 +08:00
Luis Pater e73cf42e28 Merge pull request #1750 from tpm2dot0/fix/claude-code-request-fingerprint-alignment
fix(cloak): align outgoing requests with real Claude Code 2.1.63
2026-03-01 01:27:28 +08:00
exe.dev userandClaude Opus 4.6 b45343e812 fix(cloak): align outgoing requests with real Claude Code 2.1.63 fingerprint
Captured and compared outgoing requests from CLIProxyAPI against real
Claude Code 2.1.63 and fixed all detectable differences:

Headers:
- Update anthropic-beta to match 2.1.63: replace fine-grained-tool-streaming
  and prompt-caching-2024-07-31 with context-management-2025-06-27 and
  prompt-caching-scope-2026-01-05
- Remove X-Stainless-Helper-Method header (real Claude Code does not send it)
- Update default User-Agent from "claude-cli/2.1.44 (external, sdk-cli)" to
  "claude-cli/2.1.63 (external, cli)"
- Force Claude Code User-Agent for non-Claude clients to avoid leaking
  real client identity (e.g. curl, OpenAI SDKs) during cloaking

Body:
- Inject x-anthropic-billing-header as system[0] (matches real format)
- Change system prompt identifier from "You are Claude Code..." to
  "You are a Claude agent, built on Anthropic's Claude Agent SDK."
- Add cache_control with ttl:"1h" to match real request format
- Fix user_id format: user_[64hex]_account_[uuid]_session_[uuid]
  (was missing account UUID)
- Disable tool name prefix (set claudeToolPrefix to empty string)

TLS:
- Switch utls fingerprint from HelloFirefox_Auto to HelloChrome_Auto
  (closer to Node.js/OpenSSL used by real Claude Code)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-28 09:19:06 +00:00
Luis Pater 8599b1560e Fixed: #1716
feat(kimi): add support for explicit disabled thinking and reasoning effort handling
2026-02-28 05:29:07 +08:00
Luis Pater 8bde8c37c0 Fixed: #1711
fix(server): use resolved log directory for request logger initialization and test fallback logic
2026-02-28 05:21:01 +08:00
RCD 0af0ad14e5 Merge upstream CLIProxyAPI v6.8.28–v6.8.32
Upstream changes:
- Codex responses compaction payload compatibility
- Codex usage_limit_reached retry-after, deterministic parsing
- Codex refresh_token_reused non-retryable fix
- Qwen rate limiting and quota error handling
- Context management compatibility simplification
- Antigravity tool_result image fix, model list backfill, deep copy cache
- Auth auto-refresh interval/concurrency limiting
- Auth hook OnResult refactor (replaces MarkResult)
- Gemini-3.1-flash-image support
- Registry cleanup of outdated model definitions

Fork resolution:
- Accept upstream's consolidated conductor.go (auto-refresh, round-tripper)
- Delete stale conductor_oauth.go, conductor_token.go (upstream reversed split)
- Delete stale provider_rotation_test.go (references removed method)
2026-02-27 20:58:16 +07:00
RCD a82585ba21 chore: add .gitallowed for upstream OAuth credentials
Public Google OAuth client IDs and secrets from upstream CLIProxyAPI.
These are intentionally embedded (installed/CLI app OAuth flow) and
identical to the upstream public repo. Allowlisting prevents GitHub
push protection from blocking merges.
2026-02-27 20:50:23 +07:00
Luis Pater 27c68f5bb2 fix(auth): replace MarkResult with hook OnResult for result handling 2026-02-27 20:47:46 +08:00
maplelove 68dd2bfe82 fix(translator): allow passthrough of custom generationConfig for all Gemini-like providers 2026-02-27 17:13:42 +08:00
Luis Pater 41b1cf2273 Merge pull request #1734 from huangusaki/main
feat(registry): add gemini-3.1-flash-image support
2026-02-27 16:12:05 +08:00
maplelove 2baf35b3ef fix(executor): bump antigravity UA to 1.19.6 and align image_gen payload 2026-02-27 14:09:37 +08:00
maplelove 846e75b893 feat(gemini): route gemini-3.1-flash-image identically to gemini-3-pro-image 2026-02-27 13:32:06 +08:00
maplelove fc0257d6d9 refactor: consolidate duplicate UA and header scrubbing into shared misc functions 2026-02-27 10:57:13 +08:00
maplelove f3c164d345 feat(antigravity): update to v1.19.5 with new models and Claude 4-6 migration 2026-02-27 10:34:27 +08:00
maplelove 4040b1e766 Merge remote-tracking branch 'upstream/dev' into dev
# Conflicts:
#	internal/runtime/executor/antigravity_executor.go
2026-02-27 10:29:50 +08:00
huang_usaki 3b4f9f43db feat(registry): add gemini-3.1-flash-image support 2026-02-27 10:20:46 +08:00
Luis Pater 0da34d3c2d Merge pull request #1668 from lyd123qw2008/fix/codex-usage-limit-retry-after
fix(codex): honor usage_limit_reached resets_at for retry_after
2026-02-27 06:01:44 +08:00
Luis Pater 74bf7eda8f Merge pull request #1686 from lyd123qw2008/fix/auth-refresh-concurrency-limit
fix(auth): limit auto-refresh concurrency to prevent refresh storms
2026-02-27 05:59:20 +08:00
Luis Pater 8c6c90da74 fix(registry): clean up outdated model definitions in static data 2026-02-26 23:12:40 +08:00
Luis Pater 24bcfd9c03 Merge pull request #1699 from 123hi123/fix/antigravity-primary-model-fallback
fix(antigravity): keep primary model list and backfill empty auths
2026-02-26 04:28:29 +08:00
Luis Pater 816fb4c5da Merge pull request #1682 from sususu98/fix/tool-result-image-parts
fix(antigravity): place tool_result images in functionResponse.parts and unify mimeType
2026-02-25 23:14:35 +08:00
RCD 6ffc26271c Merge upstream CLIProxyAPI v6.8.27
Upstream changes:
- Post-auth hook system (RequestInfo refactor + hook chain)
- Credential-based round-robin for gemini-cli virtual auths
- Codex additive device-code login flow
- File input passthrough for /chat/completions and /responses
- Gemini → OpenAI usage conversion fix
- Responses stream: model/usage in translated streams, valid SSE error chunks
- Revert reasoning effort clamping

Fork resolution:
- Keep both integrationManager (fork) and postAuthHook (upstream) in handler struct
2026-02-25 14:49:42 +07:00
Luis Pater d24ea4ce2a Merge pull request #1664 from ciberponk/pr/responses-compaction-compat
feat: add codex responses compatibility for compaction payloads
2026-02-25 01:21:59 +08:00
Luis Pater 2c30c981ae Merge pull request #1687 from lyd123qw2008/fix/codex-refresh-token-reused-no-retry
fix(codex): stop retrying refresh_token_reused errors
2026-02-25 01:19:30 +08:00
Luis Pater aa1da8a858 Merge pull request #1685 from lyd123qw2008/fix/auth-auto-refresh-interval
fix(auth): respect configured auto-refresh interval
2026-02-25 01:13:47 +08:00
Luis Pater f1e9a787d7 Merge pull request #1676 from piexian/feat/qwen-quota-handling-clean
feat(qwen): add rate limiting and quota error handling
2026-02-25 01:07:55 +08:00
Luis Pater c66cb0afd2 Merge pull request #1683 from dusty-du/codex/device-login-flow
Add additive Codex device-code login flow
2026-02-25 00:50:48 +08:00
Luis Pater fb48eee973 Merge pull request #1680 from canxin121/fix/responses-stream-error-chunks
fix(responses): emit schema-valid SSE chunks
2026-02-25 00:49:06 +08:00
Luis Pater bb44e5ec44 Merge pull request #1701 from router-for-me/openai
Revert "Merge pull request #1627 from thebtf/fix/reasoning-effort-clamping"
2026-02-25 00:46:13 +08:00
comalot 514ae341c8 fix(antigravity): deep copy cached model metadata 2026-02-24 20:14:01 +08:00
hkfires 0659ffab75 Revert "Merge pull request #1627 from thebtf/fix/reasoning-effort-clamping" 2026-02-24 19:47:53 +08:00
comalot 8ce07f38dd fix(antigravity): keep primary model list and backfill empty auths 2026-02-24 16:16:44 +08:00
Luis Pater 7cb398d167 Merge pull request #1663 from rensumo/main
feat: implement credential-based round-robin for gemini-cli
2026-02-24 06:02:50 +08:00
Luis Pater c3e12c5e58 Merge pull request #1654 from alexey-yanchenko/feature/pass-file-inputs
Pass file input from /chat/completions and /responses to codex and claude
2026-02-24 05:53:11 +08:00
Luis Pater 1825fc7503 Merge pull request #1643 from alexey-yanchenko/fix/gemini-prompt-tokens
Fix usage convertation from gemini response to openai format
2026-02-24 05:46:13 +08:00
Luis Pater 48732ba05e Merge pull request #1527 from HEUDavid/feat/auth-hook
feat(auth): add post-auth hook mechanism
2026-02-24 05:33:13 +08:00
canxin121 acf483c9e6 fix(responses): reject invalid SSE data JSON
Guard the openai-response streaming path against truncated/invalid SSE data payloads by validating data: JSON before forwarding; surface a 502 terminal error instead of letting clients crash with JSON parse errors.
2026-02-24 01:42:54 +08:00
lyd123qw2008 3b3e0d1141 test(codex): log non-retryable refresh error and cover single-attempt behavior 2026-02-23 22:41:33 +08:00
lyd123qw2008 7acd428507 fix(codex): stop retrying refresh_token_reused errors 2026-02-23 22:31:30 +08:00
lyd123qw2008 0aaf177640 fix(auth): limit auto-refresh concurrency to prevent refresh storms 2026-02-23 22:28:41 +08:00
lyd123qw2008 450d1227bd fix(auth): respect configured auto-refresh interval 2026-02-23 22:07:50 +08:00
Alexey Yanchenko b7588428c5 fix: preserve input_audio content parts when proxying to Antigravity
- Add input_audio handling in chat/completions translator (antigravity_openai_request.go)
- Add input_audio handling in responses translator (gemini_openai-responses_request.go)
- Map OpenAI audio formats (mp3, wav, ogg, flac, aac, webm, pcm16, g711_ulaw, g711_alaw) to correct MIME types for Gemini inlineData
2026-02-23 20:50:28 +07:00
test 492b9c46f0 Add additive Codex device-code login flow 2026-02-23 06:30:04 -05:00
RCD dd41652e99 feat: add CODEOWNERS, PR template, and /health endpoint 2026-02-23 15:38:56 +07:00
RCD f4f66ad0d3 feat: add pre-commit hooks, go vet, and test coverage threshold (30%) in CI 2026-02-23 15:33:43 +07:00
sususu98 4e26182d14 fix(antigravity): place tool_result images in functionResponse.parts and unify mimeType
Move base64 image data from Claude tool_result into functionResponse.parts
as inlineData instead of outer sibling parts, preventing context bloat.
Unify all inlineData field naming to camelCase mimeType across Claude,
OpenAI, and Gemini translators. Add comprehensive edge case tests and
Gemini-side regression test for functionResponse.parts preservation.
2026-02-23 13:38:21 +08:00
maplelove 8f97a5f77c feat(registry): expose input modalities, token limits, and generation methods for Antigravity models 2026-02-23 13:33:51 +08:00
canxin121 eb7571936c revert: translator changes (path guard)
CI blocks PRs that modify internal/translator. Revert translator edits and keep only the /v1/responses streaming error-chunk fix; file an issue for translator conformance work.
2026-02-23 13:30:43 +08:00
canxin121 5382764d8a fix(responses): include model and usage in translated streams
Ensure response.created and response.completed chunks produced by the OpenAI/Gemini/Claude translators always include required fields (response.model and response.usage) so clients validating Responses SSE do not fail schema validation.
2026-02-23 13:22:06 +08:00
canxin121 49c8ec69d0 fix(openai): emit valid responses stream error chunks
When /v1/responses streaming fails after headers are sent, we now emit a type=error chunk instead of an HTTP-style {error:{...}} payload, preventing AI SDK chunk validation errors.
2026-02-23 12:59:50 +08:00
RCD cf558dd166 Merge upstream CLIProxyAPI v6.8.18–v6.8.26
Upstream changes:
- Codex WebSocket executor and Codex response handlers
- Header passthrough (upstream response headers forwarded to clients)
- ExecuteStream returns *StreamResult (wraps channel + headers)
- Embeddings handler with synthetic fallback
- User ID cache for executors
- Gemini schema/request fixes
- New test coverage for bootstrap retries, error responses

Fork resolution:
- Delete upstream's modular TUI files (app.go, styles.go, dashboard.go,
  auth_tab.go, config_tab.go, keys_tab.go, logs_tab.go, oauth_tab.go,
  usage_tab.go, i18n.go, loghook.go) — keep fork's Flight Deck tui.go
- Add PassthroughHeaders field to SDKConfig
- Fix embeddings handler to capture 3-value ExecuteWithAuthManager return
- Update test mocks (conductor_test, auth_flow_test, multi_provider_test,
  gemini_executor_test) for new ExecuteStream signature
- Fix tuiMode → launchTUI flag variable reference
- Remove unused "io" import from main.go
2026-02-23 11:58:54 +07:00
piexian 3b421c8181 feat(qwen): add rate limiting and quota error handling
- Add 60 requests/minute rate limiting per credential using sliding window
- Detect insufficient_quota errors and set cooldown until next day (Beijing time)
- Map quota errors (HTTP 403/429) to 429 with retryAfter for conductor integration
- Cache Beijing timezone at package level to avoid repeated syscalls
- Add redactAuthID function to protect credentials in logs
- Extract wrapQwenError helper to consolidate error handling
2026-02-23 00:38:46 +08:00
Luis Pater 713388dd7b Fixed: #1675
fix(gemini): add model definitions for Gemini 3.1 Pro High and Image
2026-02-23 00:12:57 +08:00
maplelove 2a4d3e60f3 Merge remote-tracking branch 'upstream/dev' into dev 2026-02-23 00:01:47 +08:00
maplelove 8b5af2ab84 fix(executor): match real Antigravity OAuth UA, remove redundant header scrubbing on new requests 2026-02-22 23:20:12 +08:00
Luis Pater e6c7af0fa9 Merge pull request #1522 from soilSpoon/feature/canceled
feature(proxy): Adds special handling for client cancellations in proxy error handler
2026-02-22 22:02:59 +08:00
Luis Pater d210be06c2 fix(gemini): update min Thinking value and add Gemini 3.1 Pro Preview model definition 2026-02-22 21:51:32 +08:00
maplelove d887716ebd refactor(executor): switch HttpRequest to whitelist-based header filtering 2026-02-22 21:00:12 +08:00
maplelove 5dc1848466 feat(scrub): add comprehensive browser fingerprint and client identity header scrubbing 2026-02-22 20:51:00 +08:00
maplelove 9491517b26 fix(executor): use singleton transport to prevent OOM from connection pool leaks 2026-02-22 20:17:30 +08:00
maplelove 9370b5bd04 fix(executor): completely scrub all proxy tracing headers in executor 2026-02-22 19:43:10 +08:00
maplelove abb51a0d93 fix(executor): correctly disable http2 ALPN in Antigravity client to resolve connection reset errors 2026-02-22 19:23:48 +08:00
maplelove c8d809131b fix(executor): improve antigravity reverse proxy emulation
- force http/1.1 instead of http/2

- explicit connection close

- strip proxy headers X-Forwarded-For and X-Real-IP

- add project id to fetch models payload
2026-02-22 18:41:58 +08:00
maplelove dd71c73a9f fix: align gemini-cli upstream communication headers
Removed legacy Client-Metadata and explicit API-Client headers. Dynamically generating accurate User-Agent strings matching the official cli.
2026-02-22 17:07:17 +08:00
fan afc8a0f9be refactor: simplify context_management compatibility handling 2026-02-21 22:20:48 +08:00
Luis Pater d6ec33e8e1 Merge pull request #1662 from matchch/contribute/cache-user-id
feat: add cache-user-id toggle for Claude cloaking
2026-02-21 20:51:30 +08:00
Luis Pater 081cfe806e fix(gemini): correct Created timestamps for Gemini 3.1 Pro Preview model definitions 2026-02-21 20:47:47 +08:00
hkfires c1c62a6c04 feat(gemini): add Gemini 3.1 Pro Preview model definitions 2026-02-21 20:42:29 +08:00
lyd123qw2008 a99522224f refactor(codex): make retry-after parsing deterministic for tests 2026-02-21 14:13:38 +08:00
lyd123qw2008 f5d46b9ca2 fix(codex): honor usage_limit_reached resets_at for retry_after 2026-02-21 13:50:23 +08:00
ciberponk d693d7993b feat: support responses compaction payload compatibility for codex translator 2026-02-21 12:56:10 +08:00
rensumo 5936f9895c feat: implement credential-based round-robin for gemini-cli virtual auths
Changes the RoundRobinSelector to use two-level round-robin when
gemini-cli virtual auths are detected (via gemini_virtual_parent attr):
- Level 1: cycle across credential groups (parent accounts)
- Level 2: cycle within each group's project auths

Credentials start from a random offset (rand.IntN) for fair distribution.
Non-virtual auths and single-credential scenarios fall back to flat RR.

Adds 3 test cases covering multi-credential grouping, single-parent
fallback, and mixed virtual/non-virtual fallback.
2026-02-21 12:49:48 +08:00
matchch 2fdf5d2793 feat: add cache-user-id toggle for Claude cloaking
Default to generating a fresh random user_id per request instead of
reusing cached IDs. Add cache-user-id config option to opt in to the
previous caching behavior.

- Add CacheUserID field to CloakConfig
- Extract user_id cache logic to dedicated file
- Generate fresh user_id by default, cache only when enabled
- Add tests for both paths
2026-02-21 12:31:20 +08:00
Luis Pater 7b0eb41ebc Merge pull request #1660 from Grivn/fix/claude-token-url
fix(claude): use api.anthropic.com for OAuth token exchange
2026-02-20 21:52:08 +08:00
GrivnandClaude Opus 4.6 ef5901c81b fix(claude): use api.anthropic.com for OAuth token exchange
console.anthropic.com is now protected by a Cloudflare managed challenge
that blocks all non-browser POST requests to /v1/oauth/token, causing
`-claude-login` to fail with a 403 error.

Switch to api.anthropic.com which hosts the same OAuth token endpoint
without the Cloudflare managed challenge.

Fixes #1659

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 20:11:27 +08:00
Luis Pater d4829c82f7 Merge pull request #1652 from thebtf/fix/claude-translator-arguments
fix(translator): handle tool call arguments in codex→claude streaming translator
2026-02-20 19:50:20 +08:00
Luis Pater a5f4166a9b Merge pull request #1644 from possible055/main
feat: add Gemini 3.1 Pro Preview model definition
2026-02-20 19:44:59 +08:00
Alexey Yanchenko 0cbfe7f457 Pass file input from /chat/completions and /responses to codex and claude 2026-02-20 10:25:44 +07:00
Kirill Turanskiy 1cc21cc45b fix: prevent duplicate function call arguments when delta events precede done
Non-spark codex models (gpt-5.3-codex, gpt-5.2-codex) stream function call
arguments via multiple delta events followed by a done event. The done handler
unconditionally emitted the full arguments, duplicating what deltas already
streamed. This produced invalid double JSON that Claude Code couldn't parse,
causing tool calls to fail with missing parameters and infinite retry loops.

Add HasReceivedArgumentsDelta flag to track whether delta events were received.
The done handler now only emits arguments when no deltas preceded it (spark
models), while delta-based streaming continues to work for non-spark models.
2026-02-19 23:18:14 +03:00
Kirill Turanskiy 07cf616e2b fix: handle response.function_call_arguments.done in codex→claude streaming translator
Some Codex models (e.g. gpt-5.3-codex-spark) send function call arguments
in a single "done" event without preceding "delta" events. The streaming
translator only handled "delta" events, causing tool call arguments to be
lost — resulting in empty tool inputs and infinite retry loops in clients
like Claude Code.

Emit the full arguments from the "done" event as a single input_json_delta
so downstream clients receive the complete tool input.
2026-02-19 23:18:14 +03:00
Luis Pater 4445a165e9 test(handlers): add tests for passthrough headers behavior in WriteErrorResponse 2026-02-19 21:49:44 +08:00
Luis Pater e92e2af71a Merge branch 'codex/pr-1626' into dev 2026-02-19 21:33:23 +08:00
Luis Pater a6bdd9a652 feat: add passthrough headers configuration
- Introduced `passthrough-headers` option in configuration to control forwarding of upstream response headers.
- Updated handlers to respect the passthrough headers setting.
- Added tests to verify behavior when passthrough is enabled or disabled.
2026-02-19 21:31:29 +08:00
Luis Pater 349a6349b3 Merge pull request #1645 from tinyc0der/fix/antigravity-tool-result-json
fix(antigravity): prevent invalid JSON when tool_result has no content
2026-02-19 21:01:25 +08:00
TinyCoder 00822770ec fix(antigravity): prevent invalid JSON when tool_result has no content
sjson.SetRaw with an empty string produces malformed JSON (e.g. "result":}).
This happens when a Claude tool_result block has no content field, causing
functionResponseResult.Raw to be "". Guard against this by falling back to
sjson.Set with an empty string only when .Raw is empty.
2026-02-19 17:08:39 +07:00
apparition 1a0ceda0fc feat: add Gemini 3.1 Pro Preview model definition 2026-02-19 17:43:08 +08:00
Alexey Yanchenko b9ae4ab803 Fix usage convertation from gemini response to openai format 2026-02-19 15:34:59 +07:00
Luis Pater 72add453d2 docs: add OmniRoute to README 2026-02-19 13:23:25 +08:00
Luis Pater 2789396435 fix: ensure connection-scoped headers are filtered in upstream requests
- Added `connectionScopedHeaders` utility to respect "Connection" header directives.
- Updated `FilterUpstreamHeaders` to remove connection-scoped headers dynamically.
- Refactored and tested upstream header filtering with additional validations.
- Adjusted upstream header handling during retries to replace headers safely.
2026-02-19 13:19:10 +08:00
Luis Pater 61da7bd981 Merge PR #1626 into codex/pr-1626 2026-02-19 04:49:14 +08:00
Luis Pater 9c040445af Merge pull request #1635 from thebtf/fix/openai-translator-tool-streaming
fix: handle tool call argument streaming in Codex→OpenAI translator
2026-02-19 04:22:12 +08:00
Luis Pater fff866424e Merge pull request #1628 from thebtf/fix/masquerading-headers
fix: update Claude masquerading headers and configurable defaults
2026-02-19 04:19:59 +08:00
Luis Pater 2d12becfd6 Merge pull request #1627 from thebtf/fix/reasoning-effort-clamping
fix: clamp reasoning_effort to valid OpenAI-format values
2026-02-19 04:15:19 +08:00
Luis Pater 252f7e0751 Merge pull request #1625 from thebtf/feat/tool-prefix-config
feat: add per-auth tool_prefix_disabled option
2026-02-19 04:07:22 +08:00
Luis Pater b2b17528cb Merge branch 'pr-1624' into dev
# Conflicts:
#	internal/runtime/executor/claude_executor.go
#	internal/runtime/executor/claude_executor_test.go
2026-02-19 04:05:04 +08:00
Luis Pater 55f938164b Merge pull request #1618 from alexey-yanchenko/fix/completions-usage
Fix empty usage in /v1/completions
2026-02-19 03:57:11 +08:00
Luis Pater 76294f0c59 Merge pull request #1608 from thebtf/fix/tool-reference-proxy-prefix-mainline
fix: add proxy_ prefix handling for tool_reference content blocks
2026-02-19 03:50:34 +08:00
Luis Pater 2bcee78c6e feat(tui): add standalone mode and API-based log polling
- Implemented `--standalone` mode to launch an embedded server for TUI.
- Enhanced TUI client to support API-based log polling when log hooks are unavailable.
- Added authentication gate for password input and connection handling.
- Improved localization and UX for logs, authentication, and status bar rendering.
2026-02-19 03:19:18 +08:00
Luis Pater 7fe8246a9f Merge branch 'tui' into dev 2026-02-19 03:18:24 +08:00
Luis Pater 93fe58e31e feat(tui): add standalone mode and API-based log polling
- Implemented `--standalone` mode to launch an embedded server for TUI.
- Enhanced TUI client to support API-based log polling when log hooks are unavailable.
- Added authentication gate for password input and connection handling.
- Improved localization and UX for logs, authentication, and status bar rendering.
2026-02-19 03:18:08 +08:00
Luis Pater e5b5dc870f chore(executor): remove unused Openai-Beta header from Codex executor 2026-02-19 02:19:48 +08:00
Luis Pater a54877c023 Merge branch 'dev' 2026-02-19 02:03:41 +08:00
Luis Pater bb86a0c0c4 feat(logging, executor): add request logging tests and WebSocket-based Codex executor
- Introduced unit tests for request logging middleware to enhance coverage.
- Added WebSocket-based Codex executor to support Responses API upgrade.
- Updated middleware logic to selectively capture request bodies for memory efficiency.
- Enhanced Codex configuration handling with new WebSocket attributes.
2026-02-19 01:57:02 +08:00
Kirill Turanskiy 5fa23c7f41 fix: handle tool call argument streaming in Codex→OpenAI translator
The OpenAI Chat Completions translator was silently dropping
response.function_call_arguments.delta and
response.function_call_arguments.done Codex SSE events, meaning
tool call arguments were never streamed incrementally to clients.

Add proper handling mirroring the proven Claude translator pattern:

- response.output_item.added: announce tool call (id, name, empty args)
- response.function_call_arguments.delta: stream argument chunks
- response.function_call_arguments.done: emit full args if no deltas
- response.output_item.done: defensive fallback for backward compat

State tracking via HasReceivedArgumentsDelta and HasToolCallAnnounced
ensures no duplicate argument emission and correct behavior for models
like codex-spark that skip delta events entirely.
2026-02-18 19:09:05 +03:00
Kirill Turanskiy 73dc0b10b8 fix: update Claude masquerading headers and make them configurable
Update hardcoded X-Stainless-* and User-Agent defaults to match
Claude Code 2.1.44 / @anthropic-ai/sdk 0.74.0 (verified via
diagnostic proxy capture 2026-02-17).

Changes:
- X-Stainless-Os/Arch: dynamic via runtime.GOOS/GOARCH
- X-Stainless-Package-Version: 0.55.1 → 0.74.0
- X-Stainless-Timeout: 60 → 600
- User-Agent: claude-cli/1.0.83 (external, cli) → claude-cli/2.1.44 (external, sdk-cli)

Add claude-header-defaults config section so values can be updated
without recompilation when Claude Code releases new versions.
2026-02-18 03:38:51 +03:00
Kirill Turanskiy 2ea95266e3 fix: clamp reasoning_effort to valid OpenAI-format values
CPA-internal thinking levels like 'xhigh' and 'minimal' are not accepted
by OpenAI-format providers (MiniMax, etc.). The OpenAI applier now maps
non-standard levels to the nearest valid reasoning_effort value before
writing to the request body:

  xhigh   → high
  minimal → low
  auto    → medium
2026-02-18 03:36:42 +03:00
Kirill Turanskiy 1f8f198c45 feat: passthrough upstream response headers to clients
CPA previously stripped ALL response headers from upstream AI provider
APIs, preventing clients from seeing rate-limit info, request IDs,
server-timing and other useful headers.

Changes:
- Add Headers field to Response and StreamResult structs
- Add FilterUpstreamHeaders helper (hop-by-hop + security denylist)
- Add WriteUpstreamHeaders helper (respects CPA-set headers)
- ExecuteWithAuthManager/ExecuteCountWithAuthManager now return headers
- ExecuteStreamWithAuthManager returns headers from initial connection
- All 11 provider executors populate Response.Headers
- All handler call sites write filtered upstream headers before response

Filtered headers (not forwarded):
- RFC 7230 hop-by-hop: Connection, Transfer-Encoding, Keep-Alive, etc.
- Security: Set-Cookie
- CPA-managed: Content-Length, Content-Encoding
2026-02-18 00:16:22 +03:00
Kirill Turanskiy 9261b0c20b feat: add per-auth tool_prefix_disabled option
Allow disabling the proxy_ tool name prefix on a per-account basis.
Users who route their own Anthropic account through CPA can set
"tool_prefix_disabled": true in their OAuth auth JSON to send tool
names unchanged to Anthropic.

Default behavior is fully preserved — prefix is applied unless
explicitly disabled.

Changes:
- Add ToolPrefixDisabled() accessor to Auth (reads metadata key
  "tool_prefix_disabled" or "tool-prefix-disabled")
- Gate all 6 prefix apply/strip points with the new flag
- Add unit tests for the accessor
2026-02-17 21:48:19 +03:00
Kirill Turanskiy 7cc725496e fix: skip proxy_ prefix for built-in tools in message history
The proxy_ prefix logic correctly skips built-in tools (those with a
non-empty "type" field) in tools[] definitions but does not skip them
in messages[].content[] tool_use blocks or tool_choice. This causes
web_search in conversation history to become proxy_web_search, which
Anthropic does not recognize.

Fix: collect built-in tool names from tools[] into a set and also
maintain a hardcoded fallback set (web_search, code_execution,
text_editor, computer) for cases where the built-in tool appears in
history but not in the current request's tools[] array. Skip prefixing
in messages and tool_choice when name matches a built-in.
2026-02-17 21:42:32 +03:00
Alexey Yanchenko 709d999f9f Add usage to /v1/completions 2026-02-17 17:21:03 +07:00
Kirill Turanskiy 24c18614f0 fix: skip built-in tools in tool_reference prefix + refactor to switch
- Collect built-in tool names (those with a "type" field like
  web_search, code_execution) and skip prefixing tool_reference
  blocks that reference them, preventing name mismatch.
- Refactor if-else if chains to switch statements in all three
  prefix functions for idiomatic Go style.
2026-02-16 19:37:11 +03:00
Kirill Turanskiy 603f06a762 fix: handle tool_reference nested inside tool_result.content[]
tool_reference blocks can appear nested inside tool_result.content[]
arrays, not just at the top level of messages[].content[]. The prefix
logic now iterates into tool_result blocks with array content to find
and prefix/strip nested tool_reference.tool_name fields.
2026-02-16 19:06:24 +03:00
Kirill TuranskiyandKirill Turanskiy 98f0a3e3bd fix: add proxy_ prefix handling for tool_reference content blocks (#1)
applyClaudeToolPrefix, stripClaudeToolPrefixFromResponse, and
stripClaudeToolPrefixFromStreamLine now handle "tool_reference" blocks
(field "tool_name") in addition to "tool_use" blocks (field "name").

Without this fix, tool_reference blocks in conversation history retain
their original unprefixed names while tool definitions carry the proxy_
prefix, causing Anthropic API 400 errors: "Tool reference 'X' not found
in available tools."

Co-authored-by: Kirill Turanskiy <kt@novamedia.ru>
2026-02-16 19:06:24 +03:00
Luis Pater 453aaf8774 chore(runtime): update Qwen executor user agent and headers for compatibility with new runtime standards 2026-02-16 23:29:47 +08:00
Supra4E8C 1b1ab1fb9b Merge pull request #1606 from router-for-me/add-qwen-3.5
feat(registry): add Qwen 3.5 Plus model definitions
2026-02-16 23:10:53 +08:00
Supra4E8C a9d0bb72da feat(registry): add Qwen 3.5 Plus model definitions 2026-02-16 22:55:37 +08:00
RCD 4cf25c05ce Merge upstream CLIProxyAPI v6.8.15–v6.8.17
Upstream changes:
- feat: add Google One login and improve Gemini CLI auto-discovery
- feat: add gpt-5.3-codex-spark model definition
- feat: add 'kimi' channel support in model definitions
- feat: pass cache usage from codex to openai chat completions
- fix: normalize Gemini credential file prefix for consistency
- refactor: replace manual pointer assignments with new()
- chore: update Go to 1.26, update Codex client version

Fork fixes:
- Bump mise Go pin to 1.26.0
- Remove stale .syso resource files (incompatible with Go 1.26 linker)
2026-02-16 08:01:38 +07:00
lhpqaq 2c8821891c fix(tui): update with review 2026-02-16 00:24:25 +08:00
haopengandgemini-code-assist[bot] 0a2555b0f3 Update internal/tui/auth_tab.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-16 00:11:31 +08:00
lhpqaq 020df41efe chore(tui): update readme, fix usage 2026-02-16 00:04:04 +08:00
lhpqaq f31f7f701a feat(tui): add i18n 2026-02-15 15:42:59 +08:00
Supra4E8C b5fe78eb70 Merge pull request #1597 from router-for-me/kimi-fix
feat(registry): add support for 'kimi' channel in model definitions
2026-02-15 15:35:17 +08:00
Supra4E8C d1f667cf8d feat(registry): add support for 'kimi' channel in model definitions 2026-02-15 15:21:33 +08:00
lhpqaq 54ad7c1b6b feat(tui): add manager tui 2026-02-15 14:52:40 +08:00
Luis Pater 55789df275 chore(docker): update Go base image to 1.26-alpine 2026-02-15 14:26:44 +08:00
Luis Pater 46a6782065 refactor(all): replace manual pointer assignments with new to enhance code readability and maintainability 2026-02-15 14:10:10 +08:00
Luis Pater c359f61859 fix(auth): normalize Gemini credential file prefix for consistency 2026-02-15 13:59:33 +08:00
Luis Pater 908c8eab5b Merge pull request #1543 from sususu98/feat/gemini-cli-google-one
feat(gemini-cli): add Google One login and improve auto-discovery
2026-02-15 13:58:21 +08:00
Luis Pater f5f2c69233 Merge pull request #1595 from alexey-yanchenko/feature/cache-usage-from-codex-to-chat-completions
Pass cache usage from codex to openai chat completions
2026-02-15 13:56:46 +08:00
Alexey Yanchenko 63d4de5eea Pass cache usage from codex to openai chat completions 2026-02-15 12:04:15 +07:00
이대희 a45c6defa7 Merge remote-tracking branch 'upstream/main' into feature/canceled 2026-02-13 15:07:32 +09:00
Luis Pater ae1e8a5191 chore(runtime, registry): update Codex client version and GPT-5.3 model creation date 2026-02-13 12:47:48 +08:00
Luis Pater b3ccc55f09 Merge pull request #1574 from fbettag/feat/gpt-5.3-codex-spark
feat(registry): add gpt-5.3-codex-spark model definition
2026-02-13 12:46:08 +08:00
이대희 40bee3e8d9 Merge branch 'main' into feature/canceled 2026-02-13 13:37:55 +09:00
Franz Bettagandgemini-code-assist[bot] 1ce56d7413 Update internal/registry/model_definitions_static_data.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-12 23:37:27 +01:00
Franz Bettag 41a78be3a2 feat(registry): add gpt-5.3-codex-spark model definition 2026-02-12 23:24:08 +01:00
Luis Pater 1ff5de9a31 docs(readme): add CLIProxyAPI Dashboard to project list 2026-02-13 00:40:39 +08:00
Luis Pater 46a6853046 Merge pull request #1568 from itsmylife44/add-cliproxyapi-dashboard
Add CLIProxyAPI Dashboard to 'Who is with us?' section
2026-02-13 00:37:41 +08:00
xSpaM 4b2d40bd67 Add CLIProxyAPI Dashboard to 'Who is with us?' section 2026-02-12 17:15:46 +01:00
RCD 064f2e6b8d Merge remote-tracking branch 'upstream/main' 2026-02-12 22:26:45 +07:00
Luis Pater 575881cb59 feat(registry): add new model definition for MiniMax-M2.5 2026-02-12 22:43:01 +08:00
hkfires f361b2716d feat(registry): add glm-5 model to iflow 2026-02-12 11:13:28 +08:00
이대희 93147dddeb Improves error handling for canceled requests
Adds explicit handling for context.Canceled errors in the reverse proxy error handler to return 499 status code without logging, which is more appropriate for client-side cancellations during polling.

Also adds a test case to verify this behavior.
2026-02-12 10:39:45 +09:00
이대희 c0f9b15a58 Merge remote-tracking branch 'upstream/main' into feature/canceled 2026-02-12 10:33:49 +09:00
이대희andgemini-code-assist[bot] 6f2fbdcbae Update internal/api/modules/amp/proxy.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-12 10:30:05 +09:00
HEUDavid 65debb874f feat/auth-hook: refactor RequstInfo to preserve original HTTP semantics 2026-02-12 07:11:17 +08:00
HEUDavid 3caadac003 feat/auth-hook: add post auth hook [CR] 2026-02-12 07:11:17 +08:00
HEUDavid 6a9e3a6b84 feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid 269972440a feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid cce13e6ad2 feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid 8a565dcad8 feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid d536110404 feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid 48e957ddff feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
HEUDavid 94563d622c feat/auth-hook: add post auth hook 2026-02-12 07:11:17 +08:00
RCD 9ee4e17e6d Merge remote-tracking branch 'upstream/main' 2026-02-12 04:36:28 +07:00
Luis Pater 58e09f8e5f Merge pull request #1542 from APE-147/fix/gemini-antigravity-schema-sanitization
fix(schema): sanitize Gemini-incompatible tool metadata fields
2026-02-11 21:34:04 +08:00
Luis Pater a146c6c0aa Merge pull request #1523 from xxddff/feature/removeUserField
fix(codex): remove unsupported 'user' field from /v1/responses payload
2026-02-11 20:38:16 +08:00
Luis Pater 4c133d3ea9 test(sdk/watcher): add tests for excluded models merging and priority parsing logic
- Added unit tests for combining OAuth excluded models across global and attribute-specific scopes.
- Implemented priority attribute parsing with support for different formats and trimming.
2026-02-11 20:35:13 +08:00
RCD 9809985f91 remove(docs): drop Chinese README translation 2026-02-11 19:06:29 +07:00
RCD a987b9fb83 Merge upstream CLIProxyAPI v6.8.11 into ProxyPilot
Upstream changes (v6.8.0–v6.8.11):
- feat: add Kimi (Moonshot AI) provider support with OAuth
- feat: add iFlow provider with OAuth and cookie auth
- feat: support Claude thinking type adaptive
- feat: capture cached token count in usage metadata
- fix: correct max completion tokens for opus 4.6 thinking
- fix: improve content handling for system and user messages
- fix: rewrite model name in response.model for Responses API SSE
- refactor: simplify provider lifecycle and registration logic
- refactor: migrate config-access to internal package

Fork integration:
- Migrate configaccess from sdk/access/config to internal/access/config_access
- Update reconcile.go to use internalconfig types directly
- Add Kimi and iFlow login flags to ProxyPilot CLI
- Integrate managementasset auto-updater
- Keep all ProxyPilot fork features (TUI, agent setup, service, etc.)
2026-02-11 19:03:07 +07:00
sususu98 f3ccd85ba1 feat(gemini-cli): add Google One login and improve auto-discovery
Add Google One personal account login to Gemini CLI OAuth flow:
- CLI --login shows mode menu (Code Assist vs Google One)
- Web management API accepts project_id=GOOGLE_ONE sentinel
- Auto-discover project via onboardUser without cloudaicompanionProject when project is unresolved

Improve robustness of auto-discovery and token handling:
- Add context-aware auto-discovery polling (30s timeout, 2s interval)
- Distinguish network errors from project-selection-required errors
- Refresh expired access tokens in readAuthFile before project lookup
- Extend project_id auto-fill to gemini auth type (was antigravity-only)

Unify credential file naming to geminicli- prefix for both CLI and web.

Add extractAccessToken unit tests (9 cases).
2026-02-11 17:53:03 +08:00
RGBadmin dc279de443 refactor: reduce code duplication in extractExcludedModelsFromMetadata 2026-02-11 15:57:16 +08:00
RGBadmin bf1634bda0 refactor: simplify per-account excluded_models merge in routing 2026-02-11 15:57:15 +08:00
NathanandClaude Opus 4.6 166d2d24d9 fix(schema): remove Gemini-incompatible tool metadata fields
Sanitize tool schemas by stripping prefill, enumTitles, $id, and patternProperties to prevent Gemini INVALID_ARGUMENT 400 errors, and add unit and executor-level tests to lock in the behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 18:29:17 +11:00
RGBadmin 4cbcc835d1 feat: read per-account excluded_models at routing time 2026-02-11 15:21:19 +08:00
RGBadmin b93026d83a feat: merge per-account excluded_models with global config 2026-02-11 15:21:15 +08:00
RGBadmin 5ed2133ff9 feat: add per-account excluded_models and priority parsing 2026-02-11 15:21:12 +08:00
Luis Pater 1510bfcb6f fix(translator): improve content handling for system and user messages
- Added support for single and array-based `content` cases.
- Enhanced `system_instruction` structure population logic.
- Improved handling of user role assignment for string-based `content`.
2026-02-11 15:04:01 +08:00
Chén Mù c6bd91b86b Merge pull request #1519 from router-for-me/thinking
feat(translator): support Claude thinking type adaptive
2026-02-10 18:31:56 +08:00
이대희andCopilot ce0c6aa82b Update internal/api/modules/amp/proxy.go
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-10 19:07:49 +09:00
hkfires 349ddcaa89 fix(registry): correct max completion tokens for opus 4.6 thinking 2026-02-10 18:05:40 +08:00
xxddffandgemini-code-assist[bot] bb9fe52f1e Update internal/translator/codex/openai/responses/codex_openai-responses_request_test.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-10 18:24:58 +09:00
xxddffandgemini-code-assist[bot] afe4c1bfb7 更新internal/translator/codex/openai/responses/codex_openai-responses_request.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-02-10 18:24:26 +09:00
이대희 3c85d2a4d7 feature(proxy): Adds special handling for client cancellations in proxy error handler
Silences logging for client cancellations during polling to reduce noise in logs.
Client-side cancellations are common during long-running operations and should not be treated as errors.
2026-02-10 18:02:08 +09:00
xxddff 865af9f19e Implement test for user field deletion
Add test to verify deletion of user field in response
2026-02-10 17:38:49 +09:00
xxddff 2b97cb98b5 Delete 'user' field from raw JSON
Remove the 'user' field from the raw JSON as requested.
2026-02-10 17:35:54 +09:00
hkfires 938a799263 feat(translator): support Claude thinking type adaptive 2026-02-10 16:20:32 +08:00
Luis Pater 0040d78496 refactor(sdk): simplify provider lifecycle and registration logic 2026-02-10 15:39:26 +08:00
Finn PhillipsandClaude Opus 4.6 2615f489d6 fix(translator): remove broken type uppercasing in OpenAI Responses-to-Gemini translator
The `ConvertOpenAIResponsesRequestToGemini` function had code that attempted
to uppercase JSON Schema type values (e.g. "string" -> "STRING") for Gemini
compatibility. This broke nullable types because when `type` is a JSON array
like `["string", "null"]`:

1. `gjson.Result.String()` returns the raw JSON text `["string","null"]`
2. `strings.ToUpper()` produces `["STRING","NULL"]`
3. `sjson.Set()` stores it as a JSON **string** `"[\"STRING\",\"NULL\"]"`
   instead of a JSON array
4. The downstream `CleanJSONSchemaForGemini()` / `flattenTypeArrays()`
   cannot detect it (since `IsArray()` returns false on a string)
5. Gemini/Antigravity API rejects it with:
   `400 Invalid value at '...type' (Type), "["STRING","NULL"]"`

This was confirmed and tested with Droid Factory (Antigravity) Gemini models
where Claude Code sends tool schemas with nullable parameters.

The fix removes the uppercasing logic entirely and passes the raw schema
through to `parametersJsonSchema`. This is safe because:
- Antigravity executor already runs `CleanJSONSchemaForGemini()` which
  properly handles type arrays, nullable fields, and all schema cleanup
- Gemini/Vertex executors use `parametersJsonSchema` which accepts raw
  JSON Schema directly (no uppercasing needed)
- The uppercasing code also only iterated top-level properties, missing
  nested schemas entirely

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-10 09:29:09 +07:00
hkfires 896de027cc docs(config): reorder antigravity model alias example 2026-02-10 10:13:54 +08:00
hkfires fc329ebf37 docs(config): simplify oauth model alias example 2026-02-10 10:12:28 +08:00
Luis Pater eaab1d6824 Merge pull request #1506 from masrurimz/fix-sse-model-mapping
fix(amp): rewrite response.model in Responses API SSE events
2026-02-10 02:08:11 +08:00
Muhammad Zahid Masruri 0cfe310df6 ci: retrigger workflows
Amp-Thread-ID: https://ampcode.com/threads/T-019c264f-1cb9-7420-a68b-876030db6716
2026-02-10 00:09:11 +07:00
Muhammad Zahid Masruri 918b6955e4 fix(amp): rewrite model name in response.model for Responses API SSE events
The ResponseRewriter's modelFieldPaths was missing 'response.model',
causing the mapped model name to leak through SSE streaming events
(response.created, response.in_progress, response.completed) in the
OpenAI Responses API (/v1/responses).

This caused Amp CLI to report 'Unknown OpenAI model' errors when
model mapping was active (e.g., gpt-5.2-codex -> gpt-5.3-codex),
because the mapped name reached Amp's backend via telemetry.

Also sorted modelFieldPaths alphabetically per review feedback
and added regression tests for all rewrite paths.

Fixes #1463
2026-02-09 23:52:59 +07:00
Luis Pater 5a3eb08739 Merge pull request #1502 from router-for-me/iflow
feat(executor): add session ID and HMAC-SHA256 signature generation for iFlow API requests
2026-02-09 19:56:12 +08:00
Luis Pater 0dff329162 Merge pull request #1492 from router-for-me/management
fix(management): ensure management.html is available synchronously and improve asset sync handling
2026-02-09 19:55:21 +08:00
hkfires 49c1740b47 feat(executor): add session ID and HMAC-SHA256 signature generation for iFlow API requests 2026-02-09 19:29:42 +08:00
hkfires 3fbee51e9f fix(management): ensure management.html is available synchronously and improve asset sync handling 2026-02-09 08:32:58 +08:00
Luis Pater 63643c44a1 Fixed: #1484
fix(translator): restructure message content handling to support multiple content types

- Consolidated `input_text` and `output_text` handling into a single case.
- Added support for processing `input_image` content with associated URLs.
2026-02-09 02:05:38 +08:00
Luis Pater 3b34521ad9 Merge pull request #1479 from router-for-me/management
refactor(management): streamline control panel management and implement sync throttling
2026-02-08 20:37:29 +08:00
hkfires 7197fb350b fix(config): prune default descendants when merging new yaml nodes 2026-02-08 19:05:52 +08:00
RCD 7fd8acef64 chore: pin Go 1.25.6 via mise for local dev 2026-02-08 18:00:48 +07:00
RCD 85bf0bc9e0 update(agents): refresh Droid factory model list
Remove deprecated Amazon Q and GPT-5.1 Codex Max entries,
add GPT-5.3 Codex.
2026-02-08 18:00:31 +07:00
RCD e94805c460 remove(registry): drop deprecated Claude and OpenAI models
Claude: remove 3.5 Haiku, 3.7 Sonnet, Sonnet 4, Opus 4.1
OpenAI: remove GPT-5, 5-codex-mini, 5.1, 5.1-codex,
5.1-codex-mini, 5.1-codex-max
2026-02-08 17:59:42 +07:00
RCD 81f6c044f2 docs: remove Amazon Q CLI references 2026-02-08 17:59:23 +07:00
RCD ef84773394 remove(webui): drop Amazon Q provider from dashboard UI
Remove provider entry, auth file detection, import handler,
and usage color definition.
2026-02-08 17:59:07 +07:00
RCD 1a78f65cb0 remove(executor): drop Amazon Q endpoint and model mappings
Remove the q.us-east-1.amazonaws.com endpoint config, amazonq-
prefixed model mappings, and amazonq- tokenizer prefix check.
2026-02-08 17:58:44 +07:00
RCD 90625182f3 remove(registry): delete Amazon Q model definitions
Remove GetAmazonQModels and its entry in the model listing.
2026-02-08 17:58:16 +07:00
RCD 346d8d3fb6 remove(cli): drop --amazonq-import flag and import command
Remove the CLI flag, variable, and DoAmazonQImport function.
2026-02-08 17:57:55 +07:00
RCD 182b46bb5d remove(agents): delete Amazon Q CLI agent handler
Remove dedicated amazonq_cli.go and its registration in
the agent manager.
2026-02-08 17:57:27 +07:00
RCD f55574adcf remove(auth): delete Amazon Q CLI authentication files
Amazon Q CLI is deprecated. Remove the SQLite token reader
and SDK authenticator.
2026-02-08 17:57:11 +07:00
hkfires 6e349bfcc7 fix(config): avoid writing known defaults during merge 2026-02-08 18:47:44 +08:00
hkfires 234056072d refactor(management): streamline control panel management and implement sync throttling 2026-02-08 10:42:49 +08:00
Luis Pater 7e9d0db6aa Merge pull request #1467 from dusty-du/fix/kimi-toolcall-reasoning-content
Fix Kimi tool-call payload normalization for reasoning_content
2026-02-07 09:35:04 +08:00
Luis Pater 2f1874ede5 chore(docs): remove Cubence sponsorship from README files and delete related asset 2026-02-07 08:55:14 +08:00
Luis Pater 78ef04fcf1 fix(kimi): reduce redundant payload cloning and simplify translation calls 2026-02-07 08:51:48 +08:00
hkfires b7e4f00c5f fix(translator): correct gemini-cli log prefix 2026-02-07 08:40:09 +08:00
Luis Pater f7d0019df7 fix(kimi): update base URL and integrate ClaudeExecutor fallback
- Updated `KimiAPIBaseURL` to remove versioning from the root path.
- Integrated `ClaudeExecutor` fallback in `KimiExecutor` methods for compatibility with Claude requests.
- Simplified token counting by delegating to `ClaudeExecutor`.
2026-02-07 06:42:08 +08:00
test 52364af5bf Fix Kimi tool-call reasoning_content normalization 2026-02-06 14:46:16 -05:00
Luis Pater f410dd0440 Merge pull request #1390 from sususu98/fix/400-invalid-request-no-retry
fix(auth): 400 invalid_request_error 立即返回不再重试
2026-02-07 03:14:25 +08:00
Luis Pater eb5582c17c Merge pull request #1386 from shenshuoyaoyouguang/sync-auth-changes
fix(auth): normalize model key for thinking suffix in selectors
2026-02-07 03:12:01 +08:00
Luis Pater 1c6cb2bec3 Merge pull request #1239 from ThanhNguyxn/fix/gitstore-gc-after-squash
fix(store): run GC after squashing history to prevent loose object accumulation
2026-02-07 02:51:27 +08:00
Luis Pater 80b5e79e75 fix(translator): normalize and restrict stop_reason/finish_reason usage
- Standardized the handling of `stop_reason` and `finish_reason` across Codex and Gemini responses.
- Restricted pass-through of specific reasons (`max_tokens`, `stop`) for consistency.
- Enhanced fallback logic for undefined reasons.
2026-02-07 02:07:51 +08:00
Luis Pater 394497fb2f Merge pull request #1465 from router-for-me/kimi-fix
fix(kimi): add OAuth model-alias channel support and cover OAuth excl…
2026-02-07 01:27:30 +08:00
LTbinglingfeng fc7b6ef086 fix(kimi): add OAuth model-alias channel support and cover OAuth excluded-models with tests 2026-02-07 01:16:39 +08:00
Luis Pater 1187aa8222 feat(translator): capture cached token count in usage metadata and handle prompt caching
- Added support to extract and include `cachedContentTokenCount` in `usage.prompt_tokens_details`.
- Logged warnings for failures to set cached token count for better debugging.
2026-02-06 21:28:40 +08:00
Luis Pater dc9b4dd017 Merge branch 'kimi-provider-support-v2' into dev 2026-02-06 20:51:48 +08:00
Luis Pater 68cb81a258 feat: add Kimi authentication support and streamline device ID handling
- Introduced `RequestKimiToken` API for Kimi authentication flow.
- Integrated device ID management throughout Kimi-related components.
- Enhanced header management for Kimi API requests with device ID context.
2026-02-06 20:43:30 +08:00
RCD 38e7f28233 Merge upstream CLIProxyAPI v6.7.53 into ProxyPilot
Changes (v6.7.49 - v6.7.53):
- feat(registry): add Claude 4.6 (Opus) model
- feat(registry): add GPT 5.3 Codex model
- fix(registry): correct Claude Opus 4.6 model metadata
- fix: enable extended thinking support for Claude Haiku 4.5
- refactor(executor): centralize Codex client version and user agent
- refactor(translator, executor): remove redundant bytes.Clone calls
- refactor(util): optimize JSON schema processing

Upstream: https://github.com/router-for-me/CLIProxyAPI/releases/tag/v6.7.53
2026-02-06 10:24:59 +07:00
hkfires c874f19f2a refactor(config): disable automatic migration during server startup 2026-02-06 09:57:47 +08:00
testandClaude Opus 4.6 f5f26f0cbe Add Kimi (Moonshot AI) provider support
- OAuth2 device authorization grant flow (RFC 8628) for authentication
- Streaming and non-streaming chat completions via OpenAI-compatible API
- Models: kimi-k2, kimi-k2-thinking, kimi-k2.5
- CLI `--kimi-login` command for device flow auth
- Token management with automatic refresh
- Thinking/reasoning effort support for thinking-enabled models

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 19:24:46 -05:00
Luis Pater 4b00312fef Merge pull request #1435 from tianyicui/fix/haiku-4-5-thinking-support
fix: Enable extended thinking support for Claude Haiku 4.5
2026-02-06 05:44:14 +08:00
Luis Pater c5fd3db01e Merge pull request #1446 from qyhfrank/fix-claude-opus-4-6-model-metadata
fix(registry): correct Claude Opus 4.6 model metadata
2026-02-06 05:43:32 +08:00
Frank Qing f870a9d2a7 fix(registry): correct Claude Opus 4.6 model metadata 2026-02-06 05:39:41 +08:00
Luis Pater b4e034be1c refactor(executor): centralize Codex client version and user agent constants
- Introduced `codexClientVersion` and `codexUserAgent` constants for better maintainability.
- Updated `EnsureHeader` calls to use the new constants.
2026-02-06 05:30:28 +08:00
Luis Pater a5a25dec57 refactor(translator, executor): remove redundant bytes.Clone calls for improved performance
- Replaced all instances of `bytes.Clone` with direct references to enhance efficiency.
- Simplified payload handling across executors and translators by eliminating unnecessary data duplication.
2026-02-06 03:26:29 +08:00
Luis Pater c71905e5e8 Merge pull request #1440 from kvokka/add-cc-opus-4-6
feat(registry): register Claude 4.6 static data
2026-02-06 03:23:59 +08:00
kvokka bc78d668ac feat(registry): register Claude 4.6 static data
Add model definition for Claude 4.6 Opus with 200k context length and thinking support capabilities.
2026-02-05 23:13:36 +04:00
Luis Pater 5bd0896ad7 feat(registry): add GPT 5.3 Codex model to static data 2026-02-06 01:52:41 +08:00
Luis Pater 09ecfbcaed refactor(executor): optimize payload cloning and streamline SDK translator usage
- Replaced unnecessary `bytes.Clone` calls for `opts.OriginalRequest` throughout executors.
- Introduced intermediate variable `originalPayloadSource` to simplify payload processing.
- Ensured better clarity and structure in request translation logic.
2026-02-06 01:44:20 +08:00
Luis Pater f0bd14b64f refactor(util): optimize JSON schema processing and keyword removal logic
- Consolidated path-finding logic into a new `findPathsByFields` helper function.
- Refactored repetitive loop structures to improve readability and performance.
- Added depth-based sorting for deletion paths to ensure proper removal order.
2026-02-06 00:19:56 +08:00
RCD 6c0c0b3a44 Merge upstream CLIProxyAPI v6.7.48 into ProxyPilot
Changes:
- feat(registry): add Kimi-K2.5 model to static data
- refactor(util, executor): optimize payload handling and schema processing
- fix(thinking): support user-defined includeThoughts setting (camelCase/snake_case)
- fix(thinking): ensure includeThoughts is false for ModeNone
- fix(gemini): support snake_case thinking config fields from Python SDK
- feat(gemini-cli): support image content in Claude request conversion
- fix(test): upstream fixed the builtin tools test we also fixed

Upstream: https://github.com/router-for-me/CLIProxyAPI/releases/tag/v6.7.48
2026-02-05 21:39:14 +07:00
Luis Pater f7d82fda3f feat(registry): add Kimi-K2.5 model to static data 2026-02-05 19:48:04 +08:00
Tianyi Cui 706590c62a fix: Enable extended thinking support for Claude Haiku 4.5
Claude Haiku 4.5 (claude-haiku-4-5-20251001) supports extended thinking
according to Anthropic's official documentation:
https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking

The model was incorrectly marked as not supporting thinking in the static
model definitions. This fix adds ThinkingSupport with the same parameters
as other Claude 4.5 models (Sonnet, Opus):
- Min: 1024 tokens
- Max: 128000 tokens
- ZeroAllowed: true
- DynamicAllowed: false
2026-02-05 19:03:23 +08:00
Luis Pater 25c6b479c7 refactor(util, executor): optimize payload handling and schema processing
- Replaced repetitive string operations with a centralized `escapeGJSONPathKey` function.
- Streamlined handling of JSON schema cleaning for Gemini and Antigravity requests.
- Improved payload management by transitioning from byte slices to strings for processing.
- Removed unnecessary cloning of byte slices in several places.
2026-02-05 19:00:30 +08:00
Chén Mù 7cf9ff0345 Merge pull request #1429 from neavo/fix/gemini-python-sdk-thinking-fields
fix(gemini): support snake_case thinking config fields from Python SDK
2026-02-05 14:32:58 +08:00
hkfires 209d74062a fix(thinking): ensure includeThoughts is false for ModeNone in budget processing 2026-02-05 10:24:42 +08:00
hkfires d86b13c9cb fix(thinking): support user-defined includeThoughts setting with camelCase and snake_case variants
Fixes #1378
2026-02-05 10:07:41 +08:00
hkfires 075e3ab69e fix(test): rename test function to reflect behavior change for builtin tools 2026-02-05 09:25:34 +08:00
Luis Pater c1c9483752 Merge pull request #1422 from dannycreations/feat-gemini-cli-claude-mime
feat(gemini-cli): support image content in Claude request conversion
2026-02-05 01:21:09 +08:00
RCD a6e817b72f Merge upstream CLIProxyAPI v6.7.47 into ProxyPilot
Changes from v6.7.43-v6.7.47:
- fix(logging): expand tilde in auth-dir and log resolution errors
- feat(pprof): add configurable pprof HTTP debug server
- feat(watcher): log auth field changes on reload
- fix(cliproxy): update auth before model registration
- docs: README updates, AICodeMirror sponsorship

Fixed upstream test bug: TestOpenAIResponsesToOpenAI now correctly expects
built-in tools to be dropped (upstream intentionally changed this behavior).

Upstream: https://github.com/router-for-me/CLIProxyAPI/releases/tag/v6.7.47
2026-02-04 22:50:54 +07:00
neavo 6c65fdf54b fix(gemini): support snake_case thinking config fields from Python SDK
Google official Gemini Python SDK sends thinking_level, thinking_budget,
and include_thoughts (snake_case) instead of thinkingLevel, thinkingBudget,
and includeThoughts (camelCase). This caused thinking configuration to be
ignored when using Python SDK.

Changes:
- Extract layer: extractGeminiConfig now reads snake_case as fallback
- Apply layer: Gemini/CLI/Antigravity appliers clean up snake_case fields
- Translator layer: Gemini->OpenAI/Claude/Codex translators support fallback
- Tests: Added 4 test cases for snake_case field coverage

Fixes #1426
2026-02-04 21:12:47 +08:00
Luis Pater 4874253d1e Merge pull request #1425 from router-for-me/auth
fix(cliproxy): update auth before model registration
2026-02-04 15:01:01 +08:00
Luis Pater b72250349f Merge pull request #1423 from router-for-me/watcher
feat(watcher): log auth field changes on reload
2026-02-04 15:00:38 +08:00
hkfires 116573311f fix(cliproxy): update auth before model registration 2026-02-04 14:03:15 +08:00
hkfires 4af712544d feat(watcher): log auth field changes on reload
Cache parsed auth contents and compute redacted diffs for prefix, proxy_url,
and disabled when auth files are added or updated.
2026-02-04 12:29:56 +08:00
dannycreations 3f9c9591bd feat(gemini-cli): support image content in Claude request conversion
- Add logic to handle `image` content type during request translation.
- Map Claude base64 image data to Gemini's `inlineData` structure.
- Support automatic extraction of `media_type` and `data` for image parts.
2026-02-04 11:00:37 +07:00
Luis Pater 1548c567ab feat(pprof): add support for configurable pprof HTTP debug server
- Introduced a new `pprof` server to enable/debug HTTP profiling.
- Added configuration options for enabling/disabling and specifying the server address.
- Integrated pprof server lifecycle management with `Service`.

#1287
2026-02-04 02:39:26 +08:00
Luis Pater 5b23fc570c Merge pull request #1396 from Xm798/fix/log-dir-tilde-expansion
fix(logging): expand tilde in auth-dir path for log directory
2026-02-04 02:00:13 +08:00
Luis Pater 04e1c7a05a docs: reorganize and update README entries for CLIProxyAPI projects 2026-02-04 01:49:27 +08:00
Luis Pater 9181e72204 Merge pull request #1409 from wangdabaoqq/main
docs: Add a new client application - Lin Jun
2026-02-04 01:47:31 +08:00
宝宝宝 4939865f6d Add a new client application - Lin Jun 2026-02-03 23:55:24 +08:00
宝宝宝 3da7f7482e Add a new client application - Lin Jun 2026-02-03 23:36:34 +08:00
宝宝宝 9072b029b2 Add a new client application - Lin Jun 2026-02-03 23:35:53 +08:00
宝宝宝 c296cfb8c0 docs: Add a new client application - Lin Jun 2026-02-03 23:32:50 +08:00
Luis Pater 2707377fcb docs: add AICodeMirror sponsorship details to README files 2026-02-03 22:34:50 +08:00
Luis Pater 259f586ff7 Fixed: #1398
fix(translator): use model group caching for client signature validation
2026-02-03 22:04:52 +08:00
Luis Pater d885b81f23 Fixed: #1403
fix(translator): handle "input" field transformation for OpenAI responses
2026-02-03 21:49:30 +08:00
Luis Pater fe6bffd080 fixed: #1407
fix(translator): adjust "developer" role to "user" and ignore unsupported tool types
2026-02-03 21:41:17 +08:00
RCD 7e3df456a5 Merge upstream CLIProxyAPI v6.7.42 into ProxyPilot
This merge brings in upstream changes from CLIProxyAPI v6.7.42 while
preserving ProxyPilot-specific customizations:

- Updated API server and executor modules
- New OAuth model alias functionality
- Enhanced thinking provider for iflow
- Updated model definitions and registry
- Improved docker build scripts

Conflicts were resolved by keeping ProxyPilot branding and merging
upstream improvements for translator and runtime components.
2026-02-03 11:08:58 +07:00
Luis Pater 250f212fa3 fix(executor): handle "global" location in AI platform URL generation 2026-02-03 01:39:57 +08:00
Cyrus a275db3fdb fix(logging): expand tilde in auth-dir and log resolution errors
- Use util.ResolveAuthDir to properly expand ~ to user home directory
- Fixes issue where logs were created in literal "~/.cli-proxy-api" folder
- Add warning log when auth-dir resolution fails for debugging

Bug introduced in 62e2b67 (refactor(logging): centralize log directory
resolution logic), where strings.TrimSpace was used instead of
util.ResolveAuthDir to process auth-dir path.
2026-02-03 00:02:54 +08:00
sususu98 233be6272a fix(auth): 400 invalid_request_error 立即返回不再重试
当上游返回 400 Bad Request 且错误消息包含 invalid_request_error 时,
表示请求本身格式错误,切换账户不会改变结果。

修改:
- 添加 isRequestInvalidError 判定函数
- 内层循环遇到此错误立即返回,不遍历其他账户
- 外层循环不再对此类错误进行重试
2026-02-02 17:35:51 +08:00
chujian 47cb52385e sdk/cliproxy/auth: update selector tests 2026-02-02 05:26:04 +08:00
hkfires 9861bf3ded fix(codex): convert system role to developer for codex input 2026-02-01 20:43:52 +07:00
hkfires 93e2e03793 docs(translator): update Codex Claude request transform docs 2026-02-01 20:43:45 +07:00
hkfires bc3bea72f3 refactor(codex): remove codex instructions injection support 2026-02-01 20:43:35 +07:00
hkfires 9eece2ea2a feat(config): track routing and cloak changes in config diff 2026-02-01 20:42:16 +07:00
hkfires 1f1160eb07 refactor(api): centralize config change logging 2026-02-01 20:42:09 +07:00
Luis Pater 157f16d3b2 Merge pull request #1380 from router-for-me/codex
refactor(codex): remove codex instructions injection support
2026-02-01 20:20:59 +08:00
Luis Pater b927b0cc6c Merge branch 'dev' into codex 2026-02-01 20:20:49 +08:00
Luis Pater 493969a742 Merge pull request #1379 from router-for-me/log
refactor(api): centralize config change logging
2026-02-01 20:19:55 +08:00
hkfires 354f6582b2 fix(codex): convert system role to developer for codex input 2026-02-01 15:37:37 +08:00
hkfires fe3ebe3532 docs(translator): update Codex Claude request transform docs 2026-02-01 14:55:41 +08:00
hkfires ac802a4646 refactor(codex): remove codex instructions injection support 2026-02-01 14:33:31 +08:00
RCDandClaude 2f72e9801a fix: address 6 issues from Codex code review
kiro_request.go:
- Fix panic: safely truncate tokenKey for logging (was slicing [:8] without length check)
- Fix order: check EventStreamError BEFORE string pattern matching in isRetryableError

kiro_auth.go:
- Fix logic: isTokenExpired now returns true on parse failures (matches function contract)

conductor_token.go:
- Fix ignored param: StartAutoRefresh now respects caller-provided interval
- Fix race condition: protect refreshCancel with mutex in Start/StopAutoRefresh
- Fix wrong key: refreshAuth now uses executorKeyFromAuth for compat auths

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 13:11:51 +07:00
RCDandClaude 3e4dccf857 fix(middleware): address remaining code review findings
MEDIUM: Return 400 on body read error instead of passing empty body
- Previously, on io.ReadAll error, body was consumed but c.Next()
  was called, causing downstream handlers to see empty body
- Now returns http.StatusBadRequest on read errors

MEDIUM: Recompute token analysis after scaffold injection
- Token analysis was computed before scaffold state was injected
- If scaffold pushed request over token threshold, trimming was skipped
- Now recomputes analyzeTokenBudget() after injection

LOW: Always strip X-CLIProxyAPI-Todo header
- Header was only stripped when memory store was available
- If memory disabled, internal header leaked upstream
- Now stripped immediately regardless of memory store state

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:52:57 +07:00
RCDandClaude 4491089ad1 fix(middleware): ensure prompt budget trimming loop executes
The trimming loop condition `for keep >= minKeep` was never true because
`keep` started at 20 while `minKeep` defaults to 25. Added clamp to ensure
`keep >= minKeep` at initialization, fixing prompt budget enforcement.

Affected functions:
- trimOpenAIChatCompletions
- trimOpenAIResponses
- trimOpenAIChatCompletionsWithMemory
- trimOpenAIResponsesWithMemory
- trimClaudeMessagesWithMemory

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:50:05 +07:00
RCDandClaude 7cc4e9d8f5 refactor(middleware): split codex_prompt_budget.go into logical modules
Split the 2,762 line codex_prompt_budget.go into focused modules:
- codex_prompt_budget.go (1,272 lines): Main middleware, scaffold injection
- codex_budget_types.go (498 lines): Constants, package vars, config functions
- codex_budget_calculator.go (944 lines): Token analysis, trim functions

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:28:00 +07:00
RCDandClaude 75ca091a73 refactor(executor): split kiro_executor.go into logical modules
Split the 3,891 line kiro_executor.go into focused modules:
- kiro_executor.go (966 lines): Main executor, public interface
- kiro_auth.go (462 lines): Authentication/credential logic
- kiro_request.go (422 lines): Request transformation and retry logic
- kiro_response.go (1,765 lines): Response handling/streaming

Fix: Corrected isRetryableError to use errors.As for EventStreamError
type assertion instead of errors.Is on string constants.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:09:33 +07:00
RCDandClaude 8927e6b71d test(auth): add unit tests for claude, codex, gemini auth packages
Add comprehensive unit tests for authentication packages:
- claude_auth_test.go: AuthBundle parsing, token serialization, validation
- codex_auth_test.go: token storage, expiry edge cases, refresh thresholds
- gemini_auth_test.go: token storage with any type, JSON field verification

Also add translator package tests for format conversion edge cases.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:08:53 +07:00
RCDandClaude ef60b1cd7e refactor(auth): split conductor.go into logical modules
Split the 2,280-line conductor.go into three focused files:
- conductor.go (1,416 lines): Core types, Manager struct, execution
- conductor_oauth.go (383 lines): OAuth/API key model alias resolution
- conductor_token.go (501 lines): Token refresh and HTTP request handling

This is a pure refactor with no logic changes.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 12:02:14 +07:00
RCDandClaude 3986099409 refactor: remove unused loop index variable
Replace `for i, part := range` with `for _, part := range` since the
index variable was captured but never used (just discarded with `_ = i`).

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:57:03 +07:00
RCDandClaude b4fd299fce refactor(modules): remove deprecated RouteModule interface
Remove the V1 RouteModule interface which was marked as deprecated.
All modules now use RouteModuleV2 exclusively. The RegisterModule
function signature is simplified to accept RouteModuleV2 directly
instead of interface{}.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:55:57 +07:00
RCDandClaude b5077879d0 chore: clarify GetRequestMonitor stub comment
Remove TODO marker and update comment to indicate the stub is
intentional for API compatibility, not incomplete work.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:54:32 +07:00
RCDandClaude 861c4c29d9 chore: sync version strings to 0.3.0
Update FileVersion and ProductVersion in versioninfo.json files
from 0.1.6 to 0.3.0 for both proxypilot-tray and server commands.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:53:41 +07:00
RCDandClaude 0db83010aa feat(config): add payload filter rules to remove JSON paths
Cherry-picked from upstream 6d8609e4

Allows configuring rules to remove specific JSON paths from request/response payloads.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:36:39 +07:00
RCDandClaude 977c5c18ad fix: handle issues #1372 #1366
Cherry-picked from upstream d216adef

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:36:17 +07:00
RCDandClaude 0801d1d101 fix(config): add codex instructions enabled change to config change details
Cherry-picked from upstream bb09708c

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:35:49 +07:00
RCDandClaude 993e6795c0 fix(misc): update opencode instructions
Cherry-picked from upstream 1150d972

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:35:26 +07:00
RCDandClaude 4ba0a04c37 feat(logging): make error-logs-max-files configurable
Cherry-picked from upstream 6db8d2a2

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:34:58 +07:00
RCDandClaude 006bd54c9a fix(misc): update user agent string for opencode
Cherry-picked from upstream 2854e04b

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:34:19 +07:00
RCDandClaude af48e0f37b fix(translator): handle stop_reason and MAX_TOKENS for Claude responses
Cherry-picked from upstream f99cddf9

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:33:36 +07:00
RCDandClaude 2f6fee08d4 fix(translator): include token usage in message_delta for Claude responses
Cherry-picked from upstream 550da0ce

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:33:20 +07:00
RCDandClaude 35b033ae06 fix(caching): ensure prompt-caching beta is always appended
Cherry-picked from upstream 7ff3936e

Adds multi-turn cache control tests.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:33:02 +07:00
RCDandClaude d9b3f07db3 feat(auth): add custom HTTP client with utls for Claude API authentication
Cherry-picked from upstream 6b6d030e

Adds uTLS-based HTTP transport to mimic browser TLS fingerprints for Claude API.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:32:40 +07:00
RCDandClaude 4a3996ca5c feat(translator): add code_execution and url_context tool passthrough
Cherry-picked from upstream 538039f5

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:31:18 +07:00
RCDandClaude 459997789e refactor(gemini): optimize removeExtensionFields with post-order traversal
Cherry-picked from upstream ca796510

Uses post-order traversal and DeleteBytes for better performance.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:30:57 +07:00
RCDandClaude 29f0da4942 fix(gemini): remove unsupported extension fields
Cherry-picked from upstream d0d66cdc

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:30:35 +07:00
RCDandClaude 39796063c5 feat(caching): implement Claude prompt caching with multi-turn support
Cherry-picked from upstream 3a43ecb1

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:30:10 +07:00
RCDandClaude a7fa518584 fix: skip empty text parts and messages for Gemini API
Cherry-picked from upstream 2666708c

When Claude API sends an assistant message with empty text content,
the translator was creating an empty part, causing Gemini API to return
"required oneof field 'data' must have one initialized field" error.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:29:47 +07:00
RCDandClaude 8473211ad6 fix(codex): avoid empty prompt_cache_key
Cherry-picked from upstream 04b22909

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:29:21 +07:00
RCDandClaude 4527e5a7e5 fix(openai): drop stream for responses/compact
Cherry-picked from upstream 53920b03

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:29:03 +07:00
RCDandClaude acdf099442 feat(openai): add responses/compact support
Cherry-picked from upstream 95096bc3

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:28:45 +07:00
RCDandClaude 1c9ade20f8 fix: change HTTP status code from 400 to 502 when no provider available
Cherry-picked from upstream 6da7ed53

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:28:20 +07:00
RCDandClaude 787af1fb12 fix(antigravity): preserve finish_reason tool_calls across streaming chunks
Cherry-picked from upstream fe6043ae

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:28:03 +07:00
RCDandClaude 070ddb0ff5 fix: prevent race condition in objectstore auth sync
Cherry-picked from upstream bc32096e

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-02-01 11:27:40 +07:00
ThanhNguyxn a406ca2d5a fix(store): add proper GC with Handler and interval gating
Address maintainer feedback on PR #1239:
- Add Handler: repo.DeleteObject to prevent nil panic in Prune
- Handle ErrLooseObjectsNotSupported gracefully
- Add 5-minute interval gating to avoid repack overhead on every write
- Remove sirupsen/logrus dependency (best-effort silent GC)

Fixes #1104
2026-02-01 11:19:43 +07:00
hkfires 6a258ff841 feat(config): track routing and cloak changes in config diff 2026-02-01 12:05:48 +08:00
hkfires 4649cadcb5 refactor(api): centralize config change logging 2026-02-01 11:31:44 +08:00
Luis Pater c82d8e250a Merge pull request #1174 from lieyan666/fix/issue-1082-change-error-status-code
fix: change HTTP status code from 400 to 502 when no provider available
2026-02-01 07:10:52 +08:00
Luis Pater 73db4e64f6 Merge pull request #874 from MohammadErfan-Jabbari/fix/streaming-finish-reason-tool-calls
fix(antigravity): preserve finish_reason tool_calls across streaming chunks
2026-02-01 07:05:39 +08:00
Luis Pater 69ca0a8fac Merge pull request #859 from shunkakinoki/fix/objectstore-sync-race-condition
fix: prevent race condition in objectstore auth sync
2026-02-01 07:01:43 +08:00
Luis Pater 3b04e11544 Merge pull request #1368 from sususu98/feat/configurable-error-logs-max-files
feat(logging): make error-logs-max-files configurable
2026-02-01 06:50:10 +08:00
Luis Pater e0927afa40 Merge pull request #1371 from kitephp/patch-2
Add CLIProxyAPI Tray section to README_CN.md
2026-02-01 06:47:36 +08:00
Luis Pater f97d9f3e11 Merge pull request #1370 from kitephp/patch-3
Add CLIProxyAPI Tray information to README
2026-02-01 06:46:39 +08:00
Luis Pater 6d8609e457 feat(config): add payload filter rules to remove JSON paths
Introduce `Filter` rules in the payload configuration to remove specified JSON paths from the payload. Update related helper functions and add examples to `config.example.yaml`.
2026-02-01 05:29:41 +08:00
Luis Pater d216adeffc Fixed: #1372 #1366
fix(caching): ensure unique cache_control injection using count validation
2026-01-31 23:48:50 +08:00
hkfires bb09708c02 fix(config): add codex instructions enabled change to config change details 2026-01-31 22:44:25 +08:00
hkfires 1150d972a1 fix(misc): update opencode instructions 2026-01-31 22:28:30 +08:00
kitephp 13bb7cf704 Add CLIProxyAPI Tray information to README
Added CLIProxyAPI Tray section with details about the application.
2026-01-31 20:28:16 +08:00
kitephp 8bce696a7c Add CLIProxyAPI Tray section to README_CN.md
Added information about CLIProxyAPI Tray application.
2026-01-31 20:26:52 +08:00
sususu98 6db8d2a28e feat(logging): make error-logs-max-files configurable
- Add ErrorLogsMaxFiles config field with default value 10
- Support hot-reload via config file changes
- Add Management API: GET/PUT/PATCH /v0/management/error-logs-max-files
- Maintain SDK backward compatibility with NewFileRequestLogger (3 params)
- Add NewFileRequestLoggerWithOptions for custom error log retention

When request logging is disabled, forced error logs are retained up to
the configured limit. Set to 0 to disable cleanup.
2026-01-31 17:48:40 +08:00
hkfires 2854e04bbb fix(misc): update user agent string for opencode 2026-01-31 11:23:08 +08:00
Luis Pater f99cddf97f fix(translator): handle stop_reason and MAX_TOKENS for Claude responses 2026-01-31 04:03:01 +08:00
Luis Pater f887f9985d Merge pull request #1248 from shekohex/feat/responses-compact
feat(openai): add responses/compact support
2026-01-31 03:12:55 +08:00
Luis Pater 550da0cee8 fix(translator): include token usage in message_delta for Claude responses 2026-01-31 02:55:27 +08:00
Luis Pater 7ff3936efe fix(caching): ensure prompt-caching beta is always appended and add multi-turn cache control tests 2026-01-31 01:42:58 +08:00
Luis Pater f36a5f5654 Merge pull request #1294 from Darley-Wey/fix/claude2gemini
fix: skip empty text parts and messages to avoid Gemini API error
2026-01-31 01:05:41 +08:00
Luis Pater c1facdff67 Merge pull request #1295 from SchneeMart/feature/claude-caching
feat(caching): implement Claude prompt caching with multi-turn support
2026-01-31 01:04:19 +08:00
Luis Pater 4ee46bc9f2 Merge pull request #1311 from router-for-me/fix/gemini-schema
fix(gemini): Removes unsupported extension fields
2026-01-30 23:55:56 +08:00
Luis Pater c3e94a8277 Merge pull request #1317 from yinkev/feat/gemini-tools-passthrough
feat(translator): add code_execution and url_context tool passthrough
2026-01-30 23:46:44 +08:00
Luis Pater 6b6d030ed3 feat(auth): add custom HTTP client with utls for Claude API authentication
Introduce a custom HTTP client utilizing utls with Firefox TLS fingerprinting to bypass Cloudflare fingerprinting on Anthropic domains. Includes support for proxy configuration and enhanced connection management for HTTP/2.
2026-01-30 21:29:41 +08:00
RCDandClaude ae7946402a fix(translator): validate complete JSON before using SetRaw for tool output
Tool outputs like "[1,2,3]\n\n[Process exited with code 0]" were being
partially parsed by gjson.Parse() which would extract just "[1,2,3]" and
lose the trailing text. This caused invalid JSON in the Gemini request.

Fix: Use gjson.Valid() to verify the ENTIRE string is valid JSON before
treating it as raw JSON. If validation fails, treat as a string with
proper escaping via sjson.Set().

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 17:19:56 +07:00
RCDandClaude a7b7856135 fix(tests): register test models in global registry for auth lookup
Tests were failing with "auth_not_found: no auth available" because the
conductor.pickNextMixed() function checks ClientSupportsModel() against
the global registry. Test auths weren't registered with their models.

Changes:
- sdk/cliproxy/auth/conductor_test.go: Add registry.RegisterClient calls
- internal/translator/gemini/.../gemini_openai-responses_request.go:
  Skip empty text parts to avoid invalid Gemini content

Note: Some pre-existing flaky tests remain in test/integration and
internal/translator/gemini (NonJSON tool output test).

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 16:07:03 +07:00
RCDandClaude c73b709a98 feat(registry): sync model definitions from plus remote
- Add SupportedEndpoints field to ModelInfo
- Add GetMiniMaxModels, GetZhipuModels stub functions
- Add GetGitHubCopilotModels, GetKiroModels, GetAmazonQModels
- Update model registry with new providers

Cherry-picked and merged from plus remote.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:44:20 +07:00
RCDandClaude 63e54f2ca4 chore(registry): disable gemini 2.5 flash image preview model
Cherry-picked from plus: 88a0f095

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:41:28 +07:00
RCDandClaude ac2d6df45e chore(registry): comment out rev19-uic3-1p model config
Cherry-picked from plus: c65f64dc

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:41:06 +07:00
RCDandClaude 6756600812 feat(api): add management model definitions endpoint
Cherry-picked from plus: d18cd217

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:40:44 +07:00
RCDandClaude 3a00e35a5a feat(auth): add support for request_retry and disable_cooling overrides
Cherry-picked from plus: 70897247

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:39:42 +07:00
RCDandClaude cb25c754ea feat(auth): add skip persistence context key for file watcher events
Cherry-picked from plus: 9c341f5a

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:39:20 +07:00
RCDandClaude a8592c8410 fix(claude): default Claude tool input schema
Cherry-picked from plus: e3e741d0

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:38:36 +07:00
RCDandClaude 9e53fc4540 fix(kiro): fix Kiro tool schema defaults
Cherry-picked from plus: 7c7c5fd9

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:38:17 +07:00
RCDandClaude e17990c2f8 fix(config): ensure empty mapping persists for oauth-model-alias deletions
When all oauth-model-alias entries are deleted, ensure an empty map
is persisted to config file rather than being omitted entirely.

Fixes #1305

Cherry-picked from upstream: a709e5a1

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:31:58 +07:00
RCDandClaude 71a502075e fix(logging): capture streaming TTFB on first chunk and make timestamps required
- Add firstChunkTimestamp field to ResponseWriterWrapper for sync capture
- Capture TTFB in Write() and WriteString() before async channel send
- Add SetFirstChunkTimestamp() to StreamingLogWriter interface
- Make requestTimestamp/apiResponseTimestamp required in LogRequest()
- Remove timestamp capture from WriteAPIResponse() (now via setter)
- Fix Gemini handler to set API_RESPONSE_TIMESTAMP before writing response

This ensures accurate TTFB measurement for all streaming API formats
(OpenAI, Gemini, Claude) by capturing timestamp synchronously when
the first response chunk arrives, not when the stream finalizes.

Cherry-picked from upstream: 295f34d7

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:31:30 +07:00
RCDandClaude bcd735b2a8 fix(logging): add API response timestamp and fix request timestamp timing
Previously:
- REQUEST INFO timestamp was captured at log write time (not request arrival)
- API RESPONSE had NO timestamp at all

This fix:
- Captures REQUEST INFO timestamp when request first arrives
- Adds API RESPONSE timestamp when upstream response arrives
- Add Timestamp field to RequestInfo, set at middleware initialization
- Set API_RESPONSE_TIMESTAMP in appendAPIResponse() and gemini handler
- Pass timestamps through logging chain to writeNonStreamingLog()
- Add timestamp output to API RESPONSE section

Cherry-picked from upstream: c41ce77e

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:30:56 +07:00
RCDandClaude 584648416a fix(translator): restore usageMetadata in Gemini responses from Antigravity
When using Gemini API format with Antigravity backend, the executor
renames usageMetadata to cpaUsageMetadata in non-terminal chunks.
The Gemini translator was returning this internal field name directly
to clients instead of the standard usageMetadata field.

Add restoreUsageMetadata() to rename cpaUsageMetadata back to
usageMetadata before returning responses to clients.

Cherry-picked from upstream: 9dc0e6d0

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-30 15:29:30 +07:00
kyinhubandClaude Opus 4.5 538039f583 feat(translator): add code_execution and url_context tool passthrough
Add support for Gemini's code_execution and url_context tools in the
request translators, enabling:

- Agentic Vision: Image analysis with Python code execution for
  bounding boxes, annotations, and visual reasoning
- URL Context: Live web page content fetching and analysis

Tools are passed through using the same pattern as google_search:
- code_execution: {} -> codeExecution: {}
- url_context: {} -> urlContext: {}

Tested with Gemini 3 Flash Preview agentic vision successfully.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 21:14:52 -08:00
이대희andAmp ca796510e9 refactor(gemini): optimize removeExtensionFields with post-order traversal and DeleteBytes
Amp-Thread-ID: https://ampcode.com/threads/T-019c0d09-330d-7399-b794-652b94847df1
Co-authored-by: Amp <amp@ampcode.com>
2026-01-30 13:02:58 +09:00
이대희andAmp d0d66cdcb7 fix(gemini): Removes unsupported extension fields
Removes x-* extension fields from JSON schemas to ensure compatibility with the Gemini API.

These fields, while valid in OpenAPI/JSON Schema, are not recognized by the Gemini API and can cause issues.
The change recursively walks the schema, identifies these extension fields, and removes them, except when they define properties.

Amp-Thread-ID: https://ampcode.com/threads/T-019c0cd1-9e59-722b-83f0-e0582aba6914
Co-authored-by: Amp <amp@ampcode.com>
2026-01-30 12:31:26 +09:00
Luis Pater d7d54fa2cc feat(ci): add cleanup step for temporary Docker tags in workflow 2026-01-30 09:15:00 +08:00
Luis Pater 31649325f0 feat(ci): add multi-arch Docker builds and manifest creation to workflow 2026-01-30 07:26:36 +08:00
Martin SchneeweissandClaude Opus 4.5 3a43ecb19b feat(caching): implement Claude prompt caching with multi-turn support
- Add ensureCacheControl() to auto-inject cache breakpoints
- Cache tools (last tool), system (last element), and messages (2nd-to-last user turn)
- Add prompt-caching-2024-07-31 beta header
- Return original payload on sjson error to prevent corruption
- Include verification test for caching logic

Enables up to 90% cost reduction on cached tokens.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 22:59:33 +01:00
Luis Pater a709e5a12d fix(config): ensure empty mapping persists for oauth-model-alias deletions #1305 2026-01-30 04:17:56 +08:00
Luis Pater f0ac77197b Merge pull request #1300 from sususu98/feat/log-api-response-timestamp
fix(logging): add API response timestamp and fix request timestamp timing
2026-01-30 03:27:17 +08:00
Luis Pater da0bbf2a3f Merge pull request #1298 from sususu98/fix/restore-usageMetadata-in-gemini-translator
fix(translator): restore usageMetadata in Gemini responses from Antigravity
2026-01-30 02:59:41 +08:00
sususu98 295f34d7f0 fix(logging): capture streaming TTFB on first chunk and make timestamps required
- Add firstChunkTimestamp field to ResponseWriterWrapper for sync capture
- Capture TTFB in Write() and WriteString() before async channel send
- Add SetFirstChunkTimestamp() to StreamingLogWriter interface
- Make requestTimestamp/apiResponseTimestamp required in LogRequest()
- Remove timestamp capture from WriteAPIResponse() (now via setter)
- Fix Gemini handler to set API_RESPONSE_TIMESTAMP before writing response

This ensures accurate TTFB measurement for all streaming API formats
(OpenAI, Gemini, Claude) by capturing timestamp synchronously when
the first response chunk arrives, not when the stream finalizes.
2026-01-29 22:32:24 +08:00
RCDandClaude 41b1ad654e feat(config): add oauth-model-alias migration support
Add migration logic for converting oauth-model-mappings to oauth-model-alias
with comprehensive test coverage.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:30:09 +07:00
RCDandClaude 7d1dc22657 feat(config): add AmpCode config and incognito browser option
- Add AmpCode configuration structure for Amp CLI proxy
- Add IncognitoBrowser option for OAuth flows
- Update SDK config mappings

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:29:39 +07:00
RCDandClaude 6b85dadce7 feat(interfaces): extend client models and types
Update interfaces with new fields for extended provider support.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:29:29 +07:00
RCDandClaude 24626d061d feat(constant): add Kiro and iFlow provider constants
Add new provider constants for Kiro and iFlow authentication.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:29:20 +07:00
RCDandClaude 3fc5b5a3b3 feat(auth): add empty token provider for unauthenticated requests
Add empty auth provider for handling requests that don't require authentication.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:23:46 +07:00
RCDandClaude 357eed3ec6 feat(auth): enhance Kiro authentication with rate limiting and metrics
Extend Kiro auth module with:
- Background token refresh
- Cooldown mechanism for failed requests
- Browser fingerprint generation
- Jitter utilities for request timing
- Metrics collection and reporting
- Rate limiter with singleton pattern
- Refresh manager for token lifecycle
- Token repository for persistent storage
- Usage checker for quota monitoring
- Web-based OAuth flow templates
- Updated AWS auth and SSO OIDC flows

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:23:31 +07:00
RCDandClaude d6104a0fca feat(auth): add iFlow authentication provider
Add iFlow auth module for cookie-based authentication:
- Cookie helper utilities
- iFlow auth client implementation
- Token management
- Local OAuth server for browser flow
- SDK auth integration

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:23:10 +07:00
RCDandClaude 45ba3b9c3f feat(auth): add GitHub Copilot OAuth authentication
Add complete Copilot authentication module:
- OAuth device flow for GitHub authentication
- Token management and storage
- Error handling for auth failures

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:22:38 +07:00
RCDandClaude 92bf72d8c5 feat(amp): add Amp CLI proxy module
Add complete Amp module for routing requests through the Amp CLI:
- Core module with lifecycle management
- Gemini bridge for model translation
- Model mapping configuration
- Proxy handler for request forwarding
- Response rewriter for format conversion
- Secret management for API keys
- Route definitions and fallback handlers
- Comprehensive test coverage

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 21:22:19 +07:00
sususu98 c41ce77eea fix(logging): add API response timestamp and fix request timestamp timing
Previously:
- REQUEST INFO timestamp was captured at log write time (not request arrival)
- API RESPONSE had NO timestamp at all

This fix:
- Captures REQUEST INFO timestamp when request first arrives
- Adds API RESPONSE timestamp when upstream response arrives

Changes:
- Add Timestamp field to RequestInfo, set at middleware initialization
- Set API_RESPONSE_TIMESTAMP in appendAPIResponse() and gemini handler
- Pass timestamps through logging chain to writeNonStreamingLog()
- Add timestamp output to API RESPONSE section

This enables accurate measurement of backend response latency in error logs.
2026-01-29 22:22:18 +08:00
RCDandClaude 1fa155621b feat: sync with upstream v6.7.28
Cherry-picked changes from CLIProxyAPI v6.7.28:

- feat(handlers): add test to verify no retries after partial stream response (4eb1e60)
- fix(config): prune oauth-model-alias when preserving config (d0bada7)

Note: fix(api): update amp module only on config changes (8510fc3) was skipped
as ProxyPilot does not have the Amp feature.

Co-Authored-By: Claude (gemini-claude-opus-4-5-thinking) <noreply@anthropic.com>
2026-01-29 18:48:10 +07:00
Luis Pater 4eb1e6093f feat(handlers): add test to verify no retries after partial stream response
Introduce `TestExecuteStreamWithAuthManager_DoesNotRetryAfterFirstByte` to validate that stream executions do not retry after receiving partial responses. Implement `payloadThenErrorStreamExecutor` for test coverage of this behavior.
2026-01-29 17:30:48 +08:00
Luis Pater 189a066807 Merge pull request #1296 from router-for-me/log
fix(api): update amp module only on config changes
2026-01-29 17:27:52 +08:00
dinhkarate 14cb2b95c6 feat(vertex): add --vertex-import-prefix flag for model namespacing 2026-01-29 13:32:38 +07:00
dinhkarate fdeef48498 feat(vertex): Add Prefix field to VertexCredentialStorage for per-file model namespacing 2026-01-29 13:32:38 +07:00
hkfires d0bada7a43 fix(config): prune oauth-model-alias when preserving config 2026-01-29 14:06:52 +08:00
sususu98 9dc0e6d08b fix(translator): restore usageMetadata in Gemini responses from Antigravity
When using Gemini API format with Antigravity backend, the executor
renames usageMetadata to cpaUsageMetadata in non-terminal chunks.
The Gemini translator was returning this internal field name directly
to clients instead of the standard usageMetadata field.

Add restoreUsageMetadata() to rename cpaUsageMetadata back to
usageMetadata before returning responses to clients.
2026-01-29 11:16:00 +08:00
hkfires 8510fc313e fix(api): update amp module only on config changes 2026-01-29 09:28:49 +08:00
Darley 2666708c30 fix: skip empty text parts and messages to avoid Gemini API error
When Claude API sends an assistant message with empty text content like:
{"role":"assistant","content":[{"type":"text","text":""}]}
The translator was creating a part object {} with no data field,
causing Gemini API to return error:
"required oneof field 'data' must have one initialized field"
This fix:
1. Skips empty text parts (text="") during translation
2. Skips entire messages when their parts array becomes empty
This ensures compatibility when clients send empty assistant messages
in their conversation history.
2026-01-29 04:13:07 +08:00
Luis Pater 9e5b1d24e8 Merge pull request #1276 from router-for-me/thinking
feat(thinking): enable thinking toggle for qwen3 and deepseek models
2026-01-28 11:16:54 +08:00
Luis Pater a7dae6ad52 Merge remote-tracking branch 'origin/dev' into dev 2026-01-28 10:59:00 +08:00
Luis Pater e93e05ae25 refactor: consolidate channel send logic with context-safe handlers
Optimize channel operations by introducing reusable context-aware send functions (`send` and `sendErr`) across `wsrelay`, `handlers`, and `cliproxy`. Ensure graceful handling of canceled contexts during stream operations.
2026-01-28 10:58:35 +08:00
hkfires c8c27325dc feat(thinking): enable thinking toggle for qwen3 and deepseek models
Fix #1245
2026-01-28 09:54:05 +08:00
hkfires c3b6f3918c chore(git): stop ignoring .idea and data directories 2026-01-28 09:52:44 +08:00
Luis Pater bbb55a8ab4 Merge pull request #1170 from BianBianY/main
feat: optimization enable/disable auth files
2026-01-28 09:34:35 +08:00
Shady Khalifa 04b2290927 fix(codex): avoid empty prompt_cache_key 2026-01-27 19:06:42 +02:00
Shady Khalifa 53920b0399 fix(openai): drop stream for responses/compact 2026-01-27 18:27:34 +02:00
RCD 1663148a32 feat: sync with upstream v6.7.25-26
Cherry-picked changes from CLIProxyAPI:
- fix(gemini): force type to string for enum fields (fixes Antigravity Gemini API error)
- feat(auth): add request_retry and disable_cooling per-auth overrides
- feat(auth): add skip persistence context key for file watcher events

Manually added RequestRetryOverride/DisableCoolingOverride methods to
types.go to preserve ProxyPilot's conductor.go compatibility while
gaining new functionality.
2026-01-27 22:08:43 +07:00
Luis Pater 7583193c2a Merge pull request #1257 from router-for-me/model
feat(api): add management model definitions endpoint
2026-01-27 20:32:04 +08:00
hkfires 7cc3bd4ba0 chore(deps): mark golang.org/x/text as indirect 2026-01-27 19:19:52 +08:00
hkfires 88a0f095e8 chore(registry): disable gemini 2.5 flash image preview model 2026-01-27 18:33:13 +08:00
hkfires c65f64dce0 chore(registry): comment out rev19-uic3-1p model config 2026-01-27 18:33:13 +08:00
hkfires d18cd217e1 feat(api): add management model definitions endpoint 2026-01-27 18:33:12 +08:00
Luis Pater ba4a1ab433 Merge pull request #1261 from Darley-Wey/fix/gemini_scheme
fix(gemini): force type to string for enum fields to fix Antigravity Gemini API error
2026-01-27 17:02:25 +08:00
Darley decddb521e fix(gemini): force type to string for enum fields to fix Antigravity Gemini API error (Relates to #1260) 2026-01-27 11:14:08 +03:30
Shady Khalifa 95096bc3fc feat(openai): add responses/compact support 2026-01-26 16:36:01 +02:00
Luis Pater 70897247b2 feat(auth): add support for request_retry and disable_cooling overrides
Implement `request_retry` and `disable_cooling` metadata overrides for authentication management. Update retry and cooling logic accordingly across `Manager`, Antigravity executor, and file synthesizer. Add tests to validate new behaviors.
2026-01-26 21:59:08 +08:00
RCD 1d29f18172 feat: sync with upstream v6.7.22-24
- Antigravity retry logic with improved error handling and capacity management
- Added request_id to error logs for better debugging
- Export OAuth constants from auth packages (antigravity, claude, codex, gemini)
- Added Antigravity AuthService in internal/auth/antigravity
- Updated Claude executor test expectations for system message handling
- Skip built-in tools in OAuth tool prefix
- Preserve displayName and description in Gemini models list
- Added Embed stubs for ProviderExecutor interface compliance
2026-01-26 20:22:43 +07:00
Luis Pater 9c341f5aa5 feat(auth): add skip persistence context key for file watcher events
Introduce `WithSkipPersist` to disable persistence during Manager Update/Register calls, preventing write-back loops caused by redundant file writes. Add corresponding tests and integrate with existing file store and conductor logic.
2026-01-26 18:20:19 +08:00
Luis Pater 2af4a8dc12 refactor(runtime): implement retry logic for Antigravity executor with improved error handling and capacity management 2026-01-26 06:22:46 +08:00
Luis Pater 0f53b952b2 Merge pull request #1225 from router-for-me/log
Add request_id to error logs and extract error messages
2026-01-25 22:08:46 +08:00
hkfires f30ffd5f5e feat(executor): add request_id to error logs
Extract error.message from JSON error responses when summarizing error bodies for debug logs
2026-01-25 21:31:46 +08:00
Luis Pater bc9a24d705 docs(readme): reposition CPA-XXX Panel section for improved visibility 2026-01-25 18:58:32 +08:00
Luis Pater 2c879f13ef Merge pull request #1216 from ferretgeek/add-cpa-xxx-panel
docs: 新增 CPA-XXX 社区面板项目
2026-01-25 18:57:32 +08:00
Gemini 07b4a08979 docs: translate CPA-XXX description to English 2026-01-25 18:00:28 +08:00
Geminiandfactory-droid[bot] 7f612bb069 docs: add CPA-XXX panel to community list
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-01-25 10:45:51 +08:00
hkfires 5743b78694 test(claude): update expectations for system message handling 2026-01-25 08:31:29 +08:00
Luis Pater 2e6a2b655c Merge pull request #1132 from XYenon/fix/gemini-models-displayname-override
fix(gemini): preserve displayName and description in models list
2026-01-25 03:40:04 +08:00
Luis Pater cb47ac21bf Merge pull request #1179 from mallendeo/main
fix(claude): skip built-in tools in OAuth tool prefix
2026-01-25 03:31:58 +08:00
Luis Pater a1394b4596 Merge pull request #1183 from Darley-Wey/fix/api-align
fix(api): enhance ClaudeModels response to align with api.anthropic.com
2026-01-25 03:30:14 +08:00
Luis Pater 9e97948f03 Merge pull request #1185 from router-for-me/auth
Refactor authentication handling for Antigravity, Claude, Codex, and Gemini
2026-01-25 03:28:53 +08:00
Yang Bian f7bfa8a05c Merge branch 'upstream-main' 2026-01-24 16:28:08 +08:00
RCD 5be8c90506 feat: sync with upstream v6.7.19-21
- Updated all executors with context cancellation handling
- Added payload rules using requested model
- Filter out Top_P when Temperature is set on Claude
- Remove empty system messages in translators
- Handle quota cooldown in retry logic
- Include requested model in executor metadata
- Normalize plan type filenames to lowercase
- Added Embed stubs for ProviderExecutor interface compliance
- Added payloadRequestedModel helper function
2026-01-24 11:17:03 +07:00
Darley 46c6fb1e7a fix(api): enhance ClaudeModels response to align with api.anthropic.com 2026-01-24 04:41:08 +03:30
hkfires 9f9fec5d4c fix(auth): improve antigravity token exchange errors 2026-01-24 09:04:15 +08:00
hkfires e95be10485 fix(auth): validate antigravity token userinfo email 2026-01-24 08:33:52 +08:00
hkfires f3d58fa0ce fix(auth): correct antigravity oauth redirect and expiry 2026-01-24 08:33:52 +08:00
hkfires 8c0eaa1f71 refactor(auth): export Gemini constants and use in handler 2026-01-24 08:33:52 +08:00
hkfires 405df58f72 refactor(auth): export Codex constants and slim down handler 2026-01-24 08:33:52 +08:00
hkfires e7f13aa008 refactor(api): slim down RequestAnthropicToken to use internal/auth 2026-01-24 08:33:51 +08:00
hkfires 7cb6a9b89a refactor(auth): export Claude OAuth constants for reuse 2026-01-24 08:33:51 +08:00
hkfires 9aa5344c29 refactor(api): slim down RequestAntigravityToken to use internal/auth 2026-01-24 08:33:51 +08:00
hkfires 8ba0ebbd2a refactor(sdk): slim down Antigravity authenticator to use internal/auth 2026-01-24 08:33:51 +08:00
hkfires c65407ab9f refactor(auth): extract Antigravity OAuth constants to internal/auth 2026-01-24 08:33:51 +08:00
hkfires 9e59685212 refactor(auth): implement Antigravity AuthService in internal/auth 2026-01-24 08:33:51 +08:00
hkfires 4a4dfaa910 refactor(auth): replace sanitizeAntigravityFileName with antigravity.CredentialFileName 2026-01-24 08:33:51 +08:00
Luis Pater 0d6ecb0191 Fixed: #1077
refactor(translator): improve tools handling by separating functionDeclarations and googleSearch nodes
2026-01-24 05:51:11 +08:00
Mauricio Allende f16461bfe7 fix(claude): skip built-in tools in OAuth tool prefix 2026-01-23 21:29:39 +00:00
Luis Pater c32e2a8196 fix(auth): handle context cancellation in executor methods 2026-01-24 04:56:55 +08:00
Luis Pater 873d41582f Merge pull request #1125 from NightHammer1000/dev
Filter out Top_P when Temp is set on Claude
2026-01-24 02:03:33 +08:00
Luis Pater 6fb7d85558 Merge pull request #1137 from augustVino/fix/remove_empty_systemmsg
fix(translator): ensure system message is only added if it contains c…
2026-01-24 02:02:18 +08:00
lieyan666 6da7ed53f2 fix: change HTTP status code from 400 to 502 when no provider available
Fixes #1082

When all Antigravity accounts are unavailable, the error response now returns
HTTP 502 (Bad Gateway) instead of HTTP 400 (Bad Request). This ensures that
NewAPI and other clients will retry the request on a different channel,
improving overall reliability.
2026-01-23 23:45:14 +08:00
RCD 377697331b feat: sync with upstream v6.7.17-18
- Updated gemini_schema.go with improved schema cleaning
- Refined signature caching logic (kept 1h TTL for memory efficiency)
- Enhanced Claude/Gemini translator tests
- Fixed Gemini function-calling INVALID_ARGUMENT via relaxed tool validation
2026-01-23 19:26:02 +07:00
hkfires d5e3e32d58 fix(auth): normalize plan type filenames to lowercase 2026-01-23 20:13:09 +08:00
Chén Mù f353a54555 Merge pull request #1171 from router-for-me/auth
refactor(auth): remove unused provider execution helpers
2026-01-23 19:43:42 +08:00
Chén Mù 1d6e2e751d Merge pull request #1140 from sxjeru/main
fix(auth): handle quota cooldown in retry logic for transient errors
2026-01-23 19:43:17 +08:00
hkfires cc50b63422 refactor(auth): remove unused provider execution helpers 2026-01-23 19:12:55 +08:00
Luis Pater 15ae83a15b Merge pull request #1169 from router-for-me/payload
feat(executor): apply payload rules using requested model
2026-01-23 18:41:31 +08:00
hkfires 81b369aed9 fix(auth): include requested model in executor metadata 2026-01-23 18:30:08 +08:00
Yang Bian c8620d1633 feat: optimization enable/disable auth files 2026-01-23 18:03:09 +08:00
hkfires ecc850bfb7 feat(executor): apply payload rules using requested model 2026-01-23 16:38:41 +08:00
Chén Mù 19b4ef33e0 Merge pull request #1102 from aldinokemal/main
feat(management): add PATCH endpoint to enable/disable auth files
2026-01-23 09:05:24 +08:00
hkfires 7ca045d8b9 fix(executor): adjust model-specific request payload 2026-01-22 20:28:08 +08:00
hkfires abfca6aab2 refactor(util): reorder gemini schema cleaner helpers 2026-01-22 18:38:48 +08:00
Chén Mù 3c71c075db Merge pull request #1131 from sowar1987/fix/gemini-malformed-function-call
Fix Gemini tool calling for Antigravity (malformed_function_call)
2026-01-22 18:07:03 +08:00
sowar1987andWarp 9c2992bfb2 test: align signature cache tests with cache behavior
Co-Authored-By: Warp <agent@warp.dev>
2026-01-22 17:12:47 +08:00
sowar1987andWarp 269a1c5452 refactor: reuse placeholder reason description
Co-Authored-By: Warp <agent@warp.dev>
2026-01-22 17:12:47 +08:00
sowar1987andWarp 22ce65ac72 test: update signature cache tests
Revert gemini translator changes for scheme A

Co-Authored-By: Warp <agent@warp.dev>
2026-01-22 17:12:47 +08:00
sowar1987 a2f8f59192 Fix Gemini function-calling INVALID_ARGUMENT by relaxing Gemini tool validation and cleaning schema 2026-01-22 17:11:07 +08:00
XYenon 8c7c446f33 fix(gemini): preserve displayName and description in models list
Previously GeminiModels handler unconditionally overwrote displayName
and description with the model name, losing the original values defined
in model definitions (e.g., 'Gemini 3 Pro Preview').

Now only set these fields as fallback when they are missing or empty.
2026-01-22 15:19:27 +08:00
sxjeru 30a59168d7 fix(auth): handle quota cooldown in retry logic for transient errors 2026-01-21 21:48:23 +08:00
hkfires c8884f5e25 refactor(translator): enhance signature handling in Claude and Gemini requests, streamline cache usage and remove unnecessary tests 2026-01-21 20:21:49 +08:00
Luis Pater d9c6317c84 refactor(cache, translator): refine signature caching logic and tests, replace session-based logic with model group handling 2026-01-21 18:30:05 +08:00
Vino d29ec95526 fix(translator): ensure system message is only added if it contains content 2026-01-21 16:45:50 +08:00
RCD e86d2b86d5 feat: sync with upstream v6.7.16
Major changes from upstream v6.7.16:
- Remove sessionID from signature caching API entirely
  - CacheSignature(modelName, text, sig) instead of 4 params
  - GetCachedSignature(modelName, text) instead of 3 params
  - HasValidSignature(modelName, sig) instead of 1 param
- Add Gemini fallback: returns "skip_thought_signature_validator" on cache miss
- Add sliding expiration (TTL refresh on cache access)
- Add GetModelGroup() for grouping cache keys by model family
- Simplify antigravity executor by removing project switch logic
- Fix OpenAI Responses request handler to skip empty assistant text
- Fix OpenAI Responses request to validate full JSON before parsing

Local fixes for compatibility:
- Add Embed stub method to AntigravityExecutor for interface compliance
- Update test to clear cache for isolation (ThinkingBlockWithoutSignature)
- Update Gemini test to expect thinking blocks to be annotated not removed
- Fix gjson.Valid check before treating tool output as raw JSON
2026-01-21 15:05:05 +07:00
Luis Pater ef4508dbc8 refactor(cache, translator): remove session ID from signature caching and clean up logic 2026-01-21 13:37:10 +08:00
Luis Pater f775e46fe2 refactor(translator): remove session ID logic from signature caching and associated tests 2026-01-21 12:45:07 +08:00
Luis Pater 65ad5c0c9d refactor(cache): simplify signature caching by removing sessionID parameter 2026-01-21 12:38:05 +08:00
Luis Pater 88bf4e77ec fix(translator): update HasValidSignature to require modelName parameter for improved validation 2026-01-21 11:31:37 +08:00
Luis Pater a4f8015caa test(logging): add unit tests for GinLogrusRecovery middleware panic handling 2026-01-21 10:57:27 +08:00
Luis Pater ffd129909e Merge pull request #1130 from router-for-me/agty
fix(executor): only strip maxOutputTokens for non-claude models
2026-01-21 10:50:39 +08:00
hkfires 9332316383 fix(translator): preserve thinking blocks by skipping signature 2026-01-21 10:49:20 +08:00
hkfires 6dcbbf64c3 fix(executor): only strip maxOutputTokens for non-claude models 2026-01-21 10:49:20 +08:00
Luis Pater 2ce3553612 feat(cache): handle gemini family in signature cache with fallback validator logic 2026-01-21 10:11:21 +08:00
Luis Pater 2e14f787d4 feat(translator): enhance ConvertGeminiRequestToAntigravity with model name and refine reasoning block handling 2026-01-21 08:31:23 +08:00
Luis Pater 523b41ccd2 test(responses): add comprehensive tests for SSE event ordering and response transformations 2026-01-21 07:08:59 +08:00
N1GHT 09970dc7af Accept Geminis Review Suggestion 2026-01-20 17:51:36 +01:00
N1GHT d81abd401c Returned the Code Comment I trashed 2026-01-20 17:36:27 +01:00
N1GHT a6cba25bc1 Small fix to filter out Top_P when Temperature is set on Claude to make requests go through 2026-01-20 17:34:26 +01:00
Luis Pater c6fa1d0e67 Merge pull request #1117 from router-for-me/cache
fix(translator): enhance signature cache clearing logic and update test cases with model name
2026-01-20 23:18:48 +08:00
Luis Pater ac56e1e88b Merge pull request #1116 from bexcodex/fix/antigravity
Fix antigravity malformed_function_call
2026-01-20 22:40:00 +08:00
hkfires 9b72ea9efa fix(translator): enhance signature cache clearing logic and update test cases with model name 2026-01-20 20:02:29 +08:00
bexcodex 9f364441e8 Fix antigravity malformed_function_call 2026-01-20 19:54:54 +08:00
Luis Pater e49a1c07bf chore(translator): update cache functions to include model name parameter in tests 2026-01-20 18:36:51 +08:00
RCD 3fb213d513 feat: sync with upstream v6.7.15
Port features from upstream CLIProxyAPI:

v6.7.13:
- Raw JSON payload rules (DefaultRaw, OverrideRaw)
- OpenCode instructions support with user agent detection

v6.7.14:
- Improve signature handling by associating with model name

v6.7.15:
- Unify model group references with GetModelGroup helper function
2026-01-20 16:49:13 +07:00
RCD e0fa10b669 feat: sync with upstream v6.7.13
Features ported from upstream:
- feat(claude): add native request cloaking support
- feat(translator): add candidate count (n param) support for Gemini
- fix(translator): consolidate multiple system messages into single message (#1064)
- feat(codex): add config toggle for codex instructions injection
- feat(auth): add hashed account ID to credential filenames for team plans
- feat(config): add support for raw JSON payload rules (default-raw, override-raw)
- feat(codex): add OpenCode instructions based on user agent

Also includes minor whitespace cleanup and code organization.
2026-01-20 14:08:05 +07:00
Luis Pater 8d9f4edf9b feat(translator): unify model group references by introducing GetModelGroup helper function 2026-01-20 13:45:25 +08:00
Luis Pater 020e61d0da feat(translator): improve signature handling by associating with model name in cache functions 2026-01-20 13:31:36 +08:00
RCD 4a0f8232d5 refactor(claude): remove redundant system instructions check
The checkSystemInstructions was being called on every request but the
cloaking/system prompt handling is now done elsewhere. This removes
redundant processing.

Cherry-picked from CLIProxyAPI: 7831cba9
2026-01-20 11:49:21 +07:00
RCD 3d4b723fb3 feat(translator): enhance session ID derivation with user_id parsing
Extract session ID from metadata.user_id field when available, using
the "session_" prefix marker. Falls back to first user message hash.

Cherry-picked from CLIProxyAPI: 6184c433 (Fixed: #1109)
2026-01-20 11:42:02 +07:00
RCD 5428a0ad74 test(antigravity): update tests to match cached-only signature behavior
Update tests to reflect the new signature handling behavior where only
cached signatures are used, not client-provided ones. This prevents
"Corrupted thought signature" errors when switching between Claude and
Gemini models.

Tests now properly cache signatures before testing conversion functions.
2026-01-20 11:39:56 +07:00
Luis Pater 6184c43319 Fixed: #1109
feat(translator): enhance session ID derivation with user_id parsing in Claude
2026-01-20 12:35:40 +08:00
RCD 02b0714e3a feat(vertex): add Imagen image generation model support
Add support for Imagen 3.0 and 4.0 image generation models in Vertex AI:

- Add 5 Imagen model definitions (4.0, 4.0-ultra, 4.0-fast, 3.0, 3.0-fast)
- Implement :predict action routing for Imagen models
- Convert Imagen request/response format to match Gemini structure
- Transform prompts to Imagen's instances/parameters format
- Convert base64 image responses to Gemini-compatible inline data

Cherry-picked from CLIProxyAPI: 8734d4cb
2026-01-20 11:31:07 +07:00
RCD 94088ea1de refactor(antigravity): remove legacy client signature comments
Cleanup dead code from signature handling in thinking blocks.
The actual fix was applied in commit 27b25bc0.
Cherry-picked from CLIProxyAPI: 5977af96
2026-01-20 11:25:37 +07:00
RCD e6e7e6db30 feat(registry): support provider-specific model info lookup
Add InfoByProvider map to ModelRegistration to store provider-specific
ModelInfo, enabling different capabilities for the same model across
providers (e.g., direct API vs OpenRouter).

Changes:
- Add InfoByProvider field to ModelRegistration struct
- Update GetModelInfo to accept provider parameter for provider-specific lookup
- Update LookupModelInfo to accept variadic provider parameter
- Add LookupStaticModelInfo for fallback to static model definitions
- Update ApplyThinking to pass providerKey for registry lookups
- Update all GetModelInfo callers to use new signature
- Remove ensureMaxTokensForThinking test (function moved to thinking package)

Ported from CLIProxyAPI e641fde2
2026-01-20 11:15:39 +07:00
RCD f528639f1c feat(claude): clamp thinking budget to max_tokens constraints
Improve budget normalization in Claude applier to handle edge cases
where budget exceeds or approaches max_tokens limits.

Cherry-picked from 239a2879.
2026-01-20 10:54:29 +07:00
RCD 5dd078ffb3 refactor(claude): move max_tokens constraint enforcement to Apply method
Move ensureMaxTokensForThinking logic from claude_executor to
thinking/provider/claude/apply.go. This centralizes Claude-specific
thinking budget constraints in the thinking package.

Cherry-picked from c421d653.
2026-01-20 10:53:37 +07:00
RCD 8d8a010577 feat(executor): enhance payload translation with original request context
Add 6th parameter 'original' to applyPayloadConfigWithRoot to support
checking defaults against the original payload. This enables proper
default rule validation when translating between formats.

Based on upstream 2a663d5c.
2026-01-20 10:49:30 +07:00
Luis Pater 2cbe4a790c chore(translator): remove unnecessary whitespace in gemini_openai_response code 2026-01-20 11:47:33 +08:00
RCD 27b25bc0d7 refactor(antigravity): remove unused client signature handling in thinking objects
- Comment out client signature extraction (incompatible across model families)
- Use only cached signatures for thinking blocks
- Switch to thinking.GetThinkingText for text extraction
- Add explanatory comment about cross-model signature issues

Cherry-picked from d4bb4e66.
2026-01-20 10:43:24 +07:00
Luis Pater 68b3565d7b Merge branch 'main' into dev (PR #961) 2026-01-20 11:42:22 +08:00
RCD 5a38b6bc04 fix(executor): stop rewriting thinkingLevel for gemini
Remove automatic thinkingLevel -> thinkingBudget:-1 conversion
for non-gemini-3 models in antigravity executor.

Cherry-picked from 1d2fe553.
2026-01-20 10:40:07 +07:00
RCD f1d05cc027 feat(registry): expand antigravity model config
- Remove static Name mapping from AntigravityModelConfig
- Add new model entries: claude-sonnet-4-5, gpt-oss-120b-medium, tab_flash_lite_preview
- Add model skip list for unlisted models
- Update thinking limits (Max: 128000, ZeroAllowed: true)

Cherry-picked from c175821c.
2026-01-20 10:39:00 +07:00
Luis Pater 3f385a8572 feat(auth): add "antigravity" provider to ignored access_token fields in filestore 2026-01-20 11:38:31 +08:00
Luis Pater 9823dc35e1 feat(auth): hash account ID for improved uniqueness in credential filenames 2026-01-20 11:37:52 +08:00
Luis Pater 059bfee91b feat(auth): add hashed account ID to credential filenames for team plans 2026-01-20 11:36:29 +08:00
RCD e80b531d68 fix(translator): avoid forcing RFC 8259 system prompt
Cherry-picked from 52e46ced.
2026-01-20 10:32:41 +07:00
RCD 8d737adaf1 feat(translator): report cached token usage in Claude output
Cherry-picked from cf9daf47.
2026-01-20 10:32:12 +07:00
Luis Pater 7beaf0eaa2 Merge pull request #869 2026-01-20 11:16:53 +08:00
Luis Pater 1fef90ff58 Merge pull request #877 from zhiqing0205/main
feat(codex): include plan type in auth filename
2026-01-20 11:11:25 +08:00
Luis Pater 8447fd27a0 fix(login): remove emojis from interactive prompt messages 2026-01-20 11:09:56 +08:00
Luis Pater 7831cba9f6 refactor(claude): remove redundant system instructions check in Claude executor 2026-01-20 11:02:52 +08:00
Luis Pater e02b2d58d5 Merge pull request #868 2026-01-20 10:57:24 +08:00
Luis Pater 28726632a9 Merge pull request #861 from umairimtiaz9/fix/gemini-cli-backend-project-id
fix(auth): use backend project ID for free tier Gemini CLI OAuth users
2026-01-20 10:32:17 +08:00
Luis Pater 3b26129c82 Merge pull request #1108 from router-for-me/modelinfo
feat(registry): support provider-specific model info lookup
2026-01-20 10:18:42 +08:00
Luis Pater d4bb4e6624 refactor(antigravity): remove unused client signature handling in thinking objects 2026-01-20 10:17:55 +08:00
Luis Pater 0766c49f93 Merge pull request #994 from adrenjc/fix/cross-model-thinking-signature
fix(antigravity): prevent corrupted thought signature when switching models
2026-01-20 10:14:05 +08:00
Luis Pater a7ffc77e3d Merge branch 'dev' into fix/cross-model-thinking-signature 2026-01-20 10:10:43 +08:00
hkfires e641fde25c feat(registry): support provider-specific model info lookup 2026-01-20 10:01:17 +08:00
Luis Pater 5717c7f2f4 Merge pull request #1103 from dinhkarate/feat/imagen
feat(vertex): add Imagen image generation model support
2026-01-20 07:11:18 +08:00
dinhkarate 8734d4cb90 feat(vertex): add Imagen image generation model support
Add support for Imagen 3.0 and 4.0 image generation models in Vertex AI:

- Add 5 Imagen model definitions (4.0, 4.0-ultra, 4.0-fast, 3.0, 3.0-fast)
- Implement :predict action routing for Imagen models
- Convert Imagen request/response format to match Gemini structure like gemini-3-pro-image
- Transform prompts to Imagen's instances/parameters format
- Convert base64 image responses to Gemini-compatible inline data
2026-01-20 01:26:37 +07:00
Aldino Kemal 2f6004d74a perf(management): optimize auth lookup in PatchAuthFileStatus
Use GetByID() for O(1) map lookup first, falling back to iteration
only for FileName matching. Consistent with pattern in disableAuth().
2026-01-19 20:05:37 +07:00
Luis Pater 5baa753539 Merge pull request #1099 from router-for-me/claude
refactor(claude): move max_tokens constraint enforcement to Apply method
2026-01-19 20:55:59 +08:00
Luis Pater ead98e4bca Merge pull request #1101 from router-for-me/argy
fix(executor): stop rewriting thinkingLevel for gemini
2026-01-19 20:55:22 +08:00
Aldino Kemal a1634909e8 feat(management): add PATCH endpoint to enable/disable auth files
Add new PATCH /v0/management/auth-files/status endpoint that allows
toggling the disabled state of auth files without deleting them.
This enables users to temporarily disable credentials from the
management UI.
2026-01-19 19:50:36 +07:00
hkfires 1d2fe55310 fix(executor): stop rewriting thinkingLevel for gemini 2026-01-19 19:49:39 +08:00
hkfires c175821cc4 feat(registry): expand antigravity model config
Remove static Name mapping and add entries for claude-sonnet-4-5,
tab_flash_lite_preview, and gpt-oss-120b-medium configs
2026-01-19 19:32:00 +08:00
hkfires 239a28793c feat(claude): clamp thinking budget to max_tokens constraints 2026-01-19 16:32:20 +08:00
hkfires c421d653e7 refactor(claude): move max_tokens constraint enforcement to Apply method 2026-01-19 15:50:35 +08:00
Luis Pater 2542c2920d Merge pull request #1096 from router-for-me/usage
feat(translator): report cached token usage in Claude output
2026-01-19 11:52:18 +08:00
hkfires 52e46ced1b fix(translator): avoid forcing RFC 8259 system prompt 2026-01-19 11:33:27 +08:00
hkfires cf9daf470c feat(translator): report cached token usage in Claude output 2026-01-19 11:23:44 +08:00
RCD 513594deb4 chore: add temp files to gitignore 2026-01-19 06:54:48 +07:00
RCD de766d80b3 refactor(translator): normalize includeThoughts field name
Rename include_thoughts to includeThoughts across all translator files
for consistency with the Gemini API field naming convention.

Cherry-picked key change from d5ef4a6d.
2026-01-19 06:54:38 +07:00
RCD eead4d59f4 fix(thinking): add original_mode to log field order
Cherry-picked from cb6caf3f. The main changes (fromSuffix parameter,
strictBudget logic) were already included in the thinking package port.
2026-01-19 06:50:42 +07:00
RCD f030ec3384 feat(thinking): add unified thinking configuration package
Port the internal/thinking package from CLIProxyAPI for unified thinking
configuration processing across all AI providers.

Features:
- Core types: ThinkingConfig, ThinkingMode, ThinkingLevel, SuffixResult
- Suffix parsing: model-name(16384) or model-name(high) syntax
- Validation: auto-conversion between budget/level formats, clamping
- Provider appliers: claude, gemini, antigravity, openai, codex
- Config extraction: extract thinking config from various request formats
- Stripping: remove thinking config for non-supporting models

Registry updates:
- Add UserDefined field to ModelInfo for passthrough behavior
- Add LookupModelInfo function for model capability lookup
2026-01-19 06:36:22 +07:00
RCD 22f91dc48e feat(translator): add reasoning state tracking and improve reasoning summary handling
Improves handling of reasoning summaries in OpenAI Responses API translation.
Cherry-picked from CLIProxyAPI.
2026-01-19 06:09:19 +07:00
RCD ed136fef5d refactor(logging): centralize log directory resolution logic
- Add ResolveLogDirectory() for consistent log path resolution
- Add SetLogLevel() for string-based log level configuration
- Update ConfigureLogOutput() to take *config.Config parameter
- Update all callers to use simplified API

Cherry-picked from CLIProxyAPI with adaptations.
2026-01-19 06:07:51 +07:00
RCD 630102632f fix(antigravity): convert non-string enum values to strings for Gemini API
Gemini API requires enum values to be strings. This adds NormalizeEnumValues
to convert numeric or boolean enum values to their string representations.
Cherry-picked from CLIProxyAPI.
2026-01-19 06:01:28 +07:00
RCD 2e490cf8f2 fix(translator): add check for empty text to prevent invalid serialization
Prevents sending empty text fields to Gemini and Antigravity APIs which
could cause invalid JSON serialization. Cherry-picked from CLIProxyAPI.
2026-01-19 06:00:12 +07:00
Luis Pater 140d6211cc feat(translator): add reasoning state tracking and improve reasoning summary handling
- Introduced `oaiToResponsesStateReasoning` to track reasoning data.
- Enhanced logic for emitting reasoning summary events and managing state transitions.
- Updated output generation to handle multiple reasoning entries consistently.
2026-01-19 03:58:28 +08:00
Luis Pater 60f9a1442c Merge pull request #1088 from router-for-me/thinking
Thinking
2026-01-18 17:01:59 +08:00
hkfires cb6caf3f87 fix(thinking): update ValidateConfig to include fromSuffix parameter and adjust budget validation logic 2026-01-18 16:37:14 +08:00
Luis Pater 99c7abbbf1 Merge pull request #1067 from router-for-me/auth-files
refactor(auth): simplify filename prefixes for qwen and iflow tokens
2026-01-18 13:41:59 +08:00
Luis Pater 8f511ac33c Merge pull request #1076 from sususu98/fix/antigravity-enum-string
fix(antigravity): convert non-string enum values to strings for Gemini API
2026-01-18 13:40:53 +08:00
Luis Pater 1046152119 Merge pull request #1068 from 0xtbug/dev
docs(readme): add ZeroLimit to projects based on CLIProxyAPI
2026-01-18 13:37:50 +08:00
Luis Pater f88228f1c5 Merge pull request #1081 from router-for-me/thinking
Refine thinking validation and cross‑provider payload conversion
2026-01-18 13:34:28 +08:00
Luis Pater 62e2b672d9 refactor(logging): centralize log directory resolution logic
- Introduced `ResolveLogDirectory` function in `logging` package to standardize log directory determination across components.
- Replaced redundant logic in `server`, `global_logger`, and `handlers` with the new utility function.
2026-01-18 12:40:57 +08:00
hkfires 03005b5d29 refactor(thinking): add Gemini family provider grouping for strict validation 2026-01-18 11:30:53 +08:00
hkfires c7e8830a56 refactor(thinking): pass source and target formats to ApplyThinking for cross-format validation
Update ApplyThinking signature to accept fromFormat and toFormat parameters
instead of a single provider string. This enables:

- Proper level-to-budget conversion when source is level-based (openai/codex)
  and target is budget-based (gemini/claude)
- Strict budget range validation when source and target formats match
- Level clamping to nearest supported level for cross-format requests
- Format alias resolution in SDK translator registry for codex/openai-response

Also adds ErrBudgetOutOfRange error code and improves iflow config extraction
to fall back to openai format when iflow-specific config is not present.
2026-01-18 10:30:15 +08:00
hkfires d5ef4a6d15 refactor(translator): remove registry model lookups from thinking config conversions 2026-01-18 10:30:14 +08:00
hkfires 97b67e0e49 test(thinking): split E2E coverage into suffix and body parameter test functions
Refactor thinking configuration tests by separating model name suffix-based
scenarios from request body parameter-based scenarios into distinct test
functions with independent case numbering.

Architectural improvements:
- Extract thinkingTestCase struct to package level for shared usage
- Add getTestModels() helper returning complete model fixture set
- Introduce runThinkingTests() runner with protocol-specific field detection
- Register level-subset-model fixture with constrained low/high level support
- Extend iflow protocol handling for glm-test and minimax-test models
- Add same-protocol strict boundary validation cases (80-89)
- Replace error responses with clamped values for boundary-exceeding budgets
2026-01-18 10:30:14 +08:00
sususu98 dd6d78cb31 fix(antigravity): convert non-string enum values to strings for Gemini API
Gemini API requires all enum values in function declarations to be
strings. Some MCP tools (e.g., roxybrowser) define schemas with numeric
enums like `"enum": [0, 1, 2]`, causing INVALID_ARGUMENT errors.

Add convertEnumValuesToStrings() to automatically convert numeric and
boolean enum values to their string representations during schema
transformation.
2026-01-18 02:00:02 +00:00
RCD 7beb9b788a docs: add auto-update and rollback documentation
- Add Auto-Updates and Rollback Support features to Features list
- Add Auto-Updates section with configuration options
- Add Rollback Support section explaining crash detection and recovery
- Document tray menu options for updates and rollback
2026-01-18 08:22:20 +07:00
RCD e845700b9e test(updates): add unit tests for update system
11 tests covering:
- Poller creation, channel setting, start/stop
- Rollback data directory handling
- Rollback info save/load operations
- Health check recording and marking
- Asset platform detection
- Download progress reader
2026-01-18 07:39:02 +07:00
RCD 2913c4a20e feat(tray): integrate auto-update and rollback features
Tray app integration:
- Health check on startup with auto-rollback trigger
- Background update polling with configurable interval
- One-click update menu item (shown when available)
- Manual rollback menu item in Settings
- Mark healthy after 30s of stable operation
- Graceful cleanup on exit (stop engine, stop poller)
2026-01-18 07:38:37 +07:00
RCD cb53b9ca2a feat(tray): add stability improvements to embedded engine
Enhanced EmbeddedEngine with:
- Panic recovery to prevent tray crashes
- Graceful shutdown with 10s timeout
- Panic and restart counters for monitoring
- Uptime tracking method
- Better error handling and logging
2026-01-18 07:37:08 +07:00
RCD 3127555850 feat(updates): add rollback support with crash detection
New rollback module for version recovery:
- Version-aware backup metadata tracking
- Platform-specific restore (Windows batch, Unix swap)
- Crash loop detection via startup health monitoring
- Auto-rollback after 3 rapid failures in 30s window
- MarkHealthy() clears failure counter after stable run

Install module updated to save rollback info on update.
2026-01-18 07:34:57 +07:00
RCD 31ca3a2d93 feat(webui): add proactive update notification banner
New UpdateBanner component for dashboard:
- Auto-checks for updates on mount with 2s delay
- Shows dismissible banner when update available
- Session-based dismissal persistence
- Download progress bar during update
- Integrated into App.tsx main layout
2026-01-18 07:34:35 +07:00
RCD 4c3d538979 feat(updates): add background update poller
New poller module for periodic update checks:
- Configurable polling interval
- Channel support (stable/prerelease)
- Callback-based notification system
- Global singleton for tray integration
- Graceful start/stop with context cancellation
2026-01-18 07:34:09 +07:00
RCD 4d14eeb608 feat(config): add auto-update configuration settings
Add UpdatesConfig struct with configurable options:
- auto-check: enable/disable automatic update checks
- check-interval-hours: polling frequency (default 24h)
- auto-download/auto-install: for future automation
- notify-on-update: toast notifications
- channel: stable/prerelease support

Includes helper methods with sensible defaults.
2026-01-18 07:33:31 +07:00
Luis Pater 46433a25f8 fix(translator): add check for empty text to prevent invalid serialization in gemini and antigravity 2026-01-18 00:50:10 +08:00
Tubagusandgemini-code-assist[bot] c8843edb81 Update README_CN.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-17 11:33:29 +07:00
Tubagusandgemini-code-assist[bot] f89feb881c Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-17 11:33:18 +07:00
Tubagus dbba71028e docs(readme): add ZeroLimit to projects based on CLIProxyAPI 2026-01-17 11:30:15 +07:00
Tubagus 8549a92e9a docs(readme): add ZeroLimit to projects based on CLIProxyAPI
Added ZeroLimit app to the list of projects in README.
2026-01-17 11:29:22 +07:00
hkfires 109cffc010 refactor(auth): simplify filename prefixes for qwen and iflow tokens 2026-01-17 12:20:58 +08:00
RCD 7fc975198d fix(translator): preserve multiple system prompts in Gemini requests
Cherry-pick from CLIProxyAPI v6.7.7 (f8f3ad8).

Fixes issue where only the last system/developer message was preserved
when multiple were provided. Added systemPartIndex counter to accumulate
parts across all system messages instead of overwriting at index 0.

Also fixed path inconsistency in gemini_openai_request.go where the
array branch incorrectly used request.systemInstruction instead of
system_instruction.

Fixes: router-for-me/CLIProxyAPI#1064
2026-01-17 08:10:59 +07:00
Luis Pater f8f3ad84fc Fixed: #1064
feat(translator): improve system message handling and content indexing across translators

- Updated logic for processing system messages in `claude`, `gemini`, `gemini-cli`, and `antigravity` translators.
- Introduced indexing for `systemInstruction.parts` to ensure proper ordering and handling of multi-part content.
- Added safeguards for accurate content transformation and serialization.
2026-01-17 05:40:56 +08:00
Luis Pater bc7167e9fe feat(runtime): add model alias support and enhance payload rule matching
- Introduced `payloadModelAliases` and `payloadModelCandidates` functions to support model aliases for improved flexibility.
- Updated rule matching logic to handle multiple model candidates.
- Refactored variable naming in executor to improve code clarity and consistency.
2026-01-17 05:05:24 +08:00
Luis Pater 384578a88c feat(cliproxy, gemini): improve ID matching logic and enrich normalized model output
- Enhanced ID matching in `cliproxy` by adding additional conditions to better handle ID equality cases.
- Updated `gemini` handlers to include `displayName` and `description` in normalized models for enriched metadata.
2026-01-17 04:44:09 +08:00
Luis Pater 65b4e1ec6c feat(codex): enable instruction toggling and update role terminology
- Added conditional logic for Codex instruction injection based on configuration.
- Updated role terminology from "user" to "developer" for better alignment with context.
2026-01-17 04:12:29 +08:00
Luis Pater 6600d58ba2 feat(codex): enhance input transformation and remove unused safety_identifier field
- Added logic to transform `inputResults` into structured JSON for improved processing.
- Removed redundant `safety_identifier` field in executor payload to streamline requests.
2026-01-16 19:59:01 +08:00
RCD 629bdad1c9 chore: remove installer-ui source and deprecated scripts
- Remove installer-ui/ React source (compiled assets already in cmd/installer/ui/)
- Remove start-tui-web.bat (deprecated)
- Update go.sum from mod tidy
2026-01-16 15:25:50 +07:00
RCD f2eabe57c5 fix(codex): ensure instructions field exists in request body
Add check to ensure 'instructions' field exists in Execute, ExecuteStream,
and CountTokens functions before sending request to Codex API.

Cherry-picked from:
- CLIProxyAPI v6.7.4 (902bea2)
2026-01-16 15:25:50 +07:00
RCD a2d701b205 fix(executor): update gemini-3-pro model name check to use internal name
Change conditional check from gemini-3-pro-preview (alias) to
gemini-3-pro-high (internal name) for system instruction injection.

Cherry-picked from:
- CLIProxyAPI v6.7.3 (c3ef46f)
2026-01-16 15:25:50 +07:00
RCD 7b22c4fd4d feat(auth): cherry-pick CLIProxyAPI v6.6.108-109 core updates
- Add ensureAntigravityProjectID to fetch project_id during token refresh
- Simplify filestore Save() to use os.O_TRUNC instead of temp file rename
- Auto-fetch project_id for antigravity provider in readAuthFile()
- Add metadataEqualIgnoringTimestamps to prevent refresh loops
- Use reflect.DeepEqual for cleaner metadata comparison

Cherry-picked from:
- CLIProxyAPI v6.6.108 (086eb3d)
- CLIProxyAPI v6.6.109-dev (7248f65)
2026-01-16 15:25:49 +07:00
Chén Mù 4dc7af5a5d Merge pull request #1054 from router-for-me/codex
fix(codex): ensure instructions field exists
2026-01-16 15:40:12 +08:00
hkfires 902bea24b4 fix(codex): ensure instructions field exists 2026-01-16 15:38:10 +08:00
hkfires c3ef46f409 feat(config): supplement missing default aliases during antigravity migration 2026-01-16 13:37:46 +08:00
Luis Pater aa0b63e214 refactor(config): clarify Codex instruction toggle documentation 2026-01-16 12:50:09 +08:00
Luis Pater ea3d22831e refactor(codex): update terminology to "official instructions" for clarity 2026-01-16 12:44:57 +08:00
Luis Pater 3b4d6d359b Merge pull request #1049 from router-for-me/codex
feat(codex): add config toggle for codex instructions injection
2026-01-16 12:38:35 +08:00
hkfires 48cba39a12 feat(codex): add config toggle for codex instructions injection 2026-01-16 12:30:12 +08:00
Luis Pater cec4e251bd feat(translator): preserve text field in serialized output during chat completions processing 2026-01-16 11:35:34 +08:00
Luis Pater 526dd866ba refactor(gemini): replace static model handling with dynamic model registry lookup 2026-01-16 10:39:16 +08:00
Luis Pater b31ddc7bf1 Merge branch 'dev' 2026-01-16 08:21:59 +08:00
Chén Mù 22e1ad3d8a Merge pull request #1018 from pikeman20/main
feat(docker): use environment variables for volume paths
2026-01-16 08:19:23 +08:00
Luis Pater f571b1deb0 feat(config): add support for raw JSON payload rules
- Introduced `default-raw` and `override-raw` rules to handle raw JSON values.
- Enhanced `PayloadConfig` to validate and sanitize raw JSON payload rules.
- Updated executor logic to apply `default-raw` and `override-raw` rules.
- Extended example YAML to include usage of raw JSON rules.
2026-01-16 08:15:28 +08:00
Luis Pater 67f8732683 Merge pull request #1033 from router-for-me/reasoning
Refactor thinking
2026-01-15 20:33:13 +08:00
hkfires 2b387e169b feat(iflow): add iflow-rome model definition 2026-01-15 20:23:55 +08:00
hkfires 199cf480b0 refactor(thinking): remove support for non-standard thinking configurations
This change removes the translation logic for several non-standard, proprietary extensions used to configure thinking/reasoning. Specifically, support for `extra_body.google.thinking_config` and the Anthropic-style `thinking` object has been dropped from the OpenAI request translators.

This simplification streamlines the translators, focusing them on the standard `reasoning_effort` parameter. It also removes the need to look up model information from the registry within these components.

BREAKING CHANGE: Support for non-standard thinking configurations via `extra_body.google.thinking_config` and the Anthropic-style `thinking` object has been removed. Clients should now use the standard `reasoning_effort` parameter to control reasoning.
2026-01-15 19:32:12 +08:00
hkfires 4ad6189487 refactor(thinking): extract antigravity logic into a dedicated provider 2026-01-15 19:08:22 +08:00
hkfires fe5b3c80cb refactor(config): rename oauth-model-mappings to oauth-model-alias 2026-01-15 18:03:26 +08:00
hkfires e0ffec885c fix(aistudio): remove levels from model definitions 2026-01-15 16:06:46 +08:00
hkfires ff4ff6bc2f feat(thinking): support zero as a valid thinking budget for capable models 2026-01-15 15:41:10 +08:00
Luis Pater 7248f65c36 feat(auth): prevent filestore writes on unchanged metadata
- Added `metadataEqualIgnoringTimestamps` to compare metadata while ignoring volatile fields.
- Prevented redundant writes caused by changes in timestamp-related fields.
- Improved efficiency in filestore operations by skipping unnecessary updates.
2026-01-15 14:05:23 +08:00
hkfires 5c40a2db21 refactor(thinking): simplify ModeNone and budget validation logic 2026-01-15 14:03:08 +08:00
Luis Pater 086eb3df7a refactor(auth): simplify file handling logic and remove redundant comparison functions
feat(auth): fetch and update Antigravity project ID from metadata during filestore operations

- Added support to retrieve and update `project_id` using the access token if missing in metadata.
- Integrated HTTP client to fetch project ID dynamically.
- Enhanced metadata persistence logic.
2026-01-15 13:29:14 +08:00
hkfires ee2976cca0 refactor(thinking): improve logging for user-defined models 2026-01-15 13:06:41 +08:00
hkfires 8bc6df329f fix(auth): apply API key model mapping to request model 2026-01-15 13:06:41 +08:00
hkfires bcd4d9595f fix(thinking): refine ModeNone handling based on provider capabilities 2026-01-15 13:06:41 +08:00
hkfires 5a77b7728e refactor(thinking): improve budget clamping and logging with provider/model context 2026-01-15 13:06:41 +08:00
hkfires 1fbbba6f59 feat(logging): order log fields for improved readability 2026-01-15 13:06:41 +08:00
hkfires 847be0e99d fix(auth): use base model name for auth matching by stripping suffix 2026-01-15 13:06:41 +08:00
hkfires f6a2d072e6 refactor(thinking): refine configuration logging 2026-01-15 13:06:41 +08:00
hkfires ed8b0f25ee fix(thinking): use LookupModelInfo for model data 2026-01-15 13:06:41 +08:00
hkfires 6e4a602c60 fix(thinking): map reasoning_effort to thinkingConfig 2026-01-15 13:06:40 +08:00
hkfires 2262479365 refactor(thinking): remove legacy utilities and simplify model mapping 2026-01-15 13:06:40 +08:00
hkfires 33d66959e9 test(thinking): remove legacy unit and integration tests 2026-01-15 13:06:40 +08:00
hkfires 7f1b2b3f6e fix(thinking): improve model lookup and validation 2026-01-15 13:06:40 +08:00
hkfires 40ee065eff fix(thinking): use static lookup to avoid alias issues 2026-01-15 13:06:40 +08:00
hkfires a75fb6af90 refactor(antigravity): remove hardcoded model aliases 2026-01-15 13:06:39 +08:00
hkfires 72f2125668 fix(executor): properly handle thinking application errors 2026-01-15 13:06:39 +08:00
hkfires e8f5888d8e fix(thinking): fix auth matching for thinking suffix and json field conflicts 2026-01-15 13:06:39 +08:00
hkfires 0b06d637e7 refactor: improve thinking logic 2026-01-15 13:06:39 +08:00
Luis Pater 5a7e5bd870 feat(auth): add Antigravity onboarding with tier selection
- Updated `ideType` to `ANTIGRAVITY` in request payload.
- Introduced tier-selection logic to determine default tier for onboarding.
- Added `antigravityOnboardUser` function for project ID retrieval via polling.
- Enhanced error handling and response decoding for onboarding flow.
2026-01-15 11:43:02 +08:00
Luis Pater 6f8a8f8136 feat(selector): add priority support for auth selection 2026-01-15 07:08:24 +08:00
pikeman20 5df195ea82 feat(docker): use environment variables for volume paths
This change introduces environment variable interpolation for volume paths, allowing users to customize where configuration, authentication, and log data are stored.

Why: Makes the project easier to deploy on various hosting environments that require decoupled data management without needing to modify the core docker-compose.yml..

Key points:

Defaults to existing paths (./config.yaml, ./auths, ./logs) to ensure zero breaking changes for current users.

Follows the existing naming convention used in the project.

Enhances portability for CI/CD and cloud-native deployments.
2026-01-15 05:42:51 +07:00
Luis Pater b163f8ed9e Fixed: #1004
feat(translator): add function name to response output item serialization

- Included `item.name` in the serialized response output to enhance output item handling.
2026-01-15 03:27:00 +08:00
Luis Pater a1da6ff5ac Fixed: #499 #985
feat(oauth): add support for customizable OAuth callback ports

- Introduced `oauth-callback-port` flag to override default callback ports.
- Updated SDK and login flows for `iflow`, `gemini`, `antigravity`, `codex`, `claude`, and `openai` to respect configurable callback ports.
- Refactored internal OAuth servers to dynamically assign ports based on the provided options.
- Revised tests and documentation to reflect the new flag and behavior.
2026-01-14 04:29:15 +08:00
adrenjcandClaude Opus 4.5 5977af96a0 fix(antigravity): prevent corrupted thought signature when switching models
When switching from Claude models (e.g., Opus 4.5) to Gemini models
(e.g., Flash) mid-conversation via Antigravity OAuth, the client-provided
thinking signatures from Claude would cause "Corrupted thought signature"
errors since they are incompatible with Gemini API.

Changes:
- Remove fallback to client-provided signatures in thinking block handling
- Only use cached signatures (from same-session Gemini responses)
- Skip thinking blocks without valid cached signatures
- tool_use blocks continue to use skip_thought_signature_validator when
  no valid signature is available

This ensures cross-model switching works correctly while preserving
signature validation for same-model conversations.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 18:24:05 +08:00
Luis Pater 43652d044c refactor(config): replace nonstream-keepalive with nonstream-keepalive-interval
- Updated `SDKConfig` to use `nonstream-keepalive-interval` (seconds) instead of the boolean `nonstream-keepalive`.
- Refactored handlers and logic to incorporate the new interval-based configuration.
- Updated config diff, tests, and example YAML to reflect the changes.
2026-01-13 03:14:38 +08:00
Luis Pater b1b379ea18 feat(api): add non-streaming keep-alive support for idle timeout prevention
- Introduced `StartNonStreamingKeepAlive` to emit periodic blank lines during non-streaming responses.
- Added `nonstream-keepalive` configuration option in `SDKConfig`.
- Updated handlers to utilize `StartNonStreamingKeepAlive` and ensure proper cleanup.
- Extended config diff and tests to include `nonstream-keepalive` changes.
2026-01-13 02:36:07 +08:00
hkfires 21ac161b21 fix(test): implement missing HttpRequest method in stream bootstrap mock 2026-01-12 16:33:43 +08:00
Luis Pater 94e979865e Fixed: #897
refactor(executor): remove `prompt_cache_retention` from request payloads
2026-01-12 10:46:47 +08:00
Luis Pater 6c324f2c8b Fixed: #936
feat(cliproxy): support multiple aliases for OAuth model mappings

- Updated mapping logic to allow multiple aliases per upstream model name.
- Adjusted `SanitizeOAuthModelMappings` to ensure aliases remain unique within channels.
- Added test cases to validate multi-alias scenarios.
- Updated example config to clarify multi-alias support.
2026-01-12 10:40:34 +08:00
Finessse e277e0f413 fix(installer): WiX v4 syntax fixes and add build-exe.bat 2026-01-12 08:21:04 +07:00
Finessse aab559c781 chore(npm): bump version to 0.2.9 2026-01-12 07:40:24 +07:00
Finessse c83da30d3d build(webui): rebuild embedded assets with rate limits component 2026-01-12 07:37:52 +07:00
Finessse 4d33b21446 chore(pricing): update model pricing table for Jan 2026
- Add Claude 4.5 model variants (opus, sonnet, haiku)
- Add Gemini 2.0/2.5 Flash and Pro pricing
- Add OpenAI o3/o4-mini pricing
- Update date reference from Dec 2024 to Jan 2026
2026-01-12 07:37:44 +07:00
Finessse e11daa1b39 feat(tray): single instance, settings menu, rate limits diagnostics
- Single-instance check prevents multiple tray apps
- Settings submenu with startup/auto-proxy toggles
- Copy Rate Limits diagnostic option
- Windows Defender exclusion option
2026-01-12 07:37:33 +07:00
Finessse d77af50d66 build(installer): add MSI installer and WinGet manifest
- WiX-based MSI installer (proxypilot.wxs)
- build-msi.ps1 script for packaging
- WinGet manifest files for package submission
2026-01-12 07:37:24 +07:00
Finessse 2d1c2070a9 feat(webui): add rate limits status dashboard component
- RateLimitsStatus component with visual gauge bar
- Shows available/cooling/disabled credential counts
- Reset cooldown button for stuck credentials
- Auto-refresh every 10 seconds
2026-01-12 07:37:14 +07:00
Finessse f415504d35 feat(api): add rate limits monitoring endpoints
- GET /v0/management/rate-limits - detailed per-credential status
- GET /v0/management/rate-limits/summary - availability overview
- Shows available, cooling_down, disabled counts and next recovery time
2026-01-12 07:37:03 +07:00
Finessse 522f0e5c89 feat(windows): add single-instance mutex and Windows service support
- winutil package with mutex-based single instance lock
- Toast notification helper for Windows
- Service stubs for future Windows service mode
2026-01-12 07:36:43 +07:00
Finessse d6dd24e2b7 feat(tui): add polished Flight Deck terminal dashboard
- Bubbletea-based TUI with 5 tabs: Status, Accounts, Rate Limits, Usage, Logs
- Industrial control room aesthetic with orange/green color scheme
- Double-line borders (╔═╗), active tab indicator 【】
- 3-column stat boxes on Status, 4-column on Usage
- Visual gauge bar for rate limit availability
- Config-optional mode allows TUI to run without config.yaml
- Full-width frame with properly aligned borders
2026-01-12 07:33:04 +07:00
Finessse 2d73c520cb chore(npm): bump version to 0.2.8 2026-01-12 05:28:05 +07:00
Finessse daa3e91278 fix(tray): remove ugly fake separators from submenus 2026-01-12 05:26:10 +07:00
Finessse 291b69ced1 fix(tray): hide console window when running CLI commands 2026-01-12 05:22:36 +07:00
Finessse 6b2dbf6840 feat(tray): make Providers menu functional with all providers
Providers submenu now has clickable login items:
- Claude, Gemini, Codex, Qwen (OAuth)
- Antigravity, Kiro (OAuth)
- MiniMax, Zhipu (API key via CLI)

Each item triggers OAuth flow or CLI login command.
2026-01-12 05:16:47 +07:00
Finessse 8a822b1f05 feat(tray): add Accounts submenu with CLI integration
New Accounts submenu:
- Copy Account List (-list-accounts)
- Cleanup Expired (-cleanup-expired)
- Export Accounts... (-export-accounts)
- Import Accounts... (-import-accounts)

All menu items harness CLI binary for single source of truth.
2026-01-12 05:11:58 +07:00
Finessse dc05446bf0 feat(tray): integrate CLI commands into Diagnostics menu
Add menu items to copy CLI output to clipboard:
- Copy Account Status (account health summary)
- Copy Usage Stats (token usage by provider)
- Copy Model List (available models)
- Copy Recent Logs (last 100 log entries)

Uses stdout capture to get formatted CLI output.
2026-01-12 05:05:47 +07:00
Finessse 16dc9c7101 feat(tray): add Refresh Tokens menu + account count in tooltip 2026-01-12 04:49:31 +07:00
Finessse 45289603b9 refactor: rename cliproxytray → proxypilot-tray
- Rename cmd/cliproxytray to cmd/proxypilot-tray
- Update all script references
- Update workflow and docs
2026-01-12 04:43:58 +07:00
Finessse 53d28c9ec0 chore(npm): bump version to 0.2.7 2026-01-12 04:35:27 +07:00
Finessse 33fbfa7b53 feat(cli): add advanced account management commands
- Add -usage flag (token usage stats per provider)
- Add -logs flag (view recent logs, -n for line count)
- Add -refresh flag (force token refresh)
- Add -list-models flag (show available models)
- Add -export-accounts/-import-accounts (backup/restore)
- Add --include-tokens and --force flags for export/import
2026-01-12 04:30:45 +07:00
Finessse 193b240b31 chore: simplify release workflows
- install.ts: read version from package.json (auto-sync)
- release.yml: manual dispatch only (no auto-trigger on tags)
- proxypilot-release.yml: add checksums.txt generation
2026-01-12 03:14:16 +07:00
Finessse ef8088f7db chore(npm): bump version to 0.2.6 2026-01-12 02:34:09 +07:00
Finessse e8a6269a45 test: add tests for logging, errors, config, and auth packages
- Add 26 tests for SetLogLevel() in logging package
- Add 6 tests for AppError in errors package
- Add 10 tests for SDKConfig in config package
- Add 3 tests for EmailRequiredError in sdk/auth
2026-01-12 02:30:46 +07:00
Finessse a09a23380e feat(cli): wire -quiet/-verbose flags to logging
- Add SetLogLevel() to logging package
- CLI flags override config-based log level
- Add tests for account.go (6 tests)
2026-01-12 02:26:06 +07:00
Finessse 5f8941b407 feat(cli): add account management commands
- Add -version, -status, -list-accounts flags
- Add -cleanup-expired, -remove-account for token management
- Add -json output mode for scripting
- Add -quiet/-verbose flags
- Colored terminal output with table formatting
2026-01-12 02:18:32 +07:00
Finessse e1b58ba16e Revert "docs: add session progress for 2026-01-11"
This reverts commit a493e9c115.
2026-01-12 02:06:51 +07:00
Finessse 68cfd33685 refactor(auth): remove unused GeminiCLI token aliases
- Remove dead code: GeminiCLIToken type alias, LoadGeminiCLIToken,
  LoadGeminiCLITokenFromPath (no callers found)
- Add tests for gemini auth (CredentialFileName, SaveTokenToFile)
2026-01-12 02:05:01 +07:00
Finessse a493e9c115 docs: add session progress for 2026-01-11 2026-01-12 01:06:09 +07:00
Luis Pater 543dfd67e0 refactor(cache): remove max entries logic and extend signature TTL to 3 hours 2026-01-12 00:20:44 +08:00
Luis Pater 28bd1323a2 Merge pull request #971 from router-for-me/codex
feat(codex): add OpenCode instructions based on user agent
2026-01-11 16:01:13 +08:00
hkfires 220ca45f74 fix(codex): only override instructions when upstream provides them 2026-01-11 15:52:21 +08:00
Finessse 3f0c29e275 chore(npm): bump version to 0.2.5 2026-01-11 14:51:43 +07:00
Finessse b654a19a09 feat(gemini): enable thinking by default for Gemini 3 Flash 2026-01-11 14:28:59 +07:00
hkfires 70a82d80ac fix(codex): only override instructions in responses for OpenCode UA 2026-01-11 15:19:37 +08:00
hkfires ac626111ac feat(codex): add OpenCode instructions based on user agent 2026-01-11 13:36:35 +08:00
Finessse 0420fd0046 build(scripts): embed version info in macOS build script
Use git describe/rev-parse for version/commit and pass via ldflags.
2026-01-11 08:43:00 +07:00
Finessse 46ad228707 sync(upstream): developer role + message_delta fix + auth cleanup
Cherry-picked:
- 7815ee33: adjust message_delta emission boundary in Claude-to-OpenAI
- 6762e081: add developer role support for Gemini translators
- 5e5d8142: fix auth error when antigravity refresh token missing
2026-01-11 06:45:24 +07:00
Finessse 741333697e sync(upstream): gemini thinking guards + thoughtSignature
Cherry-picked:
- 05444cf3: abort default injection on existing thinking keys
- 8edbda57: add thoughtSignature to node parts for Gemini/Antigravity

Skipped ef6bafbf (context cancellation) - structural conflict with our
multi-project fallback loops.
2026-01-11 06:45:24 +07:00
Finessse d3b5b0017f fix(config): preserve comments + deep copy nodes for YAML merge
Cherry-picked config fixes from upstream:
- 2e88c485: avoid adding new keys when merging
- ee552f87: deep copy nodes to prevent shared references
- c8e72ba0: preserve comment nodes during merge
- 09455f9e: additional merge edge case fixes

Kept our isZeroValueNode for smarter zero-value detection.
2026-01-11 06:33:53 +07:00
Finessse 9f5eb93f64 sync(upstream): add HttpRequest support across executors
Cherry-picked from e8e3bc86. Adds HttpRequest method to ProviderExecutor
interface for injecting credentials into arbitrary HTTP requests.

- Added HttpRequest to conductor.go interface
- Added HttpRequest stubs to kiro, minimax, zhipu executors
- Added http-request example
- Updated mock executors in tests

Also kept our Embed method and CountTokens implementations.
2026-01-11 06:32:53 +07:00
Finessse baf72225a5 sync(upstream): codex subscription dates + logger cleanup
Cherry-picked:
- 6494330c: add subscription date fields to ID token claims
- bc3195c8: remove unnecessary request details limit logic
2026-01-11 06:24:54 +07:00
Finessse 01e1d5aed2 sync(upstream): auth rotation atomic fix + memory leak fixes
- fix(auth): make provider rotation atomic (keep shouldKeepProviderOrder)
- fix(server): resolve memory leaks in failed attempts and codex cache
  - Add background cleanup goroutine for stale IP entries
  - Add cache expiry cleanup for codex prompt cache
- Update provider rotation tests for atomic rotation

Cherry-picked: 8be06255, 47dacce6
Merged with ProxyPilot's shouldKeepProviderOrder for gemini-3 fallback
2026-01-11 06:11:37 +07:00
Finessse 19bf935a2e sync(upstream): Gemini 3 Pro and Antigravity executor improvements
- feat(executor): enhance Antigravity payload with user role and dynamic system instructions
- feat(executor): add model-specific support for "gemini-3-pro" in execution
- feat(executor): update system instruction handling for Claude and Gemini-3-Pro models
- fix(executor): update gemini model identifier to gemini-3-pro-preview
- feat(executor): centralize systemInstruction handling

Cherry-picked: 67985d82, bda04eed, 1b2f9076, b6a0f7a0, 59a448b6
2026-01-11 06:03:27 +07:00
Finessse fd9d097b8e sync(upstream): management API and executor improvements
- feat(management): add generic API call handler
- Fix: disable thinking when tool_choice forces tool use
- feat(api): add ManagementTokenRequester interface (sans iflow)
- fix(management): refresh antigravity token for api-call $TOKEN$
- fix(auth): error when antigravity refresh token missing during refresh

Cherry-picked: ade71947, aca2ef63, ee171bc5, b01619b4, 5e5d8142
Adapted: removed iflow references (not in ProxyPilot)
2026-01-11 06:00:37 +07:00
Finessse 4bf4256e3f sync(upstream): logging/handlers improvements
- fix(logging): improve request/response capture
- fix(handlers): match raw error text before JSON body for duplicate detection
- feat(logging): disambiguate OAuth credential selection in debug logs
- Various logging refinements for auth selection

Cherry-picked from upstream: a091d12f, 3ca5fb10, 0e4148b2, 79fbcb3e, 48f6d7ab, 48f19aab, cb3bdffb, a95428f2
2026-01-11 05:57:48 +07:00
Finessse 95bbb4d7f3 sync(upstream): add index field to image response for LiteLLM
- Uses json.Marshal for cleaner image payload construction
- Cherry-picked from upstream 671558a8, a7fc2ee4
2026-01-11 05:50:58 +07:00
Finessse a9cef821f9 sync(upstream): preserve built-in tools across openai<->responses
Cherry-picked from upstream 0b834fcb
2026-01-11 05:48:45 +07:00
Finessse a1620c5cb0 fix(auth): support both Antigravity IDE and Gemini CLI token paths
- Check OS-specific Antigravity path first, fallback to ~/.gemini/
- Add expiry_date field support (Unix ms timestamp)
- Windows: %APPDATA%\Antigravity -> %USERPROFILE%\.gemini
- macOS: ~/Library/Application Support/Antigravity -> ~/.gemini
- Linux: ~/.antigravity -> ~/.gemini
2026-01-11 05:20:13 +07:00
Finessse 2465a8fff1 chore: remove upstream Community Projects section from README 2026-01-11 05:14:16 +07:00
Finessse f0568a5c20 docs(cli): update --antigravity-import flag description 2026-01-11 05:11:20 +07:00
Finessse 63da07d1f1 fix(cmd): update antigravity import to use new SDK method 2026-01-11 05:11:13 +07:00
Finessse 7157230427 refactor(auth): rename ImportFromGeminiCLI to ImportFromAntigravityIDE 2026-01-11 05:11:05 +07:00
Finessse bcdbba5f76 fix(auth): read tokens from Antigravity IDE instead of Gemini CLI
Update token paths to OS-specific Antigravity locations:
- Linux: ~/.antigravity/oauth_creds.json
- macOS: ~/Library/Application Support/Antigravity/oauth_creds.json
- Windows: %APPDATA%\Antigravity\oauth_creds.json
2026-01-11 05:10:59 +07:00
Finessse 9679f69b81 feat(auth): add Gemini CLI token import for Antigravity
- Add internal/auth/antigravity package with token loading from ~/.gemini/oauth_creds.json
- Add ImportFromGeminiCLI method to AntigravityAuthenticator
- Add DoAntigravityImport CLI command
- Add --antigravity-import flag to server binary

Usage: proxypilot --antigravity-import
2026-01-11 04:10:54 +07:00
Finessse 8ddaa140af chore: sync non-code changes from upstream v6.6.98
- .dockerignore: add .codex, .agents, .opencode entries
- .gitignore: add .codex, .agents, .opencode entries
- README.md: add Community Projects section (Quotio, CodMate, Claude Proxy VSCode)
2026-01-11 04:01:21 +07:00
extremk 5bb9c2a2bd Add candidate count parameter to OpenAI request 2026-01-10 18:50:13 +08:00
extremk 0b5bbe9234 Add candidate count handling in OpenAI request 2026-01-10 18:49:29 +08:00
extremk 14c74e5e84 Handle 'n' parameter for candidate count in requests
Added handling for the 'n' parameter to set candidate count in generationConfig.
2026-01-10 18:48:33 +08:00
extremk 6448d0ee7c Add candidate count handling in OpenAI request 2026-01-10 18:47:41 +08:00
extremk b0c17af2cf Enhance Gemini to OpenAI response conversion
Refactor response handling to support multiple candidates and improve parameter management.
2026-01-10 18:46:25 +08:00
Luis Pater 8cfe26f10c Merge branch 'sdk' into dev 2026-01-10 16:26:23 +08:00
Luis Pater 80db2dc254 Merge pull request #955 from router-for-me/api
feat(codex): add subscription date fields to ID token claims
2026-01-10 16:26:07 +08:00
Luis Pater e8e3bc8616 feat(executor): add HttpRequest support across executors for better http request handling 2026-01-10 16:25:25 +08:00
Luis Pater bc3195c8d8 refactor(logger): remove unnecessary request details limit logic 2026-01-10 14:46:59 +08:00
hkfires 6494330c6b feat(codex): add subscription date fields to ID token claims 2026-01-10 11:15:20 +08:00
Finessse 34f9bbd56e fix(auth): prevent race in kiro auth callback server shutdown 2026-01-10 06:03:03 +07:00
Finessse cddccdd5cb feat(executor): add project and model fallback on 429 for gemini-cli 2026-01-10 06:02:48 +07:00
Finessse 06c41e1a00 test(executor): add antigravity project switch integration test 2026-01-10 06:02:35 +07:00
Finessse 092cef6fa3 feat(executor): add project and model fallback on 429 for antigravity 2026-01-10 06:02:20 +07:00
Finessse 7806419df5 test(executor): add quota fallback unit tests 2026-01-10 06:02:06 +07:00
Finessse ff5a078229 feat(executor): add quota fallback helpers for project and model switching 2026-01-10 06:01:52 +07:00
Luis Pater 4d7f389b69 Fixed: #941
fix(translator): ensure fallback to valid originalRequestRawJSON in response handling
2026-01-10 01:01:09 +08:00
Finessse e2894fa447 docs(readme): add security defaults and lightweight profile sections 2026-01-09 23:43:06 +07:00
Finessse d9500d4961 docs(config): document lightweight profile and new config options 2026-01-09 23:42:50 +07:00
Finessse ab2be5d03c fix(auth): simplify auto-refresh interval validation 2026-01-09 23:42:36 +07:00
Finessse 0761e2b695 fix(auth): prioritize paidTier over isDefault for antigravity tier detection 2026-01-09 23:42:13 +07:00
Finessse db647820c9 fix(util): add kiro prefix fallback and reduce debug log noise 2026-01-09 23:41:57 +07:00
Finessse 8c991a8ed3 feat(registry): add kiro thinking model definitions 2026-01-09 23:41:39 +07:00
Finessse 123fd00c0a feat(executor): add kiro thinking model variants mapping 2026-01-09 23:41:25 +07:00
Finessse b87fe4580d fix(executor): update antigravity user-agent and add required headers 2026-01-09 23:41:11 +07:00
Finessse aeff3e8c09 fix(memory): handle cliproxyexecutor.Response in auth adapter 2026-01-09 23:40:53 +07:00
Luis Pater 95f87d5669 Merge pull request #947 from pykancha/fix-memory-leak
Resolve memory leaks causing OOM in k8s deployment
2026-01-10 00:40:47 +08:00
Finessse 3a8fac2514 feat(server): wire up lightweight profile toggles and configurable CORS 2026-01-09 23:40:39 +07:00
Finessse 283e8cfb52 feat(config): add lightweight profile options and CORS settings 2026-01-09 23:40:25 +07:00
Finessse 854bd25940 feat(cache): add max-bytes size limit for prompt cache 2026-01-09 23:40:10 +07:00
Finessse f42cadf459 feat(cache): add max-bytes size limit for response cache 2026-01-09 23:39:57 +07:00
Finessse b4a54444d8 feat(usage): add sampling rate support for usage statistics 2026-01-09 23:39:42 +07:00
Finessse 6990e769ea fix(management): return 404 when request history is disabled 2026-01-09 23:39:28 +07:00
Finessse 69ba18a095 fix(middleware): respect request history sampling in logging middleware 2026-01-09 23:39:14 +07:00
Finessse 8b9f5ebe00 feat(middleware): add runtime toggle and sampling for request history 2026-01-09 23:39:00 +07:00
Finessse 65e243ec1b feat(middleware): add runtime toggle for Prometheus metrics 2026-01-09 23:38:47 +07:00
Finessse fce1e62aa4 perf(middleware): pool response body buffers to reduce GC pressure 2026-01-09 23:38:34 +07:00
Finessse bc3d89d958 perf(handlers): cache request details lookup per model 2026-01-09 23:38:21 +07:00
Finessse 5d9d4328f9 refactor(handlers): use pooled SSE writer helpers across all providers 2026-01-09 23:38:09 +07:00
Finessse b02b3c32ce perf(sdk): use pre-allocated byte slice for SSE keep-alive 2026-01-09 23:37:55 +07:00
Finessse 616cde1a0f test(sdk): add stream forwarder benchmarks 2026-01-09 23:37:41 +07:00
Finessse d2efc1dd8e feat(sdk): add pooled SSE writer helpers for reduced allocations 2026-01-09 23:37:29 +07:00
Luis Pater c83365a349 Merge pull request #938 from router-for-me/log
refactor(logging): clean up oauth logs and debugs
2026-01-10 00:02:45 +08:00
Luis Pater 6b3604cf2b Merge pull request #943 from ben-vargas/fix-tool-mappings
Fix Claude OAuth tool name mapping (proxy_)
2026-01-09 23:52:29 +08:00
Luis Pater af6bdca14f Fixed: #942
fix(executor): ignore non-SSE lines in OpenAI-compatible streams
2026-01-09 23:41:50 +08:00
hemanta212 1c773c428f fix: Remove investigation artifacts 2026-01-09 17:47:59 +05:45
Ben Vargas e785bfcd12 Use unprefixed Claude request for translation
Keep the upstream payload prefixed for OAuth while passing the unprefixed request body into response translators. This avoids proxy_ leaking into OpenAI Responses echoed tool metadata while preserving the Claude OAuth workaround.
2026-01-09 00:54:35 -07:00
hemanta212andAmp 47dacce6ea fix(server): resolve memory leaks causing OOM in k8s deployment
- usage/logger_plugin: cap modelStats.Details at 1000 entries per model
- cache/signature_cache: add background cleanup for expired sessions (10 min)
- management/handler: add background cleanup for stale IP rate-limit entries (1 hr)
- executor/cache_helpers: add mutex protection and TTL cleanup for codexCacheMap (15 min)
- executor/codex_executor: use thread-safe cache accessors

Add reproduction tests demonstrating leak behavior before/after fixes.

Amp-Thread-ID: https://ampcode.com/threads/T-019ba0fc-1d7b-7338-8e1d-ca0520412777
Co-authored-by: Amp <amp@ampcode.com>
2026-01-09 13:33:46 +05:45
Ben Vargas dcac3407ab Fix Claude OAuth tool name mapping
Prefix tool names with proxy_ for Claude OAuth requests and strip the prefix from streaming and non-streaming responses to restore client-facing names.

Updates the Claude executor to:
- add prefixing for tools, tool_choice, and tool_use messages when using OAuth tokens
- strip the prefix from tool_use events in SSE and non-streaming payloads
- add focused unit tests for prefix/strip helpers
2026-01-09 00:10:38 -07:00
hkfires 7004295e1d build(docker): move stats export execution after image build 2026-01-09 11:24:00 +08:00
hkfires ee62ef4745 refactor(logging): clean up oauth logs and debugs 2026-01-09 11:20:55 +08:00
Luis Pater ef6bafbf7e fix(executor): handle context cancellation and deadline errors explicitly 2026-01-09 10:48:29 +08:00
Luis Pater ed28b71e87 refactor(amp): remove duplicate comments in response rewriter 2026-01-09 08:21:13 +08:00
Luis Pater d47b7dc79a refactor(response): enhance parameter handling for Codex to Claude conversion 2026-01-09 05:20:19 +08:00
Luis Pater 49b9709ce5 Merge pull request #787 from sususu98/fix/antigravity-429-retry-delay-parsing
fix(antigravity): parse retry-after delay from 429 response body
2026-01-09 04:45:25 +08:00
Luis Pater a2eba2cdf5 Merge pull request #763 from mvelbaum/feature/improve-oauth-use-logging
feat(logging): disambiguate OAuth credential selection in debug logs
2026-01-09 04:43:21 +08:00
Luis Pater 3d01b3cfe8 Merge pull request #553 from XInTheDark/fix/builtin-tools-web-search
fix(translator): preserve built-in tools (web_search) to Responses API
2026-01-09 04:40:13 +08:00
Luis Pater af2efa6f7e Merge pull request #605 from soilSpoon/feature/amp-compat
feature: Improves Amp client compatibility
2026-01-09 04:28:17 +08:00
Luis Pater d73b61d367 Merge pull request #901 from uzhao/vscode-plugin
Vscode plugin
2026-01-08 22:22:27 +08:00
Luis Pater 59a448b645 feat(executor): centralize systemInstruction handling for Claude and Gemini-3-Pro models 2026-01-08 21:05:33 +08:00
Chén Mù 4adb9eed77 Merge pull request #921 from router-for-me/atgy
fix(executor): update gemini model identifier to gemini-3-pro-preview
2026-01-08 19:20:32 +08:00
hkfires b6a0f7a07f fix(executor): update gemini model identifier to gemini-3-pro-preview
Update the model name check in `buildRequest` to target "gemini-3-pro-preview" instead of "gemini-3-pro" when applying specific system instruction handling.
2026-01-08 19:14:52 +08:00
Luis Pater 1b2f907671 feat(executor): update system instruction handling for Claude and Gemini-3-Pro models 2026-01-08 12:42:26 +08:00
Luis Pater bda04eed8a feat(executor): add model-specific support for "gemini-3-pro" in execution and payload handling 2026-01-08 12:27:03 +08:00
Luis Pater 67985d8226 feat(executor): enhance Antigravity payload with user role and dynamic system instructions 2026-01-08 10:55:25 +08:00
Jianyang Zhaoandgemini-code-assist[bot] cbcb061812 Update README_CN.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-07 20:07:01 -05:00
Jianyang Zhaoandgemini-code-assist[bot] 9fc2e1b3c8 Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-07 20:06:55 -05:00
Jianyang Zhao 3b484aea9e Add Claude Proxy VSCode to README_CN.md
Added information about Claude Proxy VSCode extension.
2026-01-07 20:03:07 -05:00
Jianyang Zhao 963a0950fa Add Claude Proxy VSCode extension to README
Added Claude Proxy VSCode extension to the README.
2026-01-07 20:02:50 -05:00
Finessse 86470c8274 feat(routing): add usage-aware credential selector
Routes requests to the account with lowest daily output tokens.
Spreads load across accounts to avoid hitting quota limits.
Config: routing.strategy = "usage-aware" or "least-used"
2026-01-08 04:45:19 +07:00
Finessse 5fdb0ff618 feat(webui): add per-account usage display
Auth table shows daily output tokens and request count.
Hover tooltip displays total usage stats.
API exposes usage field in auth-files response.
2026-01-08 04:34:50 +07:00
Luis Pater f4ba1ab910 fix(executor): remove unused tokenRefreshTimeout constant and pass zero timeout to HTTP client 2026-01-07 18:16:49 +08:00
Luis Pater 2662f91082 feat(management): add PostOAuthCallback handler to token requester interface 2026-01-07 10:47:32 +08:00
Luis Pater c1db2c7d7c Merge pull request #888 from router-for-me/api-call-TOKEN-fix
fix(management): refresh antigravity token for api-call $TOKEN$
2026-01-07 01:19:24 +08:00
LTbinglingfeng 5e5d8142f9 fix(auth): error when antigravity refresh token missing during refresh 2026-01-07 01:09:50 +08:00
LTbinglingfeng b01619b441 fix(management): refresh antigravity token for api-call $TOKEN$ 2026-01-07 00:14:02 +08:00
Luis Pater f861bd6a94 docs: add 9Router to community projects in README 2026-01-06 23:15:28 +08:00
Luis Pater 6dbfdd140d Merge pull request #871 from decolua/patch-1
Update README.md
2026-01-06 22:58:53 +08:00
zhiqing0205 aa8526edc0 fix(codex): use unicode title casing for plan 2026-01-06 10:24:02 +08:00
Finessse f9f4425147 chore: ignore local planning docs and debug configs 2026-01-06 06:39:59 +07:00
Finessse dc0685561e chore: rebuild webui assets 2026-01-06 06:24:55 +07:00
Finessse 0551a8bd18 chore: remove managementasset references from server 2026-01-06 06:24:20 +07:00
Finessse 33be41ba03 feat(cache): wire cache initialization and add docs
Initialize response/prompt caches in Service.Run from config.
Add cache lookup to executor payload helpers.
Document cache config and management API in README.
2026-01-06 06:24:01 +07:00
Finessse d317728d93 feat(webui): add priority controls and token expiry display
ProviderLogins table now shows:
- Priority column with up/down reorder buttons
- Expires column with color-coded status (green/yellow/red)
API exposes token_expires_at for WebUI consumption.
2026-01-06 06:22:40 +07:00
Finessse c8176cddab chore: remove legacy management UI
Remove /management.html, pp_open_legacy_ui tray binding,
disable-control-panel and panel-github-repository config options.
OpenManagementUI now opens /proxypilot.html directly.
2026-01-06 06:22:06 +07:00
Finessse 30978f1f17 feat(cache): add response cache and prompt cache tracking
Response cache stores completions keyed by request hash.
Prompt cache tracking aggregates cache_read/cache_creation tokens.
WebUI CacheStats component shows hit rates and token savings.
2026-01-06 06:21:54 +07:00
zhiqing0205 ac3ca0ad8e feat(codex): include plan type in auth filename 2026-01-06 02:25:56 +08:00
MohammadErfan JabbariandClaude fe6043aec7 fix(antigravity): preserve finish_reason tool_calls across streaming chunks
When streaming responses with tool calls, the finish_reason was being
overwritten. The upstream sends functionCall in chunk 1, then
finishReason: STOP in chunk 2. The old code would set finish_reason
from every chunk, causing "tool_calls" to be overwritten by "stop".

This broke clients like Claude Code that rely on finish_reason to
detect when tool calls are complete.

Changes:
- Add SawToolCall bool to track tool calls across entire stream
- Add UpstreamFinishReason to cache the finish reason
- Only emit finish_reason on final chunk (has both finishReason + usage)
- Priority: tool_calls > max_tokens > stop

Includes 5 unit tests covering:
- Tool calls not overwritten by subsequent STOP
- Normal text gets "stop"
- MAX_TOKENS without tool calls gets "max_tokens"
- Tool calls take priority over MAX_TOKENS
- Intermediate chunks have no finish_reason

Fixes streaming tool call detection for Claude Code + Gemini models.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 18:45:25 +01:00
decoluaandgemini-code-assist[bot] 386ccffed4 Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-05 20:54:33 +07:00
FakerLandgemini-code-assist[bot] 08d21b76e2 Update sdk/auth/filestore.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2026-01-05 21:38:26 +08:00
decolua ffddd1c90a Update README.md 2026-01-05 20:29:26 +07:00
Zhi YangandClaude 33aa665555 fix(auth): persist access_token on refresh for providers that need it
Previously, metadataEqualIgnoringTimestamps() ignored access_token for all
providers, which prevented refreshed tokens from being persisted to disk/database.
This caused tokens to be lost on server restart for providers like iFlow.

This change makes the behavior provider-specific:
- Providers like gemini/gemini-cli that issue new tokens on every refresh and
  can re-fetch when needed will continue to ignore access_token (optimization)
- Other providers like iFlow will now persist access_token changes

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-05 13:25:46 +00:00
maoring24andClaude Opus 4.5 00280b6fe8 feat(claude): add native request cloaking for non-claude-code clients
integrate claude-cloak functionality to disguise api requests:
- add CloakConfig with mode (auto/always/never) and strict-mode options
- generate fake user_id in claude code format (user_[hex]_account__session_[uuid])
- inject claude code system prompt (configurable strict mode)
- obfuscate sensitive words with zero-width characters
- auto-detect claude code clients via user-agent

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-05 20:32:51 +08:00
Finessse 1f3e82af04 fix(ci): move secrets check to step level 2026-01-05 13:02:06 +07:00
Finessse 093e77c8c0 feat: add priority/usage APIs, WebUI dashboard, config options
- PATCH /v0/management/auth/:id/priority endpoint
- GET /v0/management/auth/:id/usage endpoint
- AccountUsage.tsx dashboard component
- AutoRefreshBuffer, DailyResetHour config fields
- Conductor wiring for refresh config
2026-01-05 12:59:29 +07:00
Luis Pater 8f8dfd081b Merge pull request #850 from can1357/main
feat(translator): add developer role support for Gemini translators
2026-01-05 11:27:24 +08:00
Luis Pater 9f1b445c7c docs: add ProxyPilot to community projects in Chinese README 2026-01-05 11:23:48 +08:00
Luis Pater ae933dfe14 Merge pull request #858 from Finesssee/add-proxypilot
docs: add ProxyPilot to community projects
2026-01-05 11:20:52 +08:00
Luis Pater e124db723b Merge pull request #862 from router-for-me/gemini
fix(gemini): abort default injection on existing thinking keys
2026-01-05 10:41:07 +08:00
hkfires 05444cf32d fix(gemini): abort default injection on existing thinking keys 2026-01-05 10:24:30 +08:00
Luis Pater 8edbda57cf feat(translator): add thoughtSignature to node parts for Gemini and Antigravity requests
Enhanced node structure by including `thoughtSignature` for inline data parts in Gemini OpenAI, Gemini CLI, and Antigravity request handlers to improve traceability of thought processes.
2026-01-05 09:25:17 +08:00
Finessse 4dd917ff31 feat(auth): wire usage tracking and token expiry to CLI
- Add authUsagePlugin to bridge usage.Record -> Auth.Usage stats
- Register plugin in service.Run() after usage.StartDefault()
- Populate TokenExpiresAt from metadata in Load/Register/Update
- Enables per-auth usage tracking and proactive token refresh
2026-01-05 07:25:02 +07:00
CodeIgnitor 52760a4eaa fix(auth): use backend project ID for free tier Gemini CLI OAuth users
Fixes issue where free tier users cannot access Gemini 3 preview models
due to frontend/backend project ID mapping.

## Problem
Google's Gemini API uses a frontend/backend project mapping system for
free tier users:
- Frontend projects (e.g., gen-lang-client-*) are user-visible
- Backend projects (e.g., mystical-victor-*) host actual API access
- Only backend projects have access to preview models (gemini-3-*)

Previously, CLIProxyAPI ignored the backend project ID returned by
Google's onboarding API and kept using the frontend ID, preventing
access to preview models.

## Solution
### CLI (internal/cmd/login.go)
- Detect free tier users (gen-lang-client-* projects or FREE/LEGACY tier)
- Show interactive prompt allowing users to choose frontend or backend
- Default to backend (recommended for preview model access)
- Pro users: maintain original behavior (keep frontend ID)

### Web UI (internal/api/handlers/management/auth_files.go)
- Detect free tier users using same logic
- Automatically use backend project ID (recommended choice)
- Pro users: maintain original behavior (keep frontend ID)

### Deduplication (internal/cmd/login.go)
- Add deduplication when user selects ALL projects
- Prevents redundant API calls when multiple frontend projects map to
  same backend
- Skips duplicate project IDs in activation loop

## Impact
- Free tier users: Can now access gemini-3-pro-preview and
  gemini-3-flash-preview models
- Pro users: No change in behavior (backward compatible)
- Only affects Gemini CLI OAuth (not antigravity or API key auth)

## Testing
- Tested with free tier account selecting single project
- Tested with free tier account selecting ALL projects
- Verified deduplication prevents redundant onboarding calls
- Confirmed pro user behavior unchanged
2026-01-05 02:41:24 +05:00
Finessse 43f625caf1 chore: integrate sdk test files into main repo 2026-01-05 03:23:41 +07:00
Finessse c33d299137 feat(auth): add priority, usage tracking, and proactive token refresh
- Add Priority field to Auth for per-provider account ordering
- Add UsageStats struct tracking total/daily tokens and requests
- Track usage in MarkResult with daily reset logic
- Add TokenExpiresAt for proactive refresh (5min buffer)
- Sort available auths by priority in selector
2026-01-05 03:18:33 +07:00
Finessse 5930e6b8c4 fix(webui): load react-grab in dev mode only 2026-01-05 00:55:32 +07:00
Finessse 3531191944 feat(webui): add react-grab for component context copying
Ctrl+C on any element copies file name, component, and HTML source.
2026-01-05 00:52:24 +07:00
Finessse b9ccbfb107 refactor: remove Continue integration
Continue VS Code extension is no longer supported.
2026-01-05 00:19:59 +07:00
Shun Kakinoki bc32096e9c fix: prevent race condition in objectstore auth sync
Remove os.RemoveAll() call in syncAuthFromBucket() that was causing
a race condition with the file watcher.

Problem:
1. syncAuthFromBucket() wipes local auth directory with RemoveAll
2. File watcher detects deletions and propagates them to remote store
3. syncAuthFromBucket() then pulls from remote, but files are now gone

Solution:
Use incremental sync instead of delete-then-pull. Just ensure the
directory exists and overwrite files as they're downloaded.
This prevents the watcher from seeing spurious delete events.
2026-01-05 00:10:59 +09:00
Finessse fecc80de5f refactor: remove TUI flags from CLI 2026-01-04 19:51:07 +07:00
Finessse 3abcc42139 refactor: remove proxypilotui command 2026-01-04 19:50:56 +07:00
Finessse b17f421233 refactor: remove TUI package
Windows CMD/PowerShell rendering issues. Will rebuild later.
2026-01-04 19:50:50 +07:00
Finessse 821249a5ed docs: add ProxyPilot to community projects 2026-01-04 18:19:41 +07:00
Luis Pater ee33863b47 Merge pull request #857 from router-for-me/management-update
Management update
2026-01-04 18:07:13 +08:00
Supra4E8C cd22c849e2 feat(management): 更新OAuth模型映射的清理逻辑以增强数据安全性 2026-01-04 17:57:34 +08:00
Supra4E8C f0e73efda2 feat(management): add vertex api key and oauth model mappings endpoints 2026-01-04 17:32:00 +08:00
Supra4E8C 3156109c71 feat(management): 支持管理接口调整日志大小/强制前缀/路由策略 2026-01-04 12:21:49 +08:00
can1357 6762e081f3 feat(translator): add developer role support for Gemini translators
Treat OpenAI's "developer" role the same as "system" role in request
translation for gemini, gemini-cli, and antigravity backends.
2026-01-03 21:01:01 +01:00
Luis Pater 7815ee338d fix(translator): adjust message_delta emission boundary in Claude-to-OpenAI conversion
Fixed incorrect boundary logic for `message_delta` emission, ensuring proper handling of usage updates and `emitMessageStopIfNeeded` within the response loop.
2026-01-04 01:36:51 +08:00
Luis Pater 44b6c872e2 feat(config): add support for Fork in OAuth model mappings with alias handling
Implemented `Fork` flag in `ModelNameMapping` to allow aliases as additional models while preserving the original model ID. Updated the `applyOAuthModelMappings` logic, added tests for `Fork` behavior, and updated documentation and examples accordingly.
2026-01-04 01:18:29 +08:00
Luis Pater 7a77b23f2d feat(executor): add token refresh timeout and improve context handling during refresh
Introduced `tokenRefreshTimeout` constant for token refresh operations and enhanced context propagation for `refreshToken` by embedding roundtrip information if available. Adjusted `refreshAuth` to ensure default context initialization and handle cancellation errors appropriately.
2026-01-04 00:26:08 +08:00
Luis Pater 672e8549c0 docs: reorganize README to adjust CodMate placement
Moved CodMate entry under ProxyPal in both English and Chinese README files for consistency in structure and better readability.
2026-01-03 21:31:53 +08:00
Luis Pater 66f5269a23 Merge pull request #837 from loocor/main
docs: add CodMate to community projects
2026-01-03 21:30:15 +08:00
Luis Pater ebec293497 feat(api): integrate TokenStore for improved auth entry management
Replaced file-based auth entry counting with `TokenStore`-backed implementation, enhancing flexibility and context-aware token management. Updated related logic to reflect this change.
2026-01-03 04:53:47 +08:00
Luis Pater e02ceecd35 feat(registry): introduce ModelRegistryHook for monitoring model registrations and unregistrations
Added support for external hooks to observe model registry events using the `ModelRegistryHook` interface. Implemented thread-safe, non-blocking execution of hooks with panic recovery. Comprehensive tests added to verify hook behavior during registration, unregistration, blocking, and panic scenarios.
2026-01-02 23:18:40 +08:00
Luis Pater c8b33a8cc3 Merge pull request #824 from router-for-me/script
feat(script): add usage statistics preservation across container rebuilds
2026-01-02 20:42:25 +08:00
Loocor dca8d5ded8 Add CodMate app information to README
Added CodMate section to README with app details.
2026-01-02 17:15:38 +08:00
Loocor 2a7fd1e897 Add CodMate description to README_CN.md
添加 CodMate 应用的描述,提供 CLI AI 会话管理功能。
2026-01-02 17:15:09 +08:00
Luis Pater b9d1e70ac2 Merge pull request #830 from router-for-me/gemini
fix(util): disable default thinking for gemini-3 series
2026-01-02 10:59:24 +08:00
hkfires fdf5720217 fix(gemini): remove default thinking for gemini 3 models 2026-01-02 10:55:59 +08:00
hkfires f40bd0cd51 feat(script): add usage statistics preservation across container rebuilds 2026-01-02 10:01:20 +08:00
hkfires e33676bb87 fix(util): disable default thinking for gemini-3 series 2026-01-02 09:43:40 +08:00
Luis Pater 2a663d5cba feat(executor): enhance payload translation with original request context
Refactored `applyPayloadConfig` to `applyPayloadConfigWithRoot`, adding support for default rule validation against the original payload when available. Updated all executors to use `applyPayloadConfigWithRoot` and incorporate an optional original request payload for translations.
2026-01-02 00:03:26 +08:00
Luis Pater 750b930679 Merge pull request #823 from router-for-me/translator
feat(translator): enhance Claude-to-OpenAI conversion with thinking block and tool result handling
2026-01-01 20:16:10 +08:00
hkfires 3902fd7501 fix(iflow): remove thinking field from request body in thinking config handler 2026-01-01 19:40:28 +08:00
hkfires 4fc3d5e935 refactor(iflow): simplify thinking config handling for GLM and MiniMax models 2026-01-01 19:31:08 +08:00
hkfires 2d2f4572a7 fix(translator): remove unnecessary whitespace trimming in reasoning text collection 2026-01-01 12:39:09 +08:00
hkfires 8f4c46f38d fix(translator): emit tool_result messages before user content in Claude-to-OpenAI conversion 2026-01-01 11:11:43 +08:00
hkfires b6ba51bc2a feat(translator): add thinking block and tool result handling for Claude-to-OpenAI conversion 2026-01-01 09:41:25 +08:00
Finessse d8eb507d6f chore(gitignore): ignore local harness artifacts 2026-01-01 00:54:39 +07:00
Finessse 7c87e241fb feat(tui): improve layout and ascii fallbacks 2026-01-01 00:52:14 +07:00
Finessse 3d9e0cb89b chore(registry): trim model catalog 2026-01-01 00:52:05 +07:00
Finessse 99c4d3ccc3 feat(memory): harden summarization pipeline 2026-01-01 00:51:56 +07:00
Finessse e5aec4a28e fix(harness): skip initializer in existing projects 2026-01-01 00:51:46 +07:00
Finessse 5f7ebd40fe fix(translator): drop defer_loading tool fields 2026-01-01 00:51:38 +07:00
Finessse 36621166c8 feat(antigravity): capture tier metadata and retry delays 2026-01-01 00:51:28 +07:00
Luis Pater 6a66d32d37 Merge pull request #803 from HsnSaboor/fix-invalid-function-names-sanitization-v2
feat(translator): resolve invalid function name errors by sanitizing Claude tool names
2026-01-01 01:15:50 +08:00
Luis Pater 8d15723195 feat(registry): add GetAvailableModelsByProvider method for retrieving models by provider 2025-12-31 23:37:46 +08:00
Chén Mù 736e0aae86 Merge pull request #814 from router-for-me/aistudio
Fix model alias thinking suffix
2025-12-31 03:08:05 -08:00
hkfires 8bf3305b2b fix(thinking): fallback to upstream model for thinking support when alias not in registry 2025-12-31 18:07:13 +08:00
hkfires d00e3ea973 feat(thinking): add numeric budget to thinkingLevel conversion fallback 2025-12-31 17:14:47 +08:00
hkfires 89db4e9481 fix(thinking): use model alias for thinking config resolution in mapped models 2025-12-31 17:09:22 +08:00
hkfires e332419081 feat(registry): add thinking support for gemini-2.5-computer-use-preview model 2025-12-31 17:09:22 +08:00
Luis Pater e998b1229a feat(updater): add fallback URL and logic for missing management asset 2025-12-31 11:51:20 +08:00
Luis Pater bbed134bd1 feat(api): add GetAuthStatus method to ManagementTokenRequester interface 2025-12-31 09:40:48 +08:00
Saboor Hassanandfactory-droid[bot] 47b9503112 chore: revert changes to internal/translator to comply with path guard
This commit reverts all modifications within internal/translator. A separate issue
will be created for the maintenance team to integrate SanitizeFunctionName into
the translators.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-31 02:19:26 +05:00
Saboor Hassanandfactory-droid[bot] 3b9253c2be fix(translator): resolve invalid function name errors by sanitizing Claude tool names
This commit centralizes tool name sanitization in SanitizeFunctionName,
applying character compliance, starting character rules, and length limits.
It also fixes a regression in gemini_schema tests and preserves MCP-specific
shortening logic while ensuring compliance.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-31 02:14:46 +05:00
Saboor Hassanandfactory-droid[bot] d241359153 fix(translator): address PR feedback for tool name sanitization
- Pre-compile sanitization regex for better performance.
- Optimize SanitizeFunctionName for conciseness and correctness.
- Handle 64-char edge cases by truncating before prepending underscore.
- Fix bug in Antigravity translator (incorrect join index).
- Refactor Gemini translators to avoid redundant sanitization calls.
- Add comprehensive unit tests including 64-char edge cases.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-31 01:54:41 +05:00
Saboor Hassanandfactory-droid[bot] f4d4249ba5 feat(translator): sanitize tool/function names for upstream provider compatibility
Implemented SanitizeFunctionName utility to ensure Claude tool names meet
Gemini/Upstream strict naming conventions (alphanumeric, starts with letter/underscore, max 64 chars).
Applied sanitization to tool definitions and usage in all relevant translators.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-12-31 01:41:07 +05:00
Finessse e15a091615 fix(tui): use net.JoinHostPort for IPv6 compatibility
Replace fmt.Sprintf for address formatting with net.JoinHostPort
to properly handle IPv6 addresses.
2025-12-31 02:27:19 +07:00
Finessse ad5c8112cb feat(scripts): add Windows TUI web launcher
Batch script to start TUI with web dashboard enabled.
2025-12-31 02:11:05 +07:00
Finessse 50b540fcae feat(scripts): add Windows watchdog script
PowerShell script to monitor and restart ProxyPilot service.
2025-12-31 02:10:40 +07:00
Finessse 2ad425588f feat(docker): add Dockerfile for TUI container
Enable containerized deployment of the TUI application.
2025-12-31 02:09:53 +07:00
Finessse e099c1dc0b fix(util): update schema tests for placeholder property behavior
Adjust test expectations to include '_' placeholder property
added to object schemas without required fields (Claude VALIDATED mode).
2025-12-31 02:09:32 +07:00
Finessse 10013ad979 chore(deps): update dependencies
Sync go.mod and go.sum with latest dependency versions.
2025-12-31 02:08:55 +07:00
Finessse 556fac1667 feat(examples): add CountTokens to custom provider example
Demonstrate token counting implementation in custom provider.
2025-12-31 02:08:39 +07:00
Finessse 1b0394bf55 feat(translator): enhance Antigravity Claude request handling
Improve request translation with additional test coverage.
2025-12-31 02:08:06 +07:00
Finessse c720fad57b feat(executor): add embeddings support to Kiro executor
Handle embedding requests in Kiro runtime executor.
2025-12-31 02:07:48 +07:00
Finessse aafbdb9c46 feat(cmd): add Kilo Code and RooCode proxy configurations
Extend agent switching to support additional AI coding assistants
with their respective proxy settings.
2025-12-31 02:07:00 +07:00
Finessse 76c52e1a47 feat(tui): minor server view adjustments
Small styling updates for server status display.
2025-12-31 02:06:40 +07:00
Finessse 0ffee090d0 feat(tui): enhance switch view styling
Apply theme styles to provider switching interface.
2025-12-31 02:06:19 +07:00
Finessse fd71a01aa7 feat(tui): update mappings view with new styles
Apply consistent theme to model mappings display.
2025-12-31 02:05:41 +07:00
Finessse 2796512cb3 feat(tui): improve usage view layout
Better formatting and styling for usage statistics display.
2025-12-31 02:05:24 +07:00
Finessse 289871da14 feat(tui): enhance login view styling
Apply new theme styles to login form components.
2025-12-31 02:05:05 +07:00
Finessse 336359c9d7 feat(tui): connect logs view to ring buffer
Display real-time logs from GlobalBuffer with filtering
and auto-scroll support.
2025-12-31 02:04:10 +07:00
Finessse 06684b81ef feat(tui): improve main layout with responsive design
Enhance sidebar, content area, and navigation with better
proportions and overflow handling.
2025-12-31 02:03:12 +07:00
Finessse f0a7040b00 feat(tui): add comprehensive theme and styles system
Define color palette, component styles, and responsive layout
helpers for consistent TUI appearance.
2025-12-31 02:02:54 +07:00
Finessse 64358ecfd8 feat(updates): add GPG signature verification for releases
Implement release signature verification using embedded public key.
Ensures binary integrity before applying updates.
2025-12-31 02:02:16 +07:00
Finessse 0ce9661a88 feat(api): serve embedded dashboard assets
Replace placeholder HTML with actual embedded React assets.
Serve index.html, JS, CSS, and static files from embed.FS.
2025-12-31 02:01:31 +07:00
Finessse e01aeda3de feat(webui): update React dashboard bundle
Rebuild frontend assets with latest UI improvements.
2025-12-31 02:01:11 +07:00
Finessse de5098f8aa feat(api): integrate connection tracker and metrics
Wire ConnectionTrackerMiddleware and /metrics endpoint into
the Gin engine for production observability.
2025-12-31 02:00:22 +07:00
Finessse 2219bc04e4 feat(api): add Prometheus metrics endpoint
Expose /metrics endpoint for observability with request counts,
latencies, and connection stats.
2025-12-31 02:00:01 +07:00
Finessse 94ef02e19d feat(api): add connection tracker middleware
Track active HTTP connections with thread-safe counter.
Exposes ActiveConnections.Count() for monitoring.
2025-12-31 01:59:17 +07:00
Finessse f5b7aaf9ae feat(logging): wire ring buffer hook into global logger
Add GlobalBuffer hook to capture all log entries for real-time
display in TUI logs view.
2025-12-31 01:58:53 +07:00
Finessse 35018f2e43 feat(logging): add ring buffer for in-memory log capture
Implement thread-safe circular buffer that captures log entries
for display in TUI and web dashboard. Integrates as a logrus hook.
2025-12-31 01:58:09 +07:00
Finessse 6d4e3ceb29 chore: add platform-specific binary names to gitignore
Add proxypilot-linux, proxypilot-darwin, and proxypilot-windows
to prevent accidental commits of compiled binaries.
2025-12-31 01:57:36 +07:00
Chén Mù cb56cb250e Merge pull request #800 from router-for-me/modelmappings
feat(watcher): add model mappings change detection
2025-12-30 06:50:42 -08:00
hkfires e0381a6ae0 refactor(watcher): extract model summary functions to dedicated file 2025-12-30 22:39:12 +08:00
hkfires 2c01b2ef64 feat(watcher): add Gemini models and OAuth model mappings change detection 2025-12-30 22:39:12 +08:00
Chén Mù e947266743 Merge pull request #795 from router-for-me/modelmappings
refactor(executor): resolve upstream model at conductor level before execution
2025-12-30 05:31:19 -08:00
Luis Pater c6b0e85b54 Fixed: #790
fix(gemini): include full text in response output events
2025-12-30 20:44:13 +08:00
hkfires 26efbed05c refactor(executor): remove redundant upstream model parameter from translateRequest 2025-12-30 20:20:42 +08:00
hkfires 96340bf136 refactor(executor): resolve upstream model at conductor level before execution 2025-12-30 19:31:54 +08:00
hkfires b055e00c1a fix(executor): use upstream model for thinking config and payload translation 2025-12-30 17:49:44 +08:00
sususu 414db44c00 fix(antigravity): parse retry-after delay from 429 response body
When receiving HTTP 429 (Too Many Requests) responses, parse the retry
delay from the response body using parseRetryDelay and populate the
statusErr.retryAfter field. This allows upstream callers to respect
the server's requested retry timing.

Applied to all error paths in Execute, executeClaudeNonStream,
ExecuteStream, CountTokens, and refreshToken functions.
2025-12-30 16:07:32 +08:00
Chén Mù 857c880f99 Merge pull request #785 from router-for-me/gemini
feat(gemini): add per-key model alias support for Gemini provider
2025-12-29 23:32:40 -08:00
hkfires ce7474d953 feat(cliproxy): propagate thinking support metadata to aliased models 2025-12-30 15:16:54 +08:00
hkfires 70fdd70b84 refactor(cliproxy): extract generic buildConfigModels function for model info generation 2025-12-30 13:35:22 +08:00
hkfires 08ab6a7d77 feat(gemini): add per-key model alias support for Gemini provider 2025-12-30 13:27:57 +08:00
Luis Pater 9fa2a7e9df Merge pull request #782 from router-for-me/modelmappings
refactor(config): rename model-name-mappings to oauth-model-mappings
2025-12-30 11:40:12 +08:00
hkfires d443c86620 refactor(config): rename model mapping fields from from/to to name/alias 2025-12-30 11:07:59 +08:00
hkfires 7be3f1c36c refactor(config): rename model-name-mappings to oauth-model-mappings 2025-12-30 11:07:58 +08:00
Luis Pater f6ab6d97b9 fix(logging): add isDirWritable utility to enhance log dir validation in ConfigureLogOutput 2025-12-30 10:48:25 +08:00
Luis Pater bc866bac49 fix(logging): refactor ConfigureLogOutput to accept config object and adjust log directory handling 2025-12-30 10:28:25 +08:00
Finessse 6982a4cc31 feat(tui): add responsive layout and fix sidebar overflow
COMPLETED:
- Added ViewWithSize(width, height) pattern to all submodels
  - login.go: responsive provider rows with adaptive widths
  - switch.go: responsive agent rows without card borders
  - mappings.go: responsive table columns with calculateColumnWidths()
  - usage.go: responsive stat cards (2x2 grid layout)
  - logs.go: responsive log entries with message truncation

- Fixed main View() layout calculation in tui.go
  - Properly accounts for border (2) + padding (2) = 4 chars per panel
  - sidebarWidth now represents content width (20/14 for normal/narrow)
  - contentWidth = m.width - sidebarWidth - 9 (accounts for both panels)

- Added new screen files:
  - integrations.go: setup/integration screen
  - logs.go: real-time log viewer with filtering
  - mappings.go: model alias mappings table
  - usage.go: usage statistics with charts

PENDING TEST:
- Verify sidebar displays correctly alongside content (was overflowing)
- Test all screens at various terminal widths (60, 80, 100+ cols)

KNOWN ISSUE BEING FIXED:
- Sidebar was showing only "[8] Setup" at top due to width overflow
- Content panel was too wide, causing horizontal wrap
2025-12-30 08:45:56 +07:00
Luis Pater 50e6d845f4 feat(cliproxy): introduce global model name mappings for improved aliasing and routing 2025-12-30 08:13:06 +08:00
Finessse bd7575ca2b chore: apply upstream fixes from CLIProxyAPI v6.6.68
Cherry-picked fixes:
- fix(antigravity): inject required placeholder when properties exist without required
- fix(translators): correct key path for system_instruction.parts in Claude request logic
2025-12-30 02:26:57 +07:00
Finessse 27036f44a2 fix(ci): remove .syso files for non-Windows builds 2025-12-30 02:01:05 +07:00
Finessse 3f737dc3c7 fix: cross-platform SysProcAttr for non-Windows builds 2025-12-30 01:57:41 +07:00
Finessse 23a1fa749c chore: bump version to 0.2.0 2025-12-30 01:52:42 +07:00
Finessse e01976448c ci: rename workflows and use v* tag format 2025-12-30 01:43:16 +07:00
Finessse 6e53bdade9 feat: add --tui flag for interactive mode 2025-12-30 01:28:38 +07:00
Finessse 7d90fda663 feat(tui): add status dashboard screen 2025-12-30 01:28:34 +07:00
Finessse 93a0643466 feat(tui): add provider login screen 2025-12-30 01:28:29 +07:00
Finessse dd113e5077 feat(tui): add agent switch screen 2025-12-30 01:28:25 +07:00
Finessse e20343eeec feat(tui): add server control screen 2025-12-30 01:28:20 +07:00
Finessse 738cd4d365 feat(tui): add main TUI app and utilities 2025-12-30 01:28:05 +07:00
Finessse 244782281c feat(tui): add styles and key bindings 2025-12-30 01:28:01 +07:00
Finessse 1e803c918c deps: add bubbletea TUI dependencies 2025-12-30 01:27:57 +07:00
Finessse 3bf998591e docs: update CLI tools table for unified proxypilot 2025-12-30 01:27:53 +07:00
Finessse bff94bd739 chore: update gitignore for cli.md 2025-12-30 01:27:50 +07:00
Finessse 4f65198207 docs: add unified CLI documentation 2025-12-30 01:27:46 +07:00
Finessse 6737add91e ci: add proxypilot npm release workflows 2025-12-30 01:27:25 +07:00
Finessse 470a371295 feat: add unified proxypilot npm package 2025-12-30 01:27:21 +07:00
Finessse 8e18f36d96 chore: remove ppswitch workflows 2025-12-30 01:27:17 +07:00
Finessse baa38a6420 chore: remove ppswitch docs 2025-12-30 01:27:13 +07:00
Finessse b7cd41110e chore: remove standalone ppswitch CLI 2025-12-30 01:27:10 +07:00
Finessse 6fe6d743bd chore: remove ppswitch npm package 2025-12-30 01:27:06 +07:00
Luis Pater a8cb01819d Merge pull request #772 from soffchen/main
fix: Implement fallback log directory for file logging on read-only system
2025-12-30 02:24:49 +08:00
Finessse ea371ccfc6 refactor: remove desktop GUI, keep CLI + tray architecture
- Delete cmd/proxypilotui/main_windows.go (desktop GUI)
- Keep cmd/proxypilotui/assets/ (web dashboard)
- Update cliproxytray to remove embedded asset server
- Update proxypilot_dashboard.go for standalone dashboard
- Update README and docs for CLI + tray architecture
- Update proxypilotpack build scripts
2025-12-30 00:25:15 +07:00
Finessse 7b58cdc5a6 docs: add ppswitch documentation 2025-12-29 23:40:55 +07:00
Finessse d103729baf Revert "docs: add ppswitch config switcher documentation"
This reverts commit edacca735a.
2025-12-29 23:39:35 +07:00
Finessse edacca735a docs: add ppswitch config switcher documentation 2025-12-29 23:38:52 +07:00
Luis Pater 530273906b Merge pull request #776 from router-for-me/fix-ag-claude
fix(antigravity): inject required placeholder when properties exist w…
2025-12-30 00:37:01 +08:00
Supra4E8C 06ddf575d9 fix(antigravity): inject required placeholder when properties exist without required 2025-12-29 23:55:59 +08:00
Finessse 3d8fe7d4e9 fix(ci): fix bun publish auth by using local .npmrc 2025-12-29 22:55:57 +07:00
Finessse 83160e11a7 fix(ppswitch): correct GitHub URL in help text 2025-12-29 22:47:35 +07:00
Finessse 594c830a39 fix(ppswitch): correct GitHub repo URL in package files
- Update REPO to Finesssee/ProxyPilot
- Fix repository and homepage URLs
2025-12-29 22:14:40 +07:00
Finessse cea2b82ffc ci(ppswitch): add bun publish workflow
- Auto-publish to registry after release workflow completes
- Support manual workflow dispatch
- Use bun for publishing
2025-12-29 22:13:46 +07:00
Finessse 8f0165f743 ci(ppswitch): add release workflow for multi-platform builds
- Build binaries for darwin, linux, windows (amd64, arm64)
- Create GitHub release on ppswitch-v* tag push
- Use matrix strategy for parallel builds
2025-12-29 22:13:32 +07:00
Finessse 936cb0a873 feat(ppswitch): add bun package for easy installation
- Add package.json with bun postinstall script
- Add install.ts for binary download
- Add bin wrapper script
- Add README with usage instructions
- Version 0.1.0
2025-12-29 22:13:20 +07:00
Finessse 4206d57bd9 build(ppswitch): add Makefile for cross-platform builds
- Add build target for current platform
- Add build-all target for all platforms
- Add clean and install targets
2025-12-29 22:13:10 +07:00
Finessse b8ffbab975 chore(ppswitch): update version to 0.1.0 and help text
- Change version from 1.0.0 to 0.1.0
- Update install command to use bun
- Improve help text formatting
2025-12-29 22:12:59 +07:00
Finessse 9583beadb8 docs: update provider count to include Gemini CLI 2025-12-29 21:23:23 +07:00
Finessse 4827af9b48 chore(build): rebuild webui assets 2025-12-29 21:22:09 +07:00
Finessse 710a2dc3bc chore(api): update dashboard route configuration 2025-12-29 21:21:42 +07:00
Finessse 2125f99650 chore(webui): misc dashboard UI improvements
Minor updates to Integrations and ProviderLogins components.
2025-12-29 21:21:28 +07:00
Finessse 997ea17f88 feat(webui): add shell config modal to agent setup
Add 'Shell' button per agent that opens modal displaying environment
variables and shell profile configuration snippets. Includes copy-to-
clipboard functionality for easy shell integration.
2025-12-29 21:21:02 +07:00
Finessse ffb7ae1b41 feat(webui): add thinking budget settings UI component
Add ThinkingBudgetSettings component with preset selection (Low/Medium/
High/Custom), enable/disable toggle, and custom token input. Integrated
into dashboard routing.
2025-12-29 21:20:50 +07:00
Finessse 4f32ceac9b feat(webui): enhance request history viewer with filtering
Add live/history toggle, date range filtering, model/provider/status
filters, pagination, export/import/clear buttons, and statistics display.
Fetches from persistent /request-history endpoint.
2025-12-29 21:20:36 +07:00
Finessse 3e8d6e3c92 feat(api): register management routes for new features
Register routes for:
- /request-history/* endpoints (persistent history)
- /thinking-budget endpoint (extended thinking config)

Initialize RequestHistoryManager with auto-save.
2025-12-29 21:20:07 +07:00
Finessse 0da9aa6cd3 feat(cmd): add ppswitch lightweight config switcher binary
Add standalone ppswitch binary for fast agent configuration switching
without server logging overhead. Usage:
- ppswitch              Show all agent statuses
- ppswitch <agent>      Show specific agent status
- ppswitch <agent> <mode>  Switch agent to proxy/native mode
2025-12-29 21:19:52 +07:00
Finessse 7afc014c0e feat(cmd): integrate switch command into main binary
Add --switch and --mode flags plus subcommand-style 'proxypilot switch'
syntax for quick agent configuration switching. Supports both flag style
(--switch claude --mode proxy) and subcommand style (proxypilot switch
claude proxy).
2025-12-29 21:19:25 +07:00
Finessse 1a85ba0e17 feat(cmd): add agent configuration switch command
Add DoSwitch() and DoSwitchStatusAll() for switching agent configs
between proxy mode (routed through ProxyPilot) and native mode (direct
API access). Supports claude, gemini, codex, opencode, droid, cursor,
kilo, and roocode agents with backup/restore functionality.
2025-12-29 21:19:12 +07:00
Finessse 891a52c5de feat(api): add thinking budget management endpoint
Add GET/PUT /thinking-budget endpoint for configuring extended
thinking token budgets. Supports preset levels (Low 2048, Medium 8192,
High 32768) and custom values with enable/disable toggle.
2025-12-29 21:18:58 +07:00
Finessse f7ae19d960 feat(api): add request history API endpoints
Add management endpoints for request history:
- GET /request-history - list entries with pagination
- GET /request-history/stats - aggregate statistics
- DELETE /request-history - clear all entries
- POST /request-history/export - export to JSON
- POST /request-history/import - import from JSON
- POST /request-history/save - force save to disk

Integrate RequestHistoryManager with request logging middleware.
2025-12-29 21:18:45 +07:00
Finessse ad355f75a7 feat(api): add persistent request history storage
Add RequestHistoryManager with file-based persistence at
~/.cli-proxy-api/request-history.json. Features:
- Max 500 entries with automatic pruning
- Auto-save every 30 seconds
- Thread-safe with mutex protection
- In-memory ring buffer for performance
2025-12-29 21:18:31 +07:00
Finessse 48c4cbcdf7 feat(agents): add shell config interface for CLI setup
Add GetShellConfig() to AgentHandler interface returning ShellConfigInfo
with environment variables and shell profile snippets. Implement for all
agents: Claude Code, Codex, Gemini CLI, Cursor, OpenCode, Factory Droid,
and Amazon Q CLI.
2025-12-29 21:17:58 +07:00
Finessse e6ea4295ab feat(config): add thinking budget configuration types
Add ThinkingBudgetConfig struct with preset levels (Low 2048, Medium 8192,
High 32768, Custom) for controlling extended thinking token budgets.
Supports enabled toggle and custom token count.
2025-12-29 21:17:44 +07:00
Finessse ea41ba8980 docs: update README with new auth providers
- Update provider count (8 -> 9)
- Add Amazon Q CLI and Antigravity providers
- Add new login command examples
- Document token import features
2025-12-29 19:01:25 +07:00
Finessse 75cf72720c feat(ui): update ProxyPilot desktop UI
- Update embedded UI assets
- Improve Windows-specific UI handling
2025-12-29 19:01:20 +07:00
Finessse 58035e8499 fix(webui): fix agent setup component
Minor fix in agent setup component
2025-12-29 19:01:11 +07:00
Finessse 15bd80da7c feat(webui): add new provider logins UI
Add UI buttons for MiniMax, Zhipu, Amazon Q, and Kiro import logins
2025-12-29 19:01:05 +07:00
Finessse 9777997886 feat(integrations): enhance Gemini integration
- Add Gemini CLI agent configuration support
- Improve settings file detection
2025-12-29 19:00:48 +07:00
Finessse d02a63311c feat(integrations): enhance Claude integration
- Add support for Claude Code agent configuration
- Improve config file detection and parsing
2025-12-29 19:00:45 +07:00
Finessse 5ab8b5adf3 refactor(integrations): enhance agents integration
Major overhaul of agent integration system:
- Add support for additional agent types
- Improve configuration detection and management
- Better error handling and validation
2025-12-29 19:00:40 +07:00
Finessse 1e48d75aa8 feat(api): register new management routes
Wire up auth files and agents v2 management endpoints
2025-12-29 19:00:30 +07:00
Finessse 233eb30219 feat(api): add agents v2 management endpoints
Add comprehensive management API for agent configuration
2025-12-29 19:00:28 +07:00
Finessse e372d2220b feat(api): add auth files management endpoints
Add management endpoints for listing and managing auth token files
2025-12-29 19:00:27 +07:00
Finessse 551c664564 feat(cmd): add provider login CLI flags to server
- Add --minimax-login, --zhipu-login for API key providers
- Add --amazonq-import for Amazon Q CLI token import
- Add --kiro-import for Kiro IDE token import
- Add --kiro-aws-login for AWS Builder ID flow
2025-12-29 19:00:17 +07:00
Finessse 21101c7a03 feat(cmd): update run command with new login flags
- Add --minimax-login and --zhipu-login flags
- Add --amazonq-import and --kiro-import flags
- Integrate new auth providers into startup flow
2025-12-29 18:59:37 +07:00
Finessse 5099678f17 feat(cmd): enhance agent setup workflow
- Add comprehensive agent configuration wizard
- Support for multiple agent types (Claude Code, Codex, Cursor, etc.)
- Auto-detect existing configurations
- Improved user prompts and validation
2025-12-29 18:59:25 +07:00
Finessse b1653fc6d0 feat(cmd): enhance agent detection
- Improve agent detection logic for multiple CLI tools
- Add support for detecting Amazon Q CLI, OpenCode
- Better path resolution and state management
2025-12-29 18:59:16 +07:00
Finessse d3aa7ece4e refactor(cmd): update Kiro login flow
- Reorganize login methods (Google OAuth, AWS Builder ID)
- Add Kiro token import from IDE config
- Improve error handling and user feedback
2025-12-29 18:59:02 +07:00
Finessse f2c51915f0 feat(cmd): add Zhipu AI API key login
Add --zhipu-login CLI flag to prompt for and save Zhipu AI API key
2025-12-29 18:58:38 +07:00
Finessse ecbe4424cb feat(cmd): add MiniMax API key login
Add --minimax-login CLI flag to prompt for and save MiniMax API key
2025-12-29 18:58:28 +07:00
Finessse cae634a64f feat(agents): add agent detection framework
- Add manager.go for centralized agent management
- Add state.go for agent state persistence
- Add detection for Claude Code, Codex, Cursor, OpenCode
- Add detection for Gemini CLI, Amazon Q CLI
- Add factory_droid.go for FactoryDroid integration
2025-12-29 18:57:56 +07:00
Finessse 42063d9f2a feat(auth): add Amazon Q CLI token import
- Add internal/auth/amazonq/token.go for token file parsing
- Add sdk/auth/amazonq.go for SDK-level Amazon Q auth
- Support importing tokens from Amazon Q CLI (~/.aws/q/)
2025-12-29 18:57:45 +07:00
Finessse 33eefe2ec3 deps: add go-toml and sqlite dependencies
- Add pelletier/go-toml/v2 for TOML parsing (Amazon Q config)
- Add modernc.org/sqlite for local state persistence
- Update indirect dependencies
2025-12-29 18:57:35 +07:00
Finessse 3ca0cccc75 chore: expand .gitignore patterns
- Add Windows artifacts (Thumbs.db, desktop.ini)
- Add local settings patterns (*.local.json/yaml/toml)
- Add backup/temp file patterns (*.bak, *.tmp, *.swp)
- Add test script patterns (*.ahk)
- Expand .mcp and .cursor ignore patterns
2025-12-29 18:57:10 +07:00
hkfires 3099114cbb refactor(api): simplify codex id token claims extraction 2025-12-29 19:48:02 +08:00
Soff 44b63f0767 fix: Return an error if the user home directory cannot be determined for the fallback log path. 2025-12-29 18:46:15 +08:00
Soff Chen 6705d20194 fix: Implement fallback log directory for file logging on read-only systems. 2025-12-29 18:35:48 +08:00
Chén Mù a38a9c0b0f Merge pull request #770 from router-for-me/api
feat(api): add id token claims extraction for codex auth entries
2025-12-29 00:44:41 -08:00
hkfires 8286caa366 feat(api): add id token claims extraction for codex auth entries 2025-12-29 16:34:16 +08:00
Chén Mù bd1ec8424d Merge pull request #767 from router-for-me/amp
feat(amp): add per-client upstream API key mapping support
2025-12-28 22:10:11 -08:00
hkfires 225e2c6797 feat(amp): add per-client upstream API key mapping support 2025-12-29 12:26:25 +08:00
Luis Pater d8fc485513 fix(translators): correct key path for system_instruction.parts in Claude request logic 2025-12-29 11:54:26 +08:00
hkfires f137eb0ac4 chore: add codex, agents, and opencode dirs to ignore files 2025-12-29 08:42:29 +08:00
Chén Mù f39a460487 Merge pull request #761 from router-for-me/log
fix(logging): improve request/response capture
2025-12-28 16:13:10 -08:00
Luis Pater ee171bc563 feat(api): add ManagementTokenRequester interface for management token request endpoints 2025-12-29 02:42:29 +08:00
hkfires a95428f204 fix(handlers): preserve upstream response logs before duplicate detection 2025-12-28 22:35:36 +08:00
Michael Velbaum cb3bdffb43 refactor(logging): streamline auth selection debug messages
Reduce duplicate Debugf calls by appending proxy info via an optional suffix and keep the debug-level guard inside the helper.
2025-12-28 16:10:11 +02:00
Finessse e590a2e7c7 fix(ci): fix Build Release and docker-image workflows
- Add bundle creation step before building custom installer
  (copies ProxyPilot.exe, config, icons to cmd/installer/bundle/)
- Make docker-image workflow conditional on DockerHub secrets
- Skip docker build when credentials aren't configured
2025-12-28 21:08:09 +07:00
Finessse a1ca0ddcb8 chore: bump version to 0.1.6 2025-12-28 20:55:46 +07:00
Finessse c6661972b1 chore: add build/ to .gitignore 2025-12-28 20:54:16 +07:00
Finessse e0756a566c chore(scripts): add build helper scripts
Add PowerShell scripts for installer builds:
- build-installer.ps1
- find-inno.ps1
- windows/build-custom-installer.ps1
2025-12-28 20:53:59 +07:00
Finessse 89bafc418c feat(installer): add Inno Setup branding assets
Add wizard images and generation script for Inno Setup installer.
2025-12-28 20:53:48 +07:00
Finessse ff0dea6cd6 feat(installer): add installer UI React application
Add React-based UI for the custom installer:
- Clean modern installation wizard interface
- Progress tracking and status display
- TypeScript + Vite build
2025-12-28 20:53:40 +07:00
Finessse cb4a7e0bbf feat(installer): add custom Go-based installer
Add custom installer application with embedded UI for ProxyPilot installation.
2025-12-28 20:53:31 +07:00
Finessse 310fd1f202 ci(release): add custom installer build to release workflow
- Build installer UI
- Copy UI files to cmd/installer
- Build custom installer executable
- Generate installer branding images
- Include custom installer in release artifacts
2025-12-28 20:53:13 +07:00
Finessse 2a8565467b feat(installer): enhance Inno Setup installer configuration
Improve installer with additional configuration options and paths.
2025-12-28 20:53:03 +07:00
Finessse 7d1b514a2e chore(ui): update proxypilotui assets 2025-12-28 20:52:54 +07:00
Finessse 7fdbb17d47 fix(embedded): improve embedded server initialization
Minor improvements to embedded server startup.
2025-12-28 20:52:42 +07:00
Finessse 4511e2a589 docs: add provider migration documentation
Document the migration from iFlow to MiniMax and Zhipu AI providers.

Includes:
- Summary of changes
- Files deleted/created/modified
- New model definitions
- API details for new providers
- Auth file format examples
- Migration notes for existing users
2025-12-28 20:52:14 +07:00
Finessse 60582b647e docs: update README for MiniMax and Zhipu AI providers
- Update provider count from 7 to 8
- Add MiniMax to supported providers table
- Add Zhipu AI to supported providers table
2025-12-28 20:51:30 +07:00
Finessse e663c9d395 feat(auth): add Zhipu AI authenticator
Add API key authenticator for Zhipu AI provider.

- Simple API key input (no OAuth required)
- Supports label for account identification
2025-12-28 20:51:19 +07:00
Michael Velbaum 48f19aab51 refactor(logging): pass request entry into auth selection log
Avoid re-creating the request-scoped log entry in the helper and use a switch for account type dispatch.
2025-12-28 15:51:11 +02:00
Finessse a20c4cefdc feat(executor): add Zhipu AI executor
Add OpenAI-compatible executor for Zhipu AI (GLM models).

- Base URL: https://open.bigmodel.cn/api/paas/v4/
- Auth: Bearer token (API key)
- Supports streaming and non-streaming requests
- Token usage tracking
2025-12-28 20:51:10 +07:00
Finessse efda335476 feat(auth): add MiniMax authenticator
Add API key authenticator for MiniMax provider.

- Simple API key input (no OAuth required)
- Supports label for account identification
2025-12-28 20:51:00 +07:00
Finessse 833a560ae1 feat(executor): add MiniMax executor
Add OpenAI-compatible executor for MiniMax API.

- Base URL: https://api.minimax.io/v1
- Auth: Bearer token (API key)
- Supports streaming and non-streaming requests
- Token usage tracking
2025-12-28 20:50:45 +07:00
Finessse 1a3c4ec586 docs: remove iFlow from configuration and documentation
- Remove iFlow example from config.example.yaml
- Remove iFlow from one-click login list in proxypilot.md
2025-12-28 20:50:34 +07:00
Finessse 50b453adc0 refactor(webui): remove iFlow from React components
- Remove iFlow from StatusBar provider list
- Remove iFlow from ProviderLogins provider list
- Remove iFlow auth detection logic
2025-12-28 20:50:15 +07:00
Finessse 7d70539d80 refactor(tray): remove iFlow from system tray app
Remove iFlow OAuth endpoint case from tray application.
2025-12-28 20:50:05 +07:00
Finessse 1878476f76 refactor(ui): remove iFlow from ProxyPilot UI
- Remove iFlow button from login panel
- Remove iFlow OAuth endpoint case
- Remove iFlow click handler
2025-12-28 20:49:54 +07:00
Finessse 9c19023a39 feat(registry): replace iFlow models with MiniMax/Zhipu
- Remove GetIFlowModels() function
- Add GetMiniMaxModels() with M2, M2.1, M2.1-Lightning
- Add GetZhipuModels() with GLM-4.5, 4.6, 4.7, 4-Long, 4.6V
2025-12-28 20:49:44 +07:00
Finessse 70f292a8c8 refactor(api): fix generic import after iFlow removal
- Remove iFlow import and case handler
- Add importResult type definition (was in deleted iflow_import.go)
2025-12-28 20:49:33 +07:00
Finessse 75a9908a3b refactor(api): remove iFlow from oauth sessions
Remove iFlow case from provider normalization switch.
2025-12-28 20:49:24 +07:00
Finessse f780519ee6 refactor(api): remove iFlow handlers from auth_files
- Remove iFlow auth import
- Remove RequestIFlowToken handler
- Remove RequestIFlowCookieToken handler
2025-12-28 20:49:15 +07:00
Finessse 7457183dd1 refactor(cli): remove iFlow login flags
Remove --iflow-login and --iflow-cookie CLI flags.
2025-12-28 20:49:04 +07:00
Finessse 8822013a74 refactor(api): remove iFlow routes from server
Remove iFlow OAuth callback and management API routes.
2025-12-28 20:48:54 +07:00
Finessse bc30977567 refactor(cmd): update auth manager for new providers
- Remove iFlow authenticator
- Add MiniMax authenticator
- Add Zhipu authenticator
2025-12-28 20:48:44 +07:00
Finessse 0fb4f42ffb refactor(sdk): remove iFlow from service, add MiniMax/Zhipu
- Remove iFlow executor and model retrieval cases
- Add MiniMax executor registration
- Add Zhipu executor registration
- Add MiniMax/Zhipu model retrieval cases
2025-12-28 20:48:35 +07:00
Finessse d8165d05d9 refactor(sdk): remove iFlow from refresh registry
Remove iFlow provider registration from refresh lead registry.
2025-12-28 20:48:15 +07:00
Finessse 0b448f7aa7 refactor(api): remove iFlow import handlers
Remove iFlow bulk import handler and tests.

Deleted files:
- internal/api/handlers/management/iflow_import.go
- internal/api/handlers/management/iflow_import_test.go
2025-12-28 20:48:02 +07:00
Finessse 91b13504f8 refactor(sdk): remove iFlow authenticator
Remove iFlow SDK authenticator implementation.

Deleted: sdk/auth/iflow.go
2025-12-28 20:47:50 +07:00
Finessse ffc608b7fe refactor(executor): remove iFlow executor
Remove the iFlow request executor implementation.

Deleted: internal/runtime/executor/iflow_executor.go
2025-12-28 20:47:36 +07:00
Finessse 9e1cd7a61d refactor(cmd): remove iFlow CLI commands
Remove iFlow login and cookie authentication CLI commands.

Deleted files:
- internal/cmd/iflow_cookie.go
- internal/cmd/iflow_login.go
2025-12-28 20:47:24 +07:00
Finessse 277e66c542 refactor(auth): remove iFlow auth package
Remove the iFlow OAuth and cookie-based authentication implementation.
This provider is being replaced with simpler API key-based providers.

Deleted files:
- internal/auth/iflow/cookie_helpers.go
- internal/auth/iflow/iflow_auth.go
- internal/auth/iflow/iflow_token.go
- internal/auth/iflow/oauth_server.go
2025-12-28 20:47:12 +07:00
Michael Velbaum 48f6d7abdf refactor(logging): dedupe auth selection debug logs
Extract repeated debug logging for selected auth credentials into a helper so execute, count, and stream paths stay consistent.
2025-12-28 15:42:35 +02:00
Michael Velbaum 79fbcb3ec4 fix(logging): quote OAuth account field
Use strconv.Quote when embedding the OAuth account in debug logs so unexpected characters (e.g. quotes) can't break key=value parsing.
2025-12-28 15:32:54 +02:00
Michael Velbaum 0e4148b229 feat(logging): disambiguate OAuth credential selection in debug logs
When multiple OAuth providers share an account email, the existing "Use OAuth" debug lines are ambiguous and hard to correlate with management usage stats. Include provider, auth file, and auth index in the selection log, and only compute these fields when debug logging is enabled to avoid impacting normal request performance.

Before:
[debug] Use OAuth user@example.com for model gemini-3-flash-preview
[debug] Use OAuth user@example.com (project-1234) for model gemini-3-flash-preview

After:
[debug] Use OAuth provider=antigravity auth_file=antigravity-user_example_com.json auth_index=1a2b3c4d5e6f7788 account="user@example.com" for model gemini-3-flash-preview
[debug] Use OAuth provider=gemini-cli auth_file=gemini-user@example.com-project-1234.json auth_index=99aabbccddeeff00 account="user@example.com (project-1234)" for model gemini-3-flash-preview
2025-12-28 15:22:36 +02:00
hkfires 3ca5fb1046 fix(handlers): match raw error text before JSON body for duplicate detection 2025-12-28 19:35:36 +08:00
hkfires a091d12f4e fix(logging): improve request/response capture 2025-12-28 19:04:31 +08:00
Luis Pater 457924828a Merge pull request #757 from ben-vargas/fix-thinking-toolchoice-conflict
Fix: disable thinking when tool_choice forces tool use
2025-12-28 14:04:30 +08:00
Finessse 9a2363d6bd chore: bump version to 0.1.5
Includes:
- Vision base64 parsing fix for OpenAI-to-Claude translation
- Memory API localhost authentication with API keys
- Global model mapping SDK hook for cross-provider aliases
- Comprehensive unit tests for auth, config, memory, and runtime
2025-12-28 10:49:06 +07:00
Finessse 352095c54c test(runtime): add unit tests for model registry, executors, and pricing
Covers model registration, quota tracking, concurrent access,
Claude/Gemini executor request prep, and pricing calculations.
2025-12-28 10:46:38 +07:00
Finessse 009fbb2a37 test(memory): add unit tests for file store, pruning, and semantic search
Covers event serialization, file operations, token-based pruning,
recency preservation, and semantic similarity scoring.
2025-12-28 10:46:21 +07:00
Finessse 7d11a35a16 test(config): add unit tests for config loading and validation
Covers YAML parsing, port validation, key sanitization, header
normalization, global model mapping lookup, and legacy migration.
2025-12-28 10:46:03 +07:00
Finessse 9cdce5e8d8 test(auth): add unit tests for Claude PKCE/token and Codex JWT parsing
Covers PKCE verifier/challenge generation, token expiry detection,
refresh timing, and JWT claim extraction for Claude and Codex auth.
2025-12-28 10:45:45 +07:00
Finessse 7d9a114bf8 feat(config): add global model mapping hook for SDK handlers
Adds GlobalModelMapperFunc type and hook to SDKConfig, allowing
SDK-level handlers to access Config-level global model mappings.
This enables cross-provider model aliasing (e.g., gpt-4o → claude-sonnet).
2025-12-28 10:45:26 +07:00
Finessse 82f02c6d59 feat(management): allow API key auth for localhost management endpoints
Enables configured API keys to authenticate management API requests
from localhost, making it easier to use tools like curl for local testing.
2025-12-28 10:45:00 +07:00
Finessse 096daa30a7 fix(translator): correct base64 image parsing for OpenAI-to-Claude translation
Split on ";base64," instead of "," to properly extract media type and data
from data URLs. Also adds support for URL-based images (https://).
2025-12-28 10:44:35 +07:00
Finessse 5b11c113fb fix(ci): remove README_CN.md from goreleaser config 2025-12-28 08:38:37 +07:00
Finessse b127b674e9 sync: squash merge upstream CLIProxyAPI v6.6.62
Synced with upstream v6.6.61-v6.6.62 changes:
- Added usage export/import endpoints
- Added normalizeCodexKey function
- Updated BootstrapRetries type
- Enhanced model definitions and antigravity config

Preserved ProxyPilot customizations:
- Kept CompressionConfig for long-context sessions
- Kept Kiro, GitHub Copilot, Amazon Q model definitions
- Kept shouldKeepProviderOrder for Gemini-3 provider stability
- Kept advanceProviderCursor pattern (separate cursor advancement)
- Removed AmpCode integration (not used)

Version: 0.1.4
2025-12-28 08:32:11 +07:00
Finessse 6163489aca fix(ci): resolve release workflow failures
1. Add permissions: contents: write to release.yml to fix 403 error
2. Add before hook to remove .syso files that break ARM64 cross-compile
3. Skip Windows ARM64 build (not commonly used)
2025-12-28 07:32:40 +07:00
Finessse 0b12eafe6c chore: bump version to 0.1.3 2025-12-28 07:17:57 +07:00
Finessse e89a0f5fcb chore(scripts): add UI state initialization script
PowerShell script to create initial ui-state.json with default
settings in %LOCALAPPDATA%\ProxyPilot.
2025-12-28 07:12:43 +07:00
Finessse c7d06a3ace chore(scripts): add auth directory migration script
PowerShell script to migrate auth files from legacy ~/.cli-proxy-api
to new %LOCALAPPDATA%\ProxyPilot\auth location.
2025-12-28 07:12:33 +07:00
Finessse 81848357c4 feat: auto-register translators on startup
Import translator package with side effects to register all
built-in format translators at initialization.
2025-12-28 07:11:28 +07:00
Finessse 74319cd89e feat(embedded): register SDK providers and configure logging
Register token store and config providers at startup, apply default
auth-dir resolution, and configure log output from config.
2025-12-28 07:10:56 +07:00
Finessse 018cba3491 feat(dashboard): add logo route and improve auth key handling
Add /logo.png route for branding and prefer server instance password
over env var for management key injection.
2025-12-28 07:10:36 +07:00
Finessse a6da22f391 refactor(desktopctl): use util.ResolveAuthDir for path handling
Simplify auth directory resolution by delegating to the centralized
util package.
2025-12-28 07:10:17 +07:00
Finessse 8ae32d440a feat(util): add cross-platform default auth directory helper
Add DefaultAuthDir() that returns OS-appropriate auth directory path
following XDG spec on Linux and LOCALAPPDATA on Windows.
2025-12-28 07:10:01 +07:00
Finessse 26a17c7456 security(webui): remove hardcoded management key from template 2025-12-28 07:09:44 +07:00
Finessse d0c29cb584 feat(api): wire translator endpoints to router
Add translation API routes for matrix, check, docs, score, and
compare endpoints.
2025-12-28 07:09:11 +07:00
Finessse 0f5836e14b refactor(translator): enhance registry with new capabilities
Update registry to support middleware, caching, pooling, and
resilience features integration.
2025-12-28 07:09:01 +07:00
Finessse e96d568671 feat(api): add translator HTTP endpoints
Add REST API handlers for translation matrix, format checking,
documentation, quality scoring, and structure comparison.
2025-12-28 07:08:51 +07:00
Finessse 21125722cd test(translator): add lazy loading tests
Add tests for lazy translator registration and loading behavior.
2025-12-28 07:08:41 +07:00
Finessse 3e47344da9 feat(translator): add testing utilities
Add mock translators and test helpers for translator unit testing.
2025-12-28 07:08:31 +07:00
Finessse 31e52f26e8 feat(translator): add translation quality scoring
Add quality assessment for translations with structural comparison
and scoring metrics.
2025-12-28 07:08:21 +07:00
Finessse 3cf08319d4 feat(translator): add documentation generation
Add markdown docs, mermaid diagram, and summary generation for
registered translators.
2025-12-28 07:08:12 +07:00
Finessse b1a4bede65 feat(translator): add API helper functions
Add compatibility matrix, format listing, and translation info
query APIs for registry introspection.
2025-12-28 07:07:57 +07:00
Finessse 6cfd29ff1d feat(translator): add middleware pipeline support
Add pre/post translation middleware for payload transformation,
logging, and conditional processing.
2025-12-28 07:07:47 +07:00
Finessse 2874e52a2a feat(translator): add resilience and recovery strategies
Add translation recovery with direct hit, fallback chain, and
auto-detect strategies for robust format conversion.
2025-12-28 07:07:35 +07:00
Finessse 40c46acc08 feat(translator): add fallback chain support
Add multi-hop translation fallback chains for indirect format
conversions when direct translators are unavailable.
2025-12-28 07:07:24 +07:00
Finessse d8eb83c8fd feat(translator): add automatic format detection
Add payload format auto-detection for OpenAI, Claude, Gemini, and
Antigravity formats based on JSON structure analysis.
2025-12-28 07:07:14 +07:00
Finessse 5de9cfa8ea feat(translator): add translation benchmarking utilities
Add benchmark suite for measuring translation performance including
P50/P95/P99 latency percentiles and comparison tools.
2025-12-28 07:07:04 +07:00
Finessse 185dcc46dd feat(translator): add batch translation processing
Add batch processor for translating multiple payloads concurrently
with configurable worker count and progress callbacks.
2025-12-28 07:06:52 +07:00
Finessse 705039b410 feat(translator): add translator instance pooling
Add object pooling for translator instances to reduce allocation
overhead and improve concurrent translation performance.
2025-12-28 07:06:40 +07:00
Finessse 782e3f26a5 feat(translator): add translation result caching
Add LRU cache for translation results with configurable TTL and size.
Improves performance by avoiding redundant translations for identical
payloads.
2025-12-28 07:06:30 +07:00
Finessse 25e73af418 feat(translator): add request/response validation utilities
Add validation helpers for translator payloads including JSON schema
validation, required field checks, and format-specific validators.
2025-12-28 07:06:07 +07:00
Ben Vargas aca2ef6359 Fix: disable thinking when tool_choice forces tool use
Anthropic API does not allow extended thinking when tool_choice is set
to "any" or a specific tool. This was causing 400 errors when using
features like Amp's /handoff command which forces tool_choice.

Added disableThinkingIfToolChoiceForced() that removes thinking config
when incompatible tool_choice is detected, applied to both streaming
and non-streaming paths.

Fixes router-for-me/CLIProxyAPI#630
2025-12-27 16:31:37 -07:00
Finessse ceec470273 refactor: consolidate tray app into single binary with embedded engine
This release removes the need for a separate proxypilot-engine.exe binary.
The ProxyPilot.exe tray app now runs the proxy service in-process using
the cliproxy SDK builder pattern.

Changes:
- Add internal/embedded package for in-process server management
- Update desktopctl to support embedded mode alongside subprocess mode
- Clean up vestigial -exe flag and engine binary references
- Update package scripts to build only single binary
- Bump version to 0.1.2

The embedded engine in cmd/cliproxytray was already implemented; this
commit cleans up the remaining references to the old two-binary architecture.
2025-12-28 04:25:45 +07:00
Finessse bbcf06f163 chore: bump version to 0.1.1
Prepare release v0.1.1 with new features:
- Model-specific pricing for cost estimation
- Auto-update with download, verify, and install flow
- Cost savings display in Analytics
- Logo branding assets
2025-12-28 03:42:33 +07:00
Luis Pater ade7194792 feat(management): add generic API call handler to management endpoints 2025-12-28 04:40:32 +08:00
Finessse 00c64b3bcb build(assets): update compiled webui assets
Rebuild embedded webui assets with latest changes including
cost savings display, auto-update flow, and component updates.
2025-12-28 03:21:23 +07:00
Finessse 24467aa957 refactor(webui): update frontend components and configuration
Update Header with logo display, improve AgentSetup and ProviderLogins
components. Update App.tsx and index.html for better structure.
Adjust Vite config for development.
2025-12-28 03:21:04 +07:00
Finessse 68cf672e6b refactor(integrations): improve agent detection and configuration
Update CLI agent detection and configuration handling. Improve
integration handlers for better error handling and status reporting.
2025-12-28 03:20:46 +07:00
Finessse d9f67d1a8a chore(assets): add ProxyPilot logo
Add logo.png to webui public folder and desktop app assets
for consistent branding across web and desktop interfaces.
2025-12-28 03:20:28 +07:00
Finessse 7e8863b45b feat(webui): add full auto-update flow to Settings
Add complete update workflow with stages: checking, available, downloading,
ready, installing. Show download progress bar, version info, and release
notes. Add Install & Restart button for applying updates.
2025-12-28 03:20:10 +07:00
Finessse 2ccbba05e5 feat(webui): add cost savings display to Analytics
Add Cost Savings hero card showing proxy cost vs direct API cost with
visual comparison bars. Add Cost column to Model Breakdown table.
Display savings percentage and total amount saved.
2025-12-28 03:19:51 +07:00
Finessse 5c60aea115 feat(api): add update management endpoints
Add handlers for update status, download, verify, and install operations.
Register new routes: GET /updates/status, POST /updates/download,
POST /updates/verify, POST /updates/install. Track download progress
with background goroutine and mutex-protected state.
2025-12-28 03:19:34 +07:00
Finessse 0a5b2f1fc0 feat(updates): add cross-platform update installation
Add install.go with archive extraction (zip, tar.gz) and binary replacement
logic. Windows uses batch script for safe replacement of running executable.
Unix directly replaces binary with backup. Includes cleanup for old versions.
2025-12-28 03:19:13 +07:00
Finessse 8dd850241a feat(updates): add download and signature verification
Add DownloadUpdate function to download platform-specific binaries from
GitHub releases with progress tracking. Add verify.go with SHA256 checksum
verification for downloaded files. Fix GitHub repo URL and add 404 handling
for repositories without releases.
2025-12-28 03:18:55 +07:00
Finessse 3ee272620e feat(usage): add model-specific pricing for cost estimation
Add comprehensive pricing table for Claude, GPT, Gemini, Qwen, and DeepSeek
models with per-million-token rates. Update cost calculation to use actual
model pricing instead of hardcoded estimates. Add new cost fields to
UsageStats for tracking actual cost, direct API cost, and savings.
2025-12-28 03:18:35 +07:00
Luis Pater 3a436e116a feat(cliproxy): implement model aliasing and hashing for Codex configurations, enhance request routing logic, and normalize Codex model entries 2025-12-28 03:06:51 +08:00
Luis Pater 336867853b Merge pull request #756 from leaph/check-ai-thinking-settings
feat(iflow): add model-specific thinking configs for GLM-4.7 and Mini…
2025-12-28 02:08:27 +08:00
leaph 6403ff4ec4 feat(iflow): add model-specific thinking configs for GLM-4.7 and MiniMax-M2.1
- GLM-4.7: Uses extra_body={"thinking": {"type": "enabled"}, "clear_thinking": false}
- MiniMax-M2.1: Uses reasoning_split=true for OpenAI-style reasoning separation
- Added preserveReasoningContentInMessages() to support re-injection of reasoning
  content in assistant message history for multi-turn conversations
- Added ThinkingSupport to MiniMax-M2.1 model definition
2025-12-27 18:39:15 +01:00
Luis Pater d222469b44 Update issue templates 2025-12-28 01:22:42 +08:00
Finessse 6a1038871f docs: update build documentation and CI workflow
- Update desktop app build process docs
- Clean up release workflow
- Update installer configuration
2025-12-28 00:07:12 +07:00
Finessse 2c09998780 build(assets): update compiled webui assets 2025-12-28 00:06:53 +07:00
Finessse 9c91f3c511 feat(desktop): add WebView2 bindings for new features
- Add agent detection and configuration bindings
- Add update check and download bindings
- Add usage and request monitoring bindings
- Update useProxyContext with new desktop API hooks
2025-12-28 00:06:27 +07:00
Finessse 281ac2e0ba refactor(backend): improve API and internal services
- Add request logging middleware
- Update integrations handler
- Improve desktopctl with browser opening
- Add client model interfaces
- Enhance usage logger plugin
- Update SDK handlers
2025-12-28 00:06:07 +07:00
Finessse 2e7b68922a feat(engine): add engine management and config editor
- Add engine.go for proxy engine lifecycle management
- Add ConfigEditor component for runtime configuration
2025-12-28 00:05:35 +07:00
Finessse bb562e3d36 feat(updates): add auto-update check system
- Add updates package with GitHub releases check
- Add updates management endpoint
2025-12-28 00:05:15 +07:00
Finessse 3f8366de1a feat(usage): add usage statistics dashboard
- Update usage management endpoint
- Add UsageStats component for token/cost tracking
2025-12-28 00:04:50 +07:00
Finessse f4a2ac6962 feat(monitor): add request monitoring dashboard
- Add requests management endpoint
- Add RequestMonitor component for real-time request tracking
2025-12-28 00:04:28 +07:00
Finessse d014612bd6 refactor(dashboard): update components for Flight Deck styling
- Refactor EngineControl with new status indicators
- Update Integrations with provider cards
- Enhance LogsViewer with better filtering and display
- Improve MemoryManager with modern UI patterns
- Update ModelMappings with collapsible sections
- Refactor ProviderLogins with OAuth flow improvements
- Update SemanticMemory styling
2025-12-28 00:03:57 +07:00
Finessse f7b02ce207 feat(ui): Flight Deck dashboard redesign
- Add icon rail navigation with collapsible panels
- Add Header component with engine status and controls
- Add StatusBar component with real-time metrics
- Add SettingsPanel for configuration management
- Add new UI components: icon-rail, provider-card, status-indicator
- Update badge, button, card components with Flight Deck styling
- Add CSS custom properties for consistent theming
- Remove react-grab.css (unused)
2025-12-28 00:03:34 +07:00
Finessse 9e2f45fcf5 feat(agents): add CLI agent detection with auto-configure/reset
- Add DetectCLIAgents for Claude Code, Codex CLI, Aider, Gemini CLI, Droid CLI
- Add ConfigureCLIAgent to auto-configure agents via shell profile or config files
- Add UnconfigureCLIAgent to reset/remove ProxyPilot configuration
- Add AgentSetup component with Configure/Reset buttons
- Shell profile agents show "restart shell" message, config file agents don't
2025-12-28 00:02:58 +07:00
Luis Pater 7646a2b877 Fixed: #749
fix(translators): ensure `gjson.String` content is non-empty before setting `parts` in OpenAI request logic
2025-12-28 00:54:26 +08:00
Luis Pater 62090f2568 Merge pull request #750 from router-for-me/config
fix(config): preserve original config structure and avoid default value pollution
2025-12-27 22:10:01 +08:00
Luis Pater c281f4cbaf Fixed: #747
fix(translators): rename and integrate `usageMetadata` as `cpaUsageMetadata` in Claude processing logic
2025-12-27 22:02:11 +08:00
hkfires 09455f9e85 fix(config): make streaming keepalive and retries ints 2025-12-27 20:56:47 +08:00
hkfires c8e72ba0dc fix(config): smart merge writes non-default new keys only 2025-12-27 20:28:54 +08:00
hkfires 375ef252ab docs(config): clarify merge mapping behavior 2025-12-27 19:30:21 +08:00
hkfires ee552f8720 chore(config): update ignore patterns 2025-12-27 19:13:14 +08:00
hkfires 2e88c4858e fix(config): avoid adding new keys when merging 2025-12-27 19:00:47 +08:00
Luis Pater 3f50da85c1 Merge pull request #745 from router-for-me/auth
fix(auth): make provider rotation atomic
2025-12-27 13:01:22 +08:00
hkfires 8be06255f7 fix(auth): make provider rotation atomic 2025-12-27 12:56:48 +08:00
Finessse 95eb896831 docs: add desktop app build process documentation 2025-12-27 07:16:21 +07:00
Finessse 660c0f7656 fix: use multi-resolution icon (16-256px) for proper Windows display 2025-12-27 07:13:13 +07:00
Finessse aca1f54478 fix: use CopyFile instead of deprecated FileCopy in installer 2025-12-27 07:05:51 +07:00
Finessse c10abab37c feat: embed ProxyPilot logo in all executables
- Add versioninfo.json for goversioninfo in tray and server
- Generate resource.syso files with embedded icon
- Update ico.go to embed actual icon.ico for tray
- All exes now show ProxyPilot logo in File Explorer
2025-12-27 07:05:13 +07:00
FinessseandClaude Opus 4.5 d71582d7d8 refactor(tray): simplify system tray to minimal menu
Before (nested submenus):
- Status
- Open Dashboard
- Engine → Start, Stop, Restart
- Connect → Copy ANTHROPIC_BASE_URL, Copy OPENAI_BASE_URL
- Settings → Launch on login, Auto-start proxy
- Tools → Open Logs, Copy Diagnostics, Advanced UI
- Updates → Check for Updates, Update ProxyPilot
- Quit

After (flat, minimal):
- Open Dashboard
- Start/Stop (toggle)
- Copy API URL
- Quit

Advanced settings moved to dashboard UI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:41:05 +07:00
Finessse f3bc99cc35 fix: add ProxyPilot logo to installer and shortcuts 2025-12-27 06:35:48 +07:00
FinessseandClaude Opus 4.5 923f3f68b7 ci: add release workflow with Inno Setup installer
- Add GitHub Actions workflow to build releases
- Update Inno Setup script for new binary structure
- Builds single-file installer (11MB) containing:
  - ProxyPilot.exe (tray + dashboard)
  - proxypilot-engine.exe (proxy server)
  - config.example.yaml

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:25:31 +07:00
FinessseandClaude Opus 4.5 0e03289627 feat(tray): embed WebView2 dashboard directly in tray app
- Embed React dashboard assets in tray binary
- Open dashboard in WebView2 window from tray
- Remove need for separate proxypilotui.exe
- Simplifies distribution to just ProxyPilot.exe + proxypilot-engine.exe

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:17:21 +07:00
FinessseandClaude Opus 4.5 7631297204 feat(webui): refactor dashboard with tabbed navigation and theme toggle
- Add 5-tab navigation: Engine, Auth, Routing, Memory, Logs
- Add dark/light/system theme toggle with persistence
- Extract 7 modular dashboard components:
  - EngineControl: proxy start/stop/restart controls
  - ProviderLogins: OAuth buttons for 6 AI providers
  - Integrations: CLI agent detection and configuration
  - ModelMappings: global model mapping CRUD
  - MemoryManager: session memory management
  - SemanticMemory: Ollama embeddings and namespaces
  - LogsViewer: diagnostics and log viewing
- Add centralized state management with ProxyProvider context
- Reduce App.tsx from 1,734 lines to 351 lines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 06:03:16 +07:00
FinessseandClaude Opus 4.5 3e3d0bf933 chore: restore logo to README
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 04:09:10 +07:00
FinessseandClaude Opus 4.5 c6d8e6abb1 chore: gitignore static and test folders
- Remove logo and test files from tracking
- Keep files locally but exclude from repo

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 04:00:38 +07:00
FinessseandClaude Opus 4.5 9fb39ff966 docs: fix Factory.ai and Anthropic research links
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:51:15 +07:00
FinessseandClaude Opus 4.5 e08235b4d1 docs: add CLIProxyAPI and VibeProxy to credits
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:50:09 +07:00
FinessseandClaude Opus 4.5 7a5fd20272 docs: add credits section for research inspirations
Credits Factory.ai and Anthropic for their research on context
compression and building effective agents.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:49:06 +07:00
FinessseandClaude Opus 4.5 b37551edd8 docs: update to GPT-5.2 models
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:46:18 +07:00
FinessseandClaude Opus 4.5 39c7c6760a docs: add 4.5 to Haiku model name
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:44:08 +07:00
FinessseandClaude Opus 4.5 7e13a0dfdd docs: update Gemini models to 3 Pro/Flash
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:42:34 +07:00
FinessseandClaude Opus 4.5 9394166777 docs: restyle README in VibeProxy format
- Cleaner centered branding with star badge
- Bold tagline with concise value prop
- GitHub tip callout for latest models
- Emoji bullet feature list
- Simplified sections
- Setup guide links

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:39:47 +07:00
FinessseandClaude Opus 4.5 a6ea590cce docs: add missing features to README
Added:
- Tool Calling Repair
- Extended Thinking support
- Quota Auto-Switch
- Usage Statistics
- 4 CLI Tools table
- Tool Integrations section (Droid, Cursor, Continue)
- Factory Droid configuration example

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:37:13 +07:00
FinessseandClaude Opus 4.5 7329675592 docs: update README with comprehensive feature list
- Added 7 auth providers, long-context features, desktop app details
- Added supported providers table with auth methods
- Simplified installation and quick start sections
- Added tool configuration examples (Claude Code, Codex CLI)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:29:38 +07:00
FinessseandClaude Opus 4.5 cab21a5089 refactor(auth): remove commented-out ErrTokenExpired
Removed dead code (commented-out ErrTokenExpired error constant) from
both claude/errors.go and codex/errors.go.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 03:01:27 +07:00
Luis Pater 72274099aa Fixed: #738
fix(translators): refine prompt token calculation by incorporating cached tokens in Claude response handling
2025-12-27 03:56:11 +08:00
FinessseandClaude Opus 4.5 c4701abb00 refactor(misc): remove duplicate embed import
Removed redundant `_ "embed"` import as `embed` is already imported
and used for embed.FS.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:50:14 +07:00
FinessseandClaude Opus 4.5 7b3ef0ea43 refactor(errors): remove unused error constructors
Removed 5 unused helper functions: BadRequest(), Unauthorized(),
Forbidden(), NotFound(), InternalServerError(). Also removed the
now-unused net/http import.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:50:05 +07:00
FinessseandClaude Opus 4.5 5a9c652f48 docs: remove stale UI spec documentation
Remove desktop-ui-spec.md and windows-ui-spec.md which reference
deleted cliproxyctl CLI that no longer exists.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:35:13 +07:00
FinessseandClaude Opus 4.5 715c71830e refactor(auth): remove unused ProjectSelectionError type
Type was defined but never used anywhere in codebase.
Keep EmailRequiredError which is actively used.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:35:02 +07:00
FinessseandClaude Opus 4.5 aab8294d96 refactor(misc): remove commented dead code in codex_instructions.go
Remove unused lastReviewPrompt variable and associated dead code block.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:34:53 +07:00
FinessseandClaude Opus 4.5 59e947e8a8 chore: add long-context-features.md to gitignore exceptions
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:14:04 +07:00
FinessseandClaude Opus 4.5 2617902571 docs: add long-context features documentation
Document Factory.ai context compression and Anthropic agentic harness
implementations with architecture diagrams and configuration reference.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:55 +07:00
FinessseandClaude Opus 4.5 270a176925 test(api): add integration tests for long-context features
Test context compression adapter and harness middleware work together
without conflicts.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:47 +07:00
FinessseandClaude Opus 4.5 f4e7d5b92e test(middleware): add session storage test for agentic harness
Add E2E test for session-based harness file detection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:39 +07:00
FinessseandClaude Opus 4.5 eb84cbe543 refactor(middleware): remove Puppeteer MCP detection from harness
Removed feature not present in original Factory.ai or Anthropic sources.
Keep implementation pure to research references.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:31 +07:00
FinessseandClaude Opus 4.5 e71648f4b6 feat(api): register AgenticHarnessMiddleware in server routes
Enable Anthropic-style INITIALIZER/CODING mode prompts for long-running
agentic clients.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:20 +07:00
FinessseandClaude Opus 4.5 1b5bd183b9 feat(cliproxy): wire up context compression in service startup
Add coreManagerWrapper to adapt auth manager types and initialize
LLM-based summarization after server creation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:13:09 +07:00
FinessseandClaude Opus 4.5 095718e31e feat(middleware): add InitSummarizerWithAuthManager for compression setup
Enables Factory.ai-style LLM summarization by wiring the summarizer
executor to the core auth manager.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:46 +07:00
FinessseandClaude Opus 4.5 abe7597d99 test(memory): add unit tests for ManagerAuthAdapter
12 tests covering adapter behavior, pipeline execution, and edge cases.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:37 +07:00
FinessseandClaude Opus 4.5 01cd7942b5 feat(memory): add CoreManagerExecutor interface and ManagerAuthAdapter
Bridge type differences between coreauth.Manager and memory.AuthExecutor
to enable LLM-based context compression through the auth pipeline.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 02:12:29 +07:00
FinessseandClaude Opus 4.5 b669cfa650 docs(readme): remove GitHub stars badge, keep X follow
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:23:31 +07:00
FinessseandClaude Opus 4.5 c53fabd3a8 fix(readme): correct X profile link
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:21:50 +07:00
FinessseandClaude Opus 4.5 4ceed0428b docs(readme): add X/Twitter follow badge
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:20:44 +07:00
FinessseandClaude Opus 4.5 462856639c fix: use transparent logo (remove white background)
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:19:36 +07:00
FinessseandClaude Opus 4.5 b75ef23d5c fix(readme): use relative path for logo
Works for both public and private repos

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:17:52 +07:00
FinessseandClaude Opus 4.5 8e236dd69d feat: add ProxyPilot logo
- Add icon.png for README header
- Update .gitignore to track the logo

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:16:00 +07:00
FinessseandClaude Opus 4.5 20146a1f7d fix(license): update copyright holders
- Fix malformed date "2025.9-present"
- Add Finesssee as ProxyPilot fork maintainer

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:08:17 +07:00
FinessseandClaude Opus 4.5 b5b6d65e79 docs(readme): redesign with vibeproxy-style formatting
- Centered logo and badges
- Catchy tagline "Stop juggling API keys"
- Emoji-styled feature list
- Latest models callout section
- Cleaner installation/usage sections

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 01:02:52 +07:00
FinessseandClaude Opus 4.5 12aa47b91c refactor(proxypilotui): modernize asset embedding
- Replace inline HTML/CSS/JS with Vite-bundled React app
- Embed compiled assets from webui build
- Simplify index.html to load external JS/CSS

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:59 +07:00
FinessseandClaude Opus 4.5 5ce65eed85 refactor(webui): improve App.tsx code quality
- Add downloadBlob helper to reduce duplication
- Refactor export functions to use helper
- Fix model mapping edit to use controlled React state
  instead of DOM getElementById manipulation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:50 +07:00
FinessseandClaude Opus 4.5 e75e5716e9 refactor(webui): remove debug console.log
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:41 +07:00
FinessseandClaude Opus 4.5 d519feeba1 refactor(webui): cleanup unused component exports
- badge.tsx: remove unused badgeVariants export
- button.tsx: remove unused buttonVariants export
- card.tsx: remove unused CardAction, CardFooter components

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:33 +07:00
FinessseandClaude Opus 4.5 f1f8e2c1a6 refactor(webui): remove unused UI components
Delete input.tsx, progress.tsx, tabs.tsx - none were imported
or used anywhere in the codebase.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:23 +07:00
FinessseandClaude Opus 4.5 bd893efee9 docs: add SECURITY.md
Vulnerability reporting policy with:
- Supported versions
- Reporting methods (GitHub advisory, email)
- Response timeline expectations
- Responsible disclosure guidelines

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:12 +07:00
FinessseandClaude Opus 4.5 18757ebe7c docs: add CONTRIBUTING.md
Guidelines for:
- Development environment setup
- Running tests
- Code style (go fmt, go vet)
- Pull request process
- Issue reporting
- Third-party provider integrations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:53:03 +07:00
FinessseandClaude Opus 4.5 09e96a45ca docs(readme): rebrand to ProxyPilot
Complete rewrite with:
- ProxyPilot branding and badges
- Feature list and architecture overview
- Quick start and configuration guide
- API endpoints documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:52:54 +07:00
FinessseandClaude Opus 4.5 8e729276b0 fix(license): correct copyright date typo
Changed "2025-2005.9" to "2024-2025"

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-27 00:52:45 +07:00
Luis Pater dcae098e23 Fixed: #736
fix(translators): handle gjson string types in Claude request processing to ensure consistent content parsing
2025-12-27 01:25:47 +08:00
Luis Pater 2eb05ec640 Merge pull request #727 from nguyenphutrong/main
docs: add Quotio to community projects
2025-12-26 11:53:09 +08:00
Luis Pater 3ce0d76aa4 feat(usage): add import/export functionality for usage statistics and enhance deduplication logic 2025-12-26 11:49:51 +08:00
Trong Nguyen a00b79d9be docs(readme): add Quotio to community projects section 2025-12-26 10:46:05 +07:00
FinessseandClaude Opus 4.5 1a1c85f043 chore: cleanup and remove Letta integration
- Remove internal/letta/ package (unused memory bridge)
- Remove Letta references from run.go and start-cliproxy.ps1
- Move docker-build scripts to scripts/
- Move TROUBLESHOOTING_ANTIGRAVITY.md and WARP.md to docs/

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 07:13:19 +07:00
FinessseandClaude Opus 4.5 9e187cd08f feat(droid): fix Droid CLI integration to use settings.json
- Update droid.go to use ~/.factory/settings.json (runtime config)
- Add /healthz endpoint for Droid health checks
- Add root-level API routes (/responses, /messages, etc.)
- Fix detection in proxypilotui to check settings.json
- Use thinking models with provider: "openai" for Responses API

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 06:52:08 +07:00
FinessseandClaude Opus 4.5 a8c389ffa6 ci: add upstream sync check workflow
Add GitHub Actions workflow to check for upstream
repository updates.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:11:17 +07:00
FinessseandClaude Opus 4.5 999529c154 fix(webui): minor App.tsx updates
Minor updates to web UI App component.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:11:05 +07:00
FinessseandClaude Opus 4.5 355932e138 docs(memory): update memory system documentation
Update docs to reflect token-aware compression
and LLM summarization features.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:54 +07:00
FinessseandClaude Opus 4.5 d3466b31af fix(sdk): update stream forwarder for compression
Update stream forwarder to work with token-aware
compression middleware.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:43 +07:00
FinessseandClaude Opus 4.5 f19594e490 fix(sdk): update handlers for compression support
Update SDK handlers to integrate with token-aware
compression middleware.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:33 +07:00
FinessseandClaude Opus 4.5 946cc75e71 feat(ui): add agent detection and model mapping bindings
Add WebView2 JavaScript bindings:
- pp_detect_agents: List installed CLI agents
- pp_configure_agent: Configure agent for ProxyPilot
- pp_get_model_mappings: Get global mappings
- pp_save_model_mappings: Save global mappings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:21 +07:00
FinessseandClaude Opus 4.5 93c0b8703c chore(ui): remove React bundle, simplify embed
Remove bloated React bundle (~500KB) in favor of
simple embedded HTML (~15KB). Update embed.go to
only include index.html and vite.svg.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:10:10 +07:00
FinessseandClaude Opus 4.5 0dda5a01a2 refactor(ui): redesign desktop UI with ProxyPal style
Complete rewrite with ProxyPal-inspired design:
- KPI tiles (Saved, Requests, Tokens, Success)
- Provider grid with OAuth buttons
- CLI Agents section with status indicators
- Model Mappings editor
- Dark/light theme toggle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:59 +07:00
FinessseandClaude Opus 4.5 572792f2c6 feat(cmd): add --detect-agents and --setup-* flags
Add CLI flags for agent detection and configuration:
- --detect-agents: List installed CLI agents
- --setup-claude: Configure Claude Code
- --setup-codex: Configure Codex CLI
- --setup-droid: Configure Factory Droid

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:45 +07:00
FinessseandClaude Opus 4.5 12ac05a22f feat(cmd): add CLI agent auto-configuration
Generate config files to point CLI agents at ProxyPilot:
- Claude Code: ~/.claude/settings.json
- Codex CLI: ~/.codex/config.toml
- Factory Droid: ~/.factory/config.json

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:34 +07:00
FinessseandClaude Opus 4.5 af37fbf2e0 feat(cmd): add CLI agent detection
Detect installed CLI agents (Claude Code, Codex, Droid, Gemini)
by checking binaries and config files.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:23 +07:00
FinessseandClaude Opus 4.5 f52bc59b2e docs(config): add model mappings example
Add global-model-mappings section to config.example.yaml
showing smart/rush/think aliases.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:11 +07:00
FinessseandClaude Opus 4.5 5cf7518f26 feat(api): add model mappings management handler
Add API handler for managing global model mappings
stored in ~/.proxypilot/model-mappings.json.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:09:00 +07:00
FinessseandClaude Opus 4.5 6767188a8e feat(config): add global model mappings support
Add GlobalModelMapping struct and LookupGlobalModelMapping()
for routing friendly model names to actual models.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:49 +07:00
FinessseandClaude Opus 4.5 7cbbf954d6 feat(api): register harness management routes
Add route registration for harness and model mappings
management endpoints.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:36 +07:00
FinessseandClaude Opus 4.5 6e8f055816 feat(api): add harness management API endpoints
Add CRUD operations for harness files:
- GET /v0/management/harness/files - list files
- GET /v0/management/harness/file - read file
- PUT /v0/management/harness/file - write file
- GET /v0/management/harness/export - export all
- POST /v0/management/harness/import - import files

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:26 +07:00
FinessseandClaude Opus 4.5 87dbbedd4b feat(middleware): enhance agentic harness prompts
Improve INITIALIZER and CODING prompts based on Anthropic guidance:
- Structured feature_list.json format
- GET BEARINGS workflow for coding mode
- Puppeteer MCP detection for browser testing
- Session-aware state detection

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:15 +07:00
FinessseandClaude Opus 4.5 a84e59f31c feat(config): add CompressionConfig struct
Add configuration options for token-aware compression:
- Token threshold percentage
- Reserved output tokens
- LLM summary enable/disable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:08:01 +07:00
FinessseandClaude Opus 4.5 ca06786892 feat(executor): add token counting helper functions
Add utilities for estimating token counts using tiktoken
to support token-aware compression decisions.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:52 +07:00
FinessseandClaude Opus 4.5 25dd8b2087 feat(middleware): add token-aware context compression
Implement proactive compression based on token count rather than bytes:
- Uses tiktoken for accurate token estimation
- Compresses at 75% threshold before hitting limits
- Reserves tokens for output generation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:42 +07:00
FinessseandClaude Opus 4.5 57d5b4b1b1 feat(memory): add anchored summary with LLM support
Update file_store.go with BuildAnchoredSummaryWithLLM() for
generating context-aware summaries during compression.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:32 +07:00
FinessseandClaude Opus 4.5 f80e1bb068 feat(memory): add LLM-based structured summarization
Add structured summary generation for context compression:
- structured_summary.go: Types and parsing for summaries
- summarizer.go: LLM summarization logic
- summarizer_executor.go: Routes to LLM pipeline

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 05:07:22 +07:00
Luis Pater 33e53a2a56 fix(translators): ensure correct handling and output of multimodal assistant content across request handlers 2025-12-26 05:08:04 +08:00
RCD d68f32f00e Merge pull request #2 from Finesssee/sync-cliproxiapiplus
feat: sync with CLIProxyAPIPlus
2025-12-26 02:13:50 +07:00
FinessseandClaude Opus 4.5 221a386040 feat: sync with CLIProxyAPIPlus (excludes Amp, GitHub Copilot)
Synced all changes from router-for-me/CLIProxyAPIPlus including:

Executor updates:
- claude_executor: response decompression, beta extraction, model resolution
- gemini_executor/codex_executor: usage reporting
- antigravity_executor: fallback URLs, thinking metadata, token refresh
- kiro_executor: token refresh, profile ARN handling, quota fallback

Translator updates:
- Updated all translators for improved request/response handling
- Enhanced tool result formatting and streaming support

Configuration:
- Added IncognitoBrowser option for OAuth
- Updated KiroKey configuration
- Enhanced PayloadConfig options

SDK updates:
- Auth refresh registry improvements
- Cliproxy service enhancements
- Added ErrNotImplemented for executor interface

Excluded features (not synced):
- Amp CLI Integration module
- GitHub Copilot executor

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 02:10:20 +07:00
Luis Pater cd5b80785f Merge pull request #722 from hungthai1401/bugfix/remove-extra-args
Fixed incorrect function signature call to `NewBaseAPIHandlers`
2025-12-26 02:56:56 +08:00
FinessseandClaude Opus 4.5 f52840b10e Merge remote-tracking branch 'origin/main'
Resolve conflicts:
- Keep Kiro executor (was deleted in remote)
- Merge antigravity executor changes (0.7 safety factor, new model names)
- Keep Kiro management API, remove broken Copilot function
- Fix Kiro translator imports

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 01:02:29 +07:00
FinessseandClaude Opus 4.5 036beb061a refactor(executor): update antigravity executor
Minor updates to antigravity executor.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:54:37 +07:00
FinessseandClaude Opus 4.5 98d5650d55 docs(config): add Kiro configuration example
Add kiro-key config example with:
- token-file, region, proxy-url
- agent-task-type, excluded-models
- oauth-excluded-models for kiro

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:54:34 +07:00
FinessseandClaude Opus 4.5 c141565eae feat(management): add Kiro OAuth support
Add Kiro OAuth handling in management API:
- Fix ExpiresAt field name in KiroTokenStorage

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:54:14 +07:00
FinessseandClaude Opus 4.5 8696d57ca6 feat(cmd): add Kiro login command
Add DoKiroLogin command for CLI authentication:
- AWS Builder ID device authorization flow
- Prompt-based auth method selection
- Token storage to auth directory

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:54:12 +07:00
FinessseandClaude Opus 4.5 9eeeb88e35 feat(sdk/auth): add Kiro authenticator
Add KiroAuthenticator for AWS Builder ID device flow:
- Client registration with AWS SSO OIDC
- Device authorization with user code display
- Token polling with timeout handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:54:09 +07:00
FinessseandClaude Opus 4.5 d407c7c779 feat(watcher): add Kiro auth handling
Add Kiro support in SnapshotCoreAuths():
- Synthesize auth entries from KiroKey config
- Support token-file and direct access-token modes
- Handle profile-arn, region, agent-task-type

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:53 +07:00
FinessseandClaude Opus 4.5 b354ff8a21 feat(translator): add Kiro translators
Add request/response translators for Kiro:
- openai/chat-completions: OpenAI <-> Kiro
- openai/responses: OpenAI Responses <-> Kiro
- claude: Claude <-> Kiro (pass-through)
- Register translators in init.go

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:50 +07:00
FinessseandClaude Opus 4.5 b7a8424238 feat(translator): add Kiro format constant
Add FormatKiro constant to SDK translator formats.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:48 +07:00
FinessseandClaude Opus 4.5 4b44ab8328 feat(executor): add Kiro executor
Add KiroExecutor for AWS CodeWhisperer API:
- AWS Event Stream binary format parsing
- Kiro payload building with origin field
- Token refresh with mutex protection
- Quota fallback: AI_EDITOR -> CLI on 429
- Auto-refresh on 401/403 errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:32 +07:00
FinessseandClaude Opus 4.5 3e4cf30ee3 feat(auth/kiro): add Kiro authentication module
Add complete Kiro authentication with dual OAuth support:
- pkce.go: PKCE code generation for secure OAuth
- errors.go: custom error types for auth failures
- kiro.go: KiroTokenData and KiroAuthBundle structs
- kiro_token.go: token storage with SaveTokenToFile
- kiro_auth.go: AWS Builder ID device flow + Google OAuth

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:29 +07:00
FinessseandClaude Opus 4.5 4dbe6f88eb feat(config): add KiroKey configuration struct
Add KiroKey struct for Kiro (AWS CodeWhisperer) configuration:
- token-file: path to IDE token file
- access-token, refresh-token: direct token config
- profile-arn, region: AWS settings
- agent-task-type: Kiro API task type
- Add SanitizeKiroKeys() method

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:53:26 +07:00
FinessseandClaude Opus 4.5 612d0b6e26 feat(constant): add Kiro provider constant
Add Kiro constant for AWS CodeWhisperer provider identification.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-26 00:52:38 +07:00
Thai Nguyen Hung 54f71aa273 fix(test): remove extra argument from ExecuteStreamWithAuthManager call 2025-12-25 21:55:35 +07:00
Luis Pater 3f949b7f84 Merge pull request #704 from tinyc0der/add-index
fix(openai): add index field to image response for LiteLLM compatibility
2025-12-25 21:35:12 +08:00
Luis Pater cf8b2dcc85 Merge pull request #67 from router-for-me/plus
v6.6.54
2025-12-25 21:07:45 +08:00
Luis Pater 8e24d9dc34 Merge branch 'main' into plus 2025-12-25 21:07:37 +08:00
Luis Pater 443c4538bb feat(config): add commercial-mode to optimize HTTP middleware for lower memory usage 2025-12-25 21:05:01 +08:00
TinyCoder a7fc2ee4cf refactor(image): avoid using json.Marshal 2025-12-25 14:21:01 +07:00
Finessse 8c8cae63d7 chore: final comprehensive cleanup of legacy models and instructions 2025-12-25 06:02:51 +07:00
Finessse 8c14135f97 chore: final cleanup of legacy model references and placeholder updates 2025-12-25 05:59:31 +07:00
Finessse f83d2b638a chore: final legacy model purge and documentation update 2025-12-25 05:52:43 +07:00
Finessse 3c72b950d3 feat(desktopctl): add thinking proxy status monitoring 2025-12-25 05:48:29 +07:00
Finessse a6eecfb8d5 chore: update documentation and global configuration templates 2025-12-25 05:47:56 +07:00
Finessse f97ef1f2a3 test: update regression tests for latest model versions 2025-12-25 05:47:41 +07:00
Finessse 53918b4c92 feat(registry): upgrade model registry and thinking logic 2025-12-25 05:47:23 +07:00
Finessse b402979a3f feat(tray): add connection helpers to system tray 2025-12-25 05:47:07 +07:00
Finessse 719027f4e9 feat(ui): enhance dashboard with integrations and live logs 2025-12-25 05:46:52 +07:00
Finessse 5d2848d951 feat(integrations): implement tool auto-configuration system 2025-12-25 05:46:37 +07:00
Finessse 02fd226098 refactor(translator): remove redundant translator wrapper 2025-12-25 05:46:22 +07:00
Finessse 7d3d5ccbb4 cleanup(cli): remove redundant legacy CLI tools 2025-12-25 05:46:06 +07:00
Finessse baf03f07b8 cleanup(providers): remove deprecated kiro and copilot providers 2025-12-25 05:45:50 +07:00
Finessse 7c8e9f39c9 refactor(access): migrate core access logic to SDK 2025-12-25 05:45:35 +07:00
Finessse 2f43e94ec2 feat(oauth): add support for manual callback URL entry 2025-12-25 05:45:19 +07:00
Finessse d39b7b3e4f fix(droid): implement payload compaction for large droid histories 2025-12-25 05:44:57 +07:00
Luis Pater 8e749ac22d docs(readme): update GLM model version from 4.6 to 4.7 in README and README_CN 2025-12-24 23:59:48 +08:00
Luis Pater 69e09d9bc7 docs(readme): update GLM model version from 4.6 to 4.7 in README and README_CN 2025-12-24 23:46:27 +08:00
Luis Pater ed57d82bc1 Merge branch 'router-for-me:main' into main 2025-12-24 23:31:09 +08:00
Luis Pater 06ad527e8c Fixed: #696
fix(translators): adjust prompt token calculation by subtracting cached tokens across Gemini, OpenAI, and Claude handlers
2025-12-24 23:29:18 +08:00
Luis Pater 7af5a90a0b Merge pull request #65 from router-for-me/plus
v6.6.52
2025-12-24 22:28:45 +08:00
Luis Pater 7551faff79 Merge branch 'main' into plus 2025-12-24 22:27:12 +08:00
Luis Pater b7409dd2de Merge pull request #706 from router-for-me/log
Log
2025-12-24 22:24:39 +08:00
hkfires 5ba325a8fc refactor(logging): standardize request id formatting and layout 2025-12-24 22:03:07 +08:00
Luis Pater d502840f91 Merge pull request #695 from NguyenSiTrung/main
feat: add cached token parsing for Gemini , Antigravity API responses
2025-12-24 21:58:55 +08:00
hkfires 99238a4b59 fix(logging): normalize warning level to warn 2025-12-24 21:11:37 +08:00
hkfires 6d43a2ff9a refactor(logging): inline request id in log output 2025-12-24 21:07:18 +08:00
Luis Pater cdb9c2e6e8 Merge remote-tracking branch 'origin/main' into router-for-me/main 2025-12-24 20:18:53 +08:00
Luis Pater 3faa1ca9af Merge pull request #700 from router-for-me/log
refactor(sdk/auth): rename manager.go to conductor.go
2025-12-24 19:36:24 +08:00
Luis Pater 9d975e0375 feat(models): add support for GLM-4.7 and MiniMax-M2.1 2025-12-24 19:30:57 +08:00
hkfires 2a6d8b78d4 feat(api): add endpoint to retrieve request logs by ID 2025-12-24 19:24:51 +08:00
TinyCoder 671558a822 fix(openai): add index field to image response for LiteLLM compatibility
LiteLLM's Pydantic model requires an index field in each image object.
Without it, responses fail validation with "images.0.index Field required".
2025-12-24 17:43:31 +07:00
Luis Pater 6b80ec79a0 Merge pull request #61 from tinyc0der/fix/kiro-tool-results
fix(kiro): Handle tool results correctly in OpenAI format translation
2025-12-24 17:23:41 +08:00
Luis Pater d3f4783a24 Merge pull request #57 from PancakeZik/my-idc-changes
feat: add AWS Identity Center (IDC) authentication support
2025-12-24 17:20:01 +08:00
Luis Pater 1cb6bdbc87 Merge pull request #62 from router-for-me/plus
v6.6.50
2025-12-24 17:14:05 +08:00
Luis Pater 96ddfc1f24 Merge branch 'main' into plus 2025-12-24 17:13:51 +08:00
TinyCoder c169b32570 refactor(kiro): Remove unused variables in OpenAI translator
Remove dead code that was never used:
- toolCallIDToName map: built but never read from
- seenToolCallIDs: declared but never populated, only suppressed with _
2025-12-24 15:10:35 +07:00
TinyCoder 36a512fdf2 fix(kiro): Handle tool results correctly in OpenAI format translation
Fix three issues in Kiro OpenAI translator that caused "Improperly formed request"
errors when processing LiteLLM-translated requests with tool_use/tool_result:

1. Skip merging tool role messages in MergeAdjacentMessages() to preserve
   individual tool_call_id fields

2. Track pendingToolResults and attach to the next user message instead of
   only the last message. Create synthetic user message when conversation
   ends with tool results.

3. Insert synthetic user message with tool results before assistant messages
   to maintain proper alternating user/assistant structure. This fixes the case
   where LiteLLM translates Anthropic user messages containing only tool_result
   blocks into tool role messages followed by assistant.

Adds unit tests covering all tool result handling scenarios.
2025-12-24 15:10:35 +07:00
hkfires 26fbb77901 refactor(sdk/auth): rename manager.go to conductor.go 2025-12-24 15:21:03 +08:00
NguyenSiTrung a277302262 Merge remote-tracking branch 'upstream/main' 2025-12-24 10:54:09 +07:00
NguyenSiTrung 969c1a5b72 refactor: extract parseGeminiFamilyUsageDetail helper to reduce duplication 2025-12-24 10:22:31 +07:00
NguyenSiTrung 872339bceb feat: add cached token parsing for Gemini API responses 2025-12-24 10:20:11 +07:00
Luis Pater 5dc0dbc7aa Merge pull request #697 from Cubence-com/main
docs(readme): add Cubence sponsor and fix PackyCode link
2025-12-24 11:19:32 +08:00
Luis Pater ee6fc4e8a1 Merge pull request #60 from router-for-me/pr-59-resolve-conflicts
v6.6.50(解决 #59 冲突)
2025-12-24 11:12:09 +08:00
Luis Pater 8fee16aecd Merge PR #59: v6.6.50 (resolve conflicts) 2025-12-24 11:06:10 +08:00
Luis Pater 2b7ba54a2f Merge pull request #688 from router-for-me/feature/request-id-tracking
feat(logging): implement request ID tracking and propagation
2025-12-24 10:54:13 +08:00
hkfires 007c3304f2 feat(logging): scope request ID tracking to AI API endpoints 2025-12-24 09:17:09 +08:00
hkfires e76ba0ede9 feat(logging): implement request ID tracking and propagation 2025-12-24 08:32:17 +08:00
Luis Pater c06ac07e23 Merge pull request #686 from ajkdrag/main
feat: regex support for model-mappings
2025-12-24 04:37:44 +08:00
Luis Pater e592a57458 Merge branch 'router-for-me:main' into main 2025-12-24 04:25:06 +08:00
Luis Pater 66769ec657 fix(translators): update role from tool to user in Gemini and Gemini-CLI requests 2025-12-24 04:24:07 +08:00
Luis Pater f413feec61 refactor(handlers): streamline error and data channel handling in streaming logic
Improved consistency across OpenAI, Claude, and Gemini handlers by replacing initial `select` statement with a `for` loop for better readability and error-handling robustness.
2025-12-24 04:07:24 +08:00
Luis Pater 2e538e3486 Merge pull request #661 from jroth1111/fix/streaming-bootstrap-forwarder
fix: improve streaming bootstrap and forwarding
2025-12-24 03:51:40 +08:00
Luis Pater 9617a7b0d6 Merge pull request #621 from dacsang97/fix/antigravity-prompt-caching
Antigravity Prompt Caching Fix
2025-12-24 03:50:25 +08:00
Luis Pater 7569320770 Merge branch 'dev' into fix/antigravity-prompt-caching 2025-12-24 03:49:46 +08:00
Fetters 8d25cf0d75 fix(readme): update PackyCode sponsorship link and remove redundant tbody 2025-12-23 23:44:40 +08:00
Fetters 64e85e7019 docs(readme): add Cubence sponsor 2025-12-23 23:30:57 +08:00
Luis Pater a862984dca Merge pull request #58 from router-for-me/plus
v6.6.48
2025-12-23 22:34:15 +08:00
Luis Pater f0365f0465 Merge branch 'main' into plus 2025-12-23 22:34:08 +08:00
Luis Pater 6d1e20e940 fix(claude_executor): update header logic for API key handling
Refined header assignment to use `x-api-key` for Anthropic API requests, ensuring correct authorization behavior based on request attributes and URL validation.
2025-12-23 22:30:25 +08:00
altamash 0c0aae1eac Robust change detection: replaced string concat with struct-based compare in hasModelMappingsChanged; removed boolTo01.
•  Performance: pre-allocate map and regex slice capacities in UpdateMappings.
   •  Verified with amp module tests (all passing)
2025-12-23 18:52:28 +05:30
altamash 5dcf7cb846 feat: regex support for model-mappings 2025-12-23 18:41:58 +05:30
Joao 349b2ba3af refactor: improve error handling and code quality
- Handle errors in promptInput instead of ignoring them
- Improve promptSelect to provide feedback on invalid input and re-prompt
- Use sentinel errors (ErrAuthorizationPending, ErrSlowDown) instead of
  string-based error checking with strings.Contains
- Move hardcoded x-amz-user-agent header to idcAmzUserAgent constant

Addresses code review feedback from Gemini Code Assist.
2025-12-23 10:20:14 +00:00
Joao 98db5aabd0 feat: persist refreshed IDC tokens to auth file
Add persistRefreshedAuth function to write refreshed tokens back to the
auth file after inline token refresh. This prevents repeated token
refreshes on every request when the token expires.

Changes:
- Add persistRefreshedAuth() to kiro_executor.go
- Call persist after all token refresh paths (401, 403, pre-request)
- Remove unused log import from sdk/auth/kiro.go
2025-12-23 10:00:14 +00:00
Luis Pater e52b542e22 Merge pull request #684 from packyme/main
docs(readme): add PackyCode sponsor
2025-12-23 17:19:25 +08:00
SmallL-U 8f6abb8a86 fix(readme): correct closing tbody tag 2025-12-23 17:17:57 +08:00
SmallL-U ed8eaae964 docs(readme): add PackyCode sponsor 2025-12-23 17:11:34 +08:00
Joao 7fd98f3556 feat: add IDC auth support with Kiro IDE headers 2025-12-23 08:18:10 +00:00
Luis Pater e8de87ee90 Merge branch 'router-for-me:main' into main 2025-12-23 08:48:29 +08:00
Luis Pater 4e572ec8b9 fix(translators): handle string system instructions in Claude translators
Updated Antigravity, Gemini, and Gemini-CLI translators to process `systemResult` of type `string` for system instructions. Ensures properly formatted JSON with dynamic content assignment.
2025-12-23 08:44:36 +08:00
Luis Pater 6c7f18c448 Merge branch 'router-for-me:main' into main 2025-12-23 03:50:35 +08:00
Luis Pater 24bc9cba67 Fixed: #639
fix(antigravity): validate function arguments before serialization

Ensure `function.arguments` is a valid JSON before setting raw bytes, fallback to setting as parameterized content if invalid.
2025-12-23 03:49:45 +08:00
Luis Pater 97356b1a04 Merge branch 'router-for-me:main' into main 2025-12-23 03:17:44 +08:00
Luis Pater 1084b53fba Fixed: #655
refactor(antigravity): clean up tool key filtering and improve signature caching logic
2025-12-23 03:16:51 +08:00
Luis Pater b1aecc2bf1 Merge branch 'router-for-me:main' into main 2025-12-23 02:49:37 +08:00
Luis Pater 83b90e106f refactor(antigravity): add sandbox URL constant and update base URLs routine 2025-12-23 02:47:56 +08:00
Luis Pater f52114dab2 Merge branch 'router-for-me:main' into main 2025-12-23 02:26:33 +08:00
Luis Pater 5106caf641 Fixed: #654
feat: handle array input for system instructions in translators

Enhanced Gemini, Gemini-CLI, and Antigravity translators to process array content for system instructions. Adds support for assigning roles and handling multiple content parts dynamically.
2025-12-23 02:24:26 +08:00
Luis Pater 12370ee84e Merge branch 'router-for-me:main' into main 2025-12-22 22:53:29 +08:00
Luis Pater b84ccc6e7a feat: add unit tests for routing strategies and implement dynamic selector updates
Added comprehensive tests for `FillFirstSelector` and `RoundRobinSelector` to ensure proper behavior, including deterministic, cyclical, and concurrent scenarios. Introduced dynamic routing strategy updates in `service.go`, normalizing strategies and seamlessly switching between `fill-first` and `round-robin`. Updated `Manager` to support selector changes via the new `SetSelector` method.
2025-12-22 22:52:23 +08:00
Luis Pater e19ddb53e7 Merge pull request #663 from jroth1111/feat/fill-first-selector
feat: add fill-first routing strategy
2025-12-22 22:26:32 +08:00
gwizz 5bf89dd757 fix: keep streaming defaults legacy-safe 2025-12-23 00:53:18 +11:00
gwizz 2a0100b2d6 docs: add routing strategy example 2025-12-23 00:39:18 +11:00
gwizz 4442574e53 fix: stop streaming loop on context cancel 2025-12-23 00:37:55 +11:00
gwizz c020fa60d0 fix: keep round-robin as default routing 2025-12-22 23:39:41 +11:00
gwizz b078be4613 feat: add fill-first routing strategy 2025-12-22 23:38:10 +11:00
gwizz 71a6dffbb6 fix: improve streaming bootstrap and forwarding 2025-12-22 23:34:23 +11:00
Luis Pater 5f65dd5bb4 Merge branch 'router-for-me:main' into main 2025-12-22 16:58:26 +08:00
Luis Pater 27b43ed63f Merge pull request #658 from moxi000/fix-responses-convert
Fix responses-format handling for chat completions(Support Cursor)
2025-12-22 16:47:46 +08:00
moxi f6a3a1d0ba Remove compat test under translator per review 2025-12-22 16:44:50 +08:00
moxi 830fd8eac2 Fix responses-format handling for chat completions 2025-12-22 13:54:02 +08:00
Luis Pater a86d501dc2 refactor: replace json.Marshal and json.Unmarshal with sjson and gjson
Optimized the handling of JSON serialization and deserialization by replacing redundant `json.Marshal` and `json.Unmarshal` calls with `sjson` and `gjson`. Introduced a `marshalJSONValue` utility for compact JSON encoding, improving performance and code simplicity. Removed unused `encoding/json` imports.
2025-12-22 11:44:06 +08:00
Evan Nguyen 24e8e20b59 Merge branch 'main' into fix/antigravity-prompt-caching 2025-12-21 19:43:24 +07:00
Luis Pater e755e567ea Merge branch 'router-for-me:main' into main 2025-12-21 19:54:13 +08:00
Evan Nguyen a87f09bad2 feat(antigravity): add session ID generation and mutex for random source 2025-12-21 17:50:41 +07:00
Luis Pater dbcbe48ead Merge pull request #641 from router-for-me/url-OAuth-add-ter
OAuth and management
2025-12-21 17:25:24 +08:00
Luis Pater 63908869f6 Merge pull request #611 from soilSpoon/feature/antigravity
feat(antigravity): Improve Claude model compatibility
2025-12-21 16:27:29 +08:00
Luis Pater db491c8f9b Merge branch 'router-for-me:main' into main 2025-12-21 16:19:04 +08:00
Luis Pater f6d625114c feat(logging): revamp request logger to support streaming and temporary file spooling
This update enhances the `FileRequestLogger` by introducing support for spooling large request and response bodies to temporary files, reducing memory consumption. It adds atomic requestLogID generation for sequential log naming and new methods for non-streaming/streaming log assembly. Also includes better error handling during logging and temp file cleanups.
2025-12-21 16:17:48 +08:00
이대희 7dc40ba6d4 Improve tool-call parsing, schema sanitization, and hint injection
Improve parsing of tool call inputs and Antigravity compatibility to avoid invalid thinking/tool_use errors.

- Parse tool call inputs robustly by accepting both object and JSON-string formats and only produce a functionCall part when valid args exist, reducing spurious or malformed parts.
- Preserve the skip_thought_signature_validator approach for calls without a valid thinking signature but stop toggling/tracking a separate "disable thinking" flag; this prevents unnecessary removal of thinkingConfig.
- Sanitize tool input schemas before attaching them to the Antigravity request to improve compatibility.
- Append the interleaved-thinking hint as a new parts entry instead of overwriting/setting text directly, preserving structure.
- Remove unused tracking logic and related comments to simplify flow.

These changes reduce errors related to missing/invalid thinking signatures, improve schema compatibility, and make hint injection safer and more consistent.
2025-12-21 17:16:40 +09:00
Luis Pater fcd6475377 Merge pull request #646 from router-for-me/amp
fix(amp): add /settings routes to proxy
2025-12-21 15:57:41 +08:00
이대희 4070c9de81 Remove interleaved-thinking header from requests
Removes the addition of the "anthropic-beta: interleaved-thinking-2025-05-14" header for Claude thinking models when building HTTP requests.

This prevents sending an experimental/feature flag header that is no longer required and avoids potential compatibility or routing issues with downstream services. Keeps request headers simpler and more standard.
2025-12-21 15:29:36 +09:00
이대희 1e9e4a86a2 Improve thinking/tool signature handling for Claude and Gemini requests
Prefer cached signatures and avoid injecting dummy thinking blocks; instead remove unsigned thinking blocks and add a skip sentinel for tool calls without a valid signature. Generate stable session IDs from the first user message, apply schema cleaning only for Claude models, and reorder thinking parts so thinking appears first. For Gemini, remove thinking blocks and attach a skip sentinel to function calls. Simplify response handling by passing raw function args through (remove special Bash conversion). Update and add tests to reflect the new behavior.

These changes prevent rejected dummy signatures, improve compatibility with Antigravity’s signature validation, provide more stable session IDs for conversation grouping, and make request/response translation more robust.
2025-12-21 15:15:50 +09:00
이대희 406a27271a Remove opencode-antigravity-auth submodule
Remove the opencode-antigravity-auth submodule reference from the repository.

Cleans up the project by eliminating an external submodule pointer that is no longer needed or maintained, reducing repository complexity and avoiding dangling submodule state.
2025-12-21 14:54:49 +09:00
이대희 9f9a4fc2af Remove unused submodules
Removes two obsolete git submodules to clean up repository state and reduce maintenance overhead.

This eliminates external references that are no longer needed, simplifying dependency management and repository maintenance going forward.
2025-12-21 14:48:50 +09:00
hkfires 3fc410a253 fix(amp): add /settings routes to proxy 2025-12-21 12:51:35 +08:00
Supra4E8C 781bc1521b fix(oauth): prevent stale session timeouts after login
- stop callback forwarders by instance to avoid cross-session shutdowns
  - clear pending sessions for a provider after successful auth
2025-12-21 10:48:40 +08:00
Supra4E8C 05d201ece8 fix(gemini): gate callback prompt on project_id 2025-12-21 07:21:12 +08:00
Supra4E8C cd0c94f48a fix(sdk/auth): prevent OAuth manual prompt goroutine leak,Use timer-based manual prompt per provider and remove oauth_callback helper. 2025-12-21 07:06:28 +08:00
Luis Pater 293cc8c1a3 Merge branch 'router-for-me:main' into main 2025-12-21 03:39:31 +08:00
Luis Pater 453e744abf Fixed: #642
fix: remove unsupported fields `type` and `cache_control` across translators
2025-12-21 03:38:38 +08:00
Luis Pater 653439698e Fixed: #606
fix: unify response field naming across translators

Standardize `text` to `delta` and add missing `output` field in all response payloads for consistency across OpenAI, Claude, and Gemini translators.
2025-12-21 03:13:58 +08:00
Supra4E8C 24970baa57 management: allow prefix updates in provider PATCH handlers 2025-12-21 02:14:28 +08:00
Luis Pater 5418bbc338 Merge branch 'router-for-me:main' into main 2025-12-20 23:40:09 +08:00
Luis Pater 89254cfc97 Merge pull request #638 from neokotora/feat/add-gemini-3-flash
fix: add gemini-3-flash-preview model definition in GetGeminiModels
2025-12-20 23:36:57 +08:00
Luis Pater 6bd9a034f7 Merge pull request #602 from ben-vargas/fix-antigravity-propertynames
fix: remove propertyNames from JSON schema for Gemini compatibility
2025-12-20 23:32:51 +08:00
Luis Pater 26fc65b051 Merge pull request #633 from ben-vargas/fix-antigravity-applypayloadconfig
feat(antigravity): add payload config support to Antigravity executor
2025-12-20 23:30:47 +08:00
Luis Pater ed5ec5b55c feat(amp): enhance model mapping and Gemini thinking configuration
This commit introduces several improvements to the AMP (Advanced Model Proxy) module:

- **Model Mapping Logic:** The `FallbackHandler` now uses a more robust approach for model mapping. It includes the extraction and preservation of dynamic "thinking suffixes" (e.g., `(xhigh)`) during mapping, ensuring that these configurations are correctly applied to the mapped model. A new `resolveMappedModel` function centralizes this logic for cleaner code.
- **ModelMapper Verification:** The `ModelMapper` in `model_mapping.go` now verifies that the target model of a mapping has available providers *after* normalizing it. This prevents mappings to non-existent or unresolvable models.
- **Gemini Thinking Configuration Cleanup:** In `gemini_thinking.go`, unnecessary `generationConfig.thinkingConfig.include_thoughts` and `generationConfig.thinkingConfig.thinkingBudget` fields are now deleted from the request body when applying Gemini thinking levels. This prevents potential conflicts or redundant configurations.
- **Testing:** A new test case `TestModelMapper_MapModel_TargetWithThinkingSuffix` has been added to `model_mapping_test.go` to specifically cover the preservation of thinking suffixes during model mapping.
2025-12-20 22:19:35 +08:00
sheauhuu df777650ac feat: add gemini-3-flash-preview model definition in GetGeminiModels 2025-12-20 20:05:20 +08:00
Supra4E8C 9855615f1e fix(gemini): avoid stale manual oauth prompt and accept schemeless callbacks 2025-12-20 19:03:38 +08:00
Finessse e23e0fb137 chore(scripts): Add Python Scripts path to start-cliproxy.ps1 2025-12-20 18:02:01 +07:00
Finessse 00b8fc07cf refactor(memory): Expose SessionDir in FileStore 2025-12-20 18:01:36 +07:00
Supra4E8C 93414f1baa feat (auth): CLI OAuth supports pasting callback URLs to complete login
- Added callback URL resolution and terminal prompt logic
  - Codex/Claude/iFlow/Antigravity/Gemini login supports callback URL or local callback completion
  - Update Gemini login option signature and manager call
  - CLI default prompt function is compatible with null input to continue waiting
2025-12-20 18:25:55 +08:00
Luis Pater 8fac6b147a Merge branch 'router-for-me:main' into main 2025-12-20 17:13:30 +08:00
Luis Pater 10f8c795ac Merge pull request #634 from router-for-me/amp
fix(amp): add /docs routes to proxy
2025-12-20 17:08:07 +08:00
Finessse 5f118810a9 docs: add memory rate limits and export limits 2025-12-20 15:49:29 +07:00
Finessse 7be4b683d7 webui: add memory export-all and semantic toggle 2025-12-20 15:49:04 +07:00
Finessse 98917aa3eb logging: redact sensitive fields in bodies 2025-12-20 15:48:39 +07:00
Finessse 5c464f116f management: add semantic health, toggles, export-all 2025-12-20 15:48:13 +07:00
Finessse 1a405d7976 middleware: add rate limits and semantic truncation 2025-12-20 15:47:50 +07:00
Finessse 9fa18f5c8b memory: add semantic stats, cache, and namespace listing 2025-12-20 15:47:30 +07:00
Finessse 57eae651d3 docs: document heuristic anchors and memory 2025-12-20 15:01:44 +07:00
Finessse f56cfdd6a2 webui: add memory management panel 2025-12-20 15:01:24 +07:00
Finessse ff7088ee8f management: add memory endpoints 2025-12-20 15:01:05 +07:00
Finessse d96d9e0b8e middleware: update agentic memory pipeline 2025-12-20 15:00:46 +07:00
Finessse d9b9863dab memory: extend store with anchors, semantic, pruning 2025-12-20 15:00:27 +07:00
Luis Pater 3e4858a624 feat(config): add log file size limit configuration #535
This commit introduces a new configuration option `logs-max-total-size-mb` that allows users to set a maximum total size (in MB) for log files in the logs directory. When this limit is exceeded, the oldest log files will be automatically deleted to stay within the specified size. Setting this value to 0 (the default) disables this feature. This change enhances log management by preventing excessive disk space usage.
2025-12-20 15:52:59 +08:00
Ben Vargas 1231dc9cda feat(antigravity): add payload config support to Antigravity executor
Add applyPayloadConfig calls to all Antigravity executor paths (Execute,
executeClaudeNonStream, ExecuteStream) to enable config.yaml payload
overrides for Antigravity/Gemini-Claude models.

This allows users to configure thinking budget and other parameters via
payload.override in config.yaml for models like gemini-claude-opus-4-5*.
2025-12-19 22:30:44 -07:00
hkfires c84ff42bcd fix(amp): add /docs routes to proxy 2025-12-20 10:15:25 +08:00
Finessse 3b4b44d113 chore: Update the example management secret key and remove extra blank lines from the config.example.yaml. 2025-12-20 06:12:40 +07:00
Finessse ed9c9c8ec6 chore: add health check wrapper 2025-12-20 06:11:27 +07:00
Finessse e4ac6390f5 chore: improve health check script 2025-12-20 06:09:59 +07:00
Finessse b0989c08cd chore: add health check script 2025-12-20 06:08:10 +07:00
Finessse d44aadd1fc fix: address local UI guard and example executor 2025-12-20 06:03:11 +07:00
Finessse 348609a93f feat: merge management UI into app 2025-12-20 05:58:35 +07:00
Finessse 33cf877a15 feat: add scaffolded prompt state and semantic memory 2025-12-20 05:58:08 +07:00
Finessse 40722131ee feat: add agentic harness middleware 2025-12-20 05:47:56 +07:00
Finessse e505267093 chore: remove temporary reproduction scripts
Deletes repro_merge.go and test_gjson.go which were likely used for debugging or testing during development.
2025-12-20 04:02:08 +07:00
Finessse ae506ce66e feat(api): add AgenticHarnessMiddleware for long-running agent support
Implements a new middleware to handle agentic headers and dynamically inject system prompts for 'Initializer' and 'Coding' agents. Also registers this middleware in the server setup.
2025-12-20 04:01:32 +07:00
Finessse 8da2bae873 docs: add troubleshooting entry for rate limit rotation fix 2025-12-20 04:00:11 +07:00
Finessse 406f8849b0 fix(auth): correct 429 state propagation to model states
Fixes a critical bug where rate limit errors were only updating the parent Auth object and not the specific ModelState. This caused the selector to incorrectly view the model as active and retry the same account immediately. Also hardens the selector to respect timestamps even if availability flags are desynchronized.
2025-12-20 03:59:59 +07:00
Finessse a31a7eac0c feat(executor): parse Retry-After headers in antigravity executor
Currently, the executor ignores upstream retry-after headers, causing the manager to default to a 1s backoff. This change parses standard HTTP Retry-After headers (seconds or date) and passes them to the error handler.
2025-12-20 03:59:41 +07:00
Luis Pater 40d78908ed Merge branch 'router-for-me:main' into main 2025-12-20 04:50:39 +08:00
Luis Pater 8a5db02165 Fixed: #607
refactor(config): re-export internal configuration types for SDK consumers
2025-12-20 04:49:02 +08:00
Finessse e76aacf5ec feat(executor): enhance Antigravity executor and handlers
- Add improvements to antigravity_executor.go for better CLI communication
- Update handlers.go with additional helper functions
2025-12-20 02:25:56 +07:00
Finessse f019f43879 feat(middleware): add Claude Code CLI support and diagnostic headers
- Add claude-cli detection to isAgenticCLI and mustKeepTools checks
- Add /v1/messages Claude Messages API format support
- Implement trimClaudeMessagesWithMemory with tool_use/tool_result adjacency preservation
- Add extractLastUserTextFromClaude, extractTextFromClaudeMessage, truncateClaudeMessageContent helpers
- Add claude case to prependToLastUserText, appendToLastUserText, extractPinnedContext
- Add response headers for localhost diagnostics:
  - X-ProxyPilot-Session: session ID
  - X-ProxyPilot-Request-Shape: detected format (chat/responses/claude)
  - X-ProxyPilot-Memory-Stored: dropped message count
  - X-ProxyPilot-Memory-Retrieved: injected snippet count
2025-12-20 02:24:56 +07:00
Luis Pater 56fa81f3c6 Merge branch 'router-for-me:main' into main 2025-12-20 03:12:35 +08:00
Luis Pater d7afb6eb0c fix(gemini): improve reasoning effort conversion for Gemini 3 models
Refactors the reasoning effort conversion logic for Gemini models.
The update specifically addresses how `reasoning_effort` is translated into Gemini 3 specific thinking configurations (`thinkingLevel`, `includeThoughts`) and ensures that numeric budgets are not incorrectly applied to level-based models.

Changes include:
- Differentiating conversion logic for Gemini 3 models versus other models.
- Handling `none`, `auto`, and validated thinking levels for Gemini 3.
- Maintaining existing conversion for models not using discrete thinking levels.
2025-12-20 03:11:28 +08:00
Finessse 035da8b358 docs: add troubleshooting antigravity guide 2025-12-20 00:31:02 +07:00
Finessse 82f2a5d7be misc: add reproduction scripts 2025-12-20 00:30:39 +07:00
Finessse b6de9e41d7 chore: ignore root logs and output files 2025-12-20 00:30:21 +07:00
Finessse 2e21fb75d5 fix(gemini-vertex): append api key to url query params 2025-12-20 00:29:57 +07:00
Finessse d7d1d06451 fix(gemini): merge consecutive same-role messages in openai translator 2025-12-20 00:25:41 +07:00
Finessse 88224aab1a fix(gemini): append api key to url query params 2025-12-20 00:25:08 +07:00
Luis Pater 03209b35c0 Merge branch 'router-for-me:main' into main 2025-12-20 00:02:07 +08:00
Luis Pater bbd1fe890a Merge pull request #598 from BigUncle/fix/token-refresh-loop
fix(auth): prevent token refresh loop by ignoring timestamp fields
2025-12-19 23:59:40 +08:00
Luis Pater 843316ea7a Merge branch 'router-for-me:main' into main 2025-12-19 22:24:26 +08:00
Luis Pater f607231efa Merge pull request #627 from router-for-me/gemini
fix(gemini): add optional skip for gemini3 thinking conversion
2025-12-19 22:20:51 +08:00
hkfires 2039062845 fix(gemini): add optional skip for gemini3 thinking conversion 2025-12-19 22:07:43 +08:00
Finessse 0c4c7556c9 feat(webui): add core UI implementation and utilities 2025-12-19 19:17:34 +07:00
Finessse 377e92542e feat(webui): add src assets 2025-12-19 19:15:49 +07:00
Finessse 17a18845a8 feat(webui): add public assets 2025-12-19 19:15:39 +07:00
Finessse f107680796 chore(webui): add configuration files and root assets 2025-12-19 19:15:24 +07:00
Finessse 87d14940a7 chore(webui): add package.json and lockfile 2025-12-19 19:10:39 +07:00
Finessse e21b21b187 chore(webui): add gitignore 2025-12-19 18:26:31 +07:00
Finessse 2913fb220a docs: add WARP documentation 2025-12-19 18:21:34 +07:00
Finessse b23106ee91 chore: update docker-compose and go.mod 2025-12-19 18:20:03 +07:00
Finessse e0a7f37d2d feat(scripts): add letta setup script 2025-12-19 18:19:07 +07:00
Finessse 607abf2338 feat(sdk): update cliproxy auth and service modules 2025-12-19 18:18:48 +07:00
Finessse b8f6781bb8 feat(runtime): update executor and runtime internals 2025-12-19 18:18:40 +07:00
Finessse ba2f9121ae docs: update documentation files 2025-12-19 18:18:24 +07:00
Finessse a782c70d47 feat(tray): update cliproxytray window and command handlers 2025-12-19 18:17:00 +07:00
Finessse 2413b8de46 docs: update README 2025-12-19 18:16:44 +07:00
Luis Pater 44f66d2257 Merge PR #55 2025-12-19 18:59:12 +08:00
Luis Pater 99478d13a8 Merge pull request #623 from router-for-me/remote-OAuth
Remote OAuth
2025-12-19 18:29:09 +08:00
Luis Pater 3b51a0fe12 Merge pull request #54 from StriveMario/fix/kiro-config-synthesis
add missing Kiro config synthesis
2025-12-19 18:25:02 +08:00
Mario 2d91c2a3f5 add missing Kiro config synthesis 2025-12-19 18:13:15 +08:00
Finessse b8866d91e7 fix(scripts): change default proxy port from 8317 to 8318 in droid setup 2025-12-19 16:58:57 +07:00
evann bc6c4cdbfc feat(antigravity): add logging for cached token setting errors in responses 2025-12-19 16:49:50 +07:00
Luis Pater 69d3a80fc3 Merge pull request #618 from router-for-me/amp
fix(amp): add management auth skipper
2025-12-19 17:37:51 +08:00
evann 404546ce93 refactor(antigravity): regarding production endpoint caching 2025-12-19 16:36:54 +07:00
Luis Pater 9e268ad103 Merge pull request #619 from router-for-me/gemini
fix(util): disable default thinking for gemini 3 flash
2025-12-19 17:36:52 +08:00
evann 6dd1cf1dd6 Merge branch 'main' into fix/antigravity-prompt-caching 2025-12-19 16:34:28 +07:00
evann 9058d406a3 feat(antigravity): enhance prompt caching support and update agent version 2025-12-19 16:33:41 +07:00
hkfires 9d9b9e7a0d fix(amp): add management auth skipper 2025-12-19 13:57:47 +08:00
hkfires 13aa82f3f3 fix(util): disable default thinking for gemini 3 flash 2025-12-19 13:11:15 +08:00
Luis Pater 4ea5586b6f Merge branch 'router-for-me:main' into main 2025-12-19 12:40:41 +08:00
Luis Pater 05e55d7dc5 feat(codex): update gpt-5.2 codex prompt instructions
The prompt for the gpt-5.2 codex model has been updated with more comprehensive instructions. This includes detailed guidelines on general usage, editing constraints, the plan tool, sandboxing configurations, handling special user requests, frontend task considerations, and final message presentation. The updates aim to improve the model's understanding and execution of complex coding tasks by providing clearer directives and constraints.
2025-12-19 12:38:28 +08:00
Supra4E8C 1b358c931c fix: restore get-auth-status ok fallback and document it 2025-12-19 12:15:22 +08:00
이대희 e04b02113a refactor: Improve cache eviction ordering and clean up session ID usage
Improve the cache eviction routine to sort entries by timestamp using the standard library sort routine (stable, clearer and faster than the prior manual selection/bubble logic), and remove a redundant request-derived session ID helper in favor of the centralized session ID function. Also drop now-unused crypto/encoding imports.

This yields clearer, more maintainable eviction logic and removes duplicated/unused code and imports to reduce surface area and potential inconsistencies.
2025-12-19 13:14:51 +09:00
이대희 3275494fde refactor: Use helper to extract wrapped "thinking" text
Improve robustness when handling "thinking" content by using a dedicated helper to extract the thinking text. This ensures wrapped or nested thinking objects are handled correctly instead of relying on a direct string extraction, reducing parsing errors for complex payloads.
2025-12-19 13:09:57 +09:00
Luis Pater e3af8783b9 Merge branch 'router-for-me:main' into main 2025-12-19 11:40:52 +08:00
Luis Pater ca09db21ff feat(codex): add gpt-5.2 codex prompt handling
This change introduces specific logic to load and use instructions for the 'gpt-5.2-codex' model variant by recognizing the 'gpt-5.2-codex_prompt.md' filename. This ensures the correct prompts are used when the '5.2-codex' model is identified, complementing the recent addition of its definition.
2025-12-19 11:39:51 +08:00
이대희 c1f8211acb fix: Normalize Bash tool args and add signature caching support
Normalize Bash tool arguments by converting a "command" key into "cmd" using JSON-aware parsing, avoiding brittle string replacements that could corrupt values. Apply this conversion in both streaming and non-streaming response paths so bash-style tool calls are emitted with the expected "cmd" field.

Add support for accumulating thinking text and carrying session identifiers to enable signature caching/restore for unsigned thinking blocks, improving handling of thinking-state continuity across requests/responses.

Also perform small cleanups: import logging, tidy comments and test descriptions. These changes make tool-argument handling more robust and enable reliable signature restoration for thinking blocks.
2025-12-19 11:12:16 +09:00
Chén Mù 718ff7a73f Merge pull request #609 from router-for-me/codex
feat(registry): add gpt 5.2 codex model definition
2025-12-19 09:54:34 +08:00
hkfires fa70b220e9 feat(registry): add gpt 5.2 codex model definition 2025-12-19 09:53:03 +08:00
이대희 98fa2a1597 feat(translator/antigravity/claude): support interleaved thinking, signature restoration and system hint injection 2025-12-19 10:30:59 +09:00
이대희 0e7c79ba23 feat(translator/antigravity/claude): support interleaved thinking, signature restoration and system hint injection 2025-12-19 10:28:25 +09:00
이대희 b6ba15fcbd fix(runtime/executor): Antigravity executor schema handling and Claude-specific headers 2025-12-19 10:28:23 +09:00
이대희 e44167d7a4 refactor(util/schema): rename and extend Gemini schema cleaning for Antigravity and add empty-schema placeholders 2025-12-19 10:28:17 +09:00
이대희 1bfa75f780 feat(util): add helper to detect Claude thinking models 2025-12-19 10:28:15 +09:00
이대희 bbcb5552f3 feat(cache): add signature cache for Claude thinking blocks 2025-12-19 10:28:12 +09:00
이대희 31bd90c748 feature: Improves Amp client compatibility
Ensures compatibility with the Amp client by suppressing
"thinking" blocks when "tool_use" blocks are also present in
the response.

The Amp client has issues rendering both types of blocks
simultaneously. This change filters out "thinking" blocks in
such cases, preventing rendering problems.
2025-12-19 08:18:27 +09:00
Ben Vargas 1b8cb7b77b fix: remove propertyNames from JSON schema for Gemini compatibility
Gemini API does not support the JSON Schema `propertyNames` keyword,
causing 400 errors when Claude tool schemas containing this field are
proxied through the Antigravity provider.

Add `propertyNames` to the list of unsupported keywords removed by
CleanJSONSchemaForGemini(), alongside existing removals like $ref,
definitions, and additionalProperties.
2025-12-18 12:50:51 -07:00
Luis Pater 774f1fbc17 Merge pull request #586 from router-for-me/chore
chore: ignore gemini metadata files
2025-12-19 01:00:30 +08:00
Supra4E8C cfa8ddb59f feat(oauth): add remote OAuth callback support with session management
Introduce a centralized OAuth session store with TTL-based expiration
  to replace the previous simple map-based status tracking. Add a new
  /api/oauth/callback endpoint that allows remote clients to relay OAuth
  callback data back to the CLI proxy, enabling OAuth flows when the
  callback cannot reach the local machine directly.

  - Add oauth_sessions.go with thread-safe session store and validation
  - Add oauth_callback.go with POST handler for remote callback relay
  - Refactor auth_files.go to use new session management APIs
  - Register new callback route in server.go
2025-12-19 00:38:29 +08:00
BigUncleandClaude 39597267ae fix(auth): prevent token refresh loop by ignoring timestamp fields
Add metadataEqualIgnoringTimestamps() function to compare metadata JSON
without timestamp/expired/expires_in/last_refresh/access_token fields.
This prevents unnecessary file writes when only these fields change
during refresh, breaking the fsnotify event → Watcher callback → refresh loop.

Key insight: Google OAuth returns a new access_token on each refresh,
which was causing file writes and triggering the refresh loop.

Fixes antigravity channel excessive log generation issue.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-18 21:37:05 +08:00
Finessse 15a2aa92ad models: add gemini-3-flash across providers 2025-12-18 19:31:20 +07:00
Finessse b914a84e72 proxypilot: add Control Center UI and simplify tray menu 2025-12-18 18:45:10 +07:00
Finessse 57473ec3c6 proxypilot: default management UI language to en 2025-12-18 18:25:06 +07:00
Finessse cacd2301b3 proxypilot: fix tray defaults when launched from bin 2025-12-18 18:12:20 +07:00
Finessse 4807312802 scripts: rebrand messages to ProxyPilot 2025-12-18 17:55:39 +07:00
Finessse 6e466e9823 readme: position ProxyPilot as Windows app 2025-12-18 17:55:29 +07:00
Finessse 3e0aac0a9c proxypilot: polish helper UI strings 2025-12-18 17:55:20 +07:00
Finessse dd83e3ae2c cliproxy: register executors after auth load 2025-12-18 17:55:11 +07:00
Finessse 39a5a0ac24 proxypilot: add localhost thinking proxy on :8317 2025-12-18 17:39:26 +07:00
Finessse 654f48dc9a docs: rebrand CLIProxyAPI to ProxyPilot 2025-12-18 17:28:48 +07:00
Finessse 60c270bd56 proxypilot: rename engine binary to proxypilot-engine 2025-12-18 17:26:54 +07:00
Finessse c2118c28c9 proxypilot: prefer proxypilot-engine + renamed launcher logs 2025-12-18 17:20:25 +07:00
Finessse f022b151c2 openai: return JSON error envelopes 2025-12-18 16:49:45 +07:00
Finessse 428b1f04c1 server: decompress gzip request bodies 2025-12-18 16:49:37 +07:00
Finessse 626f501f49 droid: map custom: model ids to real model names 2025-12-18 16:32:08 +07:00
Finessse 893c43ae30 agentic: preserve tool call/result pairs when trimming chat payloads 2025-12-18 16:12:01 +07:00
Finessse 423e24211a gemini: add gemini-3-pro-low-preview limits 2025-12-18 15:56:48 +07:00
Finessse cd1a61a8a5 antigravity: populate token limits for /v1/models 2025-12-18 15:56:40 +07:00
Finessse 35e139bb3d models: always include context_length and max_completion_tokens in /v1/models 2025-12-18 15:56:33 +07:00
Finessse 358f7a6439 codex: synth SSE for huge/compaction responses with MAX_TOKENS retry 2025-12-18 14:18:28 +07:00
Finessse 9812ab3fb4 docs: update ProxyPilot and gemini-3 provider preference 2025-12-18 14:18:05 +07:00
Finessse 99eb979353 models: add gemini-3-flash and gemini-3-pro-low (antigravity) 2025-12-18 14:17:57 +07:00
Finessse 24edfc63ff proxypilot: tray OAuth helpers and in-app WebView2 dashboard 2025-12-18 14:17:44 +07:00
Finessse 70dd0cd283 api: add ProxyPilot local dashboard and diagnostics endpoints 2025-12-18 14:17:36 +07:00
Finessse c3b058a7af desktopctl: persist ProxyPilot state and management key 2025-12-18 14:17:27 +07:00
hkfires 393e38f2c0 chore: ignore gemini metadata files 2025-12-18 13:18:15 +08:00
Luis Pater 0f646800f6 Merge branch 'router-for-me:main' into main 2025-12-18 08:36:59 +08:00
Luis Pater ca993238f3 Merge pull request #42 from Ravens2121/master
feat(kiro): 新增授权码登录流程,优化邮箱获取与官方 Thinking 模式解析 预支持
2025-12-18 08:36:27 +08:00
Luis Pater d1220de02d chore(docs): remove legacy documentation and unused PR workflow file 2025-12-18 08:21:58 +08:00
Ravens2121andAmp cf9a246d53 feat(kiro): 新增 AWS Builder ID 授权码流程认证及用户邮箱获取增强
Amp-Thread-ID: https://ampcode.com/threads/T-019b2ecc-fb2d-713f-b30d-1196c7dce3e2
Co-authored-by: Amp <amp@ampcode.com>
2025-12-18 08:16:52 +08:00
Luis Pater 13eb5268de Merge pull request #582 from ben-vargas/fix-gemini-3-thinking-level
feat: use thinkingLevel for Gemini 3 models per Google documentation
2025-12-18 07:19:37 +08:00
Ben Vargas 88798816f2 fix: require dot in gemini25Pattern regex for precise matching 2025-12-17 16:09:50 -07:00
Ben Vargas 598f0af19b fix: apply thinkingLevel from model suffix metadata for Gemini 3
The previous commit added thinkingLevel support but didn't apply it
when the reasoning effort came from model name suffix (e.g., model(minimal)).

This was because ResolveThinkingConfigFromMetadata returns nil for
level-based models, bypassing the metadata application.

Changes:
- Add ApplyGemini3ThinkingLevelFromMetadata for standard Gemini API
- Add ApplyGemini3ThinkingLevelFromMetadataCLI for CLI API format
- Update gemini_cli_executor to apply Gemini 3 thinkingLevel from metadata
- Update antigravity_executor to apply Gemini 3 thinkingLevel from metadata
- Update aistudio_executor to apply Gemini 3 thinkingLevel from metadata
- Add comprehensive test coverage for Gemini 3 thinkingLevel functions
2025-12-17 16:08:38 -07:00
Ben Vargas a33f5d31fc feat: use thinkingLevel for Gemini 3 models per Google documentation
Per Google's official documentation, Gemini 3 models should use
thinkingLevel (string) instead of thinkingBudget (number) for
optimal performance.

From Google's Gemini Thinking docs:
> Use the thinkingLevel parameter with Gemini 3 models. While
> thinkingBudget is accepted for backwards compatibility, using
> it with Gemini 3 Pro may result in suboptimal performance.

Changes:
- Add model family detection functions (IsGemini3Model, IsGemini25Model,
  IsGemini3ProModel, IsGemini3FlashModel)
- Add ApplyGeminiThinkingLevel and ApplyGeminiCLIThinkingLevel functions
  for applying thinkingLevel config
- Add ValidateGemini3ThinkingLevel for model-specific level validation
- Add ThinkingBudgetToGemini3Level for backward compatibility conversion
- Update NormalizeGeminiThinkingBudget to convert budget to level for
  Gemini 3 models
- Update ApplyDefaultThinkingIfNeeded to not set a default level for
  Gemini 3 (lets API use its dynamic default "high")
- Update ConvertThinkingLevelToBudget to preserve thinkingLevel for
  Gemini 3 models
- Add Levels field to all Gemini 3 model definitions:
  - Gemini 3 Pro: ["low", "high"]
  - Gemini 3 Flash: ["minimal", "low", "medium", "high"]

Backward compatibility:
- Gemini 2.5 models continue to use thinkingBudget as before
- If thinkingBudget is provided for Gemini 3, it's converted to the
  appropriate thinkingLevel
- Existing configurations continue to work
2025-12-17 15:28:20 -07:00
Ravens2121 54acd69e9d Merge branch 'router-for-me:main' into master 2025-12-18 04:39:17 +08:00
Ravens2121 d687ee2777 feat(kiro): implement official reasoningContentEvent and improve metadat 2025-12-18 04:38:22 +08:00
Luis Pater 54c2fefbad Merge branch 'router-for-me:main' into main 2025-12-18 03:29:00 +08:00
Luis Pater 506699fba1 ci(workflows): update pr-test-build workflow 2025-12-18 03:28:23 +08:00
Luis Pater f7b17ee6ec Merge pull request #36 from rezhajulio/feat/gpt-5.2
Add GPT-5.2 model support for GitHub Copilot
2025-12-18 03:16:25 +08:00
Luis Pater 408614c74c Merge branch 'router-for-me:main' into main 2025-12-18 03:13:48 +08:00
Luis Pater 68a27772b3 feat(antigravity): enable token counting via API with resilient routing
Introduces the capability to count tokens for Antigravity-backed requests. This implementation leverages the `countTokens` endpoint of the Antigravity API, replacing the prior unsupported stub.

Key aspects of this update include:

- **API Integration**: Direct integration with the Antigravity `countTokens` API, including necessary request payload translation and authentication.
- **Resilient Infrastructure**: A fallback mechanism has been established, allowing the system to attempt connections across multiple Antigravity base URLs to ensure request success even in the event of temporary service interruptions.
- **Model Aliasing**: Added mappings for `gemini-3-flash` and `gemini-3-flash-preview` to ensure compatibility with the latest model variants.
- **Robust Error Handling**: Comprehensive error handling and logging are in place to manage failures during API interactions.
2025-12-18 03:12:46 +08:00
Ben Vargas de87fb622b docs: add redirect info and disable Pull app auto-sync 2025-12-17 12:06:39 -07:00
Finessse b540106287 docs: rebrand to ProxyPilot with fork attribution 2025-12-18 01:58:36 +07:00
Finessse 3336d15282 management: apply ProxyPilot branding at serve-time 2025-12-18 01:58:28 +07:00
Finessse 6c39925728 proxypilot: rebrand tray and engine labels 2025-12-18 01:58:20 +07:00
Finessse dc17f8f600 proxypilotui: force Edge lang to en-US 2025-12-18 01:47:35 +07:00
Finessse 2151171175 packaging: inno installer + zip, remove legacy ps1 startup 2025-12-18 01:43:26 +07:00
Finessse e2fe9f2403 auth: primary email override, trace headers, and cooldown reset 2025-12-18 01:43:07 +07:00
Finessse a2e1849032 proxypilot: tray UX, desktop UI window, and updater 2025-12-18 01:42:56 +07:00
Finessse 8a570a471b desktopctl: persist auto-start proxy state 2025-12-18 01:42:43 +07:00
Luis Pater 0155a01bb1 Merge pull request #40 from router-for-me/plus
v6.6.24
2025-12-18 01:04:17 +08:00
Luis Pater cfeee5d511 Merge branch 'main' into plus 2025-12-18 01:04:10 +08:00
Luis Pater f27672f6cf feat(antigravity): add Gemini 3 Flash Preview model definition with enhanced capabilities 2025-12-18 01:02:19 +08:00
Luis Pater 28420c14e4 Merge pull request #580 from router-for-me/chore
chore: ignore agent and bmad artifacts
2025-12-18 00:46:25 +08:00
Luis Pater 10e0ea1309 Merge main into pr-39 2025-12-18 00:36:51 +08:00
Luis Pater 0bd221ff41 refactor(antigravity): optimize response handling in Claude model with JSON manipulation 2025-12-17 23:57:41 +08:00
Luis Pater 5fda6f8ef3 feat(antigravity): implement non-streaming execution for Claude model requests 2025-12-17 23:17:11 +08:00
hkfires 9b956f6338 chore: ignore agent and bmad artifacts 2025-12-17 23:15:15 +08:00
Finessse 7bef161e7e packaging: add proxypilotpack (no-ps1 builder) 2025-12-17 21:49:06 +07:00
Finessse 4cc8d086ff docs: add ProxyPilot overview and update memory docs 2025-12-17 21:43:31 +07:00
Finessse c5d64d807a memory: normalize escaped todo/pinned text 2025-12-17 21:31:40 +07:00
Luis Pater 09923f654c feat(antigravity): add streaming support for Claude model requests 2025-12-17 22:16:57 +08:00
Finessse 2f5bb3a501 docs: note caching-friendly packed state 2025-12-17 21:16:06 +07:00
Finessse 34082f2eef middleware: pack state into last user message 2025-12-17 21:15:58 +07:00
Finessse 1d000affec memory: add pinned+summary readers 2025-12-17 21:15:49 +07:00
Finessse 03da5113c3 docs: document persistent todo 2025-12-17 21:01:22 +07:00
Finessse 0a74cf7efb middleware: inject persistent todo 2025-12-17 21:01:14 +07:00
Finessse e1b9fa0a36 memory: add session todo file 2025-12-17 21:01:05 +07:00
Finessse 11b994cd14 memory: anchored summary + pinned context 2025-12-17 20:53:54 +07:00
Finessse 9471a0d9ee docs: add memory + ignore state 2025-12-17 20:45:55 +07:00
Finessse 80e383098f middleware: persist + retrieve trimmed history 2025-12-17 20:45:47 +07:00
Finessse ce03ba863b memory: add file-backed store 2025-12-17 20:45:13 +07:00
Finessse 72be557be8 middleware: keep tools for droid/factory 2025-12-17 20:34:06 +07:00
Finessse d23af0518d middleware: model-aware prompt budget 2025-12-17 20:30:03 +07:00
Finessse efb6965ef3 openai: treat Droid UA as agentic 2025-12-17 20:29:48 +07:00
Finessse e57cfdffb2 openai: inject default Factory tools 2025-12-17 20:29:17 +07:00
Finessse 944f70aedb factory: compact huge droid history + inject instructions 2025-12-17 20:14:01 +07:00
Finessse 1d2a9f6b5e factory: truncate oversized input_text 2025-12-17 20:01:56 +07:00
Finessse 6c3df69ded branding: rename tray app to ProxyPilot 2025-12-17 19:50:37 +07:00
Finessse e7678e4ab8 scripts: build self-extracting tray installer 2025-12-17 19:46:52 +07:00
Finessse 29bb32ccfd tray: GUI build, autostart toggle, packaging 2025-12-17 19:39:57 +07:00
Finessse 932f40b13f cmd: add Windows tray manager 2025-12-17 19:32:58 +07:00
Finessse 1548b30abb openai: convert <tool_call> tags to function_call 2025-12-17 19:25:23 +07:00
Finessse d219b04b69 openai: enforce strict tool args 2025-12-17 19:18:06 +07:00
Finessse 7eeb81293b cmd: add cliproxymgr local UI 2025-12-17 19:11:32 +07:00
Finessse 9bd149e6dd cmd: add cliproxyctl 2025-12-17 19:11:25 +07:00
Finessse 3bff4ed6f1 desktopctl: add process control + healthz 2025-12-17 19:11:18 +07:00
Finessse 206897308f docs: track shared desktop UI spec 2025-12-17 19:02:47 +07:00
Finessse 90b3eabc68 docs: add shared desktop UI spec 2025-12-17 19:02:20 +07:00
Finessse 6f1cb57908 test: cover antigravity strict fallback 2025-12-17 18:13:36 +07:00
Finessse ee8bbb3aa8 auth: strict fallback for antigravity creds 2025-12-17 18:13:28 +07:00
Finessse d8e55c7318 auth: allow probing unknown client model support 2025-12-17 18:02:15 +07:00
Finessse d4c3f6fcad codex: avoid role=system in input 2025-12-17 17:55:17 +07:00
Finessse 7649532c4a codex: always send official instructions; keep client as system 2025-12-17 17:53:55 +07:00
Finessse d3ca1218c5 codex: move instructions into system input 2025-12-17 17:52:13 +07:00
Finessse bc38faa2ad codex: prefix official instructions for non-codex clients 2025-12-17 17:47:27 +07:00
Finessse 0d6e1e6037 openai: stream errors to factory-cli as SSE 2025-12-17 17:37:51 +07:00
Finessse aa42fc0ee7 docs: refine Windows UI controller spec 2025-12-17 17:32:48 +07:00
Finessse be88c3c9b2 docs: add Hindsight sidecar integration notes 2025-12-17 17:29:40 +07:00
Finessse 755291cef8 middleware: preserve tool call/result pairs when trimming 2025-12-17 17:15:45 +07:00
Finessse 52d5bd83f2 openai: return JSON error when streaming fails early 2025-12-17 17:06:49 +07:00
Finessse b1b30d10ea codex: cap injected default instructions 2025-12-17 17:06:41 +07:00
Finessse ef732615a4 claude: do not auto-enable extended thinking 2025-12-17 17:06:33 +07:00
Finessse 2b53dbb09c middleware: harden agentic request trimming 2025-12-17 17:06:25 +07:00
Luis Pater ae7b972649 Merge pull request #577 from router-for-me/refactor-watcher-phase3
Refactor-watcher-phase3
2025-12-17 17:53:04 +08:00
Luis Pater 47885e3710 test(gemini): add test cases and improve compatibility for complex schema cases in CleanJSONSchemaForGemini function 2025-12-17 17:38:53 +08:00
Finessse 3167b12f0c api: trim oversized Codex CLI requests 2025-12-17 16:16:28 +07:00
Finessse ed30fd6f63 codex: avoid duplicating system instructions 2025-12-17 16:16:02 +07:00
Finessse 13d1ba7137 remove amp support 2025-12-17 16:15:10 +07:00
Finessse 1fd1dc26da scripts: split windows/macos helpers 2025-12-17 16:14:12 +07:00
Luis Pater 4b9a260b37 Merge pull request #575 from soilSpoon/feature/antigravity-gemini-compat
feature: Improves Antigravity(gemini-claude) JSON schema compatibility
2025-12-17 16:53:06 +08:00
Luis Pater 462a70541e Merge pull request #38 from router-for-me/plus
v6.6.22
2025-12-17 16:43:53 +08:00
Luis Pater 2407c1f4af Merge branch 'main' into plus 2025-12-17 16:43:46 +08:00
Luis Pater 2c743c8f0b Merge pull request #572 from router-for-me/watcher
refactor(watcher): extract auth synthesizer to synthesizer package
2025-12-17 16:39:59 +08:00
Luis Pater 9f2c278ee6 refactor(translator): replace client.Content structs with JSON-based content generation for more efficient handling of Claude requests 2025-12-17 16:39:32 +08:00
이대희 aea337cfe2 feature: Improves schema flattening and tool use handling
Updates schema flattening logic to handle multiple non-null types, providing a more descriptive "Accepts" hint.

Removes redundant tracking of the current tool name in `Params` as it's no longer needed for streaming limits, simplifying the structure.
2025-12-17 17:30:23 +09:00
hkfires 811f8f8b4f test(watcher): add comprehensive unit tests for watcher edge cases
Add extensive test coverage for watcher module including:
- Auth file handling for empty and missing files
- Persist async error paths and nil receiver handling
- Dispatch loop context cancellation scenarios
- Event processing for errors and channel closures
- Handle event cases: unrelated files, config changes, auth writes,
  remove debouncing, atomic replace detection
- Normalize auth path and debounce cleanup logic
- Runtime auth dispatch and refresh state
- Config reload with mirrored auth dir and OAuth provider filtering
- Start failure when auth dir is missing
- Auth equality comparison ignoring temporal fields
- Reload clients filtering without full rescan
2025-12-17 16:29:11 +08:00
이대희andgemini-code-assist[bot] 27734a23b1 Update internal/util/translator.go
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-17 17:15:11 +09:00
이대희 1b8e538a77 feature: Improves Gemini JSON schema compatibility
Enhances compatibility with the Gemini API by implementing a schema cleaning process.

This includes:
- Centralizing schema cleaning logic for Gemini in a dedicated utility function.
- Converting unsupported schema keywords to hints within the description field.
- Flattening complex schema structures like `anyOf`, `oneOf`, and type arrays to simplify the schema.
- Handling streaming responses with empty tool names, which can occur in subsequent chunks after the initial tool use.
2025-12-17 17:10:53 +09:00
hkfires 41c2385aca refactor(watcher): split watcher.go into focused modules
- Create dispatcher.go for auth update queue management
- Create events.go for fsnotify event handling
- Create config_reload.go for hot-reload logic
- Create clients.go for client lifecycle management
- Simplify watcher.go to core coordinator (~150 lines)
- Maintain 100% API backward compatibility
- All tests passing with 72%+ coverage
2025-12-17 15:53:28 +08:00
Finessse 5a576264dd feat(routing): gemini-3-pro fallback to gemini-cli 2025-12-17 14:20:33 +07:00
Finessse 22313d9cd7 docs: add compatibility matrix 2025-12-17 14:20:10 +07:00
Finessse e7e1b26f11 fix(antigravity): keep scalar text parts 2025-12-17 14:19:45 +07:00
Finessse f9859ff6f3 fix(droid): strip non-JSON done sentinel from SSE 2025-12-17 14:19:23 +07:00
Finessse 4c95db775e chore(windows): add startup + restart scripts 2025-12-17 14:19:01 +07:00
Finessse 7f260eb15e feat(openai): add embeddings + base-url aliases 2025-12-17 14:18:38 +07:00
hkfires d605985f45 refactor(watcher): extract auth synthesis logic into separate synthesizer package 2025-12-17 15:00:43 +08:00
hkfires d52b28b147 fix(config): use correct formatting function for prefix change details 2025-12-17 15:00:43 +08:00
Luis Pater 4afe1f42ca Merge pull request #571 from router-for-me/revert-570-fix/antigravity-thinking-signature
Revert "Fix invalid thinking signature when proxying Claude via Antigravity"
2025-12-17 14:56:29 +08:00
Luis Pater 7481c0eaa0 Revert "Fix invalid thinking signature when proxying Claude via Antigravity" 2025-12-17 14:53:52 +08:00
Luis Pater 024bc25b2c Merge branch 'router-for-me:main' into main 2025-12-17 13:18:47 +08:00
Luis Pater ffdfad8482 Fixed: #551
fix(translator): standardize content node handling across translators for assistant and tool calls
2025-12-17 13:16:07 +08:00
Luis Pater b91ee8d008 Merge branch 'router-for-me:main' into main 2025-12-17 04:01:19 +08:00
Luis Pater 6586f08584 fix(translator): correct funcName extraction and ensure proper handling of function response data in Antigravity Claude requests 2025-12-17 03:57:35 +08:00
Rezha Julio 92c62bb2fb Add GPT-5.2 model support for GitHub Copilot 2025-12-17 02:15:10 +07:00
Luis Pater f49e887fe6 Merge pull request #570 from fuguiKz/fix/antigravity-thinking-signature
Fix invalid thinking signature when proxying Claude via Antigravity
2025-12-17 03:04:41 +08:00
Luis Pater 344066fd11 refactor(api): remove unused OpenAI compatibility provider logic
Simplify handler logic by removing OpenAI compatibility provider management, including related mutex handling and configuration updates.
2025-12-17 02:58:14 +08:00
Luis Pater bcb8092488 Merge pull request #35 from router-for-me/plus
v6.6.19
2025-12-17 02:50:49 +08:00
Luis Pater 1efade8bdb Merge branch 'main' into plus 2025-12-17 02:50:14 +08:00
Luis Pater a5b3ff11fd Merge pull request #569 from router-for-me/watcher
Watcher Module Progressive Refactoring - Phase 1
2025-12-17 02:43:34 +08:00
Luis Pater 084558f200 test(config): add unit tests for model prefix changes in config diff 2025-12-17 02:31:16 +08:00
kz b602eae215 Fix antigravity Claude thinking signature handling 2025-12-17 02:28:58 +08:00
Luis Pater d02bf9c243 feat(diff): add support for model prefix changes in config diff logic
Enhance the configuration diff logic to include detection and reporting of `prefix` changes for all model types. Update related struct naming for consistency across the watcher module.
2025-12-17 02:05:03 +08:00
Luis Pater 26a5f67df2 Merge branch 'dev' into watcher 2025-12-17 01:48:11 +08:00
Finessse 99e9ff1ad6 docs: Claude Code via local proxy
- Document Windows Claude Code settings for using CLIProxyAPI (base URL, auth token, default model mapping)
- Add Claude alias remapping for opus/sonnet/haiku to Gemini-backed models
- Improve auth unavailability reporting (429 cooldown vs 503 blocked) and fallback provider inference
2025-12-17 00:33:25 +07:00
Luis Pater 600fd42a83 Merge pull request #564 from router-for-me/think
feat(thinking): unify budget/effort conversion logic and add iFlow thinking support
2025-12-17 01:21:24 +08:00
Luis Pater 670685139a fix(api): update route patterns to support wildcards for Gemini actions
Normalize action handling by accommodating wildcard patterns in route definitions for Gemini endpoints. Adjust `request.Action` parsing logic to correctly process routes with prefixed actions.
2025-12-17 01:17:02 +08:00
Luis Pater 52b6306388 feat(config): add support for model prefixes and prefix normalization
Refactor model management to include an optional `prefix` field for model credentials, enabling better namespace handling. Update affected configuration files, APIs, and handlers to support prefix normalization and routing. Remove unused OpenAI compatibility provider logic to simplify processing.
2025-12-17 01:07:26 +08:00
Luis Pater f957b8948c chore(deps): bump golang.org/x/term to v0.37.0 2025-12-17 00:19:15 +08:00
Luis Pater cd0b14dd2d Merge pull request #32 from Ravens2121/master
feat: enhance thinking mode support for Kiro translator
2025-12-17 00:00:57 +08:00
Ravens2121 894703a484 Merge branch 'router-for-me:main' into master 2025-12-16 23:06:06 +08:00
hkfires 521ec6f1b8 fix(watcher): simplify vertex apikey idKind to exclude base suffix 2025-12-16 22:55:38 +08:00
hkfires b0c5d9640a refactor(diff): improve security and stability of config change detection
Introduce formatProxyURL helper to sanitize proxy addresses before
logging, stripping credentials and path components while preserving
host information. Rework model hash computation to sort and deduplicate
name/alias pairs with case normalization, ensuring consistent output
regardless of input ordering. Add signature-based identification for
anonymous OpenAI-compatible provider entries to maintain stable keys
across configuration reloads. Replace direct stdout prints with
structured logger calls for file change notifications.
2025-12-16 22:39:19 +08:00
hkfires ef8e94e992 refactor(watcher): extract config diff helpers
Break out config diffing, hashing, and OpenAI compatibility utilities into a dedicated diff package, update watcher to consume them, and add comprehensive tests for diff logic and watcher behavior.
2025-12-16 21:45:33 +08:00
Finessse e2950408bc fix(codex): emit fallback text when upstream returns none 2025-12-16 20:01:39 +07:00
Finessse d6aff12ace fix(responses): keep non-JSON tool output as string 2025-12-16 20:01:08 +07:00
Finessse 52f4d23c85 fix(antigravity): normalize tool call/response adjacency 2025-12-16 20:00:33 +07:00
hkfires 9df96a4bb4 test(thinking): add effort to budget coverage 2025-12-16 18:34:43 +08:00
hkfires 28a428ae2f fix(thinking): align budget effort mapping across translators
Unify thinking budget-to-effort conversion in a shared helper, handle disabled/default thinking cases in translators, adjust zero-budget mapping, and drop the old OpenAI-specific helper with updated tests.
2025-12-16 18:34:43 +08:00
hkfires b326ec3641 feat(iflow): add thinking support for iFlow models 2025-12-16 18:34:43 +08:00
Luis Pater fcecbc7d46 Merge pull request #562 from thomasvan/fix/openai-claude-message-start-order
fix(translator): emit message_start on first chunk regardless of role field
2025-12-16 16:54:58 +08:00
Finessse d7eacf9524 Fix Codex 400 from empty streaming done text 2025-12-16 13:46:27 +07:00
Finessse 4303412761 Fix synthetic /v1/responses SSE for tool calls 2025-12-16 13:23:47 +07:00
Thong Van f4007f53ba fix(translator): emit message_start on first chunk regardless of role field
Some OpenAI-compatible providers (like GitHub Copilot) may send tool_calls
in the first streaming chunk without including the role field. The previous
implementation only emitted message_start when the first chunk contained
role="assistant", causing Anthropic protocol violations when tool calls
arrived first.

This fix ensures message_start is always emitted on the very first chunk,
preventing 'content_block_start before message_start' errors in clients
that strictly validate Anthropic SSE event ordering.
2025-12-16 13:01:09 +07:00
Finessse d0da29f954 Fix /v1/responses streaming for Factory Droid 2025-12-16 13:00:22 +07:00
Finessse 153d2bec96 Responses: ensure message output precedes reasoning 2025-12-16 13:00:12 +07:00
Finessse 2298be6958 Fix antigravity OpenAI chat streaming parsing 2025-12-16 13:00:04 +07:00
Finessse 6558cbbc0a Fix gemini-cli OpenAI chat streaming parsing 2025-12-16 12:59:56 +07:00
Luis Pater d08a2453f7 Merge pull request #33 from router-for-me/plus
v6.6.18
2025-12-16 13:19:42 +08:00
Luis Pater 3f53eea1e0 Merge branch 'main' into plus 2025-12-16 13:19:32 +08:00
Luis Pater 5a812a1e93 feat(remote-management): add support for custom GitHub repository for panel updates
Introduce `panel-github-repository` in the configuration to allow specifying a custom repository for management panel assets. Update dependency versions and enhance asset URL resolution logic to support overrides.
2025-12-16 13:09:26 +08:00
Chén Mù 5e624cc7b1 Merge pull request #558 from router-for-me/worker
chore: ignore .bmad directory
2025-12-16 09:24:32 +08:00
Ravens2121 f3d1cc8dc1 chore: change debug logs from INFO to DEBUG level 2025-12-16 05:32:03 +08:00
Ravens2121 e889efeda7 fix: add signature field to thinking blocks for non-streaming mode
- Add generateThinkingSignature() function in kiro_claude_response.go
2025-12-16 05:21:49 +08:00
Ravens2121 0a3a95521c feat: enhance thinking mode support for Kiro translator
Changes:
2025-12-16 05:01:40 +08:00
Luis Pater 4ebaf6f7a9 Merge pull request #31 from router-for-me/plus
v6.6.17
2025-12-15 23:54:30 +08:00
Luis Pater 59ac1a3f60 Merge branch 'main' into plus 2025-12-15 23:53:23 +08:00
Luis Pater 3af24597ee docs: remove Amp CLI integration guides and update references 2025-12-15 23:50:56 +08:00
Muzhen Gaming 0b834fcb54 fix(translator): preserve built-in tools across openai<->responses
- Pass through non-function tool definitions like web_search

- Translate tool_choice for built-in tools and function tools

- Add regression tests for built-in tool passthrough
2025-12-15 21:18:54 +08:00
hkfires e0be6c5786 chore: ignore .bmad directory 2025-12-15 20:53:43 +08:00
Luis Pater 88b101ebf5 Merge pull request #549 from router-for-me/log
Improve Request Logging Efficiency and Standardize Error Responses
2025-12-15 20:43:12 +08:00
Luis Pater 923a5d6efb Merge branch 'router-for-me:main' into main 2025-12-15 20:40:23 +08:00
Luis Pater 734b7e42ad Merge pull request #28 from tsln1998/main
fix(kiro): remove the extra quotation marks from the protocol handler
2025-12-15 20:40:07 +08:00
Luis Pater d9a65745df fix(translator): handle empty item type and string content in OpenAI response parser 2025-12-15 20:35:52 +08:00
hkfires 97ab623d42 fix(api): prevent double logging for streaming responses 2025-12-15 18:00:32 +08:00
hkfires 14aa6cc7e8 fix(api): ensure all response writes are captured for logging
The response writer wrapper has been refactored to more reliably capture response bodies for logging, fixing several edge cases.

- Implements `WriteString` to capture writes from `io.StringWriter`, which were previously missed by the `Write` method override.
- A new `shouldBufferResponseBody` helper centralizes the logic to ensure the body is buffered only when logging is active or for errors when `logOnErrorOnly` is enabled.
- Streaming detection is now more robust. It correctly handles non-streaming error responses (e.g., `application/json`) that are generated for a request that was intended to be streaming.

BREAKING CHANGE: The public methods `Status()`, `Size()`, and `Written()` have been removed from the `ResponseWriterWrapper` as they are no longer required by the new implementation.
2025-12-15 17:45:16 +08:00
Luis Pater 10e77fcf24 Merge pull request #29 from router-for-me/plus
v6.6.15
2025-12-15 16:36:23 +08:00
Luis Pater bbb21d7c2b Merge branch 'main' into plus 2025-12-15 16:36:11 +08:00
hkfires 3bc489254b fix(api): prevent double logging for error responses
The WriteErrorResponse function now caches the error response body in the gin context.

The deferred request logger checks for this cached response. If an error response is found, it bypasses the standard response logging. This prevents scenarios where an error is logged twice or an empty payload log overwrites the original, more detailed error log.
2025-12-15 16:36:01 +08:00
hkfires 4c07ea41c3 feat(api): return structured JSON error responses
The API error handling is updated to return a structured JSON payload
instead of a plain text message. This provides more context and allows
clients to programmatically handle different error types.

The new error response has the following structure:
{
  "error": {
    "message": "...",
    "type": "..."
  }
}

The `type` field is determined by the HTTP status code, such as
`authentication_error`, `rate_limit_error`, or `server_error`.

If the underlying error message from an upstream service is already a
valid JSON string, it will be preserved and returned directly.

BREAKING CHANGE: API error responses are now in a structured JSON
format instead of plain text. Clients expecting plain text error
messages will need to be updated to parse the new JSON body.
2025-12-15 16:19:52 +08:00
Luis Pater f6720f8dfa Merge pull request #547 from router-for-me/amp
feat(amp): require API key authentication for management routes
2025-12-15 16:14:49 +08:00
Chén Mù e19ab3a066 Merge pull request #543 from router-for-me/log
feat(auth): add proxy information to debug logs
2025-12-15 15:59:16 +08:00
Tsln c46099c5d7 fix(kiro): remove the extra quotation marks from the protocol handler 2025-12-15 15:53:25 +08:00
hkfires 8f1dd69e72 feat(amp): require API key authentication for management routes
All Amp management endpoints (e.g., /api/user, /threads) are now protected by the standard API key authentication middleware. This ensures that all management operations require a valid API key, significantly improving security.

As a result of this change:
- The `restrict-management-to-localhost` setting now defaults to `false`. API key authentication provides a stronger and more flexible security control than IP-based restrictions, improving usability in containerized environments.
- The reverse proxy logic now strips the client's `Authorization` header after authenticating the initial request. It then injects the configured `upstream-api-key` for the request to the upstream Amp service.

BREAKING CHANGE: Amp management endpoints now require a valid API key for authentication. Requests without a valid API key in the `Authorization` header will be rejected with a 401 Unauthorized error.
2025-12-15 13:24:53 +08:00
hkfires f26da24a2f feat(auth): add proxy information to debug logs 2025-12-15 13:14:55 +08:00
Luis Pater 407020de0c Merge branch 'router-for-me:main' into main 2025-12-15 10:36:39 +08:00
Luis Pater 8e4fbcaa7d Merge pull request #533 from router-for-me/think
refactor(thinking): centralize reasoning effort mapping and normalize budget values
2025-12-15 10:34:41 +08:00
hkfires 09c339953d fix(openai): forward reasoning.effort value
Drop the hardcoded effort mapping in request conversion so
unknown values are preserved instead of being coerced to `auto
2025-12-15 09:16:15 +08:00
hkfires 367a05bdf6 refactor(thinking): export thinking helpers
Expose thinking/effort normalization helpers from the executor package
so conversion tests use production code and stay aligned with runtime
validation behavior.
2025-12-15 09:16:15 +08:00
hkfires d20b71deb9 fix(thinking): normalize effort mapping
Route OpenAI reasoning effort through ThinkingEffortToBudget for Claude
translators, preserve "minimal" when translating OpenAI Responses, and
treat blank/unknown efforts as no-ops for Gemini thinking configs.

Also map budget -1 to "auto" and expand cross-protocol thinking tests.
2025-12-15 09:16:15 +08:00
hkfires 712ce9f781 fix(thinking): drop unsupported none effort
When budget 0 maps to "none" for models that use thinking levels
but don't support that effort level, strip thinking fields instead
of setting an invalid reasoning_effort value.
Tests now expect removal for this edge case.
2025-12-15 09:16:14 +08:00
hkfires a4a3274a55 test(thinking): expand conversion edge case coverage 2025-12-15 09:16:14 +08:00
hkfires 716aa71f6e fix(thinking): centralize reasoning_effort mapping
Move OpenAI `reasoning_effort` -> Gemini `thinkingConfig` budget logic into
shared helpers used by Gemini, Gemini CLI, and antigravity translators.

Normalize Claude thinking handling by preferring positive budgets, applying
budget token normalization, and gating by model support.

Always convert Gemini `thinkingBudget` back to OpenAI `reasoning_effort` to
support allowCompat models, and update tests for normalization behavior.
2025-12-15 09:16:14 +08:00
hkfires e8976f9898 fix(thinking): map budgets to effort for level models 2025-12-15 09:16:14 +08:00
hkfires 8496cc2444 test(thinking): cover openai-compat reasoning passthrough 2025-12-15 09:16:14 +08:00
hkfires 5ef2d59e05 fix(thinking): gate reasoning effort by model support
Only map OpenAI reasoning effort to Claude thinking for models that support
thinking and use budget tokens (not level-based thinking).

Also add "xhigh" effort mapping and adjust minimal/low budgets, with new
raw-payload conversion tests across protocols and models.
2025-12-15 09:16:14 +08:00
Chén Mù 07bb89ae80 Merge pull request #542 from router-for-me/aistudio 2025-12-15 09:13:25 +08:00
hkfires 27a5ad8ec2 Fixed: #534
fix(aistudio): correct JSON string boundary detection for backslash sequences
2025-12-15 09:00:14 +08:00
Luis Pater 707b07c5f5 Merge pull request #537 from sukakcoding/fix/function-response-fallback
fix: handle malformed json in function response parsing
2025-12-15 03:31:09 +08:00
sukakcoding 4a764afd76 refactor: extract parseFunctionResponse helper to reduce duplication 2025-12-15 01:05:36 +08:00
sukakcoding ecf49d574b fix: handle malformed json in function response parsing 2025-12-15 00:59:46 +08:00
Finessse 4b4cd108ce Fix tool result ordering for Droid CLI 2025-12-14 23:34:54 +07:00
Luis Pater 188de4ff2a Merge branch 'router-for-me:main' into main 2025-12-15 00:31:29 +08:00
Luis Pater 5a75ef8ffd Merge pull request #536 from AoaoMH/feature/auth-model-check
feat: using Client Model Infos;
2025-12-15 00:29:33 +08:00
Test 07279f8746 feat: using Client Model Infos; 2025-12-15 00:13:05 +08:00
Luis Pater 71f788b13a fix(registry): remove unused ThinkingSupport from DeepSeek-R1 model 2025-12-14 21:30:17 +08:00
Luis Pater 59c62dc580 fix(registry): correct DeepSeek-V3.2 experimental model ID 2025-12-14 21:27:43 +08:00
Luis Pater 8fb1f114bc Merge pull request #25 from Ravens2121/master
fix(kiro): Always parse thinking tags from Kiro API responses
2025-12-14 20:29:14 +08:00
Luis Pater 6a4cff6699 Merge branch 'router-for-me:main' into main 2025-12-14 17:28:28 +08:00
Luis Pater d5310a3300 Merge pull request #531 from AoaoMH/feature/auth-model-check
feat: add API endpoint to query models for auth credentials
2025-12-14 16:46:43 +08:00
Ravens2121andAmp de0ea3ac49 fix(kiro): Always parse thinking tags from Kiro API responses
Amp-Thread-ID: https://ampcode.com/threads/T-019b1c00-17b4-713d-a8cc-813b71181934
Co-authored-by: Amp <amp@ampcode.com>
2025-12-14 16:46:17 +08:00
Ravens2121 12116b018d Merge branch 'router-for-me:main' into master 2025-12-14 16:42:30 +08:00
Ravens2121 c3ed3b40ea feat(kiro): Add token usage cross-validation and simplify thinking mode handling 2025-12-14 16:40:33 +08:00
Luis Pater b80c2aabb0 Merge branch 'router-for-me:main' into main 2025-12-14 16:19:29 +08:00
Luis Pater f0a3eb574e fix(registry): update DeepSeek model definitions with new IDs and descriptions 2025-12-14 16:17:11 +08:00
Test bb15855443 feat: add API endpoint to query models for auth credentials 2025-12-14 15:16:26 +08:00
Luis Pater 14ce6aebd1 Merge pull request #449 from sususu98/fix/gemini-cli-429-retry-delay-parsing
fix(gemini-cli): enhance 429 retry delay parsing
2025-12-14 14:04:14 +08:00
Luis Pater 2fe83723f2 Merge pull request #515 from teeverc/fix/response-rewriter-streaming-flush
fix(amp): flush response buffer after each streaming chunk write
2025-12-14 13:26:05 +08:00
Luis Pater e73b9e10a6 Merge pull request #24 from Ravens2121/master
feat(kiro): Major Refactoring + OpenAI Translator Implementation + Streaming Fixes
2025-12-14 12:51:28 +08:00
Ravens2121 9c04c18c04 feat(kiro): enhance request translation and fix streaming issues
English:
- Fix <thinking> tag parsing: only parse at response start, avoid misinterpreting discussion text
- Add token counting support using tiktoken for local estimation
- Support top_p parameter in inference config
- Handle max_tokens=-1 as maximum (32000 tokens)
- Add tool_choice and response_format parameter handling via system prompt hints
- Support multiple thinking mode detection formats (Claude API, OpenAI reasoning_effort, AMP/Cursor)
- Shorten MCP tool names exceeding 64 characters
- Fix duplicate [DONE] marker in OpenAI SSE streaming
- Enhance token usage statistics with multiple event format support
- Add code fence markers to constants

中文:
- 修复 <thinking> 标签解析:仅在响应开头解析,避免误解析讨论文本中的标签
- 使用 tiktoken 实现本地 token 计数功能
- 支持 top_p 推理配置参数
- 处理 max_tokens=-1 转换为最大值(32000 tokens)
- 通过系统提示词注入实现 tool_choice 和 response_format 参数支持
- 支持多种思考模式检测格式(Claude API、OpenAI reasoning_effort、AMP/Cursor)
- 截断超过64字符的 MCP 工具名称
- 修复 OpenAI SSE 流中重复的 [DONE] 标记
- 增强 token 使用量统计,支持多种事件格式
- 添加代码围栏标记常量
2025-12-14 11:57:16 +08:00
Ravens2121 81ae09d0ec Merge branch 'kiro-refactor-backup' 2025-12-14 07:03:24 +08:00
Ravens2121 01cf221167 feat(kiro): 代码优化重构 + OpenAI翻译器实现 2025-12-14 06:58:50 +08:00
teeverc cd8c86c6fb refactor: only flush stream response on successful write 2025-12-13 13:32:54 -08:00
teeverc 52d5fd1a67 fix: streaming for amp cli 2025-12-13 13:17:53 -08:00
Luis Pater 7ecc7aabda Merge pull request #23 from router-for-me/plus
v6.6.9
2025-12-14 00:07:57 +08:00
Luis Pater 79033aee34 Merge branch 'main' into plus 2025-12-14 00:07:46 +08:00
Luis Pater b6ad243e9e Merge pull request #498 from teeverc/fix/claude-streaming-flush
fix(claude): flush Claude SSE chunks immediately
2025-12-13 23:58:34 +08:00
Luis Pater 92ca5078c1 docs(readme): update contributors for Kiro integration (AWS CodeWhisperer) 2025-12-13 13:40:39 +08:00
Luis Pater aca8523060 Merge pull request #22 from Ravens2121/master
feat(kiro): enhance thinking support and fix truncation issues
2025-12-13 13:37:47 +08:00
Ravens2121 1ea0cff3a4 fix: add missing import declarations for net and time packages 2025-12-13 12:57:47 +08:00
Ravens2121 75793a18f0 feat(kiro): Add Kiro OAuth login entry and auth file filter in Web UI
为Kiro供应商添加WEB UI OAuth登录入口和认证文件过滤器

## Changes / 更改内容

### Frontend / 前端 (management.html)
- Add Kiro OAuth card UI with support for AWS Builder ID, Google, and GitHub login methods
- 添加Kiro OAuth卡片UI,支持AWS Builder ID、Google和GitHub三种登录方式
- Add i18n translations for Kiro OAuth (Chinese and English)
- 添加Kiro OAuth的中英文国际化翻译
- Add Kiro filter button in auth files management page
- 在认证文件管理页面添加Kiro过滤按钮
- Implement JavaScript methods: startKiroOAuth(), openKiroLink(), copyKiroLink(), copyKiroDeviceCode(), startKiroOAuthPolling(), resetKiroOAuthUI()
- 实现JavaScript方法:startKiroOAuth()、openKiroLink()、copyKiroLink()、copyKiroDeviceCode()、startKiroOAuthPolling()、resetKiroOAuthUI()

### Backend / 后端
- Add /kiro-auth-url endpoint for Kiro OAuth authentication (auth_files.go)
- 添加/kiro-auth-url端点用于Kiro OAuth认证 (auth_files.go)
- Fix GetAuthStatus() to correctly parse device_code and auth_url status
- 修复GetAuthStatus()以正确解析device_code和auth_url状态
- Change status delimiter from ':' to '|' to avoid URL parsing issues
- 将状态分隔符从':'改为'|'以避免URL解析问题
- Export CreateToken method in social_auth.go
- 在social_auth.go中导出CreateToken方法
- Register Kiro OAuth routes in server.go
- 在server.go中注册Kiro OAuth路由

## Files Modified / 修改的文件
- management.html
- internal/api/handlers/management/auth_files.go
- internal/api/server.go
- internal/auth/kiro/social_auth.go
2025-12-13 11:39:22 +08:00
Ravens2121 58866b21cb feat: optimize connection pooling and improve Kiro executor reliability
## 中文说明

### 连接池优化
- 为 AMP 代理、SOCKS5 代理和 HTTP 代理配置优化的连接池参数
- MaxIdleConnsPerHost 从默认的 2 增加到 20,支持更多并发用户
- MaxConnsPerHost 设为 0(无限制),避免连接瓶颈
- 添加 IdleConnTimeout (90s) 和其他超时配置

### Kiro 执行器增强
- 添加 Event Stream 消息解析的边界保护,防止越界访问
- 实现实时使用量估算(每 5000 字符或 15 秒发送 ping 事件)
- 正确从上游事件中提取并传递 stop_reason
- 改进输入 token 计算,优先使用 Claude 格式解析
- 添加 max_tokens 截断警告日志

### Token 计算改进
- 添加 tokenizer 缓存(sync.Map)避免重复创建
- 为 Claude/Kiro/AmazonQ 模型添加 1.1 调整因子
- 新增 countClaudeChatTokens 函数支持 Claude API 格式
- 支持图像 token 估算(基于尺寸计算)

### 认证刷新优化
- RefreshLead 从 30 分钟改为 5 分钟,与 Antigravity 保持一致
- 修复 NextRefreshAfter 设置,防止频繁刷新检查
- refreshFailureBackoff 从 5 分钟改为 1 分钟,加快失败恢复

---

## English Description

### Connection Pool Optimization
- Configure optimized connection pool parameters for AMP proxy, SOCKS5 proxy, and HTTP proxy
- Increase MaxIdleConnsPerHost from default 2 to 20 to support more concurrent users
- Set MaxConnsPerHost to 0 (unlimited) to avoid connection bottlenecks
- Add IdleConnTimeout (90s) and other timeout configurations

### Kiro Executor Enhancements
- Add boundary protection for Event Stream message parsing to prevent out-of-bounds access
- Implement real-time usage estimation (send ping events every 5000 chars or 15 seconds)
- Correctly extract and pass stop_reason from upstream events
- Improve input token calculation, prioritize Claude format parsing
- Add max_tokens truncation warning logs

### Token Calculation Improvements
- Add tokenizer cache (sync.Map) to avoid repeated creation
- Add 1.1 adjustment factor for Claude/Kiro/AmazonQ models
- Add countClaudeChatTokens function to support Claude API format
- Support image token estimation (calculated based on dimensions)

### Authentication Refresh Optimization
- Change RefreshLead from 30 minutes to 5 minutes, consistent with Antigravity
- Fix NextRefreshAfter setting to prevent frequent refresh checks
- Change refreshFailureBackoff from 5 minutes to 1 minute for faster failure recovery
2025-12-13 10:21:40 +08:00
Luis Pater 660aabc437 fix(executor): add allowCompat support for reasoning effort normalization
Introduced `allowCompat` parameter to improve compatibility handling for reasoning effort in payloads across OpenAI and similar models.
2025-12-13 04:06:02 +08:00
Ravens2121 db80b20bc2 feat(kiro): enhance thinking support and fix truncation issues
- **Thinking Support**:
    - Enabled thinking support for all Kiro Claude models, including Haiku 4.5 and agentic variants.
    - Updated `model_definitions.go` with thinking configuration (Min: 1024, Max: 32000, ZeroAllowed: true).
    - Fixed `extended_thinking` field names in `model_registry.go` (from `min_budget`/`max_budget` to `min`/`max`) to comply with Claude API specs, enabling thinking control in clients like Claude Code.

- **Kiro Executor Fixes**:
    - Fixed `budget_tokens` handling: explicitly disable thinking when budget is 0 or negative.
    - Removed aggressive duplicate content filtering logic that caused truncation/data loss.
    - Enhanced thinking tag parsing with `extractThinkingFromContent` to correctly handle interleaved thinking/text blocks.
    - Added EOF handling to flush pending thinking tag characters, preventing data loss at stream end.

- **Performance**:
    - Optimized Claude stream handler (v6.2) with reduced buffer size (4KB) and faster flush interval (50ms) to minimize latency and prevent timeouts.
2025-12-13 03:57:13 +08:00
Luis Pater 566120e8d5 Merge pull request #505 from router-for-me/think
fix(thinking): map budgets to effort levels
2025-12-12 22:17:11 +08:00
Luis Pater f3f0f1717d Merge branch 'dev' into think 2025-12-12 22:16:44 +08:00
Luis Pater 05b499fb83 Merge branch 'router-for-me:main' into main 2025-12-12 22:09:08 +08:00
Luis Pater 7621ec609e Merge pull request #501 from huynguyen03dev/fix/openai-compat-model-alias-resolution
fix(openai-compat): prevent model alias from being overwritten
2025-12-12 21:58:15 +08:00
Luis Pater 9f511f0024 fix(executor): improve model compatibility handling for OpenAI-compatibility
Enhances payload handling by introducing OpenAI-compatibility checks and refining how reasoning metadata is resolved, ensuring broader model support.
2025-12-12 21:57:25 +08:00
hkfires 374faa2640 fix(thinking): map budgets to effort levels
Ensure thinking settings translate correctly across providers:
- Only apply reasoning_effort to level-based models and derive it from numeric
  budget suffixes when present
- Strip effort string fields for budget-based models and skip Claude/Gemini
  budget resolution for level-based or unsupported models
- Default Gemini include_thoughts when a nonzero budget override is set
- Add cross-protocol conversion and budget range tests
2025-12-12 21:33:20 +08:00
Luis Pater ba6aa5fbbe Merge branch 'router-for-me:main' into main 2025-12-12 20:09:31 +08:00
Luis Pater 1c52a89535 Merge pull request #502 from router-for-me/iflow
fix(auth): prevent duplicate iflow BXAuth tokens
2025-12-12 20:03:37 +08:00
hkfires e7cedbee6e fix(auth): prevent duplicate iflow BXAuth tokens 2025-12-12 19:57:19 +08:00
Luis Pater 75ce0919a0 Merge pull request #21 from router-for-me/plus
v6.6.6
2025-12-12 18:42:09 +08:00
Luis Pater 7f4f6bc9ca Merge branch 'main' into plus 2025-12-12 18:41:39 +08:00
Luis Pater b8194e717c Merge pull request #500 from router-for-me/think
fix(codex): raise default reasoning effort to medium
2025-12-12 18:35:26 +08:00
huynguyen03.devandAmp 15c3cc3a50 fix(openai-compat): prevent model alias from being overwritten by ResolveOriginalModel
When using OpenAI-compatible providers with model aliases (e.g., glm-4.6-zai -> glm-4.6),
the alias resolution was correctly applied but then immediately overwritten by
ResolveOriginalModel, causing 'Unknown Model' errors from upstream APIs.

This fix skips the ResolveOriginalModel override when a model alias has already
been resolved, ensuring the correct model name is sent to the upstream provider.

Co-authored-by: Amp <amp@ampcode.com>
2025-12-12 17:20:24 +07:00
hkfires d131435e25 fix(codex): raise default reasoning effort to medium 2025-12-12 18:18:48 +08:00
Luis Pater 6e43669498 Fixed: #440
feat(watcher): normalize auth file paths and implement debounce for remove events
2025-12-12 16:50:56 +08:00
teevercandgemini-code-assist[bot] 5ab3032335 Update sdk/api/handlers/claude/code_handlers.go
thank you gemini

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-12 00:26:01 -08:00
teevercandAmp 1215c635a0 fix: flush Claude SSE chunks immediately to match OpenAI behavior
- Write each SSE chunk directly to c.Writer and flush immediately
- Remove buffered writer and ticker-based flushing that caused delayed output
- Add 500ms timeout case for consistency with OpenAI/Gemini handlers
- Clean up unused bufio import

This fixes the 'not streaming' issue where small responses were held
in the buffer until timeout/threshold was reached.

Amp-Thread-ID: https://ampcode.com/threads/T-019b1186-164e-740c-96ab-856f64ee6bee
Co-authored-by: Amp <amp@ampcode.com>
2025-12-12 00:14:19 -08:00
Luis Pater 54d4fd7f84 remove PR_DOCUMENTATION.md 2025-12-12 16:10:15 +08:00
Luis Pater 8dc690a638 Merge pull request #20 from Ravens2121/master
feat(kiro): 支持思考模型 (Thinking Mode) 并通过多配额故障转移增强稳定性
2025-12-12 16:09:28 +08:00
Ravens2121 fdeb84db2b Merge branch 'router-for-me:main' into master 2025-12-12 13:44:07 +08:00
Ravens2121 84920cb670 feat(kiro): add multi-endpoint fallback & thinking mode support 2025-12-12 13:43:36 +08:00
Ravens2121 204bba9dea refactor(kiro): update Kiro executor to use CodeWhisperer endpoint and improve tool calling support 2025-12-12 09:27:30 +08:00
Luis Pater 35fdd7bc05 Merge branch 'router-for-me:main' into main 2025-12-12 08:54:36 +08:00
Luis Pater fc054db51a Merge pull request #494 from ben-vargas/fix-gpt-reasoning-none
fix(models): add "none" reasoning effort level to gpt-5.2
2025-12-12 08:53:19 +08:00
Luis Pater 6e2306a5f2 refactor(handlers): improve request logging and payload handling 2025-12-12 08:52:52 +08:00
Ben Vargas b09e2115d1 fix(models): add "none" reasoning effort level to gpt-5.2
Per OpenAI API documentation, gpt-5.2 supports reasoning_effort values
of "none", "low", "medium", "high", and "xhigh". The "none" level was
missing from the model definition.

Reference: https://platform.openai.com/docs/api-reference/chat/create#chat_create-reasoning_effort
2025-12-11 15:26:23 -07:00
Luis Pater 6a94afab6c Merge branch 'router-for-me:main' into main 2025-12-12 04:08:54 +08:00
Luis Pater a68c97a40f Fixed: #492 2025-12-12 04:08:11 +08:00
Luis Pater 218dc17713 Merge branch 'router-for-me:main' into main 2025-12-12 03:03:36 +08:00
Luis Pater cd2da152d4 feat(models): add GPT 5.2 model definition and prompts 2025-12-12 03:02:27 +08:00
Luis Pater 28469576bf Merge branch 'router-for-me:main' into main 2025-12-12 02:41:05 +08:00
Ravens2121 40e7f066e4 feat(kiro): enhance Kiro executor with retry, deduplication and event filtering 2025-12-12 01:59:06 +08:00
Luis Pater ef0edbfe69 refactor(claude): replace strings.Builder with simpler output string concatenation 2025-12-11 22:34:06 +08:00
Luis Pater bb6312b4fc Merge pull request #488 from router-for-me/gemini
Unify the Gemini executor style
2025-12-11 22:14:17 +08:00
hkfires 3c315551b0 refactor(executor): relocate gemini token counters 2025-12-11 21:56:44 +08:00
hkfires 27c9c5c4da refactor(executor): clarify executor comments and oauth names 2025-12-11 21:56:44 +08:00
hkfires fc9f6c974a refactor(executor): clarify providers and streams
Add package and constructor documentation for AI Studio, Antigravity,
Gemini CLI, Gemini API, and Vertex executors to describe their roles and
inputs.

Introduce a shared stream scanner buffer constant in the Gemini API
executor and reuse it in Gemini CLI and Vertex streaming code so stream
handling uses a consistent configuration.

Update Refresh implementations for AI Studio, Gemini CLI, Gemini API
(API key), and Vertex executors to short‑circuit and simply return the
incoming auth object, while keeping Antigravity token renewal as the
only executor that performs OAuth refresh.

Remove OAuth2-based token refresh logic and related dependencies from
the Gemini API executor, since it now operates strictly with API key
credentials.
2025-12-11 21:56:43 +08:00
Luis Pater 242b4d5754 Merge pull request #19 from router-for-me/plus
v6.6.1
2025-12-11 21:35:16 +08:00
Luis Pater 4ce7c61a17 Merge branch 'main' into plus 2025-12-11 21:33:49 +08:00
Luis Pater a74ee3f319 Merge pull request #481 from sususu98/fix/increase-buffer-size
fix: increase buffer size for stream scanners to 50MB across multiple executors
2025-12-11 21:20:54 +08:00
Luis Pater 564bcbaa54 Merge pull request #487 from router-for-me/amp
fix(amp): set status on claude stream errors
2025-12-11 21:18:19 +08:00
hkfires 88bdd25f06 fix(amp): set status on claude stream errors 2025-12-11 20:12:06 +08:00
hkfires e79f65fd8e refactor(thinking): use parentheses for metadata suffix 2025-12-11 18:39:07 +08:00
Luis Pater 2760989401 Merge pull request #485 from router-for-me/think
Think
2025-12-11 18:27:00 +08:00
hkfires facfe7c518 refactor(thinking): use bracket tags for thinking meta
Align thinking suffix handling on a single bracket-style marker.

NormalizeThinkingModel strips a terminal `[value]` segment from
model identifiers and turns it into either a thinking budget (for
numeric values) or a reasoning effort hint (for strings). Emission
of `ThinkingIncludeThoughtsMetadataKey` is removed.

Executor helpers and the example config are updated so their
comments reference the new `[value]` suffix format instead of the
legacy dash variants.

BREAKING CHANGE: dash-based thinking suffixes (`-thinking`,
`-thinking-N`, `-reasoning`, `-nothinking`) are no longer parsed
for thinking metadata; only `[value]` annotations are recognized.
2025-12-11 18:17:28 +08:00
hkfires 6285459c08 fix(runtime): unify claude thinking config resolution 2025-12-11 17:20:44 +08:00
hkfires 21bbceca0c docs(runtime): document reasoning effort precedence 2025-12-11 16:35:36 +08:00
hkfires f6300c72b7 fix(runtime): validate thinking config in iflow and qwen 2025-12-11 16:21:50 +08:00
hkfires 007572b58e fix(util): do not strip thinking suffix on registered models
NormalizeThinkingModel now checks ModelSupportsThinking before removing
"-thinking" or "-thinking-<ver>", avoiding accidental parsing of model
names where the suffix is part of the official id (e.g., kimi-k2-thinking,
qwen3-235b-a22b-thinking-2507).

The registry adds ThinkingSupport metadata for several models and
propagates it via ModelInfo (e.g., kimi-k2-thinking, deepseek-r1,
qwen3-235b-a22b-thinking-2507, minimax-m2), enabling accurate detection
of thinking-capable models and correcting base model inference.
2025-12-11 15:52:14 +08:00
hkfires 3a81ab22fd fix(runtime): unify reasoning effort metadata overrides 2025-12-11 14:35:05 +08:00
hkfires 519da2e042 fix(runtime): validate reasoning effort levels 2025-12-11 12:36:54 +08:00
hkfires 169f4295d0 fix(util): align reasoning effort handling with registry 2025-12-11 12:20:12 +08:00
hkfires d06d0eab2f fix(util): centralize reasoning effort normalization 2025-12-11 12:14:51 +08:00
hkfires 3ffd120ae9 feat(runtime): add thinking config normalization 2025-12-11 11:51:33 +08:00
hkfires a03d514095 feat(registry): add thinking metadata for models 2025-12-11 11:28:44 +08:00
sususuandClaude Opus 4.5 07d21463ca fix(gemini-cli): enhance 429 retry delay parsing
Add fallback parsing for quota reset delay when RetryInfo is not present:
- Try ErrorInfo.metadata.quotaResetDelay (e.g., "373.801628ms")
- Parse from error.message "Your quota will reset after Xs."

This ensures proper cooldown timing for rate-limited requests.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-11 09:34:39 +08:00
Luis Pater 69fccf0015 Merge pull request #18 from Ravens2121/master
Kiro Executor Stability and API Compatibility Improvements
2025-12-11 08:35:22 +08:00
Luis Pater 1da03bfe15 Merge pull request #479 from router-for-me/claude
fix(claude): prevent final events when no content streamed
2025-12-11 08:18:59 +08:00
Ravens2121 6133bac226 feat(kiro): enhance Kiro executor stability and compatibility
## Changes Overview
This commit includes multiple improvements to the Kiro executor for better
stability, API compatibility, and code quality.

## Detailed Changes

### 1. Output Token Calculation Improvement (lines 317-330)
- Replace simple len(content)/4 estimation with tiktoken-based calculation
- Add fallback to character count estimation if tiktoken fails
- Improves token counting accuracy for usage tracking

### 2. Stream Handler Panic Recovery (lines 528-533)
- Add defer/recover block in streamToChannel goroutine
- Prevents single request crashes from affecting the entire service

### 3. Struct Field Reordering (lines 670-673)
- Reorder kiroToolResult struct fields: Content, Status, ToolUseID
- Ensures consistency with API expectations

### 4. Message Merging Function (lines 778-780, 2356-2483)
- Add mergeAdjacentMessages() to combine consecutive messages with same role
- Add helper functions: mergeMessageContent(), blockToMap(), createMergedMessage()
- Required by Kiro API which doesn't allow adjacent messages from same role

### 5. Empty Content Handling (lines 791-800)
- Add default content for empty history messages
- User messages with tool results: "Tool results provided."
- User messages without tool results: "Continue"

### 6. Assistant Last Message Handling (lines 811-830)
- Detect when last message is from assistant
- Create synthetic "Continue" user message to satisfy Kiro API requirements
- Kiro API requires currentMessage to be userInputMessage type

### 7. Duplicate Content Event Detection (lines 1650-1660)
- Track lastContentEvent to detect duplicate streaming events
- Skip redundant events to prevent duplicate content in responses
- Based on AIClient-2-API implementation for Kiro

### 8. Streaming Token Calculation Enhancement (lines 1785-1817)
- Add accumulatedContent buffer for streaming token calculation
- Use tiktoken for accurate output token counting during streaming
- Add fallback to character count estimation with proper logging

### 9. JSON Repair Enhancement (lines 2665-2818)
- Implement conservative JSON repair strategy
- First try to parse JSON directly - if valid, return unchanged
- Add bracket balancing detection and repair
- Only repair when necessary to avoid corrupting valid JSON
- Validate repaired JSON before returning

### 10. HELIOS_CHK Filtering Removal (lines 2500-2504, 3004-3039)
- Remove filterHeliosDebugInfo function
- Remove heliosDebugPattern regex
- HELIOS_CHK fields now handled by client-side processing

### 11. Comment Translation
- Translate Chinese comments to English for code consistency
- Affected areas: token calculation, buffer handling, message processing
2025-12-11 08:13:33 +08:00
Ravens2121 f302be5ce6 Merge branch 'router-for-me:main' into master 2025-12-11 05:40:10 +08:00
Ravens2121 cd4e84a360 feat(kiro): enhance request format, stream handling, and usage tracking
## English Description

### Request Format Fixes
- Fix conversationState field order (chatTriggerType must be first)
- Add conditional profileArn inclusion based on auth method
- builder-id auth (AWS SSO) doesn't require profileArn
- social auth (Google OAuth) requires profileArn

### Stream Processing Enhancements
- Add headersLen boundary validation to prevent slice out of bounds
- Handle incomplete tool use at EOF by flushing pending data
- Separate message_delta and message_stop events for proper streaming
- Add error logging for JSON unmarshal failures

### JSON Repair Improvements
- Add escapeNewlinesInStrings() to handle control characters in JSON strings
- Remove incorrect unquotedKeyPattern that broke valid JSON content
- Fix handling of streaming fragments with embedded newlines/tabs

### Debug Info Filtering (Optional)
- Add filterHeliosDebugInfo() to remove [HELIOS_CHK] blocks
- Pattern matches internal state tracking from Kiro/Amazon Q
- Currently disabled pending further testing

### Usage Tracking
- Add usage information extraction in message_delta response
- Include prompt_tokens, completion_tokens, total_tokens in OpenAI format

---

## 中文描述

### 请求格式修复
- 修复 conversationState 字段顺序(chatTriggerType 必须在第一位)
- 根据认证方式条件性包含 profileArn
- builder-id 认证(AWS SSO)不需要 profileArn
- social 认证(Google OAuth)需要 profileArn

### 流处理增强
- 添加 headersLen 边界验证,防止切片越界
- 在 EOF 时处理未完成的工具调用,刷新待处理数据
- 分离 message_delta 和 message_stop 事件以实现正确的流式传输
- 添加 JSON 反序列化失败的错误日志

### JSON 修复改进
- 添加 escapeNewlinesInStrings() 处理 JSON 字符串中的控制字符
- 移除错误的 unquotedKeyPattern,该模式会破坏有效的 JSON 内容
- 修复包含嵌入换行符/制表符的流式片段处理

### 调试信息过滤(可选)
- 添加 filterHeliosDebugInfo() 移除 [HELIOS_CHK] 块
- 模式匹配来自 Kiro/Amazon Q 的内部状态跟踪信息
- 目前已禁用,等待进一步测试

### 使用量跟踪
- 在 message_delta 响应中添加 usage 信息提取
- 以 OpenAI 格式包含 prompt_tokens、completion_tokens、total_tokens
2025-12-11 05:37:22 +08:00
Luis Pater 4360ed8a7b Merge branch 'router-for-me:main' into main 2025-12-11 03:17:55 +08:00
Luis Pater 423ce97665 feat(util): implement dynamic thinking suffix normalization and refactor budget resolution logic
- Added support for parsing and normalizing dynamic thinking model suffixes.
- Centralized budget resolution across executors and payload helpers.
- Retired legacy Gemini-specific thinking handlers in favor of unified logic.
- Updated executors to use metadata-based thinking configuration.
- Added `ResolveOriginalModel` utility for resolving normalized upstream models using request metadata.
- Updated executors (Gemini, Codex, iFlow, OpenAI, Qwen) to incorporate upstream model resolution and substitute model values in payloads and request URLs.
- Ensured fallbacks handle cases with missing or malformed metadata to derive models robustly.
- Refactored upstream model resolution to dynamically incorporate metadata for selecting and normalizing models.
- Improved handling of thinking configurations and model overrides in executors.
- Removed hardcoded thinking model entries and migrated logic to metadata-based resolution.
- Updated payload mutations to always include the resolved model.
2025-12-11 03:10:50 +08:00
Luis Pater b27a175fef Merge pull request #17 from Ravens2121/master
由AI进行更改修复了Kiro供应商的Claude协议与OpenAI协议。(对比AIClient-2-API项目进行变更)
2025-12-11 01:31:47 +08:00
RavensandAmp 8d5f89ccfd fix(kiro): fix translator format mismatch for OpenAI protocol
Amp-Thread-ID: https://ampcode.com/threads/T-019b092b-f2de-72a1-b428-72511c0de628
Co-authored-by: Amp <amp@ampcode.com>
2025-12-11 01:15:00 +08:00
RavensandAmp 084e2666cb fix(kiro): add SSE event: prefix for Claude client compatibility
Amp-Thread-ID: https://ampcode.com/threads/T-019b08fc-ff96-766e-a942-63dd35ed28c6
Co-authored-by: Amp <amp@ampcode.com>
2025-12-11 00:14:20 +08:00
Luis Pater 2eb2dbb266 Merge branch 'router-for-me:main' into main 2025-12-10 23:56:59 +08:00
Luis Pater e717939edb Fixed: #478
feat(antigravity): add support for inline image data in client responses
2025-12-10 23:55:53 +08:00
Ravens2121 7758a86d1e Merge branch 'router-for-me:main' into main 2025-12-10 23:25:23 +08:00
sususu 76c563d161 fix(executor): increase buffer size for stream scanners to 50MB across multiple executors 2025-12-10 23:20:04 +08:00
hkfires a89514951f fix(claude): prevent final events when no content streamed 2025-12-10 22:19:55 +08:00
Luis Pater 9f72a875f8 Merge branch 'router-for-me:main' into main 2025-12-10 16:54:31 +08:00
Luis Pater 94d61c7b2b fix(logging): update response aggregation logic to include all attempts 2025-12-10 16:53:48 +08:00
Luis Pater f999650322 Merge branch 'router-for-me:main' into main 2025-12-10 16:04:18 +08:00
Luis Pater 1249b07eb8 feat(responses): add unique identifiers for responses, function calls, and tool uses 2025-12-10 16:02:54 +08:00
Luis Pater 38319b0483 Merge branch 'router-for-me:main' into main 2025-12-10 15:29:19 +08:00
Luis Pater 6b37f33d31 feat(antigravity): add unique identifier for tool use blocks in response 2025-12-10 15:27:57 +08:00
Luis Pater af543238aa Merge pull request #16 from fuko2935/fix/remove-unstable-kiro-auto
fix(registry): remove unstable kiro-auto model
2025-12-10 00:23:31 +08:00
Luis Pater 2de27c560b Merge pull request #15 from StriveMario/feature/fix-kiro-refreshtoken
fix kiro cannot refresh the token
2025-12-10 00:22:36 +08:00
Luis Pater 773ed6cc64 Merge branch 'router-for-me:main' into main 2025-12-10 00:17:43 +08:00
fuko2935 a594338bc5 fix(registry): remove unstable kiro-auto model
- Removes kiro-auto from static model registry
- Removes kiro-auto mapping from executor
- Fixes compatibility issues reported in #7

Fixes #7
2025-12-09 19:14:40 +03:00
Luis Pater f25f419e5a fix(antigravity): remove references to autopush endpoint and update fallback logic 2025-12-10 00:13:20 +08:00
Luis Pater 1fd1ccca17 Merge branch 'router-for-me:main' into main 2025-12-09 21:13:08 +08:00
Luis Pater b7e382008f Merge pull request #465 from router-for-me/think
Move thinking budget normalization from translators to executor
2025-12-09 21:10:33 +08:00
hkfires 70d6b95097 feat(amp): add /news.rss proxy route 2025-12-09 21:05:06 +08:00
hkfires 9b202b6c1c fix(executor): centralize default thinking config 2025-12-09 21:05:06 +08:00
hkfires 6a66b6801a feat(executor): enforce minimum thinking budget for antigravity models 2025-12-09 21:05:06 +08:00
hkfires 5b6d201408 refactor(translator): remove thinking budget normalization across all translators 2025-12-09 21:05:06 +08:00
hkfires 5ec9b5e5a9 feat(executor): normalize thinking budget across all Gemini executors 2025-12-09 21:05:06 +08:00
Luis Pater 5db3b58717 Merge pull request #470 from router-for-me/agry
fix(gemini): normalize model listing output
2025-12-09 21:00:29 +08:00
Mario 1fa5514d56 fix kiro cannot refresh the token 2025-12-09 20:13:16 +08:00
hkfires 347769b3e3 fix(openai-compat): use model id for auth model display 2025-12-09 18:09:14 +08:00
hkfires 3cfe7008a2 fix(registry): update gpt 5.1 model names 2025-12-09 17:55:21 +08:00
Luis Pater c353606860 Merge pull request #14 from router-for-me/plus
v6.5.59
2025-12-09 17:51:46 +08:00
Luis Pater 2ba31ecc2d Merge branch 'main' into plus 2025-12-09 17:51:18 +08:00
hkfires da23ddb061 fix(gemini): normalize model listing output 2025-12-09 17:34:15 +08:00
Luis Pater 39b6b3b289 Fixed: #463
fix(antigravity): remove `$ref` and `$defs` from JSON during key deletion
2025-12-09 17:32:17 +08:00
Luis Pater c600519fa4 refactor(logging): replace log.Fatalf with log.Errorf and add error handling paths 2025-12-09 17:16:30 +08:00
hkfires e5312fb5a2 feat(antigravity): support canonical names for antigravity models 2025-12-09 16:54:13 +08:00
Luis Pater 36380846a7 Merge branch 'router-for-me:main' into main 2025-12-09 10:03:16 +08:00
Luis Pater 92df0cada9 Merge pull request #461 from router-for-me/aistudio
feat(aistudio): normalize thinking budget in request translation
2025-12-09 08:41:46 +08:00
hkfires 96b55acff8 feat(aistudio): normalize thinking budget in request translation 2025-12-09 08:27:44 +08:00
Luis Pater 608cd8ee3d Merge pull request #13 from router-for-me/v6.5.57
v6.5.57
2025-12-08 23:33:52 +08:00
Luis Pater 9f41894573 Merge branch 'main' into v6.5.57 2025-12-08 23:33:39 +08:00
Luis Pater bb45fee1cf Merge remote-tracking branch 'origin/dev' into dev 2025-12-08 23:28:22 +08:00
Luis Pater af00304b0c fix(antigravity): remove exclusiveMaximum from JSON during key deletion 2025-12-08 23:28:01 +08:00
vuonglv(Andy) 5c3a013cd1 feat(config): add configurable host binding for server (#454)
* feat(config): add configurable host binding for server
2025-12-08 23:16:39 +08:00
Luis Paterandhkfires ab9e9442ec v6.5.56 (#12)
* feat(api): add comprehensive ampcode management endpoints

Add new REST API endpoints under /v0/management/ampcode for managing
ampcode configuration including upstream URL, API key, localhost
restriction, model mappings, and force model mappings settings.

- Move force-model-mappings from config_basic to config_lists
- Add GET/PUT/PATCH/DELETE endpoints for all ampcode settings
- Support model mapping CRUD with upsert (PATCH) capability
- Add comprehensive test coverage for all ampcode endpoints

* refactor(api): simplify request body parsing in ampcode handlers

* feat(logging): add upstream API request/response capture to streaming logs

* style(logging): remove redundant separator line from response section

* feat(antigravity): enforce thinking budget limits for Claude models

* refactor(logging): remove unused variable in `ensureAttempt` and redundant function call

---------

Co-authored-by: hkfires <10558748+hkfires@users.noreply.github.com>
2025-12-08 22:32:29 +08:00
Luis Pater 6ad188921c refactor(logging): remove unused variable in ensureAttempt and redundant function call 2025-12-08 22:25:58 +08:00
Luis Pater 15ed98d6a9 Merge pull request #458 from router-for-me/agry
feat(antigravity): enforce thinking budget limits for Claude models
2025-12-08 20:55:52 +08:00
hkfires a283545b6b feat(antigravity): enforce thinking budget limits for Claude models 2025-12-08 20:36:17 +08:00
Luis Pater 3efbd865a8 Merge pull request #457 from router-for-me/requestlog
style(logging): remove redundant separator line from response section
2025-12-08 18:21:24 +08:00
hkfires aee659fb66 style(logging): remove redundant separator line from response section 2025-12-08 18:18:33 +08:00
Luis Pater 5aa386d8b9 Merge pull request #453 from router-for-me/amp
add ampcode management api
2025-12-08 17:42:13 +08:00
Luis Pater 0adc0ee6aa Merge pull request #455 from router-for-me/requestlog
feat(logging): add upstream API request/response capture to streaming logs
2025-12-08 17:40:10 +08:00
hkfires 92f13fc316 feat(logging): add upstream API request/response capture to streaming logs 2025-12-08 17:21:58 +08:00
hkfires 05cfa16e5f refactor(api): simplify request body parsing in ampcode handlers 2025-12-08 14:45:35 +08:00
hkfires 93a6e2d920 feat(api): add comprehensive ampcode management endpoints
Add new REST API endpoints under /v0/management/ampcode for managing
ampcode configuration including upstream URL, API key, localhost
restriction, model mappings, and force model mappings settings.

- Move force-model-mappings from config_basic to config_lists
- Add GET/PUT/PATCH/DELETE endpoints for all ampcode settings
- Support model mapping CRUD with upsert (PATCH) capability
- Add comprehensive test coverage for all ampcode endpoints
2025-12-08 12:03:00 +08:00
Luis Pater 6b49580716 Merge branch 'router-for-me:main' into main 2025-12-08 10:52:39 +08:00
Luis Pater de77903915 Merge pull request #450 from router-for-me/amp
refactor(config): rename prioritize-model-mappings to force-model-mappings
2025-12-08 10:51:32 +08:00
hkfires 56ed0d8d90 refactor(config): rename prioritize-model-mappings to force-model-mappings 2025-12-08 10:44:39 +08:00
Luis Pater 0d4f32a881 Merge branch 'router-for-me:main' into main 2025-12-08 10:20:08 +08:00
Luis Pater 42e818ce05 Merge pull request #435 from heyhuynhgiabuu/fix/amp-model-mapping-priority
fix: prioritize model mappings over local providers for Amp CLI
2025-12-08 10:17:19 +08:00
Luis Pater 2d4c54ba54 Merge pull request #448 from router-for-me/iflow
Iflow
2025-12-08 09:50:05 +08:00
hkfires e9eb4db8bb feat(auth): refresh API key during cookie authentication 2025-12-08 09:48:31 +08:00
Luis Pater d26ed069fa Merge pull request #441 from huynguyen03dev/fix/claude-to-openai-whitespace-text
fix: filter whitespace-only text in Claude to OpenAI translation
2025-12-08 09:43:44 +08:00
huynhgiabuu afcab5efda feat: add prioritize-model-mappings config option
Add a configuration option to control whether model mappings take
precedence over local API keys for Amp CLI requests.

- Add PrioritizeModelMappings field to AmpCode config struct
- When false (default): Local API keys take precedence (original behavior)
- When true: Model mappings take precedence over local API keys
- Add management API endpoints GET/PUT /prioritize-model-mappings

This allows users who want mapping priority to enable it explicitly
while preserving backward compatibility.

Config example:
  ampcode:
    model-mappings:
      - from: claude-opus-4-5-20251101
        to: gemini-claude-opus-4-5-thinking
    prioritize-model-mappings: true
2025-12-07 22:47:43 +07:00
Ravens2121 1770c491db Merge branch 'router-for-me:main' into main 2025-12-07 22:25:42 +08:00
Ravens2121 a0c6cffb0d fix(kiro):修复 base64 图片格式转换问题 (#10) 2025-12-07 21:55:13 +08:00
Your Name 2bf9e08b31 style(kiro): convert Chinese comments to English in base64 image handling 2025-12-07 21:51:24 +08:00
Ravens2121 f56bfaa689 Merge branch 'router-for-me:main' into main 2025-12-07 21:35:16 +08:00
Your Name 5d716dc796 fix(kiro): 修复 base64 图片格式转换问题 2025-12-07 21:34:44 +08:00
Luis Pater f81ff16022 Merge pull request #8 from Ravens2121/main
feat: 添加Kiro渠道图片支持功能,借鉴justlovemaki/AIClient-2-API实现
2025-12-07 20:18:31 +08:00
Luis Pater 6cf1d8a947 Merge pull request #444 from router-for-me/agry
feat(registry): add explicit thinking support config for antigravity models
2025-12-07 19:38:43 +08:00
hkfires a174d015f2 feat(openai): handle thinking.budget_tokens from Anthropic-style requests 2025-12-07 19:14:05 +08:00
hkfires 9c09128e00 feat(registry): add explicit thinking support config for antigravity models 2025-12-07 19:12:55 +08:00
Your Name 68cbe20664 feat: 添加Kiro渠道图片支持功能,借鉴justlovemaki/AIClient-2-API实现 2025-12-07 17:56:06 +08:00
huynguyen03.dev 549c0c2c5a fix: filter whitespace-only text content in Claude to OpenAI translation
Remove redundant existence check since TrimSpace handles empty strings
2025-12-07 16:08:12 +07:00
huynguyen03.dev f092801b61 fix: filter whitespace-only text in Claude to OpenAI translation
Skip text content blocks that are empty or contain only whitespace
when translating Claude messages to OpenAI format. This fixes GLM-4.6
and other strict OpenAI-compatible providers that reject empty text
with error 'text cannot be empty'.
2025-12-07 15:39:58 +07:00
Luis Pater 15353a6b6a Merge branch 'router-for-me:main' into main 2025-12-07 13:37:43 +08:00
Luis Pater 1b638b3629 Merge pull request #432 from huynguyen03dev/fix/amp-gemini-model-mapping
fix(amp): pass mapped model to gemini bridge via context
2025-12-07 13:33:28 +08:00
Luis Pater 6f5f81753d Merge pull request #439 from router-for-me/log
feat(logging): add version info to request log output
2025-12-07 13:31:06 +08:00
Luis Pater 76af454034 **feat(antigravity): enhance handling of "thinking" content and refine Claude model response processing** 2025-12-07 13:19:12 +08:00
hkfires e54d2f6b2a feat(logging): add version info to request log output 2025-12-07 12:49:14 +08:00
huynguyen03.dev bfc738b76a refactor: remove duplicate provider check in gemini v1beta1 route
Simplifies routing logic by delegating all provider/mapping/proxy
decisions to FallbackHandler. Previously, the route checked for
provider/mapping availability before calling the handler, then
FallbackHandler performed the same checks again.

Changes:
- Remove model extraction and provider checking from route (lines 182-201)
- Route now only checks if request is POST with /models/ path
- FallbackHandler handles provider -> mapping -> proxy fallback
- Remove unused internal/util import

Benefits:
- Eliminates duplicate checks (addresses PR review feedback #2)
- Centralizes all provider/mapping logic in FallbackHandler
- Reduces routing code by ~20 lines
- Aligns with how other /api/provider routes work

Performance: No impact (checks still happen once in FallbackHandler)
2025-12-07 10:54:58 +07:00
huynguyen03.dev 396899a530 refactor: improve gemini bridge testability and code quality
- Change createGeminiBridgeHandler to accept gin.HandlerFunc instead of *gemini.GeminiAPIHandler
  This allows tests to inject mock handlers instead of duplicating bridge logic
- Replace magic number 8 with len(modelsPrefix) for better maintainability
- Remove redundant test case that doesn't test edge case in production
- Update routes.go to pass geminiHandlers.GeminiHandler directly

Addresses PR review feedback on test architecture and code clarity.

Amp-Thread-ID: https://ampcode.com/threads/T-1ae2c691-e434-4b99-a49a-10cabd3544db
2025-12-07 10:15:42 +07:00
Luis Pater 04f0070a80 Merge branch 'router-for-me:main' into main 2025-12-07 02:38:32 +08:00
Luis Pater f383840cf9 fix(antigravity): update toolNode role from "tool" to "user" in chat completions 2025-12-07 02:37:46 +08:00
Luis Pater 239fc4a8c4 Merge branch 'router-for-me:main' into main 2025-12-07 01:58:03 +08:00
Luis Pater fd29ab418a Fixed: #424
**feat(antigravity): add support for maxOutputTokens and refine Claude model handling**
2025-12-07 01:55:57 +08:00
Luis Pater df91408919 Merge branch 'router-for-me:main' into main 2025-12-07 01:49:20 +08:00
Luis Pater 7a628426dc Fixed: #433
refactor(translator): normalize finish reason casing across all OpenAI response handlers
2025-12-07 01:48:24 +08:00
Luis Pater aa6c7facab Merge pull request #5 from router-for-me/plus
Sync
2025-12-07 01:23:53 +08:00
Luis Pater 8ba4c7c7ed Merge branch 'main' into plus 2025-12-07 01:23:36 +08:00
Luis Pater 56b4d7a76e docs(readme): add ProxyPal CLIProxyAPI GUI to project list 2025-12-07 01:13:30 +08:00
Luis Pater b211c3546d Merge pull request #429 from heyhuynhgiabuu/feature/add-proxypal
docs: add ProxyPal to 'Who is with us?' section
2025-12-07 01:10:44 +08:00
huynguyen03.dev edc654edf9 refactor: simplify provider check logic in amp routes
Amp-Thread-ID: https://ampcode.com/threads/T-a18fd71c-32ce-4c29-93d7-09f082740e51
2025-12-06 22:07:40 +07:00
huynguyen03.dev 08586334af fix(amp): pass mapped model to gemini bridge via context
Gemini handler extracts model from URL path, not JSON body, so
rewriting the request body alone wasn't sufficient for model mapping.

- Add MappedModelContextKey constant for context passing
- Update routes.go to use NewFallbackHandlerWithMapper
- Add check for valid mapping before routing to local handler
- Add tests for gemini bridge model mapping
2025-12-06 18:59:44 +07:00
Luis Pater a4804b358f Merge branch 'router-for-me:main' into main 2025-12-06 15:15:27 +08:00
Luis Pater 7ea14479fb Merge pull request #428 from router-for-me/amp
feat(amp): add response rewriter for model name substitution in responses
2025-12-06 15:14:10 +08:00
hkfires 54af96d321 fix(amp): restore request body before fallback handler execution 2025-12-06 15:09:25 +08:00
hkfires 22579155c5 refactor(amp): consolidate and simplify model mapping debug logs 2025-12-06 14:54:38 +08:00
Huynh Gia Buuandgemini-code-assist[bot] c04c3832a4 Update README.md
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-12-06 13:48:08 +07:00
huynhgiabuu 5ffbd54755 docs: add ProxyPal to 'Who is with us?' section 2025-12-06 13:45:49 +07:00
hkfires 5d12d4ce33 feat(amp): add response rewriter for model name substitution in responses 2025-12-06 14:15:44 +08:00
Luis Pater b73e53d6c4 docs: update README to fix formatting for GitHub Copilot and Kiro support sections 2025-12-06 12:14:23 +08:00
Luis Pater b06463c6d9 docs: update README to include Kiro (AWS CodeWhisperer) support integration details 2025-12-06 12:04:36 +08:00
Luis Pater 5eb8453e91 Merge pull request #3 from fuko2935/feature/kiro-integration
Feature/kiro integration
2025-12-06 12:00:48 +08:00
Luis Pater f77c22e6ff Merge branch 'main' into feature/kiro-integration 2025-12-06 11:52:59 +08:00
Mansi df83ba877f refactor: replace custom stringContains with strings.Contains
- Remove custom stringContains and findSubstring helper functions
- Use standard library strings.Contains for better maintainability
- No functional change, just cleaner code

Addresses Gemini Code Assist review feedback
2025-12-05 23:16:48 +03:00
Mansi 9583f6b1c5 refactor: extract setKiroIncognitoMode helper to reduce code duplication
- Added setKiroIncognitoMode() helper function to handle Kiro auth incognito mode setting
- Replaced 3 duplicate code blocks (21 lines) with single function calls (3 lines)
- Kiro auth defaults to incognito mode for multi-account support
- Users can override with --incognito or --no-incognito flags

This addresses the code duplication noted in PR #1 review.
2025-12-05 23:06:07 +03:00
Mansi 02d8a1cfec feat(kiro): add AWS Builder ID authentication support
- Add --kiro-aws-login flag for AWS Builder ID device code flow
- Add DoKiroAWSLogin function for AWS SSO OIDC authentication
- Complete Kiro integration with AWS, Google OAuth, and social auth
- Add kiro executor, translator, and SDK components
- Update browser support for Kiro authentication flows
2025-12-05 22:46:24 +03:00
Luis Pater 92f033dec0 Merge branch 'router-for-me:main' into main 2025-12-06 01:33:34 +08:00
Luis Pater 0ebabf5152 feat(antigravity): add FetchAntigravityProjectID function and integrate project ID retrieval 2025-12-06 01:32:12 +08:00
Luis Pater 4b01ecba2e Merge branch 'router-for-me:main' into main 2025-12-06 01:12:43 +08:00
Luis Pater d7564173dd fix(antigravity): restore production base URL in the executor 2025-12-06 01:11:37 +08:00
Luis Pater f241124599 Merge branch 'router-for-me:main' into main 2025-12-06 00:43:02 +08:00
Luis Pater c44c46dd80 Fixed: #421
feat(antigravity): implement project ID retrieval and integration in payload processing
2025-12-06 00:40:55 +08:00
Luis Pater aa810ee719 Merge branch 'router-for-me:main' into main 2025-12-05 23:06:46 +08:00
Luis Pater 412148af0e feat(antigravity): add function ID to FunctionCall and FunctionResponse models 2025-12-05 23:05:35 +08:00
Luis Pater 5d2baf6058 Merge branch 'router-for-me:main' into main 2025-12-05 21:37:55 +08:00
Luis Pater d28258501a Merge pull request #423 from router-for-me/amp
fix(amp): suppress ErrAbortHandler panics in reverse proxy handler
2025-12-05 21:36:01 +08:00
hkfires 55cd31fb96 fix(amp): suppress ErrAbortHandler panics in reverse proxy handler 2025-12-05 21:28:58 +08:00
Luis Pater d138df07bf Merge branch 'router-for-me:main' into main 2025-12-05 21:28:32 +08:00
Luis Pater c5df8e7897 Merge pull request #422 from router-for-me/amp
Amp
2025-12-05 21:25:43 +08:00
Luis Pater d4d529833d **refactor(antigravity): handle anyOf property, remove exclusiveMinimum, and comment unused prod URL** 2025-12-05 21:24:12 +08:00
hkfires caa48e7c6f fix(amp): improve proxy state management and request logging behavior 2025-12-05 21:09:53 +08:00
hkfires acdfb3bceb feat(amp): add root-level /threads routes for CLI compatibility 2025-12-05 18:14:10 +08:00
hkfires 89d68962b1 fix(amp): filter amp request logging to only provider endpoint 2025-12-05 18:14:09 +08:00
Luis Pater 691cdb6bdf **fix(api): update GitHub release URL and user agent for CLIProxyAPIPlus** 2025-12-05 10:32:28 +08:00
Luis Pater 8064cba288 Merge branch 'router-for-me:main' into main 2025-12-05 10:31:30 +08:00
Luis Pater 361443db10 **feat(api): add GetLatestVersion endpoint to fetch latest release version from GitHub** 2025-12-05 10:29:12 +08:00
Luis Pater d6352dd4d4 **feat(util): add DeleteKey function and update antigravity executor for Claude model compatibility** 2025-12-05 01:55:45 +08:00
Luis Pater f8aba62860 Merge branch 'router-for-me:main' into main 2025-12-05 00:45:51 +08:00
Luis Pater a7eeb06f3d Merge pull request #418 from router-for-me/amp
Amp
2025-12-05 00:43:15 +08:00
hkfires 9426be7a5c fix(amp): update log message wording for disabled proxy state 2025-12-04 21:36:16 +08:00
hkfires 4a135f1986 feat(amp): add hot-reload support for upstream URL and localhost restriction 2025-12-04 21:30:59 +08:00
hkfires c4c02f4ad0 feat(amp): add partial reload support with config change detection 2025-12-04 21:30:59 +08:00
Luis Pater b87b9b455f Merge pull request #416 from router-for-me/amp
Amp
2025-12-04 20:52:33 +08:00
hkfires db03ae9663 feat(watcher): add AmpCode config change detection 2025-12-04 19:50:54 +08:00
hkfires 969ff6bb68 fix(amp): update explicit API key on config change 2025-12-04 19:32:44 +08:00
Luis Pater e24af6e545 Merge branch 'router-for-me:main' into main 2025-12-04 18:03:42 +08:00
Luis Pater bceecfb2e3 Fixed: #414
**refactor(gemini): comment out unused CLI preview entry**
2025-12-04 17:55:13 +08:00
Luis Pater 48dd987867 Merge branch 'router-for-me:main' into main 2025-12-04 16:14:52 +08:00
Luis Pater 6a2906e3e5 **feat(antigravity): add support for Claude-Opus-4-5-Thinking model** 2025-12-04 16:13:13 +08:00
Luis Pater d72886c801 Merge pull request #405 from thurstonsand/fix/amp-missing-proxy-routes
fix(amp): add missing /auth/* and /api/tab/* proxy routes for AMP CLI
2025-12-03 22:23:41 +08:00
Luis Pater 6efba3d829 Merge pull request #406 from router-for-me/api
refactor(api): remove legacy generative-language-api-key endpoints and duplicate GetConfigYAML
2025-12-03 22:21:15 +08:00
Luis Pater 6b60bdd139 Merge branch 'router-for-me:main' into main 2025-12-03 21:55:29 +08:00
Luis Pater 897c40bed8 feat(registry): add DeepSeek-V3.2-Chat model definition
Add new DeepSeek-V3.2-Chat model to the registry with standard chat configuration, positioned before the experimental variant for better organization.
2025-12-03 21:34:50 +08:00
Thurston Sandberg 373ea8d7e4 fix(logging): handle nil caller in LogFormatter to prevent panic 2025-12-03 05:54:38 -05:00
hkfires b5de004c01 refactor(api): remove legacy generative-language-api-key endpoints and duplicate GetConfigYAML 2025-12-03 18:35:08 +08:00
Thurston Sandberg 94ec772521 test(amp): add tests for /auth/* and /api/tab/* routes 2025-12-03 05:03:25 -05:00
Thurston Sandberg e216d26731 fix(amp): add missing /auth/* and /api/tab/* proxy routes 2025-12-03 04:40:32 -05:00
Luis Pater 8a98506a15 Merge branch 'router-for-me:main' into main 2025-12-03 16:20:02 +08:00
Luis Pater 6eb94dac33 Merge pull request #404 from router-for-me/config
Legacy Config Migration and Amp Consolidation
2025-12-03 16:11:06 +08:00
hkfires c4a5be6edf style(amp): standardize log message capitalization 2025-12-03 13:53:18 +08:00
hkfires 651179a642 refactor(config): add detailed logging for legacy configuration migration 2025-12-03 13:39:10 +08:00
hkfires 8c42b21e66 refactor(config): improve OpenAI compatibility target matching logic 2025-12-03 12:41:17 +08:00
hkfires b693d632d2 docs(config): comment out example API key configurations 2025-12-03 12:31:41 +08:00
hkfires b5033c22d8 refactor(config): auto-persist migrated legacy configuration fields 2025-12-03 12:26:04 +08:00
hkfires df0fd1add1 refactor(config): remove deprecated AMP configuration keys during save 2025-12-03 11:42:15 +08:00
hkfires b6bdbe78ef refactor(config): relocate legacy migration helpers to end of file 2025-12-03 11:23:11 +08:00
hkfires 06c0d2bab2 refactor(config): remove deprecated legacy API key fields 2025-12-03 11:01:56 +08:00
hkfires bd1678457b refactor(config): consolidate Amp settings into AmpCode struct 2025-12-03 10:42:28 +08:00
hkfires 559b7df404 refactor(config): restructure and uncomment example configuration 2025-12-03 10:29:36 +08:00
Luis Pater dcd0ff834e Merge branch 'router-for-me:main' into main 2025-12-03 07:24:42 +08:00
Luis Pater 8b13c91132 **docs(internal): add Codex instruction guides for GPT-5 CLI**
- Added `gpt_5_1_prompt.md` and `gpt_5_codex_prompt.md` to document Codex instruction guidelines.
- These detail the behavior, constraints, and execution policies for GPT-5-based Codex agents in the CLI environment.
2025-12-03 07:23:01 +08:00
Luis Pater e93f87294a refactor(antigravity): uncomment prod environment URL in fallback chain 2025-12-02 22:47:18 +08:00
Luis Pater a6fa622aca Merge branch 'router-for-me:main' into main 2025-12-02 22:41:23 +08:00
Luis Pater a67b6811d1 Fixed: #397
fix(auth): use proxy HTTP client for Gemini CLI token requests
2025-12-02 22:39:01 +08:00
Luis Pater 6ee95b18f7 Merge branch 'router-for-me:main' into main 2025-12-02 22:29:53 +08:00
Luis Pater 35fdc4cfd3 fix some bugs (#399)
* feat(config): add pruning of stale YAML mapping keys during config save

* Revert watcher.go in "fix: enable hot reload for amp-model-mappings config"
2025-12-02 22:28:30 +08:00
hkfires 3ebbab0a9a Revert watcher.go in "fix: enable hot reload for amp-model-mappings config" 2025-12-02 22:17:54 +08:00
hkfires 480cd714b2 feat(config): add pruning of stale YAML mapping keys during config save 2025-12-02 21:38:54 +08:00
Luis Pater 8afcc710d4 Merge branch 'router-for-me:main' into main 2025-12-02 18:34:13 +08:00
Luis Pater 41ee44432d **fix(translator): rename responseSchema key for generationConfig**
- Renamed `generationConfig.responseSchema` to `generationConfig.responseJsonSchema` in Gemini request transformation to align with updated schema expectations.
2025-12-02 18:32:23 +08:00
Luis Pater 4419b71699 Merge pull request #2 from router-for-me/v6.5.32
v6.5.32
2025-12-02 11:46:42 +08:00
Luis Pater 43cac7b5f6 Merge branch 'main' into v6.5.32 2025-12-02 11:46:05 +08:00
Luis Pater 1434bc38e5 **refactor(registry): remove Qwen3-Coder from model definitions** 2025-12-02 11:34:38 +08:00
Luis Pater 0fd2abbc3b **refactor(cliproxy, config): remove vertex-compat flow, streamline Vertex API key handling**
- Removed `vertex-compat` executor and related configuration.
- Consolidated Vertex compatibility checks into `vertex` handling with `apikey`-based model resolution.
- Streamlined model generation logic for Vertex API key entries.
2025-12-02 09:18:24 +08:00
Aero 0ebb654019 feat: Add support for VertexAI compatible service (#375)
feat: consolidate Vertex AI compatibility with API key support in Gemini
2025-12-02 08:14:22 +08:00
Luis Pater 08a1d2edf9 Merge pull request #390 from NguyenSiTrung/main
feat(amp): add model mapping support for routing unavailable models to alternatives
2025-12-02 08:07:56 +08:00
NguyenSiTrung 3409f4e336 fix: enable hot reload for amp-model-mappings config
- Store ampModule in Server struct to access it during config updates
- Call ampModule.OnConfigUpdated() in UpdateClients() for hot reload
- Watch config directory instead of file to handle atomic saves (vim, VSCode, etc.)
- Improve config file event detection with basename matching
- Add diagnostic logging for config reload tracing
2025-12-01 13:34:49 +07:00
NguyenSiTrung 9354b87e54 Merge branch 'router-for-me:main' into main 2025-12-01 08:12:29 +07:00
Luis Pater c6ecdf4a7e Merge pull request #1 from router-for-me/Plus
v6.5.31
2025-12-01 09:10:55 +08:00
Luis Pater 838f47a7e9 Merge branch 'main' into Plus 2025-12-01 09:10:29 +08:00
Luis Pater 54e24110ec Merge pull request #386 from auroraflux/feat/dedupe-thinking-metadata-helpers
refactor(executor): dedupe thinking metadata helpers across Gemini executors
2025-12-01 09:00:27 +08:00
Luis Pater 717c703bff docs(readme): add CCS (Claude Code Switch) to projects list 2025-12-01 07:22:42 +08:00
auroraflux 1c6f4be8ae refactor(executor): dedupe thinking metadata helpers across Gemini executors
Extract applyThinkingMetadata and applyThinkingMetadataCLI helpers to
payload_helpers.go and use them across all four Gemini-based executors:
- gemini_executor.go (Execute, ExecuteStream, CountTokens)
- gemini_cli_executor.go (Execute, ExecuteStream, CountTokens)
- aistudio_executor.go (translateRequest)
- antigravity_executor.go (Execute, ExecuteStream)

This eliminates code duplication introduced in the -reasoning suffix PR
and centralizes the thinking config application logic.

Net reduction: 28 lines of code.
2025-11-30 15:20:15 -08:00
Luis Pater 0de2560cee Merge pull request #379 from kaitranntt/docs/add-ccs-project
docs: add CCS (Claude Code Switch) to projects list
2025-12-01 07:20:04 +08:00
Kai (Tam Nhu) Tran 85eb926482 fix: change AGY to Antigravity 2025-11-30 12:43:12 -05:00
Kai (Tam Nhu) Tran c52ef08e67 docs: add CCS to projects list 2025-11-30 12:40:35 -05:00
Luis Pater 5b01eba943 Merge branch 'router-for-me:main' into main 2025-11-30 21:30:49 +08:00
Luis Pater cb580cd083 Merge pull request #377 from router-for-me/gemini
feat(registry): add thinking support to gemini models
2025-11-30 21:27:54 +08:00
hkfires 75e278c7a5 feat(registry): add thinking support to gemini models 2025-11-30 20:56:29 +08:00
Luis Pater 73208c4e55 Merge pull request #376 from auroraflux/feat/reasoning-suffix-support
feat(util): add -reasoning suffix support for Gemini models
2025-11-30 20:55:38 +08:00
Luis Pater 8203bf64ec **docs: update README for CLIProxyAPI Plus and rename artifacts**
- Updated README files to reflect the new 'Plus' variant with detailed third-party provider support information.
- Adjusted Dockerfile, `docker-compose.yml`, and build configurations to align with the `CLIProxyAPIPlus` naming convention.
- Added information about GitHub Copilot OAuth integration contributed by the community.
2025-11-30 20:16:51 +08:00
Luis Pater 52e5551d8f **chore(build): rename artifacts and adjust workflows for 'plus' variant**
- Updated Docker and release workflows to use `cli-proxy-api-plus` as the Docker repository name and adjusted tag generation logic.
- Renamed artifacts in Goreleaser configuration to align with the new 'plus' variant naming convention.
2025-11-30 17:54:37 +08:00
Luis Pater 0087eecad8 **fix(build): append '-plus' suffix to version metadata in workflows and Goreleaser**
- Updated release and Docker workflows to ensure the `-plus` suffix is added to build versions when missing.
- Adjusted Goreleaser configuration to include `-plus` suffix in `main.Version` during build process.
2025-11-30 17:23:47 +08:00
auroraflux 32d3809f8c **feat(util): add -reasoning suffix support for Gemini models**
Adds support for the `-reasoning` model name suffix which enables
thinking/reasoning mode with dynamic budget. This allows clients to
request reasoning-enabled inference using model names like
`gemini-2.5-flash-reasoning` without explicit configuration.

The suffix is normalized to the base model (e.g., gemini-2.5-flash)
with thinkingBudget=-1 (dynamic) and include_thoughts=true.

Follows the existing pattern established by -nothinking and
-thinking-N suffixes.
2025-11-30 01:18:57 -08:00
Luis Pater fa087eeefa Merge pull request #362 from em4go/feature/github-copilot-auth
feat(auth): add GitHub Copilot authentication and API integration
2025-11-30 17:08:26 +08:00
Luis Pater 1a9f939eac Merge branch 'plus-dev' into feature/github-copilot-auth 2025-11-30 17:08:00 +08:00
Luis Pater a748e93fd9 **fix(executor, auth): ensure index assignment consistency for auth objects**
- Updated `usage_helpers.go` to call `EnsureIndex()` for proper index assignment in reporter initialization.
- Adjusted `auth/manager.go` to assign auth indices inside a locked section when they are unassigned, ensuring thread safety and consistency.
2025-11-30 16:56:29 +08:00
Luis Pater 54a9c4c3c7 Merge pull request #371 from ben-vargas/test-amp-tools
fix(amp): add /threads.rss root-level route for AMP CLI
2025-11-30 15:18:23 +08:00
Luis Pater 18b5c35dea Merge pull request #366 from router-for-me/blacklist
Add Model Blacklist
2025-11-30 15:17:46 +08:00
hkfires 7b7871ede2 feat(api): add oauth excluded model management 2025-11-30 13:38:23 +08:00
hkfires c4e3646b75 docs(config): expand model exclusion examples 2025-11-30 11:55:47 +08:00
hkfires 022aa81be1 feat(cliproxy): support wildcard exclusions for models 2025-11-30 08:02:00 +08:00
hkfires c43f0ea7b1 refactor(config): rename model blacklist fields to excluded models 2025-11-29 21:23:47 +08:00
hkfires 6a191358af fix(auth): fix runtime auth reload on oauth blacklist change 2025-11-29 20:30:11 +08:00
Ben Vargas db1119dd78 fix(amp): add /threads.rss root-level route for AMP CLI
AMP CLI requests /threads.rss at the root level, but the AMP module
only registered routes under /api/*. This caused a 404 error during
AMP CLI startup.

Add the missing root-level route with the same security middleware
(noCORS, optional localhost restriction) as other management routes.
2025-11-29 05:01:19 -07:00
Trung Nguyen 33a5656235 docs: add model mapping documentation for Amp CLI integration
- Add model mapping feature to README.md Amp CLI section
- Add detailed Model Mapping Configuration section to amp-cli-integration.md
- Update architecture diagram to show model mapping flow
- Update Model Fallback Behavior to include mapping step
- Add Table of Contents entry for model mapping
2025-11-29 12:51:03 +07:00
Trung Nguyen 2cd59806e2 feat(amp): add model mapping support for routing unavailable models to alternatives
- Add AmpModelMapping config to route models like 'claude-opus-4.5' to 'claude-sonnet-4'
- Add ModelMapper interface and DefaultModelMapper implementation with hot-reload support
- Enhance FallbackHandler to apply model mappings before falling back to ampcode.com
- Add structured logging for routing decisions (local provider, mapping, amp credits)
- Update config.example.yaml with amp-model-mappings documentation
2025-11-29 12:44:09 +07:00
Ernesto Martínez 7515090cb6 refactor(executor): improve concurrency and code quality in GitHub Copilot executor
- Replace concurrent-unsafe metadata caching with thread-safe sync.RWMutex-protected map
- Extract magic numbers and hardcoded header values to named constants
- Replace verbose status code checks with isHTTPSuccess() helper
- Simplify normalizeModel() to no-op with explanatory comment (models already canonical)
- Remove redundant metadata manipulation in token caching
- Improve code clarity and performance with proper cache management
2025-11-28 08:33:51 +01:00
Ernesto Martínez 2c296e9cb1 refactor(copilot): improve code quality in authentication module
- Add Unwrap() to AuthenticationError for proper error chain handling with errors.Is/As
- Extract hardcoded header values to constants for maintainability
- Replace verbose status code checks with isHTTPSuccess() helper
- Remove unused ExtractBearerToken() and BuildModelsURL() functions
- Make buildChatCompletionURL() private (only used internally)
- Remove unused 'strings' import
2025-11-28 08:32:36 +01:00
hkfires 5983e3ec87 feat(auth): add oauth provider model blacklist 2025-11-28 10:37:10 +08:00
Ernesto Martínez efd28bf981 refactor(copilot): address PR review feedback
- Simplify error type checking in oauth.go using errors.As directly
- Remove redundant errors.As call in GetUserFriendlyMessage
- Remove unused CachedAPIToken and TokenManager types (dead code)
2025-11-27 22:47:51 +01:00
Ernesto Martínez 3a9ac7ef33 feat(auth): add GitHub Copilot authentication and API integration
Add complete GitHub Copilot support including:
- Device flow OAuth authentication via GitHub's official client ID
- Token management with automatic caching (25 min TTL)
- OpenAI-compatible API executor for api.githubcopilot.com
- 16 model definitions (GPT-5 variants, Claude variants, Gemini, Grok, Raptor)
- CLI login command via -github-copilot-login flag
- SDK authenticator and refresh registry integration

Enables users to authenticate with their GitHub Copilot subscription and
use it as a backend provider alongside existing providers.
2025-11-27 20:14:30 +01:00
hkfires f8cebb9343 feat(config): add per-key model blacklist for providers 2025-11-27 21:57:07 +08:00
Luis Pater 72c7ef7647 **fix(translator): handle non-JSON output parsing for OpenAI function responses**
- Updated `antigravity_openai_request.go` to process non-JSON outputs gracefully by verifying and distinguishing between JSON and plain string formats.
- Ensured proper assignment of parsed or raw response to `functionResponse`.
2025-11-27 16:18:49 +08:00
Luis Pater d2e4639b2a **feat(registry): add context length and update max tokens for Claude model configurations**
- Added `ContextLength` field with a value of 200,000 to all applicable Claude model definitions.
- Standardized `MaxCompletionTokens` values across models for consistency and alignment.
2025-11-27 16:13:25 +08:00
Luis Pater 08321223c4 Merge pull request #340 from nestharus/fix/339-thinking-openai-gemini-compat
fix(thinking): resolve OpenAI/Gemini compatibility for thinking model…
2025-11-27 16:03:24 +08:00
Luis Pater 7e30157590 Fixed: #354
**fix(translator): add support for "xhigh" reasoning effort in OpenAI responses**

- Updated handling in `openai_openai-responses_request.go` to include the new "xhigh" reasoning effort level.
2025-11-27 15:59:15 +08:00
nestharusandClaude e73cdf5cff fix(claude): ensure max_tokens exceeds thinking budget for thinking models
Fixes an issue where Claude thinking models would return 400 errors when
the thinking.budget_tokens was greater than or equal to max_tokens.

Changes:
- Add MaxCompletionTokens: 128000 to all Claude thinking model definitions
- Add ensureMaxTokensForThinking() function in claude_executor.go that:
  - Checks if thinking is enabled with a budget_tokens value
  - Looks up the model's MaxCompletionTokens from the registry
  - Ensures max_tokens is set to at least the model's MaxCompletionTokens
  - Falls back to budget_tokens + 4000 buffer if registry lookup fails

This ensures Anthropic API constraint (max_tokens > thinking.budget_tokens)
is always satisfied when using extended thinking features.

Fixes: #339

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-26 22:31:05 -08:00
Luis Pater 39621a0340 **fix(translator): normalize function calls and outputs for consistent input processing**
- Implemented logic to pair consecutive function calls and their outputs, ensuring proper sequencing for processing.
- Adjusted `gemini_openai-responses_request.go` to normalize message structures and maintain expected flow.
2025-11-27 10:25:45 +08:00
Luis Pater 346b663079 **fix(translator): handle non-JSON output gracefully in function call outputs**
- Updated handling of `output` in `gemini_openai-responses_request.go` to use `.Str` instead of `.Raw` when parsing non-JSON string outputs.
- Added checks to distinguish between JSON and non-JSON `output` types for accurate `functionResponse` construction.
2025-11-27 09:40:00 +08:00
Luis Pater 0bcae68c6c **fix(translator): preserve raw JSON encoding in function call outputs**
- Updated handling of `output` in `gemini_openai-responses_request.go` to use `.Raw` instead of `.String` for preserving original JSON encoding.
- Ensured proper setting of raw JSON output when constructing `functionResponse`.
2025-11-27 08:26:53 +08:00
Luis Pater c8cee547fd **fix(translator): ensure partial content is retained while skipping encrypted thoughtSignature**
- Updated handling of `thoughtSignature` across all translator modules to retain other content payloads if present.
- Adjusted logic for `thought_signature` and `inline_data` keys for consistent processing.
2025-11-27 00:52:17 +08:00
Luis Pater 36755421fe Merge pull request #343 from router-for-me/misc
style(amp): tidy whitespace in proxy module and tests
2025-11-26 19:03:07 +08:00
hkfires 6c17dbc4da style(amp): tidy whitespace in proxy module and tests 2025-11-26 18:57:26 +08:00
Luis Pater ee6429cc75 **feat(registry): add Gemini 3 Pro Image Preview model and remove Claude Sonnet 4.5 Thinking**
- Added new `Gemini 3 Pro Image Preview` model with detailed metadata and configuration.
- Removed outdated `Claude Sonnet 4.5 Thinking` model definition for cleanup and relevance.
2025-11-26 18:22:40 +08:00
Luis Pater a4a26d978e Fixed: #339
**feat(handlers, executor): add Gemini 3 Pro Preview support and refine Claude system instructions**

- Added support for the new "Gemini 3 Pro Preview" action in Gemini handlers, including detailed metadata and configuration.
- Removed redundant `cache_control` field from Claude system instructions for cleaner payload structure.
2025-11-26 11:42:57 +08:00
Luis Pater ed9f6e897e Fixed: #337
**fix(executor): replace redundant commented code with `checkSystemInstructions` helper**

- Replaced commented-out `sjson.SetRawBytes` lines with the new `checkSystemInstructions` function.
- Centralized system instruction handling for better code clarity and reuse.
- Ensured consistent logic for managing `system` field across Claude executor flows.
2025-11-26 08:27:48 +08:00
Luis Pater 9c1e3c0687 Merge pull request #334 from nestharus/feat/claude-thinking-and-beta-headers
feat(claude): add thinking model variants and beta headers support
2025-11-26 02:17:02 +08:00
Luis Pater 2e5681ea32 Merge branch 'dev' into feat/claude-thinking-and-beta-headers 2025-11-26 02:16:40 +08:00
Luis Pater 52c17f03a5 **fix(executor): comment out redundant code for setting Claude system instructions**
- Commented out multiple instances of `sjson.SetRawBytes` for setting `system` key to Claude instructions as they are redundant.
- Code cleanup to improve clarity and maintainability without affecting functionality.
2025-11-26 02:06:16 +08:00
nestharus d0e694d4ed feat(claude): add thinking model variants and beta headers support
- Add Claude thinking model definitions (sonnet-4-5-thinking, opus-4-5-thinking variants)
- Add Thinking support for antigravity models with -thinking suffix
- Add injectThinkingConfig() for automatic thinking budget based on model suffix
- Add resolveUpstreamModel() mappings for thinking variants to actual Claude models
- Add extractAndRemoveBetas() to convert betas array to anthropic-beta header
- Update applyClaudeHeaders() to merge custom betas from request body

Closes #324
2025-11-25 03:33:05 -08:00
Luis Pater 506f1117dd **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.
2025-11-25 11:37:02 +08:00
Luis Pater 113db3c5bf **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.
2025-11-25 09:19:01 +08:00
Luis Pater 1aa0b6cd11 Merge pull request #322 from ben-vargas/feat-claude-opus-4-5
feat(registry): add Claude Opus 4.5 model definition
2025-11-25 08:38:06 +08:00
Ben Vargas 0895533400 fix(registry): correct Claude Opus 4.5 created timestamp
Update epoch from 1730419200 (2024-11-01) to 1761955200 (2025-11-01).
2025-11-24 12:27:23 -07:00
Ben Vargas 43f007c234 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.
2025-11-24 12:26:39 -07:00
Luis Pater 0ceee56d99 Merge pull request #318 from router-for-me/log
feat(logs): add limit query param to cap returned logs
2025-11-24 20:35:28 +08:00
hkfires 943a8c74df feat(logs): add limit query param to cap returned logs 2025-11-24 19:59:24 +08:00
Luis Pater 0a47b452e9 **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.
2025-11-24 17:15:43 +08:00
Luis Pater 261f08a82a **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.
2025-11-24 17:12:04 +08:00
Luis Pater d114d8d0bd **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.
2025-11-24 10:41:29 +08:00
Luis Pater bb9955e461 **fix(auth): resolve index reassignment issue during auth management**
- Fixed improper handling of `indexAssigned` and `Index` during auth reassignment.
- Ensured `EnsureIndex` is invoked after validating existing auth entries.
2025-11-24 10:10:09 +08:00
Luis Pater 7063a176f4 #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`.
2025-11-24 09:55:15 +08:00
Luis Pater e3082887a6 **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.
2025-11-23 22:41:57 +08:00
Luis Pater ddb0c0ec1c **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.
2025-11-23 20:52:23 +08:00
Luis Pater d1736cb29c Merge pull request #315 from router-for-me/aistudio
fix(aistudio): strip Gemini generation config overrides
2025-11-23 20:25:59 +08:00
hkfires 62bfd62871 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.
2025-11-23 19:44:03 +08:00
Luis Pater 257621c5ed **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.
2025-11-23 17:53:07 +08:00
Luis Pater ac064389ca **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.
2025-11-23 11:32:37 +08:00
Luis Pater 8d23ffc873 **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.
2025-11-23 03:16:14 +08:00
Luis Pater 4307f08bbc **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.
2025-11-23 01:22:16 +08:00
Luis Pater 9d50a68768 **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.
2025-11-22 21:34:34 +08:00
Luis Pater 7c3c24addc Merge pull request #306 from router-for-me/usage
fix some bugs
2025-11-22 17:45:49 +08:00
hkfires 166fa9e2e6 fix(gemini): parse stream usage from JSON, skip thoughtSignature 2025-11-22 16:07:12 +08:00
hkfires 88e566281e fix(gemini): filter SSE usage metadata in streams 2025-11-22 15:53:36 +08:00
hkfires d32bb9db6b fix(runtime): treat non-empty finishReason as terminal 2025-11-22 15:39:46 +08:00
hkfires 8356b35320 fix(executor): expire stop chunks without usage metadata 2025-11-22 15:27:47 +08:00
hkfires 19a048879c feat(runtime): track antigravity usage and token counts 2025-11-22 14:04:28 +08:00
hkfires 1061354b2f fix: handle empty and non-JSON SSE chunks safely 2025-11-22 13:49:23 +08:00
hkfires 46b4110ff3 fix: preserve SSE usage metadata-only trailing chunks 2025-11-22 13:25:25 +08:00
hkfires c29931e093 fix(translator): ignore empty JSON chunks in OpenAI responses 2025-11-22 13:09:16 +08:00
hkfires b05cfd9f84 fix(translator): include empty text chunks in responses 2025-11-22 13:03:50 +08:00
hkfires 8ce22b8403 fix(sse): preserve usage metadata for stop chunks 2025-11-22 12:50:23 +08:00
Luis Pater d1cdedc4d1 Merge pull request #303 from router-for-me/image
feat(translator): support image size and googleSearch tools
2025-11-22 11:20:58 +08:00
Luis Pater d291eb9489 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.
2025-11-22 11:18:13 +08:00
hkfires dc8d3201e1 feat(translator): support image size and googleSearch tools 2025-11-22 10:36:52 +08:00
Luis Pater 7757210af6 **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.
2025-11-22 01:45:06 +08:00
Luis Pater cbf9a57135 **build(goreleaser): set CGO_ENABLED=0 for cli-proxy-api binaries**
- Disabled CGO to produce statically linked binaries.
- Minor formatting adjustment for newline at EOF.
2025-11-21 23:59:02 +08:00
Luis Pater c1031e2d3f **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`.
2025-11-21 23:40:59 +08:00
Luis Pater 327cc7039e **refactor(auth): use customizable HTTP client for Antigravity requests**
- Replaced `http.DefaultClient` with a configurable `http.Client` instance for Antigravity OAuth flow methods.
- Updated `exchangeAntigravityCode` and `fetchAntigravityUserInfo` to accept `httpClient` as a parameter.
- Added `util.SetProxy` usage to initialize the `httpClient` with proxy support.
2025-11-21 20:54:56 +08:00
Luis Pater b4d15ace91 Merge pull request #296 from router-for-me/antigravity
Antigravity bugfix
2025-11-21 17:32:36 +08:00
hkfires abc2465b29 fix(gemini-cli): ignore thoughtSignature and empty parts 2025-11-21 17:12:56 +08:00
hkfires 4ba5b43d82 feat(executor): share SSE usage filtering across streams 2025-11-21 16:51:05 +08:00
hkfires 27faf718a3 fix(auth): use fixed antigravity callback port 51121 2025-11-21 13:56:33 +08:00
Luis Pater 2d84d2fb6a **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.
2025-11-21 12:43:16 +08:00
Luis Pater cbcfeb92cc 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.
2025-11-21 00:48:12 +08:00
Luis Pater db81331ae8 **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**
2025-11-20 23:20:40 +08:00
Luis Pater 93fa1d1802 **docs: add Amp CLI integration guide to Chinese documentation**
- Updated `README_CN.md` to introduce Amp CLI and IDE support.
- Added detailed integration guide in `docs/amp-cli-integration_CN.md`.
- Covered setup, configuration, OAuth, security, and usage of Amp CLI with Google/ChatGPT/Claude subscriptions.
2025-11-20 21:07:20 +08:00
Luis Pater b70bfd8092 Merge pull request #287 from ben-vargas/feat-amp-cli-module
Amp CLI Integration Module
2025-11-20 20:28:03 +08:00
Luis Pater 9ff38dd785 Merge branch 'dev' into feat-amp-cli-module 2025-11-20 20:26:47 +08:00
Luis Pater 98596c0a3f **refactor(translator): remove service_tier from Codex OpenAI request payload** 2025-11-20 20:12:06 +08:00
Luis Pater 670ce2e528 Merge pull request #285 from router-for-me/iflow
feat(iflow): add cookie-based authentication endpoint
2025-11-20 20:04:38 +08:00
hkfires 3f4f8b3b2d feat(iflow): add cookie-based authentication endpoint 2025-11-20 18:23:43 +08:00
Luis Pater 371324c090 **feat(registry): expand Gemini model definitions and support Vertex AI** 2025-11-20 18:16:26 +08:00
Luis Pater d50b0f7524 **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.
2025-11-20 17:49:37 +08:00
Ben Vargas a6cb16bb48 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.
2025-11-19 22:09:04 -07:00
Ben Vargas 70ee4e0aa0 chore: remove unused httpx sdk package 2025-11-19 21:17:52 -07:00
Ben Vargas 03334f8bb4 chore: revert gitignore change 2025-11-19 20:42:23 -07:00
Ben Vargas 5a2bebccfa fix: remove duplicate CountTokens stub 2025-11-19 20:00:39 -07:00
Luis Pater 0586da9c2b **refactor(registry): move Gemini 3 Pro Preview model definition to base set** 2025-11-20 10:51:16 +08:00
Ben Vargas 3d8d02bfc3 Fix amp v1beta1 routing and gemini retry config 2025-11-19 19:11:35 -07:00
Ben Vargas 7ae00320dc 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.
2025-11-19 18:23:17 -07:00
Ben Vargas 1fb96f5379 docs: reposition Amp CLI as integrated feature for upstream PR
- Update README.md to present Amp CLI as standard feature, not fork differentiator
- Remove USING_WITH_FACTORY_AND_AMP.md (fork-specific, Factory docs live upstream)
- Add comprehensive docs/amp-cli-integration.md with setup, config, troubleshooting
- Eliminate fork justification messaging throughout documentation
- Prepare Amp CLI integration for upstream merge consideration

This positions Amp CLI support as a natural extension of CLIProxyAPI's
multi-client architecture rather than a fork-specific feature.
2025-11-19 18:23:17 -07:00
Ben Vargas 897d108e4c docs: update Factory config with GPT-5.1 models and explicit reasoning levels
- Replace deprecated GPT-5 and GPT-5-Codex with GPT-5.1 family
- Add explicit reasoning effort levels (low/medium/high)
- Remove duplicate base models (use medium as default)
- GPT-5.1 Codex Mini supports medium/high only (per OpenAI docs)
- Remove older Claude Sonnet 4 (keep 4.5)
- Final config: 11 models (3 Claude + 8 GPT-5.1 variants)
2025-11-19 18:23:17 -07:00
Ben Vargas 72d82268e5 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.
2025-11-19 18:23:17 -07:00
Ben Vargas 8193392bfe 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
2025-11-19 18:23:17 -07:00
Ben Vargas 9ad0f3f91e 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
2025-11-19 18:23:17 -07:00
Luis Pater 618511ff67 Merge pull request #280 from ben-vargas/feat-enable-gemini-3-cli
feat: enable Gemini 3 Pro Preview with OAuth support
2025-11-20 08:46:57 +08:00
Ben Vargas 0ff094b87f 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
2025-11-19 13:14:40 -07:00
Ben Vargas ed23472d94 fix(executor): prevent streaming from 429 response when fallback available
Fix critical bug where ExecuteStream would create a streaming channel
using a 429 error response instead of continuing to the next fallback
model after exhausting retries.

When 429 retries were exhausted and a fallback model was available,
the inner retry loop would break but immediately fall through to the
streaming channel creation, attempting to stream from the failed 429
response instead of trying the next model.

Solution: Add shouldContinueToNextModel flag to explicitly skip the
streaming logic and continue the outer model loop when appropriate.

Identified by: codex-bot review
Ref: https://github.com/router-for-me/CLIProxyAPI/pull/280#pullrequestreview-3484479106
2025-11-19 13:05:38 -07:00
Ben Vargas ede4471b84 feat(translator): add default thinkingConfig for gemini-3-pro-preview
Match official Gemini CLI behavior by always sending default
thinkingConfig when client doesn't specify reasoning parameters.

- Set thinkingBudget=-1 (dynamic) for gemini-3-pro-preview
- Set include_thoughts=true to return thinking process
- Apply to both /v1/chat/completions and /v1/responses endpoints
- See: ai-gemini-cli/packages/core/src/config/defaultModelConfigs.ts
2025-11-19 12:47:39 -07:00
Ben Vargas 6a3de3a89c feat(executor): add intelligent retry logic for 429 rate limits
Implement Google RetryInfo.retryDelay support for handling 429 rate
limit errors. Retries same model up to 3 times using exact delays
from Google's API before trying fallback models.

- Add parseRetryDelay() to extract Google's retry guidance
- Implement inner retry loop in Execute() and ExecuteStream()
- Context-aware waiting with cancellation support
- Cap delays at 60s maximum for safety
2025-11-19 12:47:39 -07:00
Ben Vargas 782bba0bc4 feat(registry): enable gemini-3-pro-preview for gemini-cli provider
Add gemini-3-pro-preview model to GetGeminiCLIModels() to make it
available for OAuth-based Gemini CLI users, matching the model
already available in AI Studio provider.

Model spec:
- ID: gemini-3-pro-preview
- Version: 3.0
- Input: 1M tokens
- Output: 64K tokens
- Thinking: 128-32K tokens (dynamic)
2025-11-19 12:47:39 -07:00
Luis Pater bf116b68f8 **feat(registry): add GPT-5.1 Codex Max model definitions and support**
- Introduced `gpt-5.1-codex-max` variants to model definitions (`low`, `medium`, `high`, `xhigh`).
- Updated executor logic to map effort levels for Codex Max models.
- Added `lastCodexMaxPrompt` processing for `gpt-5.1-codex-max` prompts.
- Defined instructions for `gpt-5.1-codex-max` in a new file: `codex_instructions/gpt-5.1-codex-max_prompt.md`.
2025-11-20 03:12:22 +08:00
Luis Pater cc3cf09c00 **feat(auth): add AuthIndex for diagnostics and ensure usage recording** 2025-11-19 22:02:40 +08:00
Luis Pater 9acfbcc2a0 Merge pull request #275 from router-for-me/iflow
Iflow
2025-11-19 20:44:54 +08:00
hkfires b285b07986 fix(iflow): adjust auth filename email sanitization 2025-11-19 19:50:06 +08:00
Luis Pater c40e00526b Merge pull request #274 from router-for-me/log
fix: detect HTML error bodies without text/html content type
2025-11-19 17:40:06 +08:00
hkfires 8a33f3ef69 fix: detect HTML error bodies without text/html content type 2025-11-19 14:45:33 +08:00
Luis Pater 7a8e00fcea **fix(translator): handle missing parameters in Gemini tool schema gracefully** 2025-11-19 13:19:46 +08:00
Luis Pater 89771216a1 **feat(translator): add ThoughtSignature handling in Gemini request transformations** 2025-11-19 11:34:13 +08:00
Luis Pater 14ddfd4b79 Merge pull request #270 from router-for-me/iflow
feat(auth): add iFlow cookie-based authentication support
2025-11-19 01:54:34 +08:00
Luis Pater 567227f35f Merge pull request #268 from router-for-me/tools
fix: use underscore suffix in short name mapping
2025-11-19 01:43:41 +08:00
Luis Pater 17016ae6a5 **feat(registry): add Gemini 3 Pro Preview model definition** 2025-11-18 23:48:21 +08:00
Luis Pater 01b7b60901 **feat(registry): add Gemini 3 Pro Preview model definition** 2025-11-18 23:46:58 +08:00
hkfires b52a5cc066 feat(auth): add iFlow cookie-based authentication support 2025-11-18 22:35:35 +08:00
hkfires 1ba057112a fix: use underscore suffix in short name mapping
Replace the "~<n>" suffix with "_<n>" when generating unique short names in codex translators (Claude, Gemini, OpenAI chat).
This avoids using a special character in identifiers, improving compatibility with downstream APIs while preserving length constraints.
2025-11-18 16:59:25 +08:00
Luis Pater 23a7633e6d **fix(registry): update Thinking parameters and replace Gemini-3 Preview with Gemini-2.5 Flash Lite** 2025-11-18 11:51:52 +08:00
Luis Pater e5e985978d Fixed: #263
**fix(translator): remove input_examples from tool schema in Gemini-Claude requests**
2025-11-18 11:27:48 +08:00
Luis Pater db2d22c978 **fix(runtime): simplify scanner buffer allocation in executor implementations** 2025-11-18 10:59:49 +08:00
Luis Pater 1c815c58a6 **fix(translator): simplify string handling in Gemini responses** 2025-11-16 19:02:27 +08:00
Luis Pater 4eab141410 **feat(translator): add support for reasoning/thinking content blocks in OpenAI-Claude and Gemini responses** 2025-11-16 17:37:39 +08:00
Luis Pater 5937b8e429 Fixed: #260
**fix(translator): handle simple string input conversion in Gemini responses**
2025-11-16 13:30:11 +08:00
Luis Pater 9875565339 **fix(claude translator): ensure default token counts when usage data is missing** 2025-11-16 13:18:21 +08:00
Luis Pater faa483b57d Merge pull request #257 from lollipopkit/main
fix(claude translator): guard tool schema properties
2025-11-16 12:19:38 +08:00
Luis Pater f0711be302 **fix(auth): prevent access to removed credentials lingering in memory**
Add logic to avoid exposing credentials that have been removed from disk but still persist in memory. Ensure `runtimeOnly` checks and proper handling of disabled or removed authentication states.
2025-11-16 12:12:24 +08:00
Luis Pater 1d0f0301b4 **refactor(api/config): centralize legacy OpenAI compatibility key migration**
Introduce `migrateLegacyOpenAICompatibilityKeys` to streamline and reuse the normalization of OpenAI compatibility entries. Remove redundant loops and enhance maintainability for compatibility key handling. Add cleanup for legacy `api-keys` in YAML configuration during persistence.
2025-11-16 11:39:35 +08:00
lollipopkit🏳️‍⚧️ c73b3fa43b fix(claude translator): guard tool schema properties 2025-11-15 19:14:13 +08:00
Luis Pater 772fa69515 Fixed: #254
**feat(registry): add Kimi-K2-Thinking model to model definitions**
2025-11-14 21:20:54 +08:00
Luis Pater 1ccb01631d **refactor(runtime): centralize reasoning effort logic for GPT models**
Extract reasoning effort mapping into a reusable function `setReasoningEffortByAlias` to reduce redundancy and improve maintainability. Introduce support for the "gpt-5.1-none" variant in the registry and runtime executor.
2025-11-14 17:24:40 +08:00
Luis Pater 1ede1347fa Merge pull request #249 from ben-vargas/fix-gpt5-1-reasoning
fix(runtime): remove gpt-5.1 minimal effort variant
2025-11-14 17:04:27 +08:00
Ben Vargas cfbaed0e90 fix(runtime): remove gpt-5.1 minimal effort variant
Stop advertising and mapping the unsupported gpt-5.1-minimal variant in the model registry and Codex executor, and align bare gpt-5.1 requests to use medium reasoning effort like Codex CLI while preserving minimal for gpt-5.
2025-11-13 19:43:52 -07:00
Luis Pater cf9b9be7ea **feat(runtime): extend executor support for GPT-5.1 Codex and variants**
Expand executor logic to handle GPT-5.1 Codex family and its variants, including reasoning effort configurations for minimal, low, medium, and high levels. Ensure proper mapping of models to payload parameters.
2025-11-14 08:08:25 +08:00
Luis Pater aa57f3237a **feat(instructions): add detailed agent behavior guidelines for Codex CLI**
Introduce comprehensive agent instruction documentation (`gpt_5_1_prompt.md`) for Codex CLI. Specify agent behavior, personality, planning requirements, task execution, sandboxing rules, and validation processes to standardize interactions and improve usability.
2025-11-14 06:51:54 +08:00
Luis Pater fcd98f4f9b **feat(runtime): add payload configuration support for executors**
Introduce `PayloadConfig` in the configuration to define default and override rules for modifying payload parameters. Implement `applyPayloadConfig` and `applyPayloadConfigWithRoot` to apply these rules across various executors, ensuring consistent parameter handling for different models and protocols. Update all relevant executors to utilize this functionality.
2025-11-13 23:27:40 +08:00
Luis Pater 75b57bc112 Fixed: #246
feat(runtime): add support for GPT-5.1 models and variants

Introduce GPT-5.1 model family, including minimal, low, medium, high, Codex, and Codex Mini variants. Update tokenization and reasoning effort handling to accommodate new models in executor and registry.
2025-11-13 17:42:19 +08:00
Luis Pater a7d2f669e7 feat(watcher): expand event handling for config and auth JSON updates
Refine `handleEvent` to support additional file system operations (Rename, Remove) for config and auth JSON files. Improve client update/removal logic with atomic file replacement handling and incremental processing for auth changes.
2025-11-13 12:13:31 +08:00
Luis Pater ce569ab36e feat(buildinfo): add build metadata and expose via HTTP headers
Introduce a new `buildinfo` package to store version, commit, and build date metadata. Update HTTP handlers to include build metadata in response headers and modify initialization to set `buildinfo` values during runtime.
2025-11-13 08:38:03 +08:00
Luis Pater d0aa741d59 feat(gemini-cli): add multi-project support and enhance credential handling
Introduce support for multi-project Gemini CLI logins, including shared and virtual credential management. Enhance runtime, metadata handling, and token updates for better project granularity and consistency across virtual and shared credentials. Extend onboarding to allow activating all available projects.
2025-11-13 02:55:32 +08:00
Luis Pater 592f6fc66b feat(vertex): add usage source resolution for Vertex projects
Extend `resolveUsageSource` to support Vertex projects by extracting and normalizing `project_id` or `project` from the metadata for accurate source resolution.
2025-11-12 08:43:02 +08:00
Luis Pater 09ecba6dab Merge pull request #237 from TUGOhost/feature/support_auto_model
feat: add auto model resolution and model creation timestamp tracking
2025-11-12 00:03:30 +08:00
Luis Pater d6bd6f3fb9 feat(vertex, management): enhance token handling and OAuth2 integration
Extend `vertexAccessToken` to support proxy-aware HTTP clients and update calls accordingly for better configurability. Add `deleteTokenRecord` to handle token cleanup, improving management of authentication files.
2025-11-11 23:42:46 +08:00
TUGOhost 92f4278039 feat: add auto model resolution and model creation timestamp tracking
- Add 'created' field to model registry for tracking model creation time
- Implement GetFirstAvailableModel() to find the first available model by newest creation timestamp
- Add ResolveAutoModel() utility function to resolve "auto" model name to actual available model
- Update request handler to resolve "auto" model before processing requests
- Ensures automatic model selection when "auto" is specified as model name

This enables dynamic model selection based on availability and creation time, improving the user experience when no specific model is requested.
2025-11-11 20:30:09 +08:00
Luis Pater 8ae8a5c296 Fixed: #233
feat(management): add auth ID normalization and file-based ID resolution

Introduce `authIDForPath` to standardize ID generation from file paths, improving consistency in authentication handling. Update `registerAuthFromFile` and `disableAuth` to utilize normalized IDs, incorporating relative path resolution and file name extraction where applicable.
2025-11-11 19:23:31 +08:00
Luis Pater dc804e96fb fix(management): improve error handling and normalize YAML comment indentation
Enhance error management for file operations and clean up temporary files. Add `NormalizeCommentIndentation` function to ensure YAML comments maintain consistent formatting.
2025-11-11 08:37:57 +08:00
Luis Pater ab76cb3662 feat(management): add Vertex service account import and WebSocket auth management
Introduce an endpoint for importing Vertex service account JSON keys and storing them as authentication records. Add handlers for managing WebSocket authentication configuration.
2025-11-10 20:48:31 +08:00
Luis Pater 2965bdadc1 fix(translator): remove debug print statement from OpenAI Gemini request processing 2025-11-10 18:37:05 +08:00
Luis Pater 40f7061b04 feat(watcher): debounce config reloads to prevent redundant operations
Introduce `scheduleConfigReload` with debounce functionality for config reloads, ensuring efficient handling of frequent changes. Added `stopConfigReloadTimer` for stopping timers during watcher shutdown.
2025-11-10 12:57:40 +08:00
Luis Pater 8c947cafbe Merge branch 'vertex' into dev 2025-11-10 12:24:07 +08:00
Luis Pater 717eadf128 feat(vertex): add support for Vertex AI Gemini authentication and execution
Introduce Vertex AI Gemini integration with support for service account-based authentication, credential storage, and import functionality. Added new executor for Vertex AI requests, including execution and streaming paths, and integrated it into the core manager. Enhanced CLI with `--vertex-import` flag for importing service account keys.
2025-11-10 12:23:51 +08:00
Luis Pater 9e105738fd fix(server): add PATCH method to CORS allowed methods 2025-11-10 12:12:05 +08:00
Luis Pater 5d806fcefc fix(translator): support system instructions with parts and inline data in OpenAI Gemini requests
Handle both `systemInstruction` and `system_instruction` keys, processing text and inline data parts (e.g., images) for system messages in Gemini.
2025-11-10 10:31:32 +08:00
Luis Pater 6ae1dd78ed Merge pull request #230 from router-for-me/api
fix(management): exclude disabled runtime-only auths from file entries
2025-11-10 08:34:47 +08:00
hkfires 43095de162 fix(management): exclude disabled runtime-only auths from file entries 2025-11-10 08:32:42 +08:00
Luis Pater ef7e8206d3 fix(executor): ensure usage reporting for upstream responses lacking usage data
Add `ensurePublished` to guarantee request counting even when usage fields (e.g., tokens) are absent in OpenAI-compatible executor responses, particularly for streaming paths.
2025-11-09 17:24:47 +08:00
Luis Pater 87291c0d75 Merge pull request #227 from router-for-me/api
add headers support for api
2025-11-09 14:00:37 +08:00
hkfires 51d2766d5c fix(management): sanitize keys and normalize headers 2025-11-09 12:13:02 +08:00
hkfires a00ba77604 refactor(config): rename SyncGeminiKeys; use Sanitize* methods 2025-11-09 08:29:47 +08:00
Luis Pater 3264605c2d Merge pull request #226 from router-for-me/headers
feat(config): support HTTP headers across providers
2025-11-08 21:41:31 +08:00
hkfires cfb9cb8951 feat(config): support HTTP headers across providers 2025-11-08 20:52:05 +08:00
Luis Pater bb00436509 fix(service): skip disabled auth entries during executor binding
Prevent disabled auth entries from overriding active provider executors, addressing lingering configs during reloads (e.g., removed OpenAI-compat entries).
2025-11-08 18:19:34 +08:00
Luis Pater 1afbc4dd96 fix(translator): separate tool calls from content in OpenAI Claude requests 2025-11-08 17:57:46 +08:00
Luis Pater d745f07044 fix(registry): replace Gemini model list with updated stable and preview versions 2025-11-08 15:51:57 +08:00
Luis Pater 695eaa5450 docs(instructions): add Codex operational and review guidelines
Added detailed operational instructions for Codex agents based on GPT-5, covering shell usage, editing constraints, sandboxing policies, and approval mechanisms. Also included comprehensive review process guidelines for flagging and communicating issues effectively.
2025-11-08 15:19:51 +08:00
Luis Pater 67ad26c35a fix(executor): remove default reasoning effort for gpt-5-codex-mini 2025-11-08 11:56:32 +08:00
Luis Pater 30d448e73c fix(executor): update model name from codex-mini-latest to gpt-5-codex-mini 2025-11-08 11:17:40 +08:00
Luis Pater d4064e3df4 Merge pull request #225 from jeffnash/feat/codex-mini-variants
feat(registry): add GPT-5 Codex Mini model variants
2025-11-08 11:11:04 +08:00
jeffnashandCopilot ec354f7a1a add default medium reasoning case for gpt-5-codex-mini
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-07 17:12:10 -08:00
jeffnashandCopilot 240e782606 add default medium reasoning case for gpt-5-codex-mini
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-07 17:11:40 -08:00
Jeff Nash fcb0293c0d feat(registry): add GPT-5 Codex Mini model variants
Adds three new Codex Mini model variants (mini, mini-medium, mini-high)
that map to codex-mini-latest. Codex Mini supports medium and high
reasoning effort levels only (no low/minimal). Base model defaults to
medium reasoning effort.
2025-11-07 17:07:39 -08:00
Luis Pater 682c4598ee fix(translator): handle gjson strings in OpenAI response formatting 2025-11-08 00:41:56 +08:00
Luis Pater a7d105bd69 Fixed: #223
fix(registry): add `MiniMax-M2` model to registry definitions
2025-11-08 00:10:51 +08:00
Luis Pater b9eef45305 Merge pull request #222 from router-for-me/api
Return auth info from memory
2025-11-07 22:41:12 +08:00
Luis Pater c8f20a66a8 fix(executor): add logging and prompt cache key handling for OpenAI responses 2025-11-07 22:40:45 +08:00
hkfires 1f6a384c9a fix(api): omit auth file entries lacking path unless runtime-only 2025-11-07 19:15:54 +08:00
hkfires c9fc033cf5 feat(management): support in-memory auth listing with disk fallback 2025-11-07 19:04:54 +08:00
Luis Pater 32c964d310 Merge pull request #221 from router-for-me/gemini
fix(translator): accept camelCase thinking config in OpenAI→Gemini
2025-11-07 17:00:07 +08:00
hkfires d60040b222 fix(translator): accept camelCase thinking config in OpenAI→Gemini 2025-11-07 16:45:31 +08:00
Luis Pater 3ce1b4159b fix(executor): remove outdated Gemini model previews from CLI fallback order 2025-11-07 10:30:22 +08:00
Luis Pater 7516ac4ce7 fix(registry): add gemini-3-pro-preview-11-2025 model to Gemini CLI model definitions 2025-11-06 08:47:17 +08:00
Luis Pater 2a73d8c4a3 fix(translator): simplify tool response handling and adjust JSON schema updates in Gemini modules 2025-11-05 22:48:50 +08:00
Luis Pater a318dff8b0 docs: add hyperlinks to sponsor images in README files (EN and CN) 2025-11-05 20:48:05 +08:00
Luis Pater 4a159d5bf5 docs: add hyperlinks to sponsor images in README files (EN and CN) 2025-11-05 20:46:58 +08:00
Luis Pater 734b040a48 fix(translator): remove strict field from Gemini Claude tool initialization 2025-11-05 20:22:26 +08:00
Luis Pater 10be026ace fix(translator): remove strict field from Gemini Claude tool initialization 2025-11-05 18:14:58 +08:00
Luis Pater 848a620568 ci: add GitHub Action to block changes under internal/translator directory in PRs 2025-11-05 09:12:05 +08:00
1345 changed files with 300789 additions and 20212 deletions
+23 -12
View File
@@ -1,6 +1,6 @@
# Git and GitHub folders
.git/*
.github/*
.git
.github
# Docker and CI/CD related files
docker-compose.yml
@@ -10,21 +10,32 @@ docker-compose.yml
Dockerfile
# Documentation and license
docs/*
docs
README.md
README_CN.md
MANAGEMENT_API.md
MANAGEMENT_API_CN.md
LICENSE
# Runtime data folders (should be mounted as volumes)
auths/*
logs/*
conv/*
auths
logs
conv
config.yaml
# Development/editor
bin/*
.claude/*
.vscode/*
.serena/*
bin
.vscode
.claude
.codex
.codex-worktrees
.gemini
.serena
.agent
.agents
.antigravitycli
.opencode
.idea
.junie
.worktrees
.bmad
_bmad
_bmad-output
+5
View File
@@ -0,0 +1,5 @@
# Cluster JWT example.
# After deploying https://github.com/router-for-me/CLIProxyAPIHome, get the JWT value with:
# curl -sS -X POST "http://<home-host>:8327/v0/management/certificates/clients" -H "X-MANAGEMENT-KEY: <management-key>" | jq -r '.home_jwt'
# Then paste it into HOME_JWT here or export it before starting Compose.
HOME_JWT=your-home-jwt-here
+19
View File
@@ -4,6 +4,25 @@
# NOTE: Environment variables are only required when using remote storage options.
# For local file-based storage (default), no environment variables need to be set.
# ------------------------------------------------------------------------------
# Anchor Summaries (heuristic long-session memory)
# ------------------------------------------------------------------------------
# CLIPROXY_ANCHOR_SUMMARY_MAX_CHARS=14000
# CLIPROXY_ANCHOR_APPEND_ONLY=1
# CLIPROXY_MEMORY_MAX_WRITES_PER_MIN=120
# CLIPROXY_MEMORY_EXPORT_MAX_BYTES=262144000
# CLIPROXY_MEMORY_MAX_AGE_DAYS=0
# CLIPROXY_MEMORY_MAX_SESSIONS=0
# CLIPROXY_MEMORY_MAX_BYTES_PER_SESSION=0
# CLIPROXY_SEMANTIC_RERANK=1
# CLIPROXY_SEMANTIC_KEYWORD_BOOST=0.25
# CLIPROXY_SEMANTIC_RECENCY_BOOST=0.15
# CLIPROXY_SEMANTIC_MAX_AGE_DAYS=0
# CLIPROXY_SEMANTIC_MAX_NAMESPACES=0
# CLIPROXY_SEMANTIC_MAX_BYTES_PER_NAMESPACE=0
# CLIPROXY_SEMANTIC_MAX_WRITES_PER_MIN=120
# CLIPROXY_SEMANTIC_QUERY_MAX_CHARS=512
# ------------------------------------------------------------------------------
# Management Web UI
# ------------------------------------------------------------------------------
+4
View File
@@ -0,0 +1,4 @@
1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com
681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com
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
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
+22
View File
@@ -0,0 +1,22 @@
# Default owner for the entire repository
* @Finesssee
# Core proxy logic
/internal/runtime/executor/ @Finesssee
/internal/translator/ @Finesssee
/sdk/ @Finesssee
# Authentication providers
/internal/auth/ @Finesssee
# API and middleware
/internal/api/ @Finesssee
# WebUI dashboard
/webui/ @Finesssee
# CI/CD and infrastructure
/.github/ @Finesssee
/Dockerfile @Finesssee
/docker-compose.yml @Finesssee
/.goreleaser.yml @Finesssee
+8 -1
View File
@@ -7,11 +7,18 @@ assignees: ''
---
**Is it a request payload issue?**
[ ] Yes, this is a request payload issue. I am using a client/cURL to send a request payload, but I received an unexpected error.
[ ] No, it's another issue.
**If it's a request payload issue, you MUST know**
Our team doesn't have any GODs or ORACLEs or MIND READERs. Please make sure to attach the request log or curl payload.
**Describe the bug**
A clear and concise description of what the bug is.
**CLI Type**
What type of CLI account do you use? (gemini-cli, gemini, codex, claude code or openai-compatibility)
What type of CLI account do you use? (gemini, codex, claude code or openai-compatibility)
**Model Name**
What model are you using? (example: gemini-2.5-pro, claude-sonnet-4-20250514, gpt-5, etc.)
+21
View File
@@ -0,0 +1,21 @@
## Description
<!-- What does this PR do? Why is it needed? -->
## Changes
<!-- List the key changes made -->
-
## Testing
<!-- How was this tested? -->
- [ ] `go test ./...` passes
- [ ] `go vet ./...` passes
- [ ] Manually tested with relevant provider(s)
## Checklist
- [ ] Code follows existing patterns and conventions
- [ ] No secrets or credentials committed
- [ ] No changes under `internal/translator/` (restricted path)
+81
View File
@@ -0,0 +1,81 @@
name: agents-md-guard
on:
pull_request:
types:
- opened
- synchronize
- reopened
permissions:
contents: read
issues: write
pull-requests: write
jobs:
close-when-agents-md-changed:
runs-on: ubuntu-latest
steps:
- name: Detect AGENTS.md changes and close PR
uses: actions/github-script@v7
with:
script: |
const prNumber = context.payload.pull_request.number;
const { owner, repo } = context.repo;
const files = await github.paginate(github.rest.pulls.listFiles, {
owner,
repo,
pull_number: prNumber,
per_page: 100,
});
const touchesAgentsMd = (path) =>
typeof path === "string" &&
(path === "AGENTS.md" || path.endsWith("/AGENTS.md"));
const touched = files.filter(
(f) => touchesAgentsMd(f.filename) || touchesAgentsMd(f.previous_filename),
);
if (touched.length === 0) {
core.info("No AGENTS.md changes detected.");
return;
}
const changedList = touched
.map((f) =>
f.previous_filename && f.previous_filename !== f.filename
? `- ${f.previous_filename} -> ${f.filename}`
: `- ${f.filename}`,
)
.join("\n");
const body = [
"This repository does not allow modifying `AGENTS.md` in pull requests.",
"",
"Detected changes:",
changedList,
"",
"Please revert these changes and open a new PR without touching `AGENTS.md`.",
].join("\n");
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body,
});
} catch (error) {
core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
}
await github.rest.pulls.update({
owner,
repo,
pull_number: prNumber,
state: "closed",
});
core.setFailed("PR modifies AGENTS.md");
@@ -0,0 +1,73 @@
name: auto-retarget-main-pr-to-dev
on:
pull_request:
types:
- opened
- reopened
- edited
branches:
- main
permissions:
contents: read
issues: write
pull-requests: write
jobs:
retarget:
if: github.actor != 'github-actions[bot]'
runs-on: ubuntu-latest
steps:
- name: Retarget PR base to dev
uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const prNumber = pr.number;
const { owner, repo } = context.repo;
const baseRef = pr.base?.ref;
const headRef = pr.head?.ref;
const desiredBase = "dev";
if (baseRef !== "main") {
core.info(`PR #${prNumber} base is ${baseRef}; nothing to do.`);
return;
}
if (headRef === desiredBase) {
core.info(`PR #${prNumber} is ${desiredBase} -> main; skipping retarget.`);
return;
}
core.info(`Retargeting PR #${prNumber} base from ${baseRef} to ${desiredBase}.`);
try {
await github.rest.pulls.update({
owner,
repo,
pull_number: prNumber,
base: desiredBase,
});
} catch (error) {
core.setFailed(`Failed to retarget PR #${prNumber} to ${desiredBase}: ${error.message}`);
return;
}
const body = [
`This pull request targeted \`${baseRef}\`.`,
"",
`The base branch has been automatically changed to \`${desiredBase}\`.`,
].join("\n");
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body,
});
} catch (error) {
core.warning(`Failed to comment on PR #${prNumber}: ${error.message}`);
}
+172
View File
@@ -0,0 +1,172 @@
name: check-upstream
on:
schedule:
# Run daily at 08:00 UTC (like vibeproxy)
- cron: '0 8 * * *'
workflow_dispatch: # Allow manual trigger
concurrency:
group: check-upstream
cancel-in-progress: true
permissions:
contents: write
pull-requests: write
jobs:
check-update:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get tracked upstream version
id: current
run: |
CURRENT_TAG=$(tr -d '[:space:]' < UPSTREAM_VERSION 2>/dev/null || true)
CURRENT_SHA=""
if [ -n "$CURRENT_TAG" ]; then
CURRENT_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git "refs/tags/$CURRENT_TAG" | cut -f1)
fi
echo "tag=$CURRENT_TAG" >> $GITHUB_OUTPUT
echo "sha=$CURRENT_SHA" >> $GITHUB_OUTPUT
- name: Get upstream release info
id: upstream
run: |
# Fetch latest release from CLIProxyAPI
RELEASE_INFO=$(curl -s https://api.github.com/repos/router-for-me/CLIProxyAPI/releases/latest)
# Extract tag name and version
TAG_NAME=$(echo "$RELEASE_INFO" | jq -r '.tag_name // empty')
if [ -z "$TAG_NAME" ]; then
echo "No release found, checking latest commit instead"
LATEST_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git HEAD | cut -f1)
echo "tag=" >> $GITHUB_OUTPUT
echo "sha=$LATEST_SHA" >> $GITHUB_OUTPUT
else
echo "Found release: $TAG_NAME"
echo "tag=$TAG_NAME" >> $GITHUB_OUTPUT
# Get the commit SHA for this tag
TAG_SHA=$(git ls-remote https://github.com/router-for-me/CLIProxyAPI.git "refs/tags/$TAG_NAME" | cut -f1)
echo "sha=$TAG_SHA" >> $GITHUB_OUTPUT
fi
- name: Check for updates
id: check
run: |
echo "Current tracked tag: ${{ steps.current.outputs.tag }}"
echo "Current SHA: ${{ steps.current.outputs.sha }}"
echo "Upstream SHA: ${{ steps.upstream.outputs.sha }}"
echo "Upstream Tag: ${{ steps.upstream.outputs.tag }}"
if [ -z "${{ steps.upstream.outputs.tag }}" ]; then
echo "Unable to determine latest upstream release tag"
exit 1
fi
if [ "${{ steps.current.outputs.tag }}" != "${{ steps.upstream.outputs.tag }}" ]; then
echo "Update available!"
echo "has_update=true" >> $GITHUB_OUTPUT
else
echo "Already up to date"
echo "has_update=false" >> $GITHUB_OUTPUT
fi
- name: Create sync branch and PR
if: steps.check.outputs.has_update == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
CURRENT_TAG="${{ steps.current.outputs.tag }}"
TAG="${{ steps.upstream.outputs.tag }}"
SHA="${{ steps.upstream.outputs.sha }}"
SHORT_SHA="${SHA:0:7}"
if [ -n "$CURRENT_TAG" ]; then
BRANCH_NAME="sync-upstream-$CURRENT_TAG-to-$TAG"
PR_TITLE="chore: sync CLIProxyAPI $CURRENT_TAG-$TAG"
PR_BODY="## Summary
ProxyPilot is currently tracking upstream CLIProxyAPI release \`$CURRENT_TAG\` and a newer release \`$TAG\` is available.
**Upstream release:** https://github.com/router-for-me/CLIProxyAPI/releases/tag/$TAG
## Tracking
- Current tracked upstream version: \`$CURRENT_TAG\`
- Latest upstream version: \`$TAG\`
- Latest upstream commit: \`$SHORT_SHA\`
## Checklist
- [ ] Merge upstream changes into ProxyPilot
- [ ] Review upstream changes
- [ ] Test locally before merging
- [ ] Update \`UPSTREAM_VERSION\`, docs, and release notes
- [ ] Cut a new ProxyPilot release tag
---
🤖 Generated by [check-upstream workflow](https://github.com/${{ github.repository }}/actions/workflows/check-upstream.yml)"
else
BRANCH_NAME="sync-upstream-$SHORT_SHA"
PR_TITLE="chore: sync CLIProxyAPI $TAG"
PR_BODY="## Summary
ProxyPilot does not have a tracked upstream version in \`UPSTREAM_VERSION\`, and upstream CLIProxyAPI release \`$TAG\` is available.
**Upstream release:** https://github.com/router-for-me/CLIProxyAPI/releases/tag/$TAG
## Checklist
- [ ] Set the correct tracked upstream version
- [ ] Merge upstream changes into ProxyPilot
- [ ] Review upstream changes
- [ ] Test locally before merging
---
🤖 Generated by [check-upstream workflow](https://github.com/${{ github.repository }}/actions/workflows/check-upstream.yml)"
fi
# Check if branch already exists
if git ls-remote --exit-code --heads origin "$BRANCH_NAME" > /dev/null 2>&1; then
echo "Branch $BRANCH_NAME already exists, skipping"
exit 0
fi
# Check if PR already exists
EXISTING_PR=$(gh pr list --search "$PR_TITLE" --state open --json number --jq '.[0].number')
if [ -n "$EXISTING_PR" ]; then
echo "PR already exists: #$EXISTING_PR"
exit 0
fi
# Configure git
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
# Create branch
git checkout -b "$BRANCH_NAME"
# Add marker files so the PR records which upstream release triggered it.
echo "$SHA" > .upstream-sync-sha
echo "$TAG" > .upstream-sync-tag
# Commit
git add .upstream-sync-sha .upstream-sync-tag
git commit -m "$PR_TITLE" --allow-empty
# Push
git push origin "$BRANCH_NAME"
# Create PR
gh pr create \
--title "$PR_TITLE" \
--body "$PR_BODY" \
--base main \
--head "$BRANCH_NAME" \
--label "sync-upstream"
+24 -5
View File
@@ -1,35 +1,54 @@
name: docker-image
on:
push:
tags:
- v*
workflow_dispatch:
env:
APP_NAME: CLIProxyAPI
DOCKERHUB_REPO: eceasy/cli-proxy-api
APP_NAME: ProxyPilot
DOCKERHUB_REPO: ${{ secrets.DOCKERHUB_REPO || 'proxypilot/proxypilot' }}
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Check DockerHub credentials
id: check-secrets
env:
HAS_USERNAME: ${{ secrets.DOCKERHUB_USERNAME != '' }}
HAS_TOKEN: ${{ secrets.DOCKERHUB_TOKEN != '' }}
run: |
if [[ "$HAS_USERNAME" != "true" || "$HAS_TOKEN" != "true" ]]; then
echo "skip=true" >> $GITHUB_OUTPUT
echo "::warning::DockerHub credentials not configured, skipping push"
else
echo "skip=false" >> $GITHUB_OUTPUT
fi
- name: Checkout
if: steps.check-secrets.outputs.skip != 'true'
uses: actions/checkout@v4
- name: Refresh models catalog
if: steps.check-secrets.outputs.skip != 'true'
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
- name: Set up QEMU
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Generate Build Metadata
if: steps.check-secrets.outputs.skip != 'true'
run: |
echo VERSION=`git describe --tags --always --dirty` >> $GITHUB_ENV
echo COMMIT=`git rev-parse --short HEAD` >> $GITHUB_ENV
echo BUILD_DATE=`date -u +%Y-%m-%dT%H:%M:%SZ` >> $GITHUB_ENV
- name: Build and push
if: steps.check-secrets.outputs.skip != 'true'
uses: docker/build-push-action@v6
with:
context: .
+28
View File
@@ -0,0 +1,28 @@
name: translator-path-guard
on:
pull_request:
types:
- opened
- synchronize
- reopened
jobs:
ensure-no-translator-changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Detect internal/translator changes
id: changed-files
uses: tj-actions/changed-files@v45
with:
files: |
internal/translator/**
- name: Fail when restricted paths change
if: steps.changed-files.outputs.any_changed == 'true'
run: |
echo "Changes under internal/translator are not allowed in pull requests."
echo "You need to create an issue for our maintenance team to make the necessary changes."
exit 1
+39
View File
@@ -0,0 +1,39 @@
name: pr-test-build
on:
pull_request:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Refresh models catalog
run: curl -fsSL https://raw.githubusercontent.com/router-for-me/models/refs/heads/main/models.json -o internal/registry/models/models.json
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: Build
run: |
go build -o test-output ./cmd/server
rm -f test-output
- name: Vet
run: go vet ./...
- name: Test with coverage
run: |
go test -coverprofile=coverage.out -covermode=atomic ./... 2>&1 | tee test-output.txt
# Extract total coverage percentage
COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | tr -d '%')
echo "Total coverage: ${COVERAGE}%"
# Fail if coverage drops below 30%
THRESHOLD=30
if [ "$(echo "$COVERAGE < $THRESHOLD" | bc -l)" -eq 1 ]; then
echo "ERROR: Coverage ${COVERAGE}% is below threshold ${THRESHOLD}%"
exit 1
fi
+31
View File
@@ -0,0 +1,31 @@
name: Publish ProxyPilot via Bun
on:
workflow_run:
workflows: ["ProxyPilot Release"]
types:
- completed
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Setup registry auth
working-directory: bun/proxypilot
run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
- name: Publish package
working-directory: bun/proxypilot
run: bun publish --access public
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+83
View File
@@ -0,0 +1,83 @@
name: ProxyPilot Release
on:
workflow_dispatch:
permissions:
contents: write
jobs:
build:
name: Build ${{ matrix.os }}-${{ matrix.arch }}
runs-on: ubuntu-latest
strategy:
matrix:
include:
- os: darwin
arch: amd64
extension: ''
- os: darwin
arch: arm64
extension: ''
- os: linux
arch: amd64
extension: ''
- os: linux
arch: arm64
extension: ''
- os: windows
arch: amd64
extension: '.exe'
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.21'
- name: Remove Windows resources for non-Windows builds
if: matrix.os != 'windows'
run: rm -f cmd/server/*.syso
- name: Build binary
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
CGO_ENABLED: 0
run: |
go build -ldflags="-s -w" -o proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }} ./cmd/server
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: proxypilot-${{ matrix.os }}-${{ matrix.arch }}
path: proxypilot-${{ matrix.os }}-${{ matrix.arch }}${{ matrix.extension }}
release:
name: Create Release
needs: build
runs-on: ubuntu-latest
steps:
- name: Download all artifacts
uses: actions/download-artifact@v4
with:
path: artifacts
- name: Prepare release assets
run: |
mkdir -p release
find artifacts -type f -exec cp {} release/ \;
cd release && sha256sum * > checksums.txt
ls -la
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: release/*
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+660 -21
View File
@@ -1,4 +1,4 @@
name: goreleaser
name: release
on:
push:
@@ -9,30 +9,669 @@ on:
permissions:
contents: write
env:
GH_REPO: ${{ github.repository }}
GO_VERSION: '1.26.4'
jobs:
goreleaser:
prepare-release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
fetch-depth: 0
- run: git fetch --force --tags
- uses: actions/setup-go@v4
with:
go-version: '>=1.24.0'
cache: true
- name: Generate Build Metadata
run: |
echo VERSION=`git describe --tags --always --dirty` >> $GITHUB_ENV
echo COMMIT=`git rev-parse --short HEAD` >> $GITHUB_ENV
echo BUILD_DATE=`date -u +%Y-%m-%dT%H:%M:%SZ` >> $GITHUB_ENV
- uses: goreleaser/goreleaser-action@v4
with:
distribution: goreleaser
version: latest
args: release --clean
fetch-tags: true
- name: Create release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ env.VERSION }}
COMMIT: ${{ env.COMMIT }}
BUILD_DATE: ${{ env.BUILD_DATE }}
run: |
set -euo pipefail
release_notes_file="$(mktemp)"
generated_notes_file="$(mktemp)"
changelog_entries_file="$(mktemp)"
changelog_notes_file="$(mktemp)"
updated_notes_file="$(mktemp)"
trap 'rm -f "$release_notes_file" "$generated_notes_file" "$changelog_entries_file" "$changelog_notes_file" "$updated_notes_file"' EXIT
cat > "$release_notes_file" <<'EOF'
<!-- cliproxyapi-linux-release-assets:start -->
## Linux release assets
- `CLIProxyAPI_<version>_linux_<arch>.tar.gz` is the default Linux build. It supports dynamic library plugins and is built against a GLIBC 2.17 baseline.
- `CLIProxyAPI_<version>_linux_<arch>_no-plugin.tar.gz` is the portable Linux build for musl-based or older systems such as OpenWrt. It does not support dynamic library plugins.
## FreeBSD release assets
- `CLIProxyAPI_<version>_freebsd_aarch64_no-plugin.tar.gz` is the FreeBSD arm64 build. It is built without CGO and does not support dynamic library plugins.
<!-- cliproxyapi-linux-release-assets:end -->
EOF
git fetch --force --tags
previous_tag=""
if previous_tag_value="$(git describe --tags --abbrev=0 "${GITHUB_REF_NAME}^" 2>/dev/null)"; then
previous_tag="$previous_tag_value"
changelog_range="${previous_tag}..${GITHUB_REF_NAME}"
else
changelog_range="$GITHUB_REF_NAME"
fi
git log --reverse --pretty=format:'- %s (%h)' "$changelog_range" |
grep -Ev '^- (docs:|test:)' > "$changelog_entries_file" || true
gh api "repos/${GH_REPO}/releases/generate-notes" \
-f tag_name="$GITHUB_REF_NAME" \
--jq .body > "$generated_notes_file"
if [[ ! -s "$generated_notes_file" ]]; then
if [[ -n "$previous_tag" ]]; then
printf '**Full Changelog**: https://github.com/%s/compare/%s...%s\n' "$GH_REPO" "$previous_tag" "$GITHUB_REF_NAME" > "$generated_notes_file"
else
printf '**Full Changelog**: https://github.com/%s/commits/%s\n' "$GH_REPO" "$GITHUB_REF_NAME" > "$generated_notes_file"
fi
fi
{
if [[ -s "$changelog_entries_file" ]]; then
printf '## Changelog\n\n'
cat "$changelog_entries_file"
printf '\n\n'
fi
cat "$generated_notes_file"
} > "$changelog_notes_file"
{
cat "$release_notes_file"
printf '\n'
cat "$changelog_notes_file"
} > "$updated_notes_file"
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
gh release edit "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes-file "$updated_notes_file"
else
gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes-file "$updated_notes_file"
fi
build-hosted:
name: build ${{ matrix.target }}
needs: prepare-release
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- target: darwin-amd64
runner: macos-15-intel
goos: darwin
goarch: amd64
asset_arch: amd64
archive_format: tar.gz
- target: darwin-arm64
runner: macos-15
goos: darwin
goarch: arm64
asset_arch: aarch64
archive_format: tar.gz
- target: windows-amd64
runner: windows-latest
goos: windows
goarch: amd64
asset_arch: amd64
archive_format: zip
- target: windows-arm64
runner: windows-11-arm
goos: windows
goarch: arm64
asset_arch: aarch64
archive_format: zip
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Refresh models catalog
shell: bash
run: |
set -euo pipefail
git fetch --depth 1 https://github.com/router-for-me/models.git main
git show FETCH_HEAD:models.json > internal/registry/models/models.json
- name: Fetch tags
shell: bash
run: git fetch --force --tags
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/cache@v4
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: go-${{ runner.os }}-${{ runner.arch }}-${{ matrix.target }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-${{ runner.os }}-${{ runner.arch }}-${{ matrix.target }}-
go-${{ runner.os }}-${{ runner.arch }}-
- name: Generate Build Metadata
shell: bash
run: |
set -euo pipefail
echo "RELEASE_VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV"
echo "COMMIT=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
echo "BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV"
- name: Build archive
shell: bash
env:
TARGET: ${{ matrix.target }}
GOOS: ${{ matrix.goos }}
GOARCH: ${{ matrix.goarch }}
ASSET_ARCH: ${{ matrix.asset_arch }}
ARCHIVE_FORMAT: ${{ matrix.archive_format }}
run: |
set -euo pipefail
binary_name="cli-proxy-api"
if [[ "$GOOS" == "windows" ]]; then
binary_name="cli-proxy-api.exe"
fi
archive_dir="dist/${TARGET}/archive"
archive_name="CLIProxyAPI_${RELEASE_VERSION}_${GOOS}_${ASSET_ARCH}.${ARCHIVE_FORMAT}"
rm -rf "dist/${TARGET}"
mkdir -p "$archive_dir"
CGO_ENABLED=1 GOOS="$GOOS" GOARCH="$GOARCH" go build \
-ldflags="-s -w -X main.Version=${RELEASE_VERSION} -X main.Commit=${COMMIT} -X main.BuildDate=${BUILD_DATE}" \
-o "$archive_dir/$binary_name" ./cmd/server/
cp LICENSE README.md README_CN.md config.example.yaml "$archive_dir/"
if [[ "$ARCHIVE_FORMAT" == "zip" ]]; then
powershell -NoProfile -Command "Compress-Archive -Path '${archive_dir}/*' -DestinationPath 'dist/${archive_name}' -Force"
else
tar -C "$archive_dir" -czf "dist/$archive_name" "$binary_name" LICENSE README.md README_CN.md config.example.yaml
fi
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.target }}
path: dist/CLIProxyAPI_*
if-no-files-found: error
- name: Upload release assets
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
shopt -s nullglob
assets=(dist/CLIProxyAPI_*.tar.gz dist/CLIProxyAPI_*.zip)
if [[ ${#assets[@]} -eq 0 ]]; then
printf 'expected archive assets, found %s\n' "${#assets[@]}" >&2
printf '%s\n' "${assets[@]}" >&2
exit 1
fi
gh release upload "$GITHUB_REF_NAME" "${assets[@]}" --clobber
- name: Refresh release checksums
continue-on-error: true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
gh release download "$GITHUB_REF_NAME" \
--pattern 'CLIProxyAPI_*.tar.gz' \
--pattern 'CLIProxyAPI_*.zip' \
--dir "$tmp_dir" \
--clobber
(
cd "$tmp_dir"
shopt -s nullglob
archives=(CLIProxyAPI_*.tar.gz CLIProxyAPI_*.zip)
if [[ ${#archives[@]} -eq 0 ]]; then
echo "No release archives found"
exit 0
fi
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "${archives[@]}" | sort -k2 > checksums.txt
else
shasum -a 256 "${archives[@]}" | sort -k2 > checksums.txt
fi
)
gh release upload "$GITHUB_REF_NAME" "$tmp_dir/checksums.txt" --clobber
build-linux-glibc:
name: build linux-${{ matrix.goarch }} glibc
needs: prepare-release
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- target: linux-amd64
runner: ubuntu-latest
goarch: amd64
asset_arch: amd64
manylinux_image: quay.io/pypa/manylinux2014_x86_64
- target: linux-arm64
runner: ubuntu-24.04-arm
goarch: arm64
asset_arch: aarch64
manylinux_image: quay.io/pypa/manylinux2014_aarch64
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Refresh models catalog
shell: bash
run: |
set -euo pipefail
git fetch --depth 1 https://github.com/router-for-me/models.git main
git show FETCH_HEAD:models.json > internal/registry/models/models.json
- name: Fetch tags
shell: bash
run: git fetch --force --tags
- name: Generate Build Metadata
shell: bash
run: |
set -euo pipefail
echo "RELEASE_VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV"
echo "COMMIT=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
echo "BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV"
- name: Build archive
shell: bash
env:
TARGET: ${{ matrix.target }}
GOARCH: ${{ matrix.goarch }}
ASSET_ARCH: ${{ matrix.asset_arch }}
MANYLINUX_IMAGE: ${{ matrix.manylinux_image }}
run: |
set -euo pipefail
archive_dir="dist/${TARGET}/archive"
archive_name="CLIProxyAPI_${RELEASE_VERSION}_linux_${ASSET_ARCH}.tar.gz"
rm -rf "dist/${TARGET}"
mkdir -p "$archive_dir"
docker run --rm \
-v "$PWD:/src" \
-w /src \
-e GO_VERSION \
-e GOARCH \
-e RELEASE_VERSION \
-e COMMIT \
-e BUILD_DATE \
"$MANYLINUX_IMAGE" \
bash -euo pipefail -c '
go_archive="go${GO_VERSION}.linux-${GOARCH}.tar.gz"
curl -fsSL "https://go.dev/dl/${go_archive}" -o "/tmp/${go_archive}"
rm -rf /usr/local/go
tar -C /usr/local -xzf "/tmp/${go_archive}"
export PATH="/usr/local/go/bin:${PATH}"
CGO_ENABLED=1 GOOS=linux GOARCH="${GOARCH}" go build -buildvcs=false \
-ldflags="-s -w -X main.Version=${RELEASE_VERSION} -X main.Commit=${COMMIT} -X main.BuildDate=${BUILD_DATE}" \
-o "'"$archive_dir"'/cli-proxy-api" ./cmd/server/
glibc_versions="$(readelf --version-info "'"$archive_dir"'/cli-proxy-api" | sed -n "s/.*Name: GLIBC_\([0-9.]*\).*/\1/p" | sort -Vu)"
if [[ -n "${glibc_versions}" ]]; then
printf "GLIBC versions:\n%s\n" "${glibc_versions}"
max_glibc="$(printf "%s\n" "${glibc_versions}" | sort -V | tail -n 1)"
if [[ "$(printf "2.17\n%s\n" "${max_glibc}" | sort -V | tail -n 1)" != "2.17" ]]; then
printf "linux ${GOARCH} binary requires GLIBC_%s, expected GLIBC_2.17 or older\n" "${max_glibc}" >&2
exit 1
fi
fi
'
cp LICENSE README.md README_CN.md config.example.yaml "$archive_dir/"
tar -C "$archive_dir" -czf "dist/$archive_name" cli-proxy-api LICENSE README.md README_CN.md config.example.yaml
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.target }}
path: dist/CLIProxyAPI_*
if-no-files-found: error
- name: Upload release assets
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
shopt -s nullglob
assets=(dist/CLIProxyAPI_*.tar.gz)
if [[ ${#assets[@]} -eq 0 ]]; then
printf 'expected archive assets, found %s\n' "${#assets[@]}" >&2
printf '%s\n' "${assets[@]}" >&2
exit 1
fi
gh release upload "$GITHUB_REF_NAME" "${assets[@]}" --clobber
- name: Refresh release checksums
continue-on-error: true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
gh release download "$GITHUB_REF_NAME" \
--pattern 'CLIProxyAPI_*.tar.gz' \
--pattern 'CLIProxyAPI_*.zip' \
--dir "$tmp_dir" \
--clobber
(
cd "$tmp_dir"
shopt -s nullglob
archives=(CLIProxyAPI_*.tar.gz CLIProxyAPI_*.zip)
if [[ ${#archives[@]} -eq 0 ]]; then
echo "No release archives found"
exit 0
fi
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "${archives[@]}" | sort -k2 > checksums.txt
else
shasum -a 256 "${archives[@]}" | sort -k2 > checksums.txt
fi
)
gh release upload "$GITHUB_REF_NAME" "$tmp_dir/checksums.txt" --clobber
build-linux-no-plugin:
name: build linux-${{ matrix.goarch }} no-plugin
needs: prepare-release
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- target: linux-amd64-no-plugin
goarch: amd64
asset_arch: amd64
- target: linux-arm64-no-plugin
goarch: arm64
asset_arch: aarch64
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Refresh models catalog
shell: bash
run: |
set -euo pipefail
git fetch --depth 1 https://github.com/router-for-me/models.git main
git show FETCH_HEAD:models.json > internal/registry/models/models.json
- name: Fetch tags
shell: bash
run: git fetch --force --tags
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/cache@v4
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: go-linux-no-plugin-${{ matrix.goarch }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-linux-no-plugin-${{ matrix.goarch }}-
go-linux-no-plugin-
- name: Generate Build Metadata
shell: bash
run: |
set -euo pipefail
echo "RELEASE_VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV"
echo "COMMIT=$(git rev-parse --short HEAD)" >> "$GITHUB_ENV"
echo "BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV"
- name: Build archive
shell: bash
env:
TARGET: ${{ matrix.target }}
GOARCH: ${{ matrix.goarch }}
ASSET_ARCH: ${{ matrix.asset_arch }}
run: |
set -euo pipefail
archive_dir="dist/${TARGET}/archive"
archive_name="CLIProxyAPI_${RELEASE_VERSION}_linux_${ASSET_ARCH}_no-plugin.tar.gz"
rm -rf "dist/${TARGET}"
mkdir -p "$archive_dir"
CGO_ENABLED=0 GOOS=linux GOARCH="$GOARCH" go build -buildvcs=false \
-ldflags="-s -w -X main.Version=${RELEASE_VERSION} -X main.Commit=${COMMIT} -X main.BuildDate=${BUILD_DATE}" \
-o "$archive_dir/cli-proxy-api" ./cmd/server/
if readelf -l "$archive_dir/cli-proxy-api" | grep -q 'Requesting program interpreter'; then
readelf -l "$archive_dir/cli-proxy-api" >&2
echo "no-plugin linux binary must not require a dynamic interpreter" >&2
exit 1
fi
cp LICENSE README.md README_CN.md config.example.yaml "$archive_dir/"
tar -C "$archive_dir" -czf "dist/$archive_name" cli-proxy-api LICENSE README.md README_CN.md config.example.yaml
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.target }}
path: dist/CLIProxyAPI_*
if-no-files-found: error
- name: Upload release assets
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
shopt -s nullglob
assets=(dist/CLIProxyAPI_*.tar.gz)
if [[ ${#assets[@]} -eq 0 ]]; then
printf 'expected archive assets, found %s\n' "${#assets[@]}" >&2
printf '%s\n' "${assets[@]}" >&2
exit 1
fi
gh release upload "$GITHUB_REF_NAME" "${assets[@]}" --clobber
- name: Refresh release checksums
continue-on-error: true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
gh release download "$GITHUB_REF_NAME" \
--pattern 'CLIProxyAPI_*.tar.gz' \
--pattern 'CLIProxyAPI_*.zip' \
--dir "$tmp_dir" \
--clobber
(
cd "$tmp_dir"
shopt -s nullglob
archives=(CLIProxyAPI_*.tar.gz CLIProxyAPI_*.zip)
if [[ ${#archives[@]} -eq 0 ]]; then
echo "No release archives found"
exit 0
fi
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "${archives[@]}" | sort -k2 > checksums.txt
else
shasum -a 256 "${archives[@]}" | sort -k2 > checksums.txt
fi
)
gh release upload "$GITHUB_REF_NAME" "$tmp_dir/checksums.txt" --clobber
build-freebsd:
name: build ${{ matrix.target }}
needs: prepare-release
runs-on: ubuntu-latest
env:
TARGET: ${{ matrix.target }}
GOARCH: ${{ matrix.goarch }}
ASSET_ARCH: ${{ matrix.asset_arch }}
ASSET_SUFFIX: ${{ matrix.asset_suffix }}
strategy:
fail-fast: false
matrix:
include:
- target: freebsd-amd64
goarch: amd64
asset_arch: amd64
asset_suffix: ''
cgo_enabled: true
- target: freebsd-arm64-no-plugin
goarch: arm64
asset_arch: aarch64
asset_suffix: _no-plugin
cgo_enabled: false
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Refresh models catalog
run: |
git fetch --depth 1 https://github.com/router-for-me/models.git main
git show FETCH_HEAD:models.json > internal/registry/models/models.json
- name: Fetch tags
run: git fetch --force --tags
- uses: actions/setup-go@v6
with:
go-version: ${{ env.GO_VERSION }}
cache: true
- uses: actions/cache@v4
with:
path: |
~/.cache/go-build
~/go/pkg/mod
key: go-freebsd-${{ matrix.goarch }}-${{ hashFiles('go.sum') }}
restore-keys: |
go-freebsd-${{ matrix.goarch }}-
go-freebsd-
- name: Generate Build Metadata
id: metadata
run: |
set -euo pipefail
release_version="${GITHUB_REF_NAME#v}"
commit="$(git rev-parse --short HEAD)"
build_date="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "RELEASE_VERSION=$release_version" >> "$GITHUB_ENV"
echo "COMMIT=$commit" >> "$GITHUB_ENV"
echo "BUILD_DATE=$build_date" >> "$GITHUB_ENV"
echo "release_version=$release_version" >> "$GITHUB_OUTPUT"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
echo "build_date=$build_date" >> "$GITHUB_OUTPUT"
- name: Prepare FreeBSD output
shell: bash
run: |
set -euo pipefail
rm -rf "dist/${TARGET}"
- name: Install FreeBSD cross-build dependencies
if: ${{ matrix.cgo_enabled }}
run: |
set -euo pipefail
sudo apt-get update
sudo apt-get install -y clang lld wget
- name: Build FreeBSD binary with CGO
if: ${{ matrix.cgo_enabled }}
timeout-minutes: 45
uses: go-cross/cgo-actions@v1
with:
dir: .
packages: ./cmd/server/
targets: ${{ env.TARGET }}
out-dir: dist/${{ env.TARGET }}/bin
output: cli-proxy-api
flags: >-
-ldflags=-s -w
-X main.Version=${{ steps.metadata.outputs.release_version }}
-X main.Commit=${{ steps.metadata.outputs.commit }}
-X main.BuildDate=${{ steps.metadata.outputs.build_date }}
- name: Build FreeBSD no-plugin binary
if: ${{ !matrix.cgo_enabled }}
shell: bash
run: |
set -euo pipefail
mkdir -p "dist/${TARGET}/bin"
CGO_ENABLED=0 GOOS=freebsd GOARCH="$GOARCH" go build -buildvcs=false \
-ldflags="-s -w -X main.Version=${RELEASE_VERSION} -X main.Commit=${COMMIT} -X main.BuildDate=${BUILD_DATE}" \
-o "dist/${TARGET}/bin/cli-proxy-api" ./cmd/server/
- name: Package FreeBSD archive
shell: bash
run: |
set -euo pipefail
archive_dir="dist/${TARGET}/archive"
archive_name="CLIProxyAPI_${RELEASE_VERSION}_freebsd_${ASSET_ARCH}${ASSET_SUFFIX}.tar.gz"
mkdir -p "$archive_dir"
echo "Packaging ${archive_name}"
cp "dist/${TARGET}/bin/cli-proxy-api" "$archive_dir/cli-proxy-api"
cp LICENSE README.md README_CN.md config.example.yaml "$archive_dir/"
tar -C "$archive_dir" -czf "dist/$archive_name" cli-proxy-api LICENSE README.md README_CN.md config.example.yaml
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.target }}
path: dist/CLIProxyAPI_*
if-no-files-found: error
- name: Upload release assets
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
shopt -s nullglob
assets=(dist/CLIProxyAPI_*.tar.gz)
if [[ ${#assets[@]} -eq 0 ]]; then
printf 'expected archive assets, found %s\n' "${#assets[@]}" >&2
printf '%s\n' "${assets[@]}" >&2
exit 1
fi
gh release upload "$GITHUB_REF_NAME" "${assets[@]}" --clobber
- name: Refresh release checksums
continue-on-error: true
shell: bash
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
gh release download "$GITHUB_REF_NAME" \
--pattern 'CLIProxyAPI_*.tar.gz' \
--pattern 'CLIProxyAPI_*.zip' \
--dir "$tmp_dir" \
--clobber
(
cd "$tmp_dir"
shopt -s nullglob
archives=(CLIProxyAPI_*.tar.gz CLIProxyAPI_*.zip)
if [[ ${#archives[@]} -eq 0 ]]; then
echo "No release archives found"
exit 0
fi
if command -v sha256sum >/dev/null 2>&1; then
sha256sum "${archives[@]}" | sort -k2 > checksums.txt
else
shasum -a 256 "${archives[@]}" | sort -k2 > checksums.txt
fi
)
gh release upload "$GITHUB_REF_NAME" "$tmp_dir/checksums.txt" --clobber
publish-checksums:
runs-on: ubuntu-latest
if: always()
needs:
- build-hosted
- build-linux-glibc
- build-linux-no-plugin
- build-freebsd
steps:
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Publish final checksums
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
cd dist
shopt -s nullglob
archives=(CLIProxyAPI_*.tar.gz CLIProxyAPI_*.zip)
if [[ ${#archives[@]} -eq 0 ]]; then
echo "No release archives found"
exit 0
fi
sha256sum "${archives[@]}" | sort -k2 > checksums.txt
gh release upload "$GITHUB_REF_NAME" checksums.txt --clobber
+83
View File
@@ -0,0 +1,83 @@
name: Build Windows Release
on:
# Only run manually - not on every tag
workflow_dispatch:
inputs:
version:
description: 'Version (e.g., 0.1.0)'
required: true
default: '0.1.0'
permissions:
contents: write
jobs:
build-windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: '1.24'
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Build WebUI
run: |
cd webui
npm ci
npm run build
- name: Build Windows binaries
run: |
mkdir -p dist
# Build tray app (includes embedded dashboard)
go build -ldflags="-s -w -H=windowsgui" -o dist/ProxyPilot.exe ./cmd/proxypilot-tray
- name: Install Inno Setup
run: |
choco install innosetup -y
- name: Generate installer branding images
run: |
cd installer/assets
powershell -ExecutionPolicy Bypass -File generate-wizard-images.ps1
- name: Get version
id: version
run: |
if ("${{ github.event.inputs.version }}" -ne "") {
$version = "${{ github.event.inputs.version }}"
} else {
$tag = "${{ github.ref_name }}"
$version = $tag -replace '^v', ''
}
$versionInfo = $version -replace '^v', '' -replace '-dev-0\.', '.' -replace '-dev-', '.'
echo "VERSION=$version" >> $env:GITHUB_OUTPUT
echo "VERSION_INFO=$versionInfo" >> $env:GITHUB_OUTPUT
- name: Build Inno Setup Installer
run: |
& "C:\Program Files (x86)\Inno Setup 6\ISCC.exe" /DAppVersion="${{ steps.version.outputs.VERSION }}" /DVersionInfoVersion="${{ steps.version.outputs.VERSION_INFO }}" installer\proxypilot.iss
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: windows-release
path: |
dist/ProxyPilot.exe
dist/ProxyPilot-*-Setup.exe
- name: Upload to Release
if: startsWith(github.ref, 'refs/tags/')
uses: softprops/action-gh-release@v1
with:
files: |
dist/ProxyPilot.exe
dist/ProxyPilot-${{ steps.version.outputs.VERSION }}-Setup.exe
+103 -1
View File
@@ -1,5 +1,9 @@
# Binaries
cli-proxy-api
/cli-proxy-api
/cliproxy
proxypilot-linux
proxypilot-darwin
proxypilot-windows
*.exe
# Configuration
@@ -11,22 +15,120 @@ bin/*
logs/*
conv/*
temp/*
refs/*
plugins/*
examples/plugin/bin/*
# Storage backends
pgstore/*
gitstore/*
objectstore/*
# Static assets
static/*
!static/icon.png
!static/icon.ico
test/
dist/*
.proxypilot/*
memory/*
# Authentication data
auths/*
/auths
!auths/.gitkeep
# Documentation
docs/*
!docs/claude-code-local-proxy.md
!docs/cursor-ide.md
!docs/compat-matrix.md
!docs/hindsight.md
!docs/desktop-ui-spec.md
!docs/windows-ui-spec.md
!docs/memory.md
!docs/proxypilot.md
!docs/agentic-harness-demo.md
!docs/long-context-features.md
!docs/desktop-app-build-process.md
!docs/cli.md
AGENTS.md
CLAUDE.md
GEMINI.md
# Tooling metadata
.vscode/*
.worktrees/
.codex/*
.claude/*
.claude
.gemini/*
.serena/*
.agent/*
.agents
.agents/*
.opencode/*
.idea/*
.beads/*
.bmad/*
_bmad/*
_bmad-output/*
.mcp/*
.cursor/*
# Local artifacts
claude-progress.txt
feature_list.json
tui-snapshot*.txt
tui-ttyd.png
# Local settings (user-specific)
*.local.json
*.local.yaml
*.local.toml
# macOS
.DS_Store
._*
.gocache/
# Windows artifacts
nul
Thumbs.db
desktop.ini
# Backup/temp files
*~
*.bak
*.tmp
*.swp
*.orig
*.proxypilot-backup
# Test scripts
*.ahk
tray_click_log.txt
# Logs
*.log
*_out.txt
# Added by Gemini CLI fix
node_modules/
dist/
.turbo/
build/
# Local files
PLAN-*.md
config-debug.yaml
.wix/
test_results.txt
test_results_full.txt
tmpclaude-*
# Opencode
.beads/
.opencode/
.cli-proxy-api/
.venv/
+20 -6
View File
@@ -1,26 +1,40 @@
before:
hooks:
# Remove Windows resource files before building
# These .syso files cause ARM64 cross-compile failures on Linux/Darwin
- find . -name "*.syso" -type f -delete || true
builds:
- id: "cli-proxy-api"
- id: "cli-proxy-api-plus"
env:
- CGO_ENABLED=0
goos:
- linux
- windows
- darwin
- freebsd
goarch:
- amd64
- arm64
ignore:
# Skip Windows ARM64 (not commonly used)
- goos: windows
goarch: arm64
main: ./cmd/server/
binary: cli-proxy-api
binary: cli-proxy-api-plus
ldflags:
- -s -w -X 'main.Version={{.Version}}' -X 'main.Commit={{.ShortCommit}}' -X 'main.BuildDate={{.Date}}'
- -s -w -X 'main.Version={{.Version}}-plus' -X 'main.Commit={{.ShortCommit}}' -X 'main.BuildDate={{.Date}}'
archives:
- id: "cli-proxy-api"
- id: "cli-proxy-api-plus"
format: tar.gz
name_template: >-
{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{- if eq .Arch "arm64" -}}aarch64{{- else -}}{{ .Arch }}{{- end -}}
format_overrides:
- goos: windows
format: zip
files:
- LICENSE
- README.md
- README_CN.md
- config.example.yaml
checksum:
@@ -34,4 +48,4 @@ changelog:
filters:
exclude:
- '^docs:'
- '^test:'
- '^test:'
+1
View File
@@ -0,0 +1 @@
15ac7fb9324095330e60f522147b8a8e81f16ab5
+1
View File
@@ -0,0 +1 @@
v7.0.2
+58
View File
@@ -0,0 +1,58 @@
# AGENTS.md
Go 1.26+ proxy server providing OpenAI/Gemini/Claude/Codex compatible APIs with OAuth and round-robin load balancing.
## Repository
- GitHub: https://github.com/router-for-me/CLIProxyAPI
## Commands
```bash
gofmt -w . # Format (required after Go changes)
go build -o cli-proxy-api ./cmd/server # Build
go run ./cmd/server # Run dev server
go test ./... # Run all tests
go test -v -run TestName ./path/to/pkg # Run single test
go build -o test-output ./cmd/server && rm test-output # Verify compile (REQUIRED after changes)
```
- Common flags: `--config <path>`, `--tui`, `--standalone`, `--local-model`, `--no-browser`, `--oauth-callback-port <port>`
## Config
- Default config: `config.yaml` (template: `config.example.yaml`)
- `.env` is auto-loaded from the working directory
- Auth material defaults under `auths/`
- Storage backends: file-based default; optional Postgres/git/object store (`PGSTORE_*`, `GITSTORE_*`, `OBJECTSTORE_*`)
## Architecture
- `cmd/server/` — Server entrypoint
- `internal/api/` — Gin HTTP API (routes, middleware, modules)
- `internal/api/modules/amp/` — Amp integration (Amp-style routes + reverse proxy)
- `internal/thinking/` — Main thinking/reasoning pipeline. `ApplyThinking()` (apply.go) parses suffixes (`suffix.go`, suffix overrides body), normalizes config to canonical `ThinkingConfig` (`types.go`), normalizes and validates centrally (`validate.go`/`convert.go`), then applies provider-specific output via `ProviderApplier`. Do not break this "canonical representation → per-provider translation" architecture.
- `internal/runtime/executor/` — Per-provider runtime executors (incl. Codex WebSocket)
- `internal/translator/` — Provider protocol translators (and shared `common`)
- `internal/registry/` — Model registry + remote updater (`StartModelsUpdater`); `--local-model` disables remote updates
- `internal/store/` — Storage implementations and secret resolution
- `internal/managementasset/` — Config snapshots and management assets
- `internal/cache/` — Request signature caching
- `internal/watcher/` — Config hot-reload and watchers
- `internal/wsrelay/` — WebSocket relay sessions
- `internal/usage/` — Usage and token accounting
- `internal/tui/` — Bubbletea terminal UI (`--tui`, `--standalone`)
- `sdk/cliproxy/` — Embeddable SDK entry (service/builder/watchers/pipeline)
- `test/` — Cross-module integration tests
## Code Conventions
- Keep changes small and simple (KISS)
- Comments in English only
- If editing code that already contains non-English comments, translate them to English (don’t add new non-English comments)
- For user-visible strings, keep the existing language used in that file/area
- New Markdown docs should be in English unless the file is explicitly language-specific (e.g. `README_CN.md`)
- As a rule, do not make standalone changes to `internal/translator/`. You may modify it only as part of broader changes elsewhere.
- If a task requires changing only `internal/translator/`, run `gh repo view --json viewerPermission -q .viewerPermission` to confirm you have `WRITE`, `MAINTAIN`, or `ADMIN`. If you do, you may proceed; otherwise, file a GitHub issue including the goal, rationale, and the intended implementation code, then stop further work.
- `internal/runtime/executor/` should contain executors and their unit tests only. Place any helper/supporting files under `internal/runtime/executor/helps/`.
- Follow `gofmt`; keep imports goimports-style; wrap errors with context where helpful
- Do not use `log.Fatal`/`log.Fatalf` (terminates the process); prefer returning errors and logging via logrus
- Shadowed variables: use method suffix (`errStart := server.Start()`)
- Wrap defer errors: `defer func() { if err := f.Close(); err != nil { log.Errorf(...) } }()`
- Use logrus structured logging; avoid leaking secrets/tokens in logs
- Avoid panics in HTTP handlers; prefer logged errors and meaningful HTTP status codes
- Timeouts are allowed only during credential acquisition; after an upstream connection is established, do not set timeouts for any subsequent network behavior. Intentional exceptions that must remain allowed are the Codex websocket liveness deadlines in `internal/runtime/executor/codex_websockets_executor.go`, the wsrelay session deadlines in `internal/wsrelay/session.go`, the management APICall timeout in `internal/api/handlers/management/api_tools.go`, and the `cmd/fetch_antigravity_models` utility timeouts
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+89
View File
@@ -0,0 +1,89 @@
# Contributing to ProxyPilot
Thank you for your interest in contributing to ProxyPilot! This guide will help you get started.
## Development Environment Setup
1. **Install Go 1.24+**
- Download from [golang.org](https://golang.org/dl/)
- Verify installation: `go version`
2. **Clone the repository**
```bash
git clone https://github.com/your-org/ProxyPilot.git
cd ProxyPilot
```
3. **Install dependencies**
```bash
go mod download
```
## Running Tests
Run all tests:
```bash
go test ./...
```
Run tests with coverage:
```bash
go test -cover ./...
```
Run tests for a specific package:
```bash
go test ./pkg/proxy/...
```
## Code Style Guidelines
We follow standard Go conventions:
- **Format code** before committing:
```bash
go fmt ./...
```
- **Run static analysis**:
```bash
go vet ./...
```
- Follow [Effective Go](https://golang.org/doc/effective_go) guidelines
- Keep functions focused and reasonably sized
- Add comments for exported functions and types
- Use meaningful variable and function names
## Pull Request Process
1. Fork the repository and create a feature branch from `main`
2. Make your changes with clear, atomic commits
3. Ensure all tests pass and add tests for new functionality
4. Run `go fmt` and `go vet` before submitting
5. Open a pull request with a clear description of the changes
6. Link any related issues in the PR description
7. Address review feedback promptly
## Issue Reporting Guidelines
When reporting issues, please include:
- **Bug reports**: Steps to reproduce, expected behavior, actual behavior, Go version, and OS
- **Feature requests**: Clear description of the proposed feature and its use case
- **Questions**: Check existing issues and documentation first
Use descriptive titles and provide as much context as possible.
## Third-Party Provider Integrations
We welcome contributions that add integrations with third-party providers! If you're adding a new provider integration:
- Follow the existing integration patterns in the codebase
- Include documentation for configuration options
- Add appropriate tests
- Update the README if necessary
## Questions?
Feel free to open an issue for any questions about contributing.
+7 -5
View File
@@ -1,7 +1,9 @@
FROM golang:1.24-alpine AS builder
FROM golang:1.26-bookworm AS builder
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends build-essential git && rm -rf /var/lib/apt/lists/*
COPY go.mod go.sum ./
RUN go mod download
@@ -12,11 +14,11 @@ ARG VERSION=dev
ARG COMMIT=none
ARG BUILD_DATE=unknown
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w -X 'main.Version=${VERSION}' -X 'main.Commit=${COMMIT}' -X 'main.BuildDate=${BUILD_DATE}'" -o ./CLIProxyAPI ./cmd/server/
RUN CGO_ENABLED=1 GOOS=linux go build -buildvcs=false -ldflags="-s -w -X 'main.Version=${VERSION}' -X 'main.Commit=${COMMIT}' -X 'main.BuildDate=${BUILD_DATE}'" -o ./CLIProxyAPI ./cmd/server/
FROM alpine:3.22.0
FROM debian:bookworm
RUN apk add --no-cache tzdata
RUN apt-get update && apt-get install -y --no-install-recommends tzdata ca-certificates && rm -rf /var/lib/apt/lists/*
RUN mkdir /CLIProxyAPI
@@ -32,4 +34,4 @@ ENV TZ=Asia/Shanghai
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo "${TZ}" > /etc/timezone
CMD ["./CLIProxyAPI"]
CMD ["./CLIProxyAPI"]
+15
View File
@@ -0,0 +1,15 @@
FROM alpine:latest
# Install ttyd
RUN apk add --no-cache ttyd
# Set working directory
WORKDIR /app
# Copy the binary (we'll mount it instead for dev)
# The binary will be mounted at runtime
EXPOSE 7681
# Run ttyd with the mounted binary
CMD ["ttyd", "-p", "7681", "-W", "./proxypilot", "tui"]
+3 -2
View File
@@ -1,7 +1,8 @@
MIT License
Copyright (c) 2025-2005.9 Luis Pater
Copyright (c) 2025.9-present Router-For.ME
Copyright (c) 2024-2025 Luis Pater
Copyright (c) 2024-2025 Router-For.ME
Copyright (c) 2025 Finesssee (ProxyPilot fork)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+6
View File
@@ -0,0 +1,6 @@
ProxyPilot
ProxyPilot is a fork and rebrand of the CLIProxyAPI project (the underlying proxy engine).
This repository is distributed under the MIT License; see LICENSE.
+163 -13
View File
@@ -1,32 +1,74 @@
# CLI Proxy API
English | [中文](README_CN.md)
English | [中文](README_CN.md) | [日本語](README_JA.md)
A proxy server that provides OpenAI/Gemini/Claude/Codex compatible API interfaces for CLI.
A proxy server that provides OpenAI/Gemini/Claude/Codex/Grok compatible API interfaces for CLI.
It now also supports OpenAI Codex (GPT models) and Claude Code via OAuth.
So you can use local or multi-account CLI access with OpenAI(include Responses)/Gemini/Claude-compatible clients and SDKs.
## Sponsor
[![https://www.packyapi.com/register?aff=cliproxyapi](./assets/packycode-en.png)](https://www.packyapi.com/register?aff=cliproxyapi)
Thanks to PackyCode for sponsoring this project!
PackyCode is a reliable and efficient API relay service provider, offering relay services for Claude Code, Codex, Gemini, and more.
PackyCode provides special discounts for our software users: register using <a href="https://www.packyapi.com/register?aff=cliproxyapi">this link</a> and enter the "cliproxyapi" promo code during recharge to get 10% off.
---
<table>
<tbody>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=TJNAIF"><img src="./assets/aicodemirror.png" alt="AICodeMirror" width="150"></a></td>
<td>Thanks to AICodeMirror for sponsoring this project! AICodeMirror provides official high-stability relay services for Claude Code / Codex / Gemini, with enterprise-grade concurrency, fast invoicing, and 24/7 dedicated technical support. Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original price, with extra discounts on top-ups! AICodeMirror offers special benefits for CLIProxyAPI users: register via <a href="https://www.aicodemirror.com/register?invitecode=TJNAIF">this link</a> to enjoy 20% off your first top-up, and enterprise customers can get up to 25% off!</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="./assets/bmoplus.png" alt="BmoPlus" width="150"></a></td>
<td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of <b>10% of the official GPT subscription price (90% OFF)</b>!</td>
</tr>
<tr>
<td width="180"><a href="https://coder.visioncoder.cn"><img src="./assets/visioncoder.png" alt="VisionCoder" width="150"></a></td>
<td>Thanks to VisionCoder for supporting this project. <a href="https://coder.visioncoder.cn">VisionCoder Developer Platform</a> is a reliable and efficient API relay service provider, offering access to mainstream AI models such as Claude Code, Codex, and Gemini. It helps developers and teams integrate AI capabilities more easily and improve productivity. Additionally, VisionCoder now offers retail channels for <b>Claude Max 200 and GPT Pro 200 premium accounts</b>, providing users with instant access to top-tier AI computing power and features.</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CLIProxyAPI"><img src="./assets/apikey.png" alt="APIKEY.FUN" width="150"></a></td>
<td>Thanks to APIKEY.FUN for sponsoring this project! APIKEY.FUN is a professional enterprise-grade AI relay platform dedicated to providing stable, efficient, and low-cost AI model API access for enterprises and individual developers. The platform supports popular mainstream models such as Claude, OpenAI, and Gemini, with prices as low as 7% of the official price. Register through this project's <a href="https://apikey.fun/register?aff=CLIProxyAPI">exclusive link</a> to enjoy a special <b>permanent 5% top-up discount</b>.</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=FivD"><img src="./assets/runapi.png" alt="RunAPI" width="150"></a></td>
<td>RunAPI is an efficient and stable API platform—an alternative to OpenRouter. A single API Key gives you access to 150+ leading models, including OpenAI, Claude, Gemini, DeepSeek, Grok, and more, at prices as low as 10% of the original (up to 90% off), with exceptional stability. It's seamlessly compatible with tools like Claude Code, OpenClaw, and others. RunAPI offers an exclusive perk for CPA users: <a href="https://runapi.co/register?aff=FivD">register</a> and contact an administrator to claim ¥7 in free credit.</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=cliproxyapi"><img src="./assets/unity2.jpg" alt="Unity2" width="150"></a></td>
<td>Thanks to Unity2.ai for sponsoring this project! Unity2.ai is a high-performance AI model API relay platform for individual developers, teams, and enterprises. It has long served leading domestic enterprises, handles more than 30 billion token calls per day, and supports high concurrency at the 5000 RPM level. It supports balance billing, first top-up bonuses, bundled subscriptions, enterprise invoicing, and dedicated integration support. Register through <a href="https://unity2.ai/register?source=cliproxyapi">this link</a> to receive a $2 balance, then join the official group to get another $10 balance, for up to $12 in free credit.</td>
</tr>
<tr>
<td width="180"><a href="https://catapi.ai/sign-up"><img src="./assets/catapi.png" alt="CatAPI" width="150"></a></td>
<td>Cat API is an AI model aggregation platform built for individual developers and teams, integrating leading large language models into a single simple, stable, and easy-to-use entry point. It provides an API fully compatible with OpenAI, Claude, and Gemini that plugs seamlessly into mainstream AI IDEs and coding tools such as Claude Code, Cursor, Windsurf, Cline, Roo Code, Continue, Codex, and Trae, and features dedicated CN2 high-speed routing for low-latency, highly reliable access. <a href="https://catapi.ai/sign-up">Sign up</a> to claim 1$ in free credits.</td>
</tr>
</tbody>
</table>
## Overview
- OpenAI/Gemini/Claude compatible API endpoints for CLI models
- OpenAI/Gemini/Claude/Grok compatible API endpoints for CLI models
- OpenAI Codex support (GPT models) via OAuth login
- Claude Code support via OAuth login
- Qwen Code support via OAuth login
- iFlow support via OAuth login
- Streaming and non-streaming responses
- Grok Build support via OAuth login
- Streaming, non-streaming, and WebSocket responses where supported
- Function calling/tools support
- Multimodal input support (text and images)
- Multiple accounts with round-robin load balancing (Gemini, OpenAI, Claude, Qwen and iFlow)
- Simple CLI authentication flows (Gemini, OpenAI, Claude, Qwen and iFlow)
- Multiple accounts with round-robin load balancing (Gemini, OpenAI, Claude, Grok)
- Simple CLI authentication flows (Gemini, OpenAI, Claude, Grok)
- Generative Language API Key support
- AI Studio Build multi-account load balancing
- Gemini CLI multi-account load balancing
- Claude Code multi-account load balancing
- Qwen Code multi-account load balancing
- iFlow multi-account load balancing
- OpenAI Codex multi-account load balancing
- Grok Build multi-account load balancing
- OpenAI-compatible upstream providers via config (e.g., OpenRouter)
- Reusable Go SDK for embedding the proxy (see `docs/sdk-usage.md`)
@@ -38,6 +80,18 @@ CLIProxyAPI Guides: [https://help.router-for.me/](https://help.router-for.me/)
see [MANAGEMENT_API.md](https://help.router-for.me/management/api)
## Usage Statistics
Since v6.10.0, CLIProxyAPI and [CPAMC](https://github.com/router-for-me/Cli-Proxy-API-Management-Center) no longer ship built-in usage statistics. If you need usage statistics, use:
### [CPA Usage Keeper](https://github.com/Willxup/cpa-usage-keeper)
Standalone persistence and visualization service for CLIProxyAPI, with periodic data sync, SQLite storage, aggregate APIs, and a built-in dashboard for usage and statistics.
### [CPA-Manager-Plus](https://github.com/seakee/CPA-Manager-Plus)
Full CLIProxyAPI management center with request-level monitoring and cost estimates. CPA-Manager tracks collected requests by account, model, channel, latency, status, and token usage; estimates cost with editable model prices and one-click LiteLLM price sync; persists events in SQLite; and provides Codex account-pool operations with batch inspection, quota detection, unhealthy account discovery, cleanup suggestions, and one-click execution for day-to-day multi-account maintenance.
## SDK Docs
- Usage: [docs/sdk-usage.md](docs/sdk-usage.md)
@@ -66,11 +120,107 @@ Native macOS menu bar app to use your Claude Code & ChatGPT subscriptions with A
### [Subtitle Translator](https://github.com/VjayC/SRT-Subtitle-Translator-Validator)
Browser-based tool to translate SRT subtitles using your Gemini subscription via CLIProxyAPI with automatic validation/error correction - no API keys needed
A cross-platform desktop and web app to translate and validate SRT subtitles using your existing LLM subscriptions (Gemini, ChatGPT, Claude, etc.) via CLIProxyAPI - no API keys needed.
> [!NOTE]
### [CCS (Claude Code Switch)](https://github.com/kaitranntt/ccs)
CLI wrapper for instant switching between multiple Claude accounts and alternative models (Gemini, Codex, Antigravity) via CLIProxyAPI OAuth - no API keys needed
### [Quotio](https://github.com/nguyenphutrong/quotio)
Native macOS menu bar app that unifies Claude, Gemini, OpenAI, and Antigravity subscriptions with real-time quota tracking and smart auto-failover for AI coding tools like Claude Code, OpenCode, and Droid - no API keys needed.
### [ProxyPilot](https://github.com/Finesssee/ProxyPilot)
Windows-native CLIProxyAPI fork with TUI, system tray, and multi-provider OAuth for AI coding tools - no API keys needed.
### [Claude Proxy VSCode](https://github.com/uzhao/claude-proxy-vscode)
VSCode extension for quick switching between Claude Code models, featuring integrated CLIProxyAPI as its backend with automatic background lifecycle management.
### [ZeroLimit](https://github.com/0xtbug/zero-limit)
Windows desktop app built with Tauri + React for monitoring AI coding assistant quotas via CLIProxyAPI. Track usage across Gemini, Claude, OpenAI Codex, and Antigravity accounts with real-time dashboard, system tray integration, and one-click proxy control - no API keys needed.
### [CPA-XXX Panel](https://github.com/ferretgeek/CPA-X)
A lightweight web admin panel for CLIProxyAPI with health checks, resource monitoring, real-time logs, auto-update, request statistics and pricing display. Supports one-click installation and systemd service.
### [CLIProxyAPI Tray](https://github.com/kitephp/CLIProxyAPI_Tray)
A Windows tray application implemented using PowerShell scripts, without relying on any third-party libraries. The main features include: automatic creation of shortcuts, silent running, password management, channel switching (Main / Plus), and automatic downloading and updating.
### [霖君](https://github.com/wangdabaoqq/LinJun)
霖君 is a cross-platform desktop application for managing AI programming assistants, supporting macOS, Windows, and Linux systems. Unified management of Claude Code, Gemini, OpenAI Codex, and other AI coding tools, with local proxy for multi-account quota tracking and one-click configuration.
### [CLIProxyAPI Dashboard](https://github.com/itsmylife44/cliproxyapi-dashboard)
A modern web-based management dashboard for CLIProxyAPI built with Next.js, React, and PostgreSQL. Features real-time log streaming, structured configuration editing, API key management, OAuth provider integration for Claude/Gemini/Codex, usage analytics, container management, and config sync with OpenCode via companion plugin - no manual YAML editing needed.
### [All API Hub](https://github.com/qixing-jk/all-api-hub)
Browser extension for one-stop management of New API-compatible relay site accounts, featuring balance and usage dashboards, auto check-in, one-click key export to common apps, in-page API availability testing, and channel/model sync and redirection. It integrates with CLIProxyAPI through the Management API for one-click provider import and config sync.
### [Shadow AI](https://github.com/HEUDavid/shadow-ai)
Shadow AI is an AI assistant tool designed specifically for restricted environments. It provides a stealthy operation
mode without windows or traces, and enables cross-device AI Q&A interaction and control via the local area network (
LAN). Essentially, it is an automated collaboration layer of "screen/audio capture + AI inference + low-friction delivery",
helping users to immersively use AI assistants across applications on controlled devices or in restricted environments.
### [ProxyPal](https://github.com/buddingnewinsights/proxypal)
Cross-platform desktop app (macOS, Windows, Linux) wrapping CLIProxyAPI with a native GUI. Connects Claude, ChatGPT, Gemini, GitHub Copilot, and custom OpenAI-compatible endpoints with usage analytics, request monitoring, and auto-configuration for popular coding tools - no API keys needed.
### [CLIProxyAPI Quota Inspector](https://github.com/AllenReder/CLIProxyAPI-Quota-Inspector)
Ready-to-use cross-platform quota inspector for CLIProxyAPI, supporting per-account codex 5h/7d quota windows, plan-based sorting, status coloring, and multi-account summary analytics.
### [CLIProxy Pool Watch](https://github.com/murasame612/CLIProxyPoolWidget)
Native macOS SwiftUI app for monitoring ChatGPT/Codex account quotas in CLIProxyAPI pools. Displays account availability, Plus-base capacity, 5-hour and weekly quota bars, plan weights, and restore forecasts through the Management API.
### [Panopticon](https://github.com/eltmon/panopticon-cli)
Multi-agent orchestration for AI coding assistants. Runs CLIProxyAPI as a local sidecar so its agents can drive GPT models through a ChatGPT subscription, pointing Claude Code at an Anthropic-compatible endpoint with no OpenAI API key required.
### [Tunnel Agent](https://github.com/Villoh/tunnel-agent)
Windows desktop UI that manages CLIProxyAPI and Perplexity WebUI Scraper from a single interface, inspired by Quotio and VibeProxy. Connect OAuth providers (Claude, Gemini, Codex, Kimi, Antigravity), custom API keys, and Perplexity session accounts, then point any coding agent at the local endpoint.
### [Quotio Desktop](https://github.com/xiaocoss/quotio-desktop)
Cross-platform (Tauri) port of Quotio for Windows, macOS and Linux. Manages a pool of AI accounts (Codex, Claude Code, GitHub Copilot, Gemini, Antigravity, Kiro, Cursor, Trae, GLM) through CLIProxyAPI, with per-account 5-hour/weekly quota bars, Codex rate-limit reset credits with one-click reset, smart scheduling, usage statistics, and multi-instance Codex — no API keys needed.
> [!NOTE]
> If you developed a project based on CLIProxyAPI, please open a PR to add it to this list.
## More choices
Those projects are ports of CLIProxyAPI or inspired by it:
### [9Router](https://github.com/decolua/9router)
A Next.js implementation inspired by CLIProxyAPI, easy to install and use, built from scratch with format translation (OpenAI/Claude/Gemini/Ollama), combo system with auto-fallback, multi-account management with exponential backoff, a Next.js web dashboard, and support for CLI tools (Cursor, Claude Code, Cline, RooCode) - no API keys needed.
### [OmniRoute](https://github.com/diegosouzapw/OmniRoute)
Never stop coding. Smart routing to FREE & low-cost AI models with automatic fallback.
OmniRoute is an AI gateway for multi-provider LLMs: an OpenAI-compatible endpoint with smart routing, load balancing, retries, and fallbacks. Add policies, rate limits, caching, and observability for reliable, cost-aware inference.
### [Playful Proxy API Panel (PPAP)](https://github.com/daishuge/playful-proxy-api-panel)
A public CLIProxyAPI-compatible fork and bundled management panel. It keeps upstream-style usage while restoring built-in usage statistics, adding cache hit rate, first-byte latency, TPS tracking, and Docker-oriented self-hosted installation docs.
### [Codex Switch](https://github.com/9ycrooked/CodexSwitch)
This is a tool built with Tauri 2 + Vue 3 for managing multiple OpenAI Codex desktop accounts. Switch between saved ChatGPT/Codex certification profiles, check 5-hour and weekly quota usage in real time, verify token health, view active account details, and import or save auth.json files without manual copying.
> [!NOTE]
> If you have developed a port of CLIProxyAPI or a project inspired by it, please open a PR to add it to this list.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+161 -15
View File
@@ -1,34 +1,75 @@
# CLI 代理 API
[English](README.md) | 中文
[English](README.md) | 中文 | [日本語](README_JA.md)
一个为 CLI 提供 OpenAI/Gemini/Claude/Codex 兼容 API 接口的代理服务器。
一个为 CLI 提供 OpenAI/Gemini/Claude/Codex/Grok 兼容 API 接口的代理服务器。
现已支持通过 OAuth 登录接入 OpenAI Codex(GPT 系列)和 Claude Code。
您可以使用本地或多账户的CLI方式,通过任何与 OpenAI(包括Responses)/Gemini/Claude 兼容的客户端和SDK进行访问。
现已新增国内提供商:[Qwen Code](https://github.com/QwenLM/qwen-code)、[iFlow](https://iflow.cn/)。
## 赞助商
[![https://www.packyapi.com/register?aff=cliproxyapi](./assets/packycode-cn.png)](https://www.packyapi.com/register?aff=cliproxyapi)
感谢 PackyCode 对本项目的赞助!
PackyCode 是一家可靠高效的 API 中转服务商,提供 Claude Code、Codex、Gemini 等多种服务的中转。
PackyCode 为本软件用户提供了特别优惠:使用<a href="https://www.packyapi.com/register?aff=cliproxyapi" target="_blank">此链接</a>注册,并在充值时输入 "cliproxyapi" 优惠码即可享受九折优惠。
---
<table>
<tbody>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=TJNAIF"><img src="./assets/aicodemirror.png" alt="AICodeMirror" width="150"></a></td>
<td>感谢 AICodeMirror 赞助了本项目!AICodeMirror 提供 Claude Code / Codex / Gemini 官方高稳定中转服务,支持企业级高并发、极速开票、7×24 专属技术支持。 Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更有折上折!AICodeMirror 为 CLIProxyAPI 的用户提供了特别福利,通过<a href="https://www.aicodemirror.com/register?invitecode=TJNAIF" target="_blank">此链接</a>注册的用户,可享受首充8折,企业客户最高可享 7.5 折!</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="./assets/bmoplus.png" alt="BmoPlus" width="150"></a></td>
<td>感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github" target="_blank">BmoPlus AI成品号专卖/代充</a>注册下单的用户,可享GPT <b>官网订阅一折</b> 的震撼价格!</td>
</tr>
<tr>
<td width="180"><a href="https://coder.visioncoder.cn"><img src="./assets/visioncoder.png" alt="VisionCoder" width="150"></a></td>
<td>感谢 VisionCoder 对本项目的支持。<a href="https://coder.visioncoder.cn">VisionCoder 开发平台</a> 是一个可靠高效的 API 中继服务提供商,提供 Claude Code、Codex、Gemini 等主流 AI 模型,帮助开发者和团队更轻松地集成 AI 功能,提升工作效率。此外,VisionCoder 还提供 <b>Claude Max 200 与 GPT Pro 200 高级成品号</b>的独家售卖渠道,助力体验全网顶配 AI 的算力与体验。</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CLIProxyAPI"><img src="./assets/apikey.png" alt="APIKEY.FUN" width="150"></a></td>
<td>感谢 APIKEY.FUN 赞助本项目!APIKEY.FUN 是一家专业的企业级 AI 中转站,致力于为企业和个人开发者提供稳定、高效、低成本的 AI 模型 API 接入服务。平台支持 Claude、OpenAI、Gemini 等主流热门模型,价格低至官方原价的 7%。通过本项目<a href="https://apikey.fun/register?aff=CLIProxyAPI">专属链接</a>注册,还可享受最高 <b>充值永久 95 折</b> 专属优惠。</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=FivD"><img src="./assets/runapi.png" alt="RunAPI" width="150"></a></td>
<td>RunAPI 是高效稳定的API OpenRouter平替平台,一个 API Key 即可访问 OpenAI、Claude、Gemini、DeepSeek、Grok 等 150+ 主流模型,低至 1 折,极其稳定,可以无缝兼容 Claude Code、OpenClaw 等工具。RunAPI 为 CPA的用户提供专属福利:<a href="https://runapi.co/register?aff=FivD">注册</a>联系管理员即可领取¥7的免费额度</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=cliproxyapi"><img src="./assets/unity2.jpg" alt="Unity2" width="150"></a></td>
<td>感谢 Unity2.ai 赞助了本项目!Unity2.ai 是面向个人开发者、团队和企业的高性能 AI 模型 API 中转平台,长期服务国内头部企业,日均承载超 300 亿 token 调用,支持 5000 RPM 级高并发。支持余额计费、首充赠额、组合订阅、企业开票和专属对接。通过<a href="https://unity2.ai/register?source=cliproxyapi">此链接</a>注册可领取 $2 余额,加入官方群再送 $10 余额,最高可领 $12 免费额度。</td>
</tr>
<tr>
<td width="180"><a href="https://catapi.ai/sign-up"><img src="./assets/catapi.png" alt="CatAPI" width="150"></a></td>
<td>Cat API 是一家面向个人开发者与团队的 AI 大模型聚合平台,致力于将主流大模型能力整合到一个简单、稳定、易用的入口中。平台提供完全兼容 OpenAI、Claude、Gemini 的 API,可无缝接入 Claude Code、Cursor、Windsurf、Cline、Roo Code、Continue、Codex、Trae 等主流 AI IDE 与编程工具,并主打 CN2 高速线路,为用户带来低延迟、高稳定的访问体验。<a href="https://catapi.ai/sign-up">注册</a>即可领取 1$ 的免费额度。</td>
</tr>
</tbody>
</table>
## 功能特性
- 为 CLI 模型提供 OpenAI/Gemini/Claude/Codex 兼容的 API 端点
- 为 CLI 模型提供 OpenAI/Gemini/Claude/Codex/Grok 兼容的 API 端点
- 新增 OpenAI Codex(GPT 系列)支持(OAuth 登录)
- 新增 Claude Code 支持(OAuth 登录)
- 新增 Qwen Code 支持(OAuth 登录)
- 新增 iFlow 支持(OAuth 登录)
- 支持流式与非流式响应
- 新增 Grok Build 支持(OAuth 登录)
- 支持流式、非流式响应,以及受支持场景下的 WebSocket 响应
- 函数调用/工具支持
- 多模态输入(文本、图片)
- 多账户支持与轮询负载均衡(Gemini、OpenAI、Claude、Qwen 与 iFlow)
- 简单的 CLI 身份验证流程(Gemini、OpenAI、Claude、Qwen 与 iFlow)
- 多账户支持与轮询负载均衡(Gemini、OpenAI、Claude、Grok)
- 简单的 CLI 身份验证流程(Gemini、OpenAI、Claude、Grok)
- 支持 Gemini AIStudio API 密钥
- 支持 AI Studio Build 多账户轮询
- 支持 Gemini CLI 多账户轮询
- 支持 Claude Code 多账户轮询
- 支持 Qwen Code 多账户轮询
- 支持 iFlow 多账户轮询
- 支持 OpenAI Codex 多账户轮询
- 支持 Grok Build 多账户轮询
- 通过配置接入上游 OpenAI 兼容提供商(例如 OpenRouter)
- 可复用的 Go SDK(见 `docs/sdk-usage_CN.md`)
@@ -40,6 +81,18 @@ CLIProxyAPI 用户手册: [https://help.router-for.me/](https://help.router-fo
请参见 [MANAGEMENT_API_CN.md](https://help.router-for.me/cn/management/api)
## 使用量统计
自v6.10.0版本以后,CLIProxyAPI及 [CPAMC](https://github.com/router-for-me/Cli-Proxy-API-Management-Center) 项目不再预置数据统计功能,如果有数据统计需求的请使用以下项目:
### [CPA Usage Keeper](https://github.com/Willxup/cpa-usage-keeper)
独立的 CLIProxyAPI 使用量持久化与可视化服务,定期同步 CLIProxyAPI 数据,存储到 SQLite,提供聚合 API,并内置使用量分析与统计仪表盘。
### [CPA-Manager-Plus](https://github.com/seakee/CPA-Manager-Plus)
面向 CLIProxyAPI 的完整管理中心,提供请求级监控和费用预估。CPA-Manager 可按账号、模型、渠道、延迟、状态和 token 用量追踪采集到的请求;支持可编辑模型价格与一键同步 LiteLLM 价格来估算费用;用 SQLite 持久化事件;并提供面向 Codex 账号池的批量巡检、配额识别、异常账号定位、清理建议与一键执行能力,适合多账号池的日常运维管理。
## SDK 文档
- 使用文档:[docs/sdk-usage_CN.md](docs/sdk-usage_CN.md)
@@ -68,18 +121,111 @@ CLIProxyAPI 用户手册: [https://help.router-for.me/](https://help.router-fo
### [Subtitle Translator](https://github.com/VjayC/SRT-Subtitle-Translator-Validator)
一款基于浏览器的 SRT 字幕翻译工具,可通过 CLI 代理 API 使用您的 Gemini 订阅。内置自动验证与错误修正功能,无需 API 密钥。
一款跨平台的桌面和 Web 应用程序,可通过 CLIProxyAPI 使用您现有的 LLM 订阅(Gemini、ChatGPT、Claude, etc.)来翻译和验证 SRT 字幕 - 无需 API 密钥。
> [!NOTE]
### [CCS (Claude Code Switch)](https://github.com/kaitranntt/ccs)
CLI 封装器,用于通过 CLIProxyAPI OAuth 即时切换多个 Claude 账户和替代模型(Gemini, Codex, Antigravity),无需 API 密钥。
### [Quotio](https://github.com/nguyenphutrong/quotio)
原生 macOS 菜单栏应用,统一管理 Claude、Gemini、OpenAI 和 Antigravity 订阅,提供实时配额追踪和智能自动故障转移,支持 Claude Code、OpenCode 和 Droid 等 AI 编程工具,无需 API 密钥。
### [ProxyPilot](https://github.com/Finesssee/ProxyPilot)
原生 Windows CLIProxyAPI 分支,集成 TUI、系统托盘及多服务商 OAuth 认证,专为 AI 编程工具打造,无需 API 密钥。
### [Claude Proxy VSCode](https://github.com/uzhao/claude-proxy-vscode)
一款 VSCode 扩展,提供了在 VSCode 中快速切换 Claude Code 模型的功能,内置 CLIProxyAPI 作为其后端,支持后台自动启动和关闭。
### [ZeroLimit](https://github.com/0xtbug/zero-limit)
Windows 桌面应用,基于 Tauri + React 构建,用于通过 CLIProxyAPI 监控 AI 编程助手配额。支持跨 Gemini、Claude、OpenAI Codex 和 Antigravity 账户的使用量追踪,提供实时仪表盘、系统托盘集成和一键代理控制,无需 API 密钥。
### [CPA-XXX Panel](https://github.com/ferretgeek/CPA-X)
面向 CLIProxyAPI 的 Web 管理面板,提供健康检查、资源监控、日志查看、自动更新、请求统计与定价展示,支持一键安装与 systemd 服务。
### [CLIProxyAPI Tray](https://github.com/kitephp/CLIProxyAPI_Tray)
Windows 托盘应用,基于 PowerShell 脚本实现,不依赖任何第三方库。主要功能包括:自动创建快捷方式、静默运行、密码管理、通道切换(Main / Plus)以及自动下载与更新。
### [霖君](https://github.com/wangdabaoqq/LinJun)
霖君是一款用于管理AI编程助手的跨平台桌面应用,支持macOS、Windows、Linux系统。统一管理Claude Code、Gemini、OpenAI Codex等AI编程工具,本地代理实现多账户配额跟踪和一键配置。
### [CLIProxyAPI Dashboard](https://github.com/itsmylife44/cliproxyapi-dashboard)
一个面向 CLIProxyAPI 的现代化 Web 管理仪表盘,基于 Next.js、React 和 PostgreSQL 构建。支持实时日志流、结构化配置编辑、API Key 管理、Claude/Gemini/Codex 的 OAuth 提供方集成、使用量分析、容器管理,并可通过配套插件与 OpenCode 同步配置,无需手动编辑 YAML。
### [All API Hub](https://github.com/qixing-jk/all-api-hub)
用于一站式管理 New API 兼容中转站账号的浏览器扩展,提供余额与用量看板、自动签到、密钥一键导出到常用应用、网页内 API 可用性测试,以及渠道与模型同步和重定向。支持通过 CLIProxyAPI Management API 一键导入 Provider 与同步配置。
### [Shadow AI](https://github.com/HEUDavid/shadow-ai)
Shadow AI 是一款专为受限环境设计的 AI 辅助工具。提供无窗口、无痕迹的隐蔽运行方式,并通过局域网实现跨设备的 AI 问答交互与控制。本质上是一个「屏幕/音频采集 + AI 推理 + 低摩擦投送」的自动化协作层,帮助用户在受控设备/受限环境下沉浸式跨应用地使用 AI 助手。
### [ProxyPal](https://github.com/buddingnewinsights/proxypal)
跨平台桌面应用(macOS、Windows、Linux),以原生 GUI 封装 CLIProxyAPI。支持连接 Claude、ChatGPT、Gemini、GitHub Copilot 及自定义 OpenAI 兼容端点,具备使用分析、请求监控和热门编程工具自动配置功能,无需 API 密钥。
### [CLIProxyAPI Quota Inspector](https://github.com/AllenReder/CLIProxyAPI-Quota-Inspector)
上手即用的面向 CLIProxyAPI 跨平台配额查询工具,支持按账号展示 codex 5h/7d 配额窗口、按计划排序、状态着色及多账号汇总分析。
### [CLIProxy Pool Watch](https://github.com/murasame612/CLIProxyPoolWidget)
原生 macOS SwiftUI 应用,用于监控 CLIProxyAPI 池中的 ChatGPT/Codex 账号额度。通过 Management API 展示账号可用状态、Plus 基准容量、5 小时与周额度进度条、套餐权重和恢复预测。
### [Panopticon](https://github.com/eltmon/panopticon-cli)
面向 AI 编程助手的多智能体编排工具。它将 CLIProxyAPI 作为本地 sidecar 运行,使其智能体可以通过 ChatGPT 订阅驱动 GPT 模型,并将 Claude Code 指向 Anthropic 兼容端点,无需 OpenAI API 密钥。
### [Tunnel Agent](https://github.com/Villoh/tunnel-agent)
Windows 桌面 UI,通过单一界面管理 CLIProxyAPI 和 Perplexity WebUI Scraper,灵感来自 Quotio 和 VibeProxy。连接 OAuth 提供商(Claude、Gemini、Codex、Kimi、Antigravity)、自定义 API 密钥和 Perplexity 会话账号,然后将任意编程智能体指向本地端点。
### [Quotio Desktop](https://github.com/xiaocoss/quotio-desktop)
Quotio 的跨平台(Tauri)移植版,支持 Windows / macOS / Linux。通过 CLIProxyAPI 管理多账号代理池(Codex、Claude Code、GitHub Copilot、Gemini、Antigravity、Kiro、Cursor、Trae、GLM),提供每账号 5 小时 / 每周额度进度条、Codex 主动重置次数与一键重置、智能调度、用量统计及 Codex 多开实例,无需 API 密钥。
> [!NOTE]
> 如果你开发了基于 CLIProxyAPI 的项目,请提交一个 PR(拉取请求)将其添加到此列表中。
## 更多选择
以下项目是 CLIProxyAPI 的移植版或受其启发:
### [9Router](https://github.com/decolua/9router)
基于 Next.js 的实现,灵感来自 CLIProxyAPI,易于安装使用;自研格式转换(OpenAI/Claude/Gemini/Ollama)、组合系统与自动回退、多账户管理(指数退避)、Next.js Web 控制台,并支持 Cursor、Claude Code、Cline、RooCode 等 CLI 工具,无需 API 密钥。
### [OmniRoute](https://github.com/diegosouzapw/OmniRoute)
代码不止,创新不停。智能路由至免费及低成本 AI 模型,并支持自动故障转移。
OmniRoute 是一个面向多供应商大语言模型的 AI 网关:它提供兼容 OpenAI 的端点,具备智能路由、负载均衡、重试及回退机制。通过添加策略、速率限制、缓存和可观测性,确保推理过程既可靠又具备成本意识。
### [Playful Proxy API Panel (PPAP)](https://github.com/daishuge/playful-proxy-api-panel)
一个公开的 CLIProxyAPI 兼容二开版本和配套管理面板,尽量保持与上游一致的使用方式,同时恢复内置使用量统计,并补充缓存命中率、首字响应时间、TPS 记录和面向 Docker 自托管的安装说明。
### [Codex Switch](https://github.com/9ycrooked/CodexSwitch)
这是一个使用 Tauri 2 + Vue 3 构建的工具,用于管理多个 OpenAI Codex 桌面账户。它可以在已保存的 ChatGPT/Codex 认证配置之间切换,实时查看 5 小时和每周配额使用情况,验证 token 健康状态,查看当前账户详情,并在无需手动复制的情况下导入或保存 auth.json 文件。
> [!NOTE]
> 如果你开发了 CLIProxyAPI 的移植或衍生项目,请提交 PR 将其添加到此列表中。
## 许可证
此项目根据 MIT 许可证授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
## 写给所有中国网友的
QQ 群:188637136
QQ 群:188637136(满)、1081218164
或
+223
View File
@@ -0,0 +1,223 @@
# CLI Proxy API
[English](README.md) | [中文](README_CN.md) | 日本語
CLI向けのOpenAI/Gemini/Claude/Codex/Grok互換APIインターフェースを提供するプロキシサーバーです。
OAuth経由でOpenAI Codex(GPTモデル)およびClaude Codeもサポートしています。
ローカルまたはマルチアカウントのCLIアクセスを、OpenAI(Responses含む)/Gemini/Claude互換のクライアントやSDKで利用できます。
## スポンサー
[![https://www.packyapi.com/register?aff=cliproxyapi](./assets/packycode-en.png)](https://www.packyapi.com/register?aff=cliproxyapi)
PackyCodeのスポンサーシップに感謝します!
PackyCodeは信頼性が高く効率的なAPIリレーサービスプロバイダーで、Claude Code、Codex、Geminiなどのリレーサービスを提供しています。
PackyCodeは当ソフトウェアのユーザーに特別割引を提供しています:<a href="https://www.packyapi.com/register?aff=cliproxyapi">こちらのリンク</a>から登録し、チャージ時にプロモーションコード「cliproxyapi」を入力すると10%割引になります。
---
<table>
<tbody>
<tr>
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=TJNAIF"><img src="./assets/aicodemirror.png" alt="AICodeMirror" width="150"></a></td>
<td>AICodeMirrorのスポンサーシップに感謝します!AICodeMirrorはClaude Code / Codex / Gemini向けの公式高安定性リレーサービスを提供しており、エンタープライズグレードの同時接続、迅速な請求書発行、24時間365日の専任技術サポートを備えています。Claude Code / Codex / Geminiの公式チャネルが元の価格の38% / 2% / 9%で利用でき、チャージ時にはさらに割引があります!CLIProxyAPIユーザー向けの特別特典:<a href="https://www.aicodemirror.com/register?invitecode=TJNAIF">こちらのリンク</a>から登録すると、初回チャージが20%割引になり、エンタープライズのお客様は最大25%割引を受けられます!</td>
</tr>
<tr>
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="./assets/bmoplus.png" alt="BmoPlus" width="150"></a></td>
<td>本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを <b>公式サイト価格の約1割(90% OFF)</b> という驚異的な価格でご利用いただけます!</td>
</tr>
<tr>
<td width="180"><a href="https://coder.visioncoder.cn"><img src="./assets/visioncoder.png" alt="VisionCoder" width="150"></a></td>
<td>VisionCoderのご支援に感謝します。<a href="https://coder.visioncoder.cn">VisionCoder 開発プラットフォーム</a> は、信頼性が高く効率的なAPIリレーサービスプロバイダーで、Claude Code、Codex、Geminiなどの主要AIモデルを提供し、開発者やチームがより簡単にAI機能を統合して生産性を向上できるよう支援します。さらに、VisionCoderは <b>Claude Max 200 と GPT Pro 200 高級即納アカウント</b> の独占販売チャネルを提供しており、最高クラスのAI算力と体験を手軽に体験できます。</td>
</tr>
<tr>
<td width="180"><a href="https://apikey.fun/register?aff=CLIProxyAPI"><img src="./assets/apikey.png" alt="APIKEY.FUN" width="150"></a></td>
<td>APIKEY.FUNのスポンサーシップに感謝します!APIKEY.FUNはプロフェッショナルなエンタープライズ向けAIリレーサービスで、企業および個人開発者に安定・高効率・低コストなAIモデルAPI接続サービスを提供しています。Claude、OpenAI、Geminiなどの主要人気モデルに対応し、価格は公式価格の7%から利用できます。本プロジェクトの<a href="https://apikey.fun/register?aff=CLIProxyAPI">専用リンク</a>から登録すると、さらに<b>チャージが永続的に5%割引</b>となる特別優待を受けられます。</td>
</tr>
<tr>
<td width="180"><a href="https://runapi.co/register?aff=FivD"><img src="./assets/runapi.png" alt="RunAPI" width="150"></a></td>
<td>RunAPIは高効率で安定したAPIプラットフォームで、OpenRouterの代替として利用できます。1つのAPI KeyでOpenAI、Claude、Gemini、DeepSeek、Grokなど150以上の主要モデルにアクセスでき、価格は公式価格の10%から、非常に安定しており、Claude Code、OpenClawなどのツールとシームレスに互換性があります。RunAPIはCPAユーザー向けに特別特典を提供しています:<a href="https://runapi.co/register?aff=FivD">登録</a>後に管理者へ連絡すると、7元分の無料クレジットを受け取れます。</td>
</tr>
<tr>
<td width="180"><a href="https://unity2.ai/register?source=cliproxyapi"><img src="./assets/unity2.jpg" alt="Unity2" width="150"></a></td>
<td>Unity2.aiのスポンサーシップに感謝します!Unity2.aiは、個人開発者、チーム、企業向けの高性能AIモデルAPIリレープラットフォームです。国内の大手企業に長期的にサービスを提供し、1日あたり300億tokenを超える呼び出しを処理し、5000 RPM級の高同時実行に対応しています。残高課金、初回チャージ特典、組み合わせサブスクリプション、企業向け請求書発行、専任サポートに対応しています。<a href="https://unity2.ai/register?source=cliproxyapi">こちらのリンク</a>から登録すると$2の残高を受け取れ、公式グループに参加するとさらに$10の残高が付与され、最大$12の無料クレジットを受け取れます。</td>
</tr>
<tr>
<td width="180"><a href="https://catapi.ai/sign-up"><img src="./assets/catapi.png" alt="CatAPI" width="150"></a></td>
<td>Cat APIは、個人開発者やチーム向けのAI大規模モデル集約プラットフォームです。主要な大規模モデルの機能を、シンプルで安定した使いやすい入口に統合することを目指しています。OpenAI、Claude、Geminiと完全互換のAPIを提供し、Claude Code、Cursor、Windsurf、Cline、Roo Code、Continue、Codex、Traeなどの主要なAI IDEやプログラミングツールへシームレスに接続できます。また、CN2高速回線を主な特徴としており、低遅延で高安定なアクセス体験を提供します。<a href="https://catapi.ai/sign-up">登録</a>すると、1$の無料クレジットを受け取れます。</td>
</tr>
</tbody>
</table>
## 概要
- CLIモデル向けのOpenAI/Gemini/Claude/Grok互換APIエンドポイント
- OAuthログインによるOpenAI Codexサポート(GPTモデル)
- OAuthログインによるClaude Codeサポート
- OAuthログインによるGrok Buildサポート
- ストリーミング、非ストリーミング、および対応環境でのWebSocketレスポンス
- 関数呼び出し/ツールのサポート
- マルチモーダル入力サポート(テキストと画像)
- ラウンドロビン負荷分散による複数アカウント対応(Gemini、OpenAI、Claude、Grok)
- シンプルなCLI認証フロー(Gemini、OpenAI、Claude、Grok)
- Generative Language APIキーのサポート
- AI Studioビルドのマルチアカウント負荷分散
- Claude Codeのマルチアカウント負荷分散
- OpenAI Codexのマルチアカウント負荷分散
- Grok Buildのマルチアカウント負荷分散
- 設定によるOpenAI互換アップストリームプロバイダー(例:OpenRouter)
- プロキシ埋め込み用の再利用可能なGo SDK(`docs/sdk-usage.md`を参照)
## はじめに
CLIProxyAPIガイド:[https://help.router-for.me/](https://help.router-for.me/)
## 管理API
[MANAGEMENT_API.md](https://help.router-for.me/management/api)を参照
## 使用量統計
v6.10.0以降、CLIProxyAPIおよび [CPAMC](https://github.com/router-for-me/Cli-Proxy-API-Management-Center) プロジェクトには使用量統計機能がプリセットされなくなりました。使用量統計が必要な場合は、次のプロジェクトをご利用ください:
### [CPA Usage Keeper](https://github.com/Willxup/cpa-usage-keeper)
CLIProxyAPI向けの独立した使用量永続化・可視化サービス。CLIProxyAPIデータを定期同期してSQLiteに保存し、集計APIと、使用量や各種統計を確認できる組み込みダッシュボードを提供します。
### [CPA-Manager-Plus](https://github.com/seakee/CPA-Manager-Plus)
リクエスト単位の監視とコスト推定を備えたCLIProxyAPI向けのフル管理センターです。CPA-Managerは、収集したリクエストをアカウント、モデル、チャネル、レイテンシ、ステータス、Token使用量ごとに追跡し、編集可能なモデル価格とLiteLLM価格のワンクリック同期でコストを推定します。SQLiteでイベントを永続化し、Codexアカウントプール向けに一括検査、クォータ判定、異常アカウント検出、クリーンアップ提案、ワンクリック実行を提供し、日常的なマルチアカウント運用に適しています。
## SDKドキュメント
- 使い方:[docs/sdk-usage.md](docs/sdk-usage.md)
- 上級(エグゼキューターとトランスレーター):[docs/sdk-advanced.md](docs/sdk-advanced.md)
- アクセス:[docs/sdk-access.md](docs/sdk-access.md)
- ウォッチャー:[docs/sdk-watcher.md](docs/sdk-watcher.md)
- カスタムプロバイダーの例:`examples/custom-provider`
## コントリビューション
コントリビューションを歓迎します!お気軽にPull Requestを送ってください。
1. リポジトリをフォーク
2. フィーチャーブランチを作成(`git checkout -b feature/amazing-feature`)
3. 変更をコミット(`git commit -m 'Add some amazing feature'`)
4. ブランチにプッシュ(`git push origin feature/amazing-feature`)
5. Pull Requestを作成
## 関連プロジェクト
CLIProxyAPIをベースにした以下のプロジェクトがあります:
### [vibeproxy](https://github.com/automazeio/vibeproxy)
macOSネイティブのメニューバーアプリで、Claude CodeとChatGPTのサブスクリプションをAIコーディングツールで使用可能 - APIキー不要
### [Subtitle Translator](https://github.com/VjayC/SRT-Subtitle-Translator-Validator)
CLIProxyAPI経由で既存のLLMサブスクリプション(Gemini、ChatGPT、Claude, etc.)を使用してSRT字幕を翻訳および検証する、クロスプラットフォームのデスクトップおよびWebアプリ - APIキー不要。
### [CCS (Claude Code Switch)](https://github.com/kaitranntt/ccs)
CLIProxyAPI OAuthを使用して複数のClaudeアカウントや代替モデル(Gemini、Codex、Antigravity)を即座に切り替えるCLIラッパー - APIキー不要
### [Quotio](https://github.com/nguyenphutrong/quotio)
Claude、Gemini、OpenAI、Antigravityのサブスクリプションを統合し、リアルタイムのクォータ追跡とスマート自動フェイルオーバーを備えたmacOSネイティブのメニューバーアプリ。Claude Code、OpenCode、Droidなどのコーディングツール向け - APIキー不要
### [ProxyPilot](https://github.com/Finesssee/ProxyPilot)
TUI、システムトレイ、マルチプロバイダーOAuthを備えたWindows向けCLIProxyAPIフォーク - AIコーディングツール用、APIキー不要
### [Claude Proxy VSCode](https://github.com/uzhao/claude-proxy-vscode)
Claude Codeモデルを素早く切り替えるVSCode拡張機能。バックエンドとしてCLIProxyAPIを統合し、バックグラウンドでの自動ライフサイクル管理を搭載
### [ZeroLimit](https://github.com/0xtbug/zero-limit)
CLIProxyAPIを使用してAIコーディングアシスタントのクォータを監視するTauri + React製のWindowsデスクトップアプリ。Gemini、Claude、OpenAI Codex、Antigravityアカウントの使用量をリアルタイムダッシュボード、システムトレイ統合、ワンクリックプロキシコントロールで追跡 - APIキー不要
### [CPA-XXX Panel](https://github.com/ferretgeek/CPA-X)
CLIProxyAPI向けの軽量Web管理パネル。ヘルスチェック、リソース監視、リアルタイムログ、自動更新、リクエスト統計、料金表示機能を搭載。ワンクリックインストールとsystemdサービスに対応
### [CLIProxyAPI Tray](https://github.com/kitephp/CLIProxyAPI_Tray)
PowerShellスクリプトで実装されたWindowsトレイアプリケーション。サードパーティライブラリに依存せず、ショートカットの自動作成、サイレント実行、パスワード管理、チャネル切り替え(Main / Plus)、自動ダウンロードおよび自動更新に対応
### [霖君](https://github.com/wangdabaoqq/LinJun)
霖君はAIプログラミングアシスタントを管理するクロスプラットフォームデスクトップアプリケーションで、macOS、Windows、Linuxシステムに対応。Claude Code、Gemini、OpenAI Codexなどのコーディングツールを統合管理し、ローカルプロキシによるマルチアカウントクォータ追跡とワンクリック設定が可能
### [CLIProxyAPI Dashboard](https://github.com/itsmylife44/cliproxyapi-dashboard)
Next.js、React、PostgreSQLで構築されたCLIProxyAPI用のモダンなWebベース管理ダッシュボード。リアルタイムログストリーミング、構造化された設定編集、APIキー管理、Claude/Gemini/Codex向けOAuthプロバイダー統合、使用量分析、コンテナ管理、コンパニオンプラグインによるOpenCodeとの設定同期機能を搭載 - 手動でのYAML編集は不要
### [All API Hub](https://github.com/qixing-jk/all-api-hub)
New API互換リレーサイトアカウントをワンストップで管理するブラウザ拡張機能。残高と使用量のダッシュボード、自動チェックイン、一般的なアプリへのワンクリックキーエクスポート、ページ内API可用性テスト、チャネル/モデルの同期とリダイレクト機能を搭載。Management APIを通じてCLIProxyAPIと統合し、ワンクリックでプロバイダーのインポートと設定同期が可能
### [Shadow AI](https://github.com/HEUDavid/shadow-ai)
Shadow AIは制限された環境向けに特別に設計されたAIアシスタントツールです。ウィンドウや痕跡のないステルス動作モードを提供し、LAN(ローカルエリアネットワーク)を介したクロスデバイスAI質疑応答のインタラクションと制御を可能にします。本質的には「画面/音声キャプチャ + AI推論 + 低摩擦デリバリー」の自動化コラボレーションレイヤーであり、制御されたデバイスや制限された環境でアプリケーション横断的にAIアシスタントを没入的に使用できるようユーザーを支援します。
### [ProxyPal](https://github.com/buddingnewinsights/proxypal)
CLIProxyAPIをネイティブGUIでラップしたクロスプラットフォームデスクトップアプリ(macOS、Windows、Linux)。Claude、ChatGPT、Gemini、GitHub Copilot、カスタムOpenAI互換エンドポイントに対応し、使用状況分析、リクエスト監視、人気コーディングツールの自動設定機能を搭載 - APIキー不要
### [CLIProxyAPI Quota Inspector](https://github.com/AllenReder/CLIProxyAPI-Quota-Inspector)
CLIProxyAPI向けのすぐに使えるクロスプラットフォームのクォータ確認ツール。アカウントごとの codex 5h/7d クォータ表示、プラン別ソート、ステータス色分け、複数アカウントの集計分析に対応。
### [CLIProxy Pool Watch](https://github.com/murasame612/CLIProxyPoolWidget)
CLIProxyAPIプール内のChatGPT/Codexアカウントクォータを監視するmacOSネイティブSwiftUIアプリ。Management APIを通じて、アカウントの可用性、Plus基準の容量、5時間/週次クォータバー、プラン重み、復元予測を表示します。
### [Panopticon](https://github.com/eltmon/panopticon-cli)
AIコーディングアシスタント向けのマルチエージェントオーケストレーションツール。CLIProxyAPIをローカルsidecarとして実行することで、エージェントがChatGPTサブスクリプション経由でGPTモデルを利用できるようにし、Claude CodeをAnthropic互換エンドポイントへ向けるため、OpenAI APIキーは不要です。
### [Tunnel Agent](https://github.com/Villoh/tunnel-agent)
CLIProxyAPIとPerplexity WebUI Scraperをひとつのインターフェースで管理するWindowsデスクトップUI。QuotioとVibeProxyにインスパイアされ、OAuthプロバイダー(Claude、Gemini、Codex、Kimi、Antigravity)、カスタムAPIキー、Perplexityセッションアカウントを接続し、任意のコーディングエージェントをローカルエンドポイントに向けることができます。
### [Quotio Desktop](https://github.com/xiaocoss/quotio-desktop)
Quotio のクロスプラットフォーム(Tauri)移植版(Windows / macOS / Linux 対応)。CLIProxyAPI 経由で複数の AI アカウント(Codex、Claude Code、GitHub Copilot、Gemini、Antigravity、Kiro、Cursor、Trae、GLM)のプールを管理し、アカウントごとの 5 時間 / 週間クォータバー、Codex のリセットクレジットとワンクリックリセット、スマートスケジューリング、使用統計、Codex マルチインスタンスに対応。API キー不要。
> [!NOTE]
> CLIProxyAPIをベースにプロジェクトを開発した場合は、PRを送ってこのリストに追加してください。
## その他の選択肢
以下のプロジェクトはCLIProxyAPIの移植版またはそれに触発されたものです:
### [9Router](https://github.com/decolua/9router)
CLIProxyAPIに触発されたNext.js実装。インストールと使用が簡単で、フォーマット変換(OpenAI/Claude/Gemini/Ollama)、自動フォールバック付きコンボシステム、指数バックオフ付きマルチアカウント管理、Next.js Webダッシュボード、CLIツール(Cursor、Claude Code、Cline、RooCode)のサポートをゼロから構築 - APIキー不要
### [OmniRoute](https://github.com/diegosouzapw/OmniRoute)
コーディングを止めない。無料および低コストのAIモデルへのスマートルーティングと自動フォールバック。
OmniRouteはマルチプロバイダーLLM向けのAIゲートウェイです:スマートルーティング、負荷分散、リトライ、フォールバックを備えたOpenAI互換エンドポイント。ポリシー、レート制限、キャッシュ、可観測性を追加して、信頼性が高くコストを意識した推論を実現します。
### [Playful Proxy API Panel (PPAP)](https://github.com/daishuge/playful-proxy-api-panel)
上流に近い使い方を維持する公開CLIProxyAPI互換フォーク兼管理パネルです。内蔵の使用量統計を復元し、キャッシュヒット率、初回バイト待ち時間、TPSの記録、Docker向けのセルフホスト手順を追加しています。
### [Codex Switch](https://github.com/9ycrooked/CodexSwitch)
Tauri 2 + Vue 3で構築された、複数のOpenAI Codexデスクトップアカウントを管理するためのツールです。保存済みのChatGPT/Codex認証プロファイルを切り替え、5時間および週次クォータ使用量をリアルタイムで確認し、tokenの状態を検証し、現在のアカウント詳細を表示し、手動コピーなしでauth.jsonファイルをインポートまたは保存できます。
> [!NOTE]
> CLIProxyAPIの移植版またはそれに触発されたプロジェクトを開発した場合は、PRを送ってこのリストに追加してください。
## ライセンス
本プロジェクトはMITライセンスの下でライセンスされています - 詳細は[LICENSE](LICENSE)ファイルを参照してください。
+58
View File
@@ -0,0 +1,58 @@
# Security Policy
## Supported Versions
The following versions of ProxyPilot are currently supported with security updates:
| Version | Supported |
| ------- | ------------------ |
| latest | :white_check_mark: |
| < 1.0 | :x: |
## Reporting a Vulnerability
We take the security of ProxyPilot seriously. If you discover a security vulnerability, please report it responsibly.
### How to Report
You can report a vulnerability through one of the following methods:
1. **GitHub Security Advisory (Preferred)**: Open a private security advisory through [GitHub Security Advisories](https://github.com/smat-dev/ProxyPilot/security/advisories/new). This allows for private discussion and coordination.
2. **Email**: Send an email to the project maintainers with details of the vulnerability. Please include:
- A description of the vulnerability
- Steps to reproduce the issue
- Potential impact of the vulnerability
- Any suggested fixes (if available)
### What to Expect
After submitting a vulnerability report:
- **Initial Response**: You will receive an acknowledgment within **48 hours** confirming we have received your report.
- **Assessment**: We will investigate and assess the vulnerability within **7 days**.
- **Resolution Timeline**: We aim to release a fix for confirmed vulnerabilities within **30 days**, depending on complexity.
- **Disclosure**: Once a fix is released, we will coordinate with you on public disclosure timing.
We will keep you informed throughout the process and credit you for the discovery (unless you prefer to remain anonymous).
## Responsible Disclosure Guidelines
To protect our users, we ask that you:
- **DO NOT** disclose the vulnerability publicly until a fix has been released.
- **DO NOT** exploit the vulnerability beyond what is necessary to demonstrate the issue.
- **DO NOT** access, modify, or delete data belonging to other users.
- **DO** provide us with reasonable time to address the issue before any public disclosure.
- **DO** act in good faith to avoid privacy violations, data destruction, or service disruption.
We are committed to working with security researchers and will not take legal action against individuals who discover and report vulnerabilities responsibly.
## Security Best Practices for Users
- Always use the latest version of ProxyPilot.
- Review and understand the proxy configurations before deployment.
- Use secure connections (HTTPS) where applicable.
- Regularly review access logs for suspicious activity.
Thank you for helping keep ProxyPilot and its users safe.
+1
View File
@@ -0,0 +1 @@
v7.0.2
Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 401 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

+2
View File
@@ -0,0 +1,2 @@
.npmrc
node_modules/
+74
View File
@@ -0,0 +1,74 @@
# proxypilot
ProxyPilot CLI - Includes the ProxyPilot server and configuration switcher for AI CLI agents.
## Features
- **Server**: Run the ProxyPilot proxy server locally
- **Switch**: Switch AI CLI agents between proxy and native modes
## Install
```bash
bun install -g proxypilot
```
Or run without installing:
```bash
bunx proxypilot
```
## Usage
```bash
# Start the ProxyPilot server
proxypilot server
# Show status of all agents
proxypilot switch
# Switch Claude to proxy mode
proxypilot switch claude proxy
# Switch Gemini to native mode
proxypilot switch gemini native
# Show help
proxypilot --help
```
## Supported Agents
| Agent | Command |
|-------|---------|
| Claude Code | `proxypilot switch claude proxy` |
| Gemini CLI | `proxypilot switch gemini proxy` |
| Codex CLI | `proxypilot switch codex proxy` |
| OpenCode | `proxypilot switch opencode proxy` |
| Factory Droid | `proxypilot switch droid proxy` |
| Cursor | `proxypilot switch cursor proxy` |
| Kilo Code* | `proxypilot switch kilo proxy` |
| RooCode* | `proxypilot switch roocode proxy` |
\* VS Code extensions require manual configuration
## Modes
- `proxy` - Route through ProxyPilot (http://127.0.0.1:8317)
- `native` - Use direct API access (restore original config)
## How It Works
The switcher manages config files for each agent:
```
~/.claude/
├── settings.json # Active config
├── settings.native.json # Original/backup config
└── settings.proxy.json # ProxyPilot config
```
## License
MIT
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bun
import { spawn } from "bun";
import { join } from "path";
const ext = process.platform === "win32" ? ".exe" : "";
const binary = join(import.meta.dir, `proxypilot${ext}`);
const proc = spawn([binary, ...process.argv.slice(2)], {
stdio: ["inherit", "inherit", "inherit"],
});
await proc.exited;
process.exit(proc.exitCode ?? 0);
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env bun
import { chmodSync } from "fs";
import { join } from "path";
import pkg from "./package.json";
const VERSION = pkg.version;
const REPO = "Finesssee/ProxyPilot";
const PLATFORM_MAP: Record<string, string> = {
darwin: "darwin",
linux: "linux",
win32: "windows",
};
const ARCH_MAP: Record<string, string> = {
x64: "amd64",
arm64: "arm64",
};
async function install() {
const platform = PLATFORM_MAP[process.platform];
const arch = ARCH_MAP[process.arch];
if (!platform || !arch) {
console.error(`Unsupported platform: ${process.platform}-${process.arch}`);
process.exit(1);
}
const ext = platform === "windows" ? ".exe" : "";
const binaryName = `proxypilot-${platform}-${arch}${ext}`;
const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${binaryName}`;
const binDir = join(import.meta.dir, "bin");
const binPath = join(binDir, platform === "windows" ? "proxypilot.exe" : "proxypilot");
console.log(`Downloading proxypilot v${VERSION} for ${platform}-${arch}...`);
try {
const response = await fetch(url, { redirect: "follow" });
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
await Bun.write(binPath, response);
// Make executable on Unix
if (platform !== "windows") {
chmodSync(binPath, 0o755);
}
console.log("proxypilot installed successfully!");
console.log('Run "proxypilot --help" to get started.');
} catch (err: any) {
console.error("Failed to download proxypilot:", err.message);
console.error(`\nYou can manually download from:\nhttps://github.com/${REPO}/releases`);
process.exit(1);
}
}
install();
+38
View File
@@ -0,0 +1,38 @@
{
"name": "proxypilot",
"version": "0.2.9",
"description": "ProxyPilot - Local API proxy for AI coding tools with CLI control",
"bin": {
"proxypilot": "bin/proxypilot"
},
"scripts": {
"postinstall": "bun run install.ts"
},
"keywords": [
"proxypilot",
"claude",
"gemini",
"codex",
"ai",
"cli",
"proxy",
"config",
"switcher"
],
"author": "ProxyPilot",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Finesssee/ProxyPilot"
},
"homepage": "https://github.com/Finesssee/ProxyPilot",
"os": [
"darwin",
"linux",
"win32"
],
"cpu": [
"x64",
"arm64"
]
}
+305
View File
@@ -0,0 +1,305 @@
// Command fetch_antigravity_models connects to the Antigravity API using the
// stored auth credentials and saves the dynamically fetched model list to a
// JSON file for inspection or offline use.
//
// Usage:
//
// go run ./cmd/fetch_antigravity_models [flags]
//
// Flags:
//
// --auths-dir <path> Directory containing auth JSON files (default: config auth-dir)
// --config <path> Config file path (default: "config.yaml")
// --output <path> Output JSON file path (default: "antigravity_models.json")
// --pretty Pretty-print the output JSON (default: true)
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
)
const (
antigravityBaseURLDaily = "https://daily-cloudcode-pa.googleapis.com"
antigravitySandboxBaseURLDaily = "https://daily-cloudcode-pa.sandbox.googleapis.com"
antigravityBaseURLProd = "https://cloudcode-pa.googleapis.com"
antigravityModelsPath = "/v1internal:fetchAvailableModels"
)
func init() {
logging.SetupBaseLogger()
log.SetLevel(log.InfoLevel)
}
// modelOutput wraps the fetched model list with fetch metadata.
type modelOutput struct {
Models []modelEntry `json:"models"`
}
// modelEntry contains only the fields we want to keep for static model definitions.
type modelEntry struct {
ID string `json:"id"`
Object string `json:"object"`
OwnedBy string `json:"owned_by"`
Type string `json:"type"`
DisplayName string `json:"display_name"`
Name string `json:"name"`
Description string `json:"description"`
ContextLength int `json:"context_length,omitempty"`
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
}
func main() {
var authsDir string
var configPath string
var outputPath string
var pretty bool
flag.StringVar(&authsDir, "auths-dir", "", "Directory containing auth JSON files (overrides config auth-dir)")
flag.StringVar(&configPath, "config", "", "Configure File Path")
flag.StringVar(&outputPath, "output", "antigravity_models.json", "Output JSON file path")
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
flag.Parse()
authsDirOverridden := false
flag.Visit(func(f *flag.Flag) {
if f.Name == "auths-dir" {
authsDirOverridden = true
}
})
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
os.Exit(1)
}
if strings.TrimSpace(configPath) == "" {
configPath = filepath.Join(wd, "config.yaml")
}
cfg, err := config.LoadConfigOptional(configPath, false)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to load config file %s: %v\n", configPath, err)
os.Exit(1)
}
if cfg == nil {
cfg = &config.Config{}
}
if !authsDirOverridden {
authsDir = cfg.AuthDir
} else if strings.TrimSpace(authsDir) != "" && !strings.HasPrefix(strings.TrimSpace(authsDir), "~") && !filepath.IsAbs(authsDir) {
authsDir = filepath.Join(wd, authsDir)
}
if authsDir, err = util.ResolveAuthDir(authsDir); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to resolve auth directory: %v\n", err)
os.Exit(1)
}
if !filepath.IsAbs(outputPath) {
outputPath = filepath.Join(wd, outputPath)
}
fmt.Printf("Scanning auth files in: %s\n", authsDir)
// Load all auth records from the directory.
fileStore := sdkauth.NewFileTokenStore()
fileStore.SetBaseDir(authsDir)
ctx := context.Background()
auths, err := fileStore.List(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
os.Exit(1)
}
if len(auths) == 0 {
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
os.Exit(1)
}
// Find the first enabled antigravity auth.
var chosen *coreauth.Auth
for _, a := range auths {
if a == nil || a.Disabled {
continue
}
if strings.EqualFold(strings.TrimSpace(a.Provider), "antigravity") {
chosen = a
break
}
}
if chosen == nil {
fmt.Fprintf(os.Stderr, "error: no enabled antigravity auth found in %s\n", authsDir)
os.Exit(1)
}
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
// Fetch models from the upstream Antigravity API.
fmt.Println("Fetching Antigravity model list from upstream...")
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
models := fetchModels(fetchCtx, chosen)
if len(models) == 0 {
fmt.Fprintln(os.Stderr, "warning: no models returned (API may be unavailable or token expired)")
} else {
fmt.Printf("Fetched %d models.\n", len(models))
}
// Build the output payload.
out := modelOutput{
Models: models,
}
// Marshal to JSON.
var raw []byte
if pretty {
raw, err = json.MarshalIndent(out, "", " ")
} else {
raw, err = json.Marshal(out)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to marshal JSON: %v\n", err)
os.Exit(1)
}
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
os.Exit(1)
}
fmt.Printf("Model list saved to: %s\n", outputPath)
}
func fetchModels(ctx context.Context, auth *coreauth.Auth) []modelEntry {
accessToken := metaStringValue(auth.Metadata, "access_token")
if accessToken == "" {
fmt.Fprintln(os.Stderr, "error: no access token found in auth")
return nil
}
baseURLs := []string{antigravityBaseURLProd, antigravityBaseURLDaily, antigravitySandboxBaseURLDaily}
for _, baseURL := range baseURLs {
modelsURL := baseURL + antigravityModelsPath
var payload []byte
if auth != nil && auth.Metadata != nil {
if pid, ok := auth.Metadata["project_id"].(string); ok && strings.TrimSpace(pid) != "" {
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, strings.TrimSpace(pid)))
}
}
if len(payload) == 0 {
payload = []byte(`{}`)
}
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, modelsURL, strings.NewReader(string(payload)))
if errReq != nil {
continue
}
httpReq.Close = true
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
httpReq.Header.Set("User-Agent", misc.AntigravityUserAgent())
httpClient := &http.Client{Timeout: 30 * time.Second}
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
httpClient.Transport = transport
}
httpResp, errDo := httpClient.Do(httpReq)
if errDo != nil {
continue
}
bodyBytes, errRead := io.ReadAll(httpResp.Body)
httpResp.Body.Close()
if errRead != nil {
continue
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
continue
}
result := gjson.GetBytes(bodyBytes, "models")
if !result.Exists() {
continue
}
var models []modelEntry
for originalName, modelData := range result.Map() {
modelID := strings.TrimSpace(originalName)
if modelID == "" {
continue
}
// Skip internal/experimental models
switch modelID {
case "chat_20706", "chat_23310", "tab_flash_lite_preview", "tab_jump_flash_lite_preview", "gemini-2.5-flash-thinking", "gemini-2.5-pro":
continue
}
displayName := modelData.Get("displayName").String()
if displayName == "" {
displayName = modelID
}
entry := modelEntry{
ID: modelID,
Object: "model",
OwnedBy: "antigravity",
Type: "antigravity",
DisplayName: displayName,
Name: modelID,
Description: displayName,
}
if maxTok := modelData.Get("maxTokens").Int(); maxTok > 0 {
entry.ContextLength = int(maxTok)
}
if maxOut := modelData.Get("maxOutputTokens").Int(); maxOut > 0 {
entry.MaxCompletionTokens = int(maxOut)
}
models = append(models, entry)
}
return models
}
return nil
}
func metaStringValue(m map[string]interface{}, key string) string {
if m == nil {
return ""
}
v, ok := m[key]
if !ok {
return ""
}
switch val := v.(type) {
case string:
return val
default:
return ""
}
}
+333
View File
@@ -0,0 +1,333 @@
// Command fetch_codex_models connects to the Codex API using stored auth
// credentials and saves the dynamically fetched Codex client model catalog to a
// JSON file for inspection or offline use.
//
// Usage:
//
// go run ./cmd/fetch_codex_models [flags]
//
// Flags:
//
// --auths-dir <path> Directory containing auth JSON files (default: config auth-dir)
// --config <path> Config file path (default: "config.yaml")
// --output <path> Output JSON file path (default: "codex_models.json")
// --client-version <ver> Codex client_version query value (default: "0.133.0")
// --pretty Pretty-print the output JSON (default: true)
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
codexauth "github.com/router-for-me/CLIProxyAPI/v7/internal/auth/codex"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
sdkauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/proxyutil"
log "github.com/sirupsen/logrus"
)
const (
codexModelsBaseURL = "https://chatgpt.com/backend-api/codex"
codexModelsPath = "/models"
defaultClientVersion = "0.133.0"
defaultCodexUserAgent = "codex_cli_rs/0.133.0 (Mac OS 26.3.1; arm64) iTerm.app/3.6.9"
defaultCodexOriginator = "codex_cli_rs"
accessTokenRefreshLeeway = 30 * time.Second
)
func init() {
logging.SetupBaseLogger()
log.SetLevel(log.InfoLevel)
}
func main() {
var authsDir string
var configPath string
var outputPath string
var clientVersion string
var pretty bool
flag.StringVar(&authsDir, "auths-dir", "", "Directory containing auth JSON files (overrides config auth-dir)")
flag.StringVar(&configPath, "config", "", "Configure File Path")
flag.StringVar(&outputPath, "output", "codex_models.json", "Output JSON file path")
flag.StringVar(&clientVersion, "client-version", defaultClientVersion, "Codex client_version query value")
flag.BoolVar(&pretty, "pretty", true, "Pretty-print the output JSON")
flag.Parse()
authsDirOverridden := false
flag.Visit(func(f *flag.Flag) {
if f.Name == "auths-dir" {
authsDirOverridden = true
}
})
wd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "error: cannot get working directory: %v\n", err)
os.Exit(1)
}
if strings.TrimSpace(configPath) == "" {
configPath = filepath.Join(wd, "config.yaml")
}
cfg, err := config.LoadConfigOptional(configPath, false)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to load config file %s: %v\n", configPath, err)
os.Exit(1)
}
if cfg == nil {
cfg = &config.Config{}
}
if !authsDirOverridden {
authsDir = cfg.AuthDir
} else if strings.TrimSpace(authsDir) != "" && !strings.HasPrefix(strings.TrimSpace(authsDir), "~") && !filepath.IsAbs(authsDir) {
authsDir = filepath.Join(wd, authsDir)
}
if authsDir, err = util.ResolveAuthDir(authsDir); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to resolve auth directory: %v\n", err)
os.Exit(1)
}
if !filepath.IsAbs(outputPath) {
outputPath = filepath.Join(wd, outputPath)
}
fmt.Printf("Scanning auth files in: %s\n", authsDir)
fileStore := sdkauth.NewFileTokenStore()
fileStore.SetBaseDir(authsDir)
ctx := context.Background()
auths, err := fileStore.List(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to list auth files: %v\n", err)
os.Exit(1)
}
if len(auths) == 0 {
fmt.Fprintf(os.Stderr, "error: no auth files found in %s\n", authsDir)
os.Exit(1)
}
chosen := findCodexAuth(auths)
if chosen == nil {
fmt.Fprintf(os.Stderr, "error: no enabled codex auth found in %s\n", authsDir)
os.Exit(1)
}
fmt.Printf("Using auth: id=%s label=%s\n", chosen.ID, chosen.Label)
accessToken, refreshed, err := ensureAccessToken(ctx, fileStore, chosen)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to prepare codex access token: %v\n", err)
os.Exit(1)
}
if refreshed {
fmt.Println("Refreshed Codex access token.")
}
fmt.Println("Fetching Codex model list from upstream...")
raw, count, err := fetchModels(ctx, chosen, accessToken, clientVersion)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to fetch codex models: %v\n", err)
os.Exit(1)
}
fmt.Printf("Fetched %d models.\n", count)
if pretty {
raw, err = prettyJSON(raw)
if err != nil {
fmt.Fprintf(os.Stderr, "error: failed to format JSON: %v\n", err)
os.Exit(1)
}
}
if err = os.WriteFile(outputPath, raw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "error: failed to write output file %s: %v\n", outputPath, err)
os.Exit(1)
}
fmt.Printf("Model list saved to: %s\n", outputPath)
}
func findCodexAuth(auths []*coreauth.Auth) *coreauth.Auth {
for _, auth := range auths {
if auth == nil || auth.Disabled {
continue
}
if !strings.EqualFold(strings.TrimSpace(auth.Provider), "codex") {
continue
}
if metaStringValue(auth.Metadata, "access_token") == "" && metaStringValue(auth.Metadata, "refresh_token") == "" {
continue
}
return auth
}
return nil
}
func ensureAccessToken(ctx context.Context, store *sdkauth.FileTokenStore, auth *coreauth.Auth) (string, bool, error) {
accessToken := metaStringValue(auth.Metadata, "access_token")
if accessToken != "" {
if expiresAt, ok := auth.ExpirationTime(); !ok || time.Now().Add(accessTokenRefreshLeeway).Before(expiresAt) {
return accessToken, false, nil
}
}
refreshToken := metaStringValue(auth.Metadata, "refresh_token")
if refreshToken == "" {
if accessToken != "" {
return accessToken, false, nil
}
return "", false, fmt.Errorf("missing access_token and refresh_token")
}
svc := codexauth.NewCodexAuthWithProxyURL(nil, auth.ProxyURL)
tokenData, errRefresh := svc.RefreshTokensWithRetry(ctx, refreshToken, 3)
if errRefresh != nil {
return "", false, errRefresh
}
if strings.TrimSpace(tokenData.AccessToken) == "" {
return "", false, fmt.Errorf("refresh response did not include access_token")
}
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
auth.Metadata["id_token"] = tokenData.IDToken
auth.Metadata["access_token"] = tokenData.AccessToken
if tokenData.RefreshToken != "" {
auth.Metadata["refresh_token"] = tokenData.RefreshToken
}
if tokenData.AccountID != "" {
auth.Metadata["account_id"] = tokenData.AccountID
}
if tokenData.Email != "" {
auth.Metadata["email"] = tokenData.Email
}
auth.Metadata["expired"] = tokenData.Expire
auth.Metadata["type"] = "codex"
auth.Metadata["last_refresh"] = time.Now().Format(time.RFC3339)
if _, errSave := store.Save(ctx, auth); errSave != nil {
return "", false, fmt.Errorf("failed to save refreshed auth: %w", errSave)
}
return tokenData.AccessToken, true, nil
}
func fetchModels(ctx context.Context, auth *coreauth.Auth, accessToken, clientVersion string) ([]byte, int, error) {
modelsURL, errURL := codexModelsURL(clientVersion)
if errURL != nil {
return nil, 0, errURL
}
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodGet, modelsURL, nil)
if errReq != nil {
return nil, 0, errReq
}
httpReq.Close = true
httpReq.Header.Set("Accept", "application/json")
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
httpReq.Header.Set("Originator", defaultCodexOriginator)
httpReq.Header.Set("User-Agent", defaultCodexUserAgent)
if accountID := metaStringValue(auth.Metadata, "account_id"); accountID != "" {
httpReq.Header.Set("Chatgpt-Account-Id", accountID)
}
if auth != nil {
util.ApplyCustomHeadersFromAttrs(httpReq, auth.Attributes)
}
httpClient := &http.Client{}
if auth != nil {
if transport, _, errProxy := proxyutil.BuildHTTPTransport(auth.ProxyURL); errProxy == nil && transport != nil {
httpClient.Transport = transport
}
}
httpResp, errDo := httpClient.Do(httpReq)
if errDo != nil {
return nil, 0, errDo
}
bodyBytes, errRead := io.ReadAll(httpResp.Body)
if errClose := httpResp.Body.Close(); errClose != nil && errRead == nil {
errRead = errClose
}
if errRead != nil {
return nil, 0, errRead
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
return nil, 0, fmt.Errorf("models request failed with status %d: %s", httpResp.StatusCode, strings.TrimSpace(string(bodyBytes)))
}
count, errCount := countModels(bodyBytes)
if errCount != nil {
return nil, 0, errCount
}
return bodyBytes, count, nil
}
func codexModelsURL(clientVersion string) (string, error) {
u, err := url.Parse(codexModelsBaseURL + codexModelsPath)
if err != nil {
return "", err
}
if strings.TrimSpace(clientVersion) != "" {
q := u.Query()
q.Set("client_version", strings.TrimSpace(clientVersion))
u.RawQuery = q.Encode()
}
return u.String(), nil
}
func countModels(raw []byte) (int, error) {
var payload struct {
Models []map[string]any `json:"models"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return 0, fmt.Errorf("failed to parse response JSON: %w", err)
}
if payload.Models == nil {
return 0, fmt.Errorf("response JSON does not contain models array")
}
return len(payload.Models), nil
}
func prettyJSON(raw []byte) ([]byte, error) {
var buf bytes.Buffer
if err := json.Indent(&buf, raw, "", " "); err != nil {
return nil, err
}
buf.WriteByte('\n')
return buf.Bytes(), nil
}
func metaStringValue(m map[string]any, key string) string {
if m == nil {
return ""
}
v, ok := m[key]
if !ok {
return ""
}
switch val := v.(type) {
case string:
return strings.TrimSpace(val)
default:
return ""
}
}
+101
View File
@@ -0,0 +1,101 @@
# ProxyPilot Installer Build Script
# This script builds the installer with embedded UI and application files.
param(
[string]$OutputPath = ".\dist\ProxyPilotInstaller.exe",
[string]$ProxyPilotExe = ".\dist\ProxyPilot.exe",
[switch]$SkipUI
)
$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$repoRoot = Split-Path -Parent (Split-Path -Parent $scriptDir)
Write-Host "Building ProxyPilot Installer..." -ForegroundColor Cyan
# Step 1: Build the installer UI (if not skipped)
if (-not $SkipUI) {
Write-Host "Building installer UI..." -ForegroundColor Yellow
Push-Location "$repoRoot\installer-ui"
try {
npm install
npm run build
}
finally {
Pop-Location
}
# Copy built UI to cmd/installer/ui
Write-Host "Copying UI assets..." -ForegroundColor Yellow
$uiSrcDir = "$repoRoot\installer-ui\dist"
$uiDstDir = "$scriptDir\ui"
if (Test-Path $uiDstDir) {
Remove-Item -Recurse -Force $uiDstDir
}
Copy-Item -Recurse $uiSrcDir $uiDstDir
}
# Step 2: Copy bundle files
Write-Host "Preparing bundle files..." -ForegroundColor Yellow
$bundleDir = "$scriptDir\bundle"
# Ensure bundle directory exists
if (-not (Test-Path $bundleDir)) {
New-Item -ItemType Directory -Path $bundleDir | Out-Null
}
# Copy ProxyPilot.exe
if (Test-Path $ProxyPilotExe) {
Copy-Item $ProxyPilotExe "$bundleDir\ProxyPilot.exe" -Force
Write-Host " Copied ProxyPilot.exe" -ForegroundColor Green
} else {
Write-Host " Warning: ProxyPilot.exe not found at $ProxyPilotExe" -ForegroundColor Yellow
}
# Copy config.example.yaml
$configExample = "$repoRoot\config.example.yaml"
if (Test-Path $configExample) {
Copy-Item $configExample "$bundleDir\config.example.yaml" -Force
Write-Host " Copied config.example.yaml" -ForegroundColor Green
}
# Copy icons
$iconIco = "$repoRoot\static\icon.ico"
$iconPng = "$repoRoot\static\icon.png"
if (Test-Path $iconIco) {
Copy-Item $iconIco "$bundleDir\icon.ico" -Force
Write-Host " Copied icon.ico" -ForegroundColor Green
}
if (Test-Path $iconPng) {
Copy-Item $iconPng "$bundleDir\icon.png" -Force
Write-Host " Copied icon.png" -ForegroundColor Green
}
# Step 3: Build the installer executable
Write-Host "Building installer executable..." -ForegroundColor Yellow
$outputDir = Split-Path -Parent $OutputPath
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir | Out-Null
}
Push-Location $repoRoot
try {
# Build with Windows GUI subsystem (no console window)
$env:GOOS = "windows"
$env:GOARCH = "amd64"
go build -ldflags="-s -w -H=windowsgui" -o $OutputPath ./cmd/installer
}
finally {
Pop-Location
}
if (Test-Path $OutputPath) {
$size = (Get-Item $OutputPath).Length / 1MB
Write-Host "Build complete: $OutputPath ($([math]::Round($size, 2)) MB)" -ForegroundColor Green
} else {
Write-Host "Build failed: Output file not created" -ForegroundColor Red
exit 1
}
+274
View File
@@ -0,0 +1,274 @@
# Server host/interface to bind to. Default is empty ("") to bind all interfaces (IPv4 + IPv6).
# Use "127.0.0.1" or "localhost" to restrict access to local machine only.
host: ""
# Server port
port: 8317
# TLS settings for HTTPS. When enabled, the server listens with the provided certificate and key.
tls:
enable: false
cert: ""
key: ""
# Management API settings
remote-management:
# Whether to allow remote (non-localhost) management access.
# When false, only localhost can access management endpoints (a key is still required).
allow-remote: false
# Management key. If a plaintext value is provided here, it will be hashed on startup.
# All management requests (even from localhost) require this key.
# Leave empty to disable the Management API entirely (404 for all /v0/management routes).
secret-key: "$2a$10$iphjVa6f4T/FARz4e/edtOHvdoxTbE4tv/9mS0ebvDg/C8fEbPtgq"
# Disable the bundled management control panel asset download and HTTP route when true.
disable-control-panel: false
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL.
panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
# Authentication directory (supports ~ for home directory)
auth-dir: "~/.cli-proxy-api"
# Long-running agent harness files root directory (feature_list.json, claude-progress.txt).
# The harness guides AI agents through structured, incremental development workflows.
# - INITIALIZER mode: Creates feature list, progress log, and init.sh for new sessions
# - CODING mode: Forces one-feature-at-a-time workflow with verification
# Leave empty to use session-based memory storage (recommended).
# Set to a specific directory to share harness files across sessions.
# harness-root-dir: ""
#
# Environment variables:
# CLIPROXY_HARNESS_ENABLED=true/false # Enable/disable harness injection (default: true)
# API keys for authentication
api-keys:
- "local-dev-key"
# Enable debug logging
debug: false
# When true, disable high-overhead HTTP middleware features to reduce per-request memory usage under high concurrency.
commercial-mode: false
# Open OAuth URLs in incognito/private browser mode.
# Useful when you want to login with a different account without logging out from your current session.
# Default: false (but Kiro auth defaults to true for multi-account support)
incognito-browser: true
# When true, write application logs to rotating files instead of stdout
logging-to-file: false
# Maximum total size (MB) of log files under the logs directory. When exceeded, the oldest log
# files are deleted until within the limit. Set to 0 to disable.
logs-max-total-size-mb: 0
# When false, disable in-memory usage statistics aggregation
usage-statistics-enabled: false
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
proxy-url: ""
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).
force-model-prefix: false
# Number of times to retry a request. Retries will occur if the HTTP response code is 403, 408, 500, 502, 503, or 504.
request-retry: 3
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.
max-retry-interval: 30
# Quota exceeded behavior
quota-exceeded:
switch-project: true # Whether to automatically switch to another project when a quota is exceeded
switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
# Routing strategy for selecting credentials when multiple match.
routing:
strategy: "round-robin" # round-robin (default), fill-first, usage-aware
# Global model mappings - route friendly names to actual models across all providers.
# These mappings are checked before per-credential model mappings.
# global-model-mappings:
# - from: "smart" # Client requests "smart"
# to: "claude-opus-4-5-20251101" # Routes to Claude Opus
# - from: "rush"
# to: "claude-haiku-4-5-20251001" # Routes to Claude Haiku (fast)
# - from: "think"
# to: "claude-opus-4-5-thinking" # Routes to thinking model
# - from: "gemini-pro"
# to: "gemini-2.5-pro-preview"
# provider: "gemini" # Only applies to Gemini provider
# - from: "cheap"
# to: "gpt-4o-mini"
# provider: "codex"
# enabled: false # Disabled mapping (kept for reference)
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
# Streaming behavior (SSE keep-alives, bootstrap retries, chunk sizing).
# streaming:
# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.
# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
# max-chunk-size: 65536 # Default: 65536 (64KB). Max bytes per response chunk. 0 disables limiting.
# Context compression behavior (Factory.ai-style structured summarization).
# Uses LLM to generate intelligent summaries with structured sections when context
# exceeds the threshold. Summaries include: session intent, file modifications,
# decisions made, next steps, and technical details.
# compression:
# enabled: true # Default: true. Enable LLM-based structured summarization.
# threshold-percent: 0.75 # Default: 0.75. Trigger compression at 75% of context window.
# max-summary-tokens: 2000 # Default: 2000. Maximum tokens for generated summaries.
# summarization-timeout-seconds: 30 # Default: 30. Timeout for LLM summarization calls.
# fallback-to-regex: true # Default: true. Use regex-based summary when LLM fails.
# Response caching - cache identical API responses to reduce upstream calls.
# response-cache:
# enabled: true
# max-size: 1000 # Max cached responses
# ttl-seconds: 300 # 5 minutes
# exclude-models: # Don't cache these models
# - "*-thinking"
# - "o1-*"
# Prompt caching - track system prompts for analytics.
# prompt-cache:
# enabled: true
# max-size: 500
# ttl-seconds: 1800 # 30 minutes
# Token-aware compression (proactive trimming based on model context window).
# Prevents "prompt too long" errors by trimming before hitting model limits.
# Environment variables:
# CLIPROXY_TOKEN_AWARE_ENABLED=true # Default: true. Enable token-based compression.
# CLIPROXY_COMPRESSION_THRESHOLD=0.75 # Default: 0.75. Trim at 75% of context window.
# CLIPROXY_RESERVE_TOKENS=8192 # Default: 8192. Tokens reserved for model output.
# Gemini API keys
# gemini-api-key:
# - api-key: "AIzaSy...01"
# prefix: "test" # optional: require calls like "test/gemini-3-pro-preview" to target this credential
# base-url: "https://generativelanguage.googleapis.com"
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080"
# excluded-models:
# - "gemini-2.5-pro" # exclude specific models from this provider (exact match)
# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)
# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview, gemini-3-flash-preview)
# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)
# - api-key: "AIzaSy...02"
# Codex API keys
# codex-api-key:
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/gpt-5-codex" to target this credential
# base-url: "https://www.example.com" # use the custom codex API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "gpt-5-codex" # upstream model name
# alias: "codex-latest" # client alias mapped to the upstream model
# excluded-models:
# - "gpt-5.2" # exclude specific models (exact match)
# - "gpt-5-*" # wildcard matching prefix (e.g. gpt-5-medium, gpt-5-codex)
# - "*-mini" # wildcard matching suffix (e.g. gpt-5-codex-mini)
# - "*codex*" # wildcard matching substring (e.g. gpt-5-codex-low)
# Claude API keys
# claude-api-key:
# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/claude-sonnet-latest" to target this credential
# base-url: "https://www.example.com" # use the custom claude API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "claude-sonnet-4-5-20250929" # upstream model name
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
# excluded-models:
# - "claude-opus-4-5-20251101" # exclude specific models (exact match)
# - "claude-4-*" # wildcard matching prefix (e.g. claude-sonnet-4-5-20250929)
# - "*-thinking" # wildcard matching suffix (e.g. claude-opus-4-5-thinking)
# - "*haiku*" # wildcard matching substring (e.g. claude-haiku-4-5-20251001)
# Kiro (AWS CodeWhisperer) configuration
# kiro-key:
# - token-file: "~/.aws/sso/cache/kiro-auth-token.json"
# region: "us-east-1"
# proxy-url: "socks5://proxy.example.com:1080"
# agent-task-type: "dev"
# excluded-models:
# - "kiro-claude-haiku"
# Kiro (AWS CodeWhisperer) configuration
# Note: Kiro API currently only operates in us-east-1 region
#kiro:
# - token-file: "~/.aws/sso/cache/kiro-auth-token.json" # path to Kiro token file
# agent-task-type: "" # optional: "vibe" or empty (API default)
# - access-token: "aoaAAAAA..." # or provide tokens directly
# refresh-token: "aorAAAAA..."
# profile-arn: "arn:aws:codewhisperer:us-east-1:..."
# proxy-url: "socks5://proxy.example.com:1080" # optional: proxy override
# OpenAI compatibility providers
# openai-compatibility:
# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.
# prefix: "test" # optional: require calls like "test/kimi-k2" to target this provider's credentials
# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.
# headers:
# X-Custom-Header: "custom-value"
# api-key-entries:
# - api-key: "sk-or-v1-...b780"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# - api-key: "sk-or-v1-...b781" # without proxy-url
# models: # The models supported by the provider.
# - name: "moonshotai/kimi-k2:free" # The actual model name.
# alias: "kimi-k2" # The alias used in the API.
# Vertex API keys (Vertex-compatible endpoints, use API key + base URL)
# vertex-api-key:
# - api-key: "vk-123..." # x-goog-api-key header
# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential
# base-url: "https://example.com/api" # e.g. https://zenmux.ai/api
# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override
# headers:
# X-Custom-Header: "custom-value"
# models: # optional: map aliases to upstream model names
# - name: "gemini-2.5-flash" # upstream model name
# alias: "vertex-flash" # client-visible alias
# - name: "gemini-1.5-pro"
# alias: "vertex-pro"
# OAuth provider excluded models
# oauth-excluded-models:
# gemini-cli:
# - "gemini-2.5-pro" # exclude specific models (exact match)
# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)
# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview, gemini-3-flash-preview)
# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)
# vertex:
# - "gemini-3-pro-preview"
# - "gemini-3-flash-preview"
# aistudio:
# - "gemini-3-pro-preview"
# antigravity:
# - "gemini-3-pro-preview"
# claude:
# - "claude-3-5-haiku-20241022"
# codex:
# - "gpt-5-codex-mini"
# qwen:
# - "vision-model"
# kiro:
# - "kiro-claude-haiku"
# Optional payload configuration
# payload:
# default: # Default rules only set parameters when they are missing in the payload.
# - models:
# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")
# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex
# params: # JSON path (gjson/sjson syntax) -> value
# "generationConfig.thinkingConfig.thinkingBudget": 32768
# override: # Override rules always set parameters, overwriting any existing values.
# - models:
# - name: "gpt-*" # Supports wildcards (e.g., "gpt-*")
# protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex
# params: # JSON path (gjson/sjson syntax) -> value
# "reasoning.effort": "high"
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+19
View File
@@ -0,0 +1,19 @@
//go:build windows
package main
import (
"embed"
)
// embeddedUI contains the built installer UI from installer-ui/dist.
// The ui directory should contain index.html and any other assets.
//
//go:embed all:ui
var embeddedUI embed.FS
// embeddedBundle contains the files to install.
// These are embedded during the build process.
//
//go:embed bundle/ProxyPilot.exe bundle/config.example.yaml bundle/icon.ico bundle/icon.png
var embeddedBundle embed.FS
+196
View File
@@ -0,0 +1,196 @@
//go:build windows
package main
import (
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
)
// InstallConfig holds the configuration for the installation process.
type InstallConfig struct {
// InstallDir is the target installation directory.
// Defaults to %LOCALAPPDATA%\ProxyPilot.
InstallDir string
// CreateDesktopShortcut indicates whether to create a Desktop shortcut.
CreateDesktopShortcut bool
// EnableAutostart indicates whether to register the app for autostart.
EnableAutostart bool
}
// ProgressCallback is called during file copy operations to report progress.
type ProgressCallback func(progress int, status string)
// bundleFiles is the list of files to extract from the embedded bundle.
var bundleFiles = []struct {
src string // Path within embeddedBundle.
dst string // Destination filename.
size int64 // Approximate size for progress calculation.
}{
{"bundle/ProxyPilot.exe", "ProxyPilot.exe", 0},
{"bundle/config.example.yaml", "config.example.yaml", 0},
{"bundle/icon.ico", "icon.ico", 0},
{"bundle/icon.png", "icon.png", 0},
}
// CopyFiles extracts the embedded bundle files to the installation directory.
func CopyFiles(config *InstallConfig, progress ProgressCallback) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
// Ensure the installation directory exists.
if err := os.MkdirAll(config.InstallDir, 0755); err != nil {
return fmt.Errorf("failed to create install directory: %w", err)
}
// Calculate total number of files for progress.
totalFiles := len(bundleFiles)
copiedFiles := 0
for _, file := range bundleFiles {
dstPath := filepath.Join(config.InstallDir, file.dst)
if progress != nil {
progress((copiedFiles*100)/totalFiles, fmt.Sprintf("Copying %s...", file.dst))
}
if err := extractEmbeddedFile(file.src, dstPath); err != nil {
return fmt.Errorf("failed to copy %s: %w", file.dst, err)
}
copiedFiles++
}
// Create config.yaml from config.example.yaml if it doesn't exist.
configPath := filepath.Join(config.InstallDir, "config.yaml")
examplePath := filepath.Join(config.InstallDir, "config.example.yaml")
if _, err := os.Stat(configPath); os.IsNotExist(err) {
if _, err := os.Stat(examplePath); err == nil {
if err := copyFile(examplePath, configPath); err != nil {
// Non-fatal: user can create config manually.
_ = err
} else if progress != nil {
progress(95, "Created default configuration")
}
}
}
if progress != nil {
progress(100, "All files copied successfully")
}
return nil
}
// extractEmbeddedFile extracts a file from the embedded bundle to the destination path.
func extractEmbeddedFile(src, dst string) error {
// Open the embedded file.
srcFile, err := embeddedBundle.Open(src)
if err != nil {
return fmt.Errorf("failed to open embedded file %s: %w", src, err)
}
defer srcFile.Close()
// Get file info for permissions.
info, err := srcFile.(fs.File).Stat()
if err != nil {
return fmt.Errorf("failed to stat embedded file: %w", err)
}
// Create destination directory if needed.
dstDir := filepath.Dir(dst)
if err := os.MkdirAll(dstDir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %w", dstDir, err)
}
// Create the destination file.
dstFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode())
if err != nil {
return fmt.Errorf("failed to create file %s: %w", dst, err)
}
defer dstFile.Close()
// Copy the content.
if _, err := io.Copy(dstFile, srcFile); err != nil {
return fmt.Errorf("failed to write file %s: %w", dst, err)
}
return nil
}
// copyFile copies a file from src to dst.
func copyFile(src, dst string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
if _, err := io.Copy(dstFile, srcFile); err != nil {
return err
}
return nil
}
// Cleanup removes all installed files on failure.
func Cleanup(config *InstallConfig) error {
if config.InstallDir == "" {
return nil
}
// Remove autostart registration.
_ = UnregisterAutostart(config)
// Remove uninstall registration.
_ = UnregisterUninstall()
// Remove shortcuts.
_ = RemoveShortcuts(config)
// Remove the installation directory.
// Only remove if it's under LocalAppData to prevent accidental deletion.
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData != "" && filepath.HasPrefix(config.InstallDir, localAppData) {
return os.RemoveAll(config.InstallDir)
}
return nil
}
// RemoveShortcuts removes all created shortcuts.
func RemoveShortcuts(config *InstallConfig) error {
var lastErr error
// Remove Start Menu shortcut.
startMenuPath := getStartMenuPath()
if startMenuPath != "" {
shortcutPath := filepath.Join(startMenuPath, appName+".lnk")
if err := os.Remove(shortcutPath); err != nil && !os.IsNotExist(err) {
lastErr = err
}
}
// Remove Desktop shortcut.
desktopPath := getDesktopPath()
if desktopPath != "" {
shortcutPath := filepath.Join(desktopPath, appName+".lnk")
if err := os.Remove(shortcutPath); err != nil && !os.IsNotExist(err) {
lastErr = err
}
}
return lastErr
}
+315
View File
@@ -0,0 +1,315 @@
//go:build windows
package main
import (
"encoding/json"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"syscall"
"unsafe"
"github.com/jchv/go-webview2"
)
const (
windowWidth = 500
windowHeight = 400
appName = "ProxyPilot"
)
var (
// assetServerURL holds the local HTTP server URL for serving embedded UI assets.
assetServerURL string
// webviewInstance is the global WebView2 instance for window control.
webviewInstance webview2.WebView
)
func main() {
// Lock this goroutine to an OS thread - required for Windows COM/GUI operations.
runtime.LockOSThread()
// Start embedded asset server for the installer UI.
assetLn, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
_ = messageBox("ProxyPilot Installer", "Failed to start asset server: "+err.Error())
os.Exit(1)
}
assetServerURL = "http://" + assetLn.Addr().String()
go func() {
fsys, err := fs.Sub(embeddedUI, "ui")
if err != nil {
return
}
_ = http.Serve(assetLn, http.FileServer(http.FS(fsys)))
}()
// Create frameless WebView2 window with dark theme.
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: false,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ProxyPilot Installer",
Width: uint(windowWidth),
Height: uint(windowHeight),
Center: true,
IconId: 1, // Use embedded icon from resource.syso if present.
},
})
if w == nil {
_ = messageBox("ProxyPilot Installer", "Failed to initialize WebView2.\n\nPlease ensure WebView2 Runtime is installed.")
os.Exit(1)
}
defer w.Destroy()
webviewInstance = w
// Bind Go functions to JavaScript.
bindInstallerFunctions(w)
// Navigate to the embedded UI.
target := assetServerURL + "/index.html"
w.Navigate(target)
// Apply dark window chrome and frameless styling after navigation.
w.Dispatch(func() {
applyDarkWindowChrome(w)
})
w.Run()
}
// bindInstallerFunctions binds all Go functions to the JavaScript window.installer object.
func bindInstallerFunctions(w webview2.WebView) {
// Create the installer namespace.
w.Init(`window.installer = {};`)
// Bind startInstall - starts the installation process.
_ = w.Bind("installer_startInstall", func(optionsJSON string) (map[string]any, error) {
var options struct {
Desktop bool `json:"desktop"`
Autostart bool `json:"autostart"`
}
if err := json.Unmarshal([]byte(optionsJSON), &options); err != nil {
options.Desktop = false
options.Autostart = true
}
config := &InstallConfig{
CreateDesktopShortcut: options.Desktop,
EnableAutostart: options.Autostart,
}
// Run installation in a goroutine to not block the UI.
go func() {
if err := runInstallation(w, config); err != nil {
callSetProgress(w, -1, "Installation failed: "+err.Error())
}
}()
return map[string]any{"started": true}, nil
})
// Bind launch - launches the installed application.
_ = w.Bind("installer_launch", func() error {
installDir := getInstallDir()
exePath := filepath.Join(installDir, "ProxyPilot.exe")
if _, err := os.Stat(exePath); err != nil {
return fmt.Errorf("ProxyPilot.exe not found at %s", exePath)
}
cmd := exec.Command(exePath)
cmd.Dir = installDir
return cmd.Start()
})
// Bind close - closes the installer window.
_ = w.Bind("installer_close", func() error {
w.Dispatch(func() {
w.Terminate()
})
return nil
})
// Bind minimize - minimizes the window.
_ = w.Bind("installer_minimize", func() error {
w.Dispatch(func() {
minimizeWindow(w)
})
return nil
})
// Bind getInstallPath - returns the default installation path.
_ = w.Bind("installer_getInstallPath", func() (string, error) {
return getInstallDir(), nil
})
// Initialize the window.installer JavaScript API.
w.Init(`
window.installer.startInstall = function(options) {
return new Promise((resolve, reject) => {
installer_startInstall(JSON.stringify(options || {}))
.then(resolve)
.catch(reject);
});
};
window.installer.launch = installer_launch;
window.installer.close = installer_close;
window.installer.minimize = installer_minimize;
window.installer.getInstallPath = installer_getInstallPath;
`)
}
// runInstallation performs the complete installation process with progress reporting.
func runInstallation(w webview2.WebView, config *InstallConfig) error {
// Initialize install configuration with defaults.
config.InstallDir = getInstallDir()
// Step 1: Prepare installation directory (10%).
callSetProgress(w, 5, "Preparing installation directory...")
if err := os.MkdirAll(config.InstallDir, 0755); err != nil {
return fmt.Errorf("failed to create install directory: %w", err)
}
callSetProgress(w, 10, "Installation directory ready")
// Step 2: Copy files (10% - 60%).
callSetProgress(w, 15, "Copying application files...")
if err := CopyFiles(config, func(progress int, status string) {
// Map 0-100 to 15-60.
mappedProgress := 15 + (progress * 45 / 100)
callSetProgress(w, mappedProgress, status)
}); err != nil {
return fmt.Errorf("failed to copy files: %w", err)
}
callSetProgress(w, 60, "Files copied successfully")
// Step 3: Create shortcuts (60% - 80%).
callSetProgress(w, 65, "Creating shortcuts...")
if err := CreateShortcuts(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 70, "Warning: Some shortcuts could not be created")
} else {
callSetProgress(w, 80, "Shortcuts created")
}
// Step 4: Register autostart if enabled (80% - 90%).
if config.EnableAutostart {
callSetProgress(w, 85, "Configuring autostart...")
if err := RegisterAutostart(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 88, "Warning: Autostart could not be configured")
} else {
callSetProgress(w, 90, "Autostart configured")
}
} else {
callSetProgress(w, 90, "Skipping autostart configuration")
}
// Step 5: Register uninstaller (90% - 100%).
callSetProgress(w, 92, "Registering application...")
if err := RegisterUninstall(config); err != nil {
// Non-fatal: log but continue.
callSetProgress(w, 95, "Warning: Uninstall registration incomplete")
} else {
callSetProgress(w, 98, "Application registered")
}
callSetProgress(w, 100, "Installation complete!")
return nil
}
// callSetProgress calls window.setProgress in the WebView.
func callSetProgress(w webview2.WebView, percent int, statusText string) {
// Escape the status text for JavaScript.
escaped := strings.ReplaceAll(statusText, "\\", "\\\\")
escaped = strings.ReplaceAll(escaped, "'", "\\'")
escaped = strings.ReplaceAll(escaped, "\n", "\\n")
js := fmt.Sprintf("if(window.setProgress){window.setProgress(%d,'%s');}", percent, escaped)
w.Dispatch(func() {
w.Eval(js)
})
}
// getInstallDir returns the default installation directory.
func getInstallDir() string {
localAppData := os.Getenv("LOCALAPPDATA")
if localAppData == "" {
home, _ := os.UserHomeDir()
localAppData = filepath.Join(home, "AppData", "Local")
}
return filepath.Join(localAppData, appName)
}
// applyDarkWindowChrome applies dark mode window chrome styling.
func applyDarkWindowChrome(w webview2.WebView) {
hwnd := getWindowHandle(w)
if hwnd == 0 {
return
}
// Enable dark mode for the window frame.
dwmapi := syscall.NewLazyDLL("dwmapi.dll")
dwmSetWindowAttribute := dwmapi.NewProc("DwmSetWindowAttribute")
// DWMWA_USE_IMMERSIVE_DARK_MODE = 20.
const DWMWA_USE_IMMERSIVE_DARK_MODE = 20
darkMode := int32(1)
_, _, _ = dwmSetWindowAttribute.Call(
hwnd,
uintptr(DWMWA_USE_IMMERSIVE_DARK_MODE),
uintptr(unsafe.Pointer(&darkMode)),
unsafe.Sizeof(darkMode),
)
// DWMWA_CAPTION_COLOR = 35 (Windows 11).
const DWMWA_CAPTION_COLOR = 35
captionColor := uint32(0x001E1E1E) // Dark gray in BGR format.
_, _, _ = dwmSetWindowAttribute.Call(
hwnd,
uintptr(DWMWA_CAPTION_COLOR),
uintptr(unsafe.Pointer(&captionColor)),
unsafe.Sizeof(captionColor),
)
}
// getWindowHandle retrieves the HWND for the WebView window.
func getWindowHandle(w webview2.WebView) uintptr {
// The go-webview2 library provides a Window() method that returns the HWND.
return uintptr(w.Window())
}
// minimizeWindow minimizes the WebView window.
func minimizeWindow(w webview2.WebView) {
hwnd := getWindowHandle(w)
if hwnd == 0 {
return
}
user32 := syscall.NewLazyDLL("user32.dll")
showWindow := user32.NewProc("ShowWindow")
const SW_MINIMIZE = 6
_, _, _ = showWindow.Call(hwnd, uintptr(SW_MINIMIZE))
}
// messageBox displays a Windows message box.
func messageBox(title, text string) error {
user32 := syscall.NewLazyDLL("user32.dll")
proc := user32.NewProc("MessageBoxW")
t, _ := syscall.UTF16PtrFromString(title)
m, _ := syscall.UTF16PtrFromString(text)
// MB_OK | MB_ICONERROR.
_, _, err := proc.Call(0, uintptr(unsafe.Pointer(m)), uintptr(unsafe.Pointer(t)), 0x00000000|0x00000010)
if err == syscall.Errno(0) {
return nil
}
return err
}
+179
View File
@@ -0,0 +1,179 @@
//go:build windows
package main
import (
"fmt"
"path/filepath"
"golang.org/x/sys/windows/registry"
)
const (
// Registry key paths.
autostartKeyPath = `Software\Microsoft\Windows\CurrentVersion\Run`
uninstallKeyPath = `Software\Microsoft\Windows\CurrentVersion\Uninstall\` + appName
uninstallKeyBase = `Software\Microsoft\Windows\CurrentVersion\Uninstall`
// Application metadata.
appPublisher = "ProxyPilot"
appVersion = "1.0.0"
)
// RegisterAutostart adds the application to the Windows autostart registry.
func RegisterAutostart(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
key, _, err := registry.CreateKey(registry.CURRENT_USER, autostartKeyPath, registry.SET_VALUE)
if err != nil {
return fmt.Errorf("failed to open autostart registry key: %w", err)
}
defer key.Close()
// Add the application with quoted path to handle spaces.
if err := key.SetStringValue(appName, `"`+exePath+`"`); err != nil {
return fmt.Errorf("failed to set autostart value: %w", err)
}
return nil
}
// UnregisterAutostart removes the application from Windows autostart.
func UnregisterAutostart(config *InstallConfig) error {
key, err := registry.OpenKey(registry.CURRENT_USER, autostartKeyPath, registry.SET_VALUE)
if err != nil {
// Key doesn't exist or can't be opened; nothing to remove.
return nil
}
defer key.Close()
if err := key.DeleteValue(appName); err != nil {
// Value doesn't exist; that's fine.
if err == registry.ErrNotExist {
return nil
}
return fmt.Errorf("failed to remove autostart value: %w", err)
}
return nil
}
// IsAutostartEnabled checks if the application is registered for autostart.
func IsAutostartEnabled() bool {
key, err := registry.OpenKey(registry.CURRENT_USER, autostartKeyPath, registry.QUERY_VALUE)
if err != nil {
return false
}
defer key.Close()
_, _, err = key.GetStringValue(appName)
return err == nil
}
// RegisterUninstall registers the application in Add/Remove Programs.
func RegisterUninstall(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
iconPath := filepath.Join(config.InstallDir, "icon.ico")
// Create the uninstall key.
key, _, err := registry.CreateKey(registry.CURRENT_USER, uninstallKeyPath, registry.SET_VALUE)
if err != nil {
return fmt.Errorf("failed to create uninstall registry key: %w", err)
}
defer key.Close()
// Set the required values.
values := map[string]string{
"DisplayName": appName,
"DisplayVersion": appVersion,
"Publisher": appPublisher,
"InstallLocation": config.InstallDir,
"DisplayIcon": iconPath,
"UninstallString": `"` + exePath + `" --uninstall`,
"QuietUninstallString": `"` + exePath + `" --uninstall --quiet`,
}
for name, value := range values {
if err := key.SetStringValue(name, value); err != nil {
return fmt.Errorf("failed to set %s: %w", name, err)
}
}
// Set NoModify and NoRepair flags.
if err := key.SetDWordValue("NoModify", 1); err != nil {
return fmt.Errorf("failed to set NoModify: %w", err)
}
if err := key.SetDWordValue("NoRepair", 1); err != nil {
return fmt.Errorf("failed to set NoRepair: %w", err)
}
// Estimate the installed size in KB.
estimatedSize := uint32(40 * 1024) // ~40 MB estimate.
if err := key.SetDWordValue("EstimatedSize", estimatedSize); err != nil {
// Non-fatal.
_ = err
}
return nil
}
// UnregisterUninstall removes the application from Add/Remove Programs.
func UnregisterUninstall() error {
// Delete the entire uninstall key.
if err := registry.DeleteKey(registry.CURRENT_USER, uninstallKeyPath); err != nil {
if err == registry.ErrNotExist {
return nil
}
return fmt.Errorf("failed to delete uninstall registry key: %w", err)
}
return nil
}
// GetInstallPathFromRegistry retrieves the installation path from the registry.
// Returns an empty string if not found.
func GetInstallPathFromRegistry() string {
key, err := registry.OpenKey(registry.CURRENT_USER, uninstallKeyPath, registry.QUERY_VALUE)
if err != nil {
return ""
}
defer key.Close()
path, _, err := key.GetStringValue("InstallLocation")
if err != nil {
return ""
}
return path
}
// SetRegistryString is a helper to set a string value in the registry.
func SetRegistryString(keyPath, valueName, value string) error {
key, _, err := registry.CreateKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE)
if err != nil {
return err
}
defer key.Close()
return key.SetStringValue(valueName, value)
}
// DeleteRegistryValue is a helper to delete a registry value.
func DeleteRegistryValue(keyPath, valueName string) error {
key, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.SET_VALUE)
if err != nil {
return err
}
defer key.Close()
return key.DeleteValue(valueName)
}
// DeleteRegistryKey is a helper to delete a registry key.
func DeleteRegistryKey(keyPath string) error {
return registry.DeleteKey(registry.CURRENT_USER, keyPath)
}
+261
View File
@@ -0,0 +1,261 @@
//go:build windows
package main
import (
"fmt"
"os"
"path/filepath"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
// GUID for IShellLinkW.
var (
CLSID_ShellLink = windows.GUID{
Data1: 0x00021401,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
IID_IShellLinkW = windows.GUID{
Data1: 0x000214F9,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
IID_IPersistFile = windows.GUID{
Data1: 0x0000010B,
Data2: 0x0000,
Data3: 0x0000,
Data4: [8]byte{0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
}
)
// IShellLinkW virtual table.
type IShellLinkWVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetPath uintptr
GetIDList uintptr
SetIDList uintptr
GetDescription uintptr
SetDescription uintptr
GetWorkingDirectory uintptr
SetWorkingDirectory uintptr
GetArguments uintptr
SetArguments uintptr
GetHotkey uintptr
SetHotkey uintptr
GetShowCmd uintptr
SetShowCmd uintptr
GetIconLocation uintptr
SetIconLocation uintptr
SetRelativePath uintptr
Resolve uintptr
SetPath uintptr
}
type IShellLinkW struct {
vtbl *IShellLinkWVtbl
}
// IPersistFile virtual table.
type IPersistFileVtbl struct {
QueryInterface uintptr
AddRef uintptr
Release uintptr
GetClassID uintptr
IsDirty uintptr
Load uintptr
Save uintptr
SaveCompleted uintptr
GetCurFile uintptr
}
type IPersistFile struct {
vtbl *IPersistFileVtbl
}
var (
ole32 = syscall.NewLazyDLL("ole32.dll")
coInitializeEx = ole32.NewProc("CoInitializeEx")
coCreateInstance = ole32.NewProc("CoCreateInstance")
coUninitialize = ole32.NewProc("CoUninitialize")
)
const (
COINIT_APARTMENTTHREADED = 0x2
CLSCTX_INPROC_SERVER = 0x1
)
// CreateShortcuts creates Start Menu and optionally Desktop shortcuts.
func CreateShortcuts(config *InstallConfig) error {
if config.InstallDir == "" {
return fmt.Errorf("install directory not specified")
}
exePath := filepath.Join(config.InstallDir, "ProxyPilot.exe")
iconPath := filepath.Join(config.InstallDir, "icon.ico")
// Create Start Menu shortcut.
startMenuPath := getStartMenuPath()
if startMenuPath != "" {
shortcutPath := filepath.Join(startMenuPath, appName+".lnk")
if err := createShortcut(shortcutPath, exePath, config.InstallDir, iconPath, "ProxyPilot - AI Proxy Router"); err != nil {
return fmt.Errorf("failed to create Start Menu shortcut: %w", err)
}
}
// Create Desktop shortcut if requested.
if config.CreateDesktopShortcut {
desktopPath := getDesktopPath()
if desktopPath != "" {
shortcutPath := filepath.Join(desktopPath, appName+".lnk")
if err := createShortcut(shortcutPath, exePath, config.InstallDir, iconPath, "ProxyPilot - AI Proxy Router"); err != nil {
return fmt.Errorf("failed to create Desktop shortcut: %w", err)
}
}
}
return nil
}
// createShortcut creates a Windows .lnk shortcut file using COM.
func createShortcut(shortcutPath, targetPath, workingDir, iconPath, description string) error {
// Initialize COM.
hr, _, _ := coInitializeEx.Call(0, uintptr(COINIT_APARTMENTTHREADED))
if hr != 0 && hr != 1 { // S_OK or S_FALSE.
return fmt.Errorf("CoInitializeEx failed: 0x%X", hr)
}
defer coUninitialize.Call()
// Create IShellLink instance.
var shellLink *IShellLinkW
hr, _, _ = coCreateInstance.Call(
uintptr(unsafe.Pointer(&CLSID_ShellLink)),
0,
uintptr(CLSCTX_INPROC_SERVER),
uintptr(unsafe.Pointer(&IID_IShellLinkW)),
uintptr(unsafe.Pointer(&shellLink)),
)
if hr != 0 {
return fmt.Errorf("CoCreateInstance failed: 0x%X", hr)
}
// Set the target path.
targetPathW, _ := syscall.UTF16PtrFromString(targetPath)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetPath, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(targetPathW)))
if hr != 0 {
return fmt.Errorf("SetPath failed: 0x%X", hr)
}
// Set the working directory.
workingDirW, _ := syscall.UTF16PtrFromString(workingDir)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetWorkingDirectory, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(workingDirW)))
if hr != 0 {
return fmt.Errorf("SetWorkingDirectory failed: 0x%X", hr)
}
// Set the description.
descriptionW, _ := syscall.UTF16PtrFromString(description)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetDescription, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(descriptionW)))
if hr != 0 {
return fmt.Errorf("SetDescription failed: 0x%X", hr)
}
// Set the icon.
if iconPath != "" {
iconPathW, _ := syscall.UTF16PtrFromString(iconPath)
hr, _, _ = syscall.SyscallN(shellLink.vtbl.SetIconLocation, uintptr(unsafe.Pointer(shellLink)), uintptr(unsafe.Pointer(iconPathW)), 0)
if hr != 0 {
// Non-fatal: continue without icon.
_ = hr
}
}
// Query for IPersistFile interface.
var persistFile *IPersistFile
hr, _, _ = syscall.SyscallN(
shellLink.vtbl.QueryInterface,
uintptr(unsafe.Pointer(shellLink)),
uintptr(unsafe.Pointer(&IID_IPersistFile)),
uintptr(unsafe.Pointer(&persistFile)),
)
if hr != 0 {
return fmt.Errorf("QueryInterface for IPersistFile failed: 0x%X", hr)
}
// Ensure the shortcut directory exists.
shortcutDir := filepath.Dir(shortcutPath)
if err := os.MkdirAll(shortcutDir, 0755); err != nil {
return fmt.Errorf("failed to create shortcut directory: %w", err)
}
// Save the shortcut.
shortcutPathW, _ := syscall.UTF16PtrFromString(shortcutPath)
hr, _, _ = syscall.SyscallN(persistFile.vtbl.Save, uintptr(unsafe.Pointer(persistFile)), uintptr(unsafe.Pointer(shortcutPathW)), 1)
if hr != 0 {
return fmt.Errorf("Save failed: 0x%X", hr)
}
// Release interfaces.
syscall.SyscallN(persistFile.vtbl.Release, uintptr(unsafe.Pointer(persistFile)))
syscall.SyscallN(shellLink.vtbl.Release, uintptr(unsafe.Pointer(shellLink)))
return nil
}
// getStartMenuPath returns the user's Start Menu Programs folder.
func getStartMenuPath() string {
// CSIDL_PROGRAMS = 0x0002.
path := getKnownFolderPath(0x0002)
if path != "" {
return path
}
// Fallback to constructing the path manually.
appData := os.Getenv("APPDATA")
if appData != "" {
return filepath.Join(appData, "Microsoft", "Windows", "Start Menu", "Programs")
}
return ""
}
// getDesktopPath returns the user's Desktop folder.
func getDesktopPath() string {
// CSIDL_DESKTOP = 0x0000.
path := getKnownFolderPath(0x0000)
if path != "" {
return path
}
// Fallback.
home, _ := os.UserHomeDir()
if home != "" {
return filepath.Join(home, "Desktop")
}
return ""
}
// getKnownFolderPath retrieves a known folder path using SHGetFolderPath.
func getKnownFolderPath(csidl int) string {
shell32 := syscall.NewLazyDLL("shell32.dll")
shGetFolderPath := shell32.NewProc("SHGetFolderPathW")
buf := make([]uint16, 260) // MAX_PATH.
hr, _, _ := shGetFolderPath.Call(
0,
uintptr(csidl),
0,
0,
uintptr(unsafe.Pointer(&buf[0])),
)
if hr != 0 {
return ""
}
return syscall.UTF16ToString(buf)
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+35
View File
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ProxyPilot Installer</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body, #root {
height: 100%;
width: 100%;
overflow: hidden;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #0a0a0b;
}
</style>
<script type="module" crossorigin src="./assets/index-Ct7uoBdX.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DTO-I4cJ.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+261
View File
@@ -0,0 +1,261 @@
//go:build windows
package main
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/desktopctl"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy"
log "github.com/sirupsen/logrus"
)
// EmbeddedEngine runs the proxy service in-process within the tray application.
// It provides thread-safe methods for starting, stopping, and querying the service status.
type EmbeddedEngine struct {
mu sync.Mutex
// running indicates whether the service is currently active.
running bool
// port is the port number the service is listening on.
port int
// configPath stores the path to the configuration file.
configPath string
// lastError holds the most recent error encountered during operation.
lastError error
// startedAt records when the service was started.
startedAt time.Time
// cancel is the function to cancel the service context.
cancel context.CancelFunc
// wg waits for the service goroutine to complete.
wg sync.WaitGroup
// panicCount tracks the number of panics for monitoring.
panicCount int
// restartCount tracks the number of automatic restarts.
restartCount int
}
// NewEmbeddedEngine creates a new EmbeddedEngine instance.
func NewEmbeddedEngine() *EmbeddedEngine {
return &EmbeddedEngine{}
}
// Start builds and runs the proxy service in a background goroutine.
// It returns an error if the service is already running or if building the service fails.
func (e *EmbeddedEngine) Start(cfg *config.Config, configPath, password string) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.running {
return errors.New("engine is already running")
}
if cfg == nil {
return errors.New("configuration is required")
}
if configPath == "" {
return errors.New("configuration path is required")
}
// Build the service using the SDK builder pattern
builder := cliproxy.NewBuilder().
WithConfig(cfg).
WithConfigPath(configPath).
WithLocalManagementPassword(password)
service, err := builder.Build()
if err != nil {
e.lastError = fmt.Errorf("failed to build proxy service: %w", err)
return e.lastError
}
// Create a cancelable context for the service
ctx, cancel := context.WithCancel(context.Background())
e.cancel = cancel
// Track state
e.running = true
e.port = cfg.Port
e.configPath = configPath
e.lastError = nil
e.startedAt = time.Now()
log.Infof("starting embedded proxy engine on port %d", e.port)
// Run the service in a goroutine with panic recovery
e.wg.Add(1)
go func() {
defer e.wg.Done()
defer func() {
// Recover from panics to prevent crashing the tray app
if r := recover(); r != nil {
e.mu.Lock()
e.panicCount++
e.running = false
e.cancel = nil
e.lastError = fmt.Errorf("proxy service panicked: %v", r)
e.mu.Unlock()
log.Errorf("embedded proxy engine panic recovered: %v", r)
}
}()
defer func() {
e.mu.Lock()
e.running = false
e.cancel = nil
e.mu.Unlock()
log.Info("embedded proxy engine stopped")
}()
err := service.Run(ctx)
if err != nil && !errors.Is(err, context.Canceled) {
e.mu.Lock()
e.lastError = fmt.Errorf("proxy service exited with error: %w", err)
e.mu.Unlock()
log.Errorf("embedded proxy engine error: %v", err)
}
}()
return nil
}
// Stop cancels the running service and waits for it to shut down gracefully.
// It returns an error if the service is not running or if shutdown times out.
func (e *EmbeddedEngine) Stop() error {
e.mu.Lock()
if !e.running {
e.mu.Unlock()
return errors.New("engine is not running")
}
if e.cancel != nil {
log.Info("stopping embedded proxy engine...")
e.cancel()
}
e.mu.Unlock()
// Wait for the goroutine to complete with a timeout
done := make(chan struct{})
go func() {
e.wg.Wait()
close(done)
}()
select {
case <-done:
log.Info("embedded proxy engine stopped gracefully")
return nil
case <-time.After(10 * time.Second):
// Force mark as stopped to prevent deadlock
e.mu.Lock()
e.running = false
e.cancel = nil
e.lastError = errors.New("shutdown timed out after 10 seconds")
e.mu.Unlock()
log.Warn("embedded proxy engine shutdown timed out, forcing stop")
return errors.New("shutdown timed out")
}
}
// Restart stops the running service (if any) and starts it again with the new configuration.
func (e *EmbeddedEngine) Restart(cfg *config.Config, configPath, password string) error {
// Stop if running (ignore error if not running)
if e.IsRunning() {
if err := e.Stop(); err != nil {
log.Warnf("error stopping engine during restart: %v", err)
}
}
// Increment restart counter
e.mu.Lock()
e.restartCount++
e.mu.Unlock()
// Start with new configuration
return e.Start(cfg, configPath, password)
}
// Status returns the current status of the embedded engine.
// The returned status is compatible with desktopctl.Status for UI integration.
func (e *EmbeddedEngine) Status() desktopctl.Status {
e.mu.Lock()
defer e.mu.Unlock()
status := desktopctl.Status{
Running: e.running,
Managed: true, // Embedded engine is always managed by the tray
Port: e.port,
ConfigPath: e.configPath,
StartedAt: e.startedAt,
}
if e.running && e.port > 0 {
status.BaseURL = fmt.Sprintf("http://127.0.0.1:%d", e.port)
}
if e.lastError != nil {
status.LastError = e.lastError.Error()
}
return status
}
// IsRunning returns whether the engine is currently running.
func (e *EmbeddedEngine) IsRunning() bool {
e.mu.Lock()
defer e.mu.Unlock()
return e.running
}
// LastError returns the most recent error encountered, or nil if none.
func (e *EmbeddedEngine) LastError() error {
e.mu.Lock()
defer e.mu.Unlock()
return e.lastError
}
// Port returns the port number the engine is configured to listen on.
func (e *EmbeddedEngine) Port() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.port
}
// PanicCount returns the number of panics that have been recovered.
func (e *EmbeddedEngine) PanicCount() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.panicCount
}
// RestartCount returns the number of times the engine has been restarted.
func (e *EmbeddedEngine) RestartCount() int {
e.mu.Lock()
defer e.mu.Unlock()
return e.restartCount
}
// Uptime returns the duration the engine has been running, or 0 if not running.
func (e *EmbeddedEngine) Uptime() time.Duration {
e.mu.Lock()
defer e.mu.Unlock()
if !e.running || e.startedAt.IsZero() {
return 0
}
return time.Since(e.startedAt)
}
+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package main
import "fmt"
func main() {
fmt.Println("proxypilot-tray is currently supported on Windows only.")
}
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"FixedFileInfo": {
"FileVersion": {
"Major": 0,
"Minor": 3,
"Patch": 0,
"Build": 0
},
"ProductVersion": {
"Major": 0,
"Minor": 3,
"Patch": 0,
"Build": 0
},
"FileFlagsMask": "3f",
"FileFlags ": "00",
"FileOS": "040004",
"FileType": "01",
"FileSubType": "00"
},
"StringFileInfo": {
"Comments": "Local AI Proxy with Embedded Engine",
"CompanyName": "ProxyPilot",
"FileDescription": "ProxyPilot - Single Binary Desktop App",
"FileVersion": "0.3.0",
"InternalName": "ProxyPilot",
"LegalCopyright": "MIT License",
"OriginalFilename": "ProxyPilot.exe",
"ProductName": "ProxyPilot",
"ProductVersion": "0.3.0"
},
"VarFileInfo": {
"Translation": {
"LangID": "0409",
"CharsetID": "04B0"
}
},
"IconPath": "../../static/icon.ico",
"ManifestPath": ""
}
+479
View File
@@ -0,0 +1,479 @@
package main
import (
"archive/zip"
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v7/internal/trayicon"
)
func main() {
var (
outDir string
repoDir string
)
flag.StringVar(&repoDir, "repo", "", "Repository root (defaults to current directory)")
flag.StringVar(&outDir, "out", "", "Output directory (defaults to <repo>/dist)")
flag.Parse()
args := flag.Args()
if len(args) == 0 {
die("usage: proxypilotpack <build|package-zip|package-setup|package-inno> [--repo <path>] [--out <path>]")
}
cmd := strings.ToLower(strings.TrimSpace(args[0]))
repoRoot, err := resolveRepoRoot(repoDir)
if err != nil {
die(err.Error())
}
distRoot := outDir
if strings.TrimSpace(distRoot) == "" {
distRoot = filepath.Join(repoRoot, "dist")
}
binRoot := filepath.Join(repoRoot, "bin")
if err := os.MkdirAll(binRoot, 0o755); err != nil {
die(err.Error())
}
if err := os.MkdirAll(distRoot, 0o755); err != nil {
die(err.Error())
}
switch cmd {
case "build":
if err := buildBinaries(repoRoot, binRoot); err != nil {
die(err.Error())
}
case "package-zip":
if err := buildBinaries(repoRoot, binRoot); err != nil {
die(err.Error())
}
if err := packageZip(repoRoot, binRoot, distRoot); err != nil {
die(err.Error())
}
case "package-setup":
// Alias to the recommended Windows installer.
if runtime.GOOS != "windows" {
die("package-setup is only supported on Windows")
}
if err := buildBinaries(repoRoot, binRoot); err != nil {
die(err.Error())
}
if err := packageInno(repoRoot, distRoot); err != nil {
die(err.Error())
}
case "package-inno":
if runtime.GOOS != "windows" {
die("package-inno is only supported on Windows")
}
if err := buildBinaries(repoRoot, binRoot); err != nil {
die(err.Error())
}
if err := packageInno(repoRoot, distRoot); err != nil {
die(err.Error())
}
case "package-iexpress":
if runtime.GOOS != "windows" {
die("package-iexpress is only supported on Windows")
}
if err := buildBinaries(repoRoot, binRoot); err != nil {
die(err.Error())
}
if err := packageSetup(repoRoot, binRoot, distRoot); err != nil {
die(err.Error())
}
default:
die(fmt.Sprintf("unknown command: %s", cmd))
}
}
func resolveRepoRoot(repoDir string) (string, error) {
root := strings.TrimSpace(repoDir)
if root == "" {
wd, err := os.Getwd()
if err != nil {
return "", err
}
root = wd
}
root, err := filepath.Abs(root)
if err != nil {
return "", err
}
// Very small validation: go.mod should exist.
if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil {
return "", fmt.Errorf("not a repo root (missing go.mod): %s", root)
}
return root, nil
}
func buildBinaries(repoRoot, binRoot string) error {
proxyExe := filepath.Join(binRoot, "proxypilot-engine.exe")
if runtime.GOOS != "windows" {
proxyExe = filepath.Join(binRoot, "proxypilot-engine")
}
trayExe := filepath.Join(binRoot, "ProxyPilot.exe")
if runtime.GOOS != "windows" {
trayExe = filepath.Join(binRoot, "ProxyPilot")
}
if err := run(repoRoot, "go", "build", "-o", proxyExe, "./cmd/server"); err != nil {
return err
}
if runtime.GOOS == "windows" {
if err := run(repoRoot, "go", "build", "-ldflags", "-H=windowsgui", "-o", trayExe, "./cmd/proxypilot-tray"); err != nil {
return err
}
} else {
if err := run(repoRoot, "go", "build", "-o", trayExe, "./cmd/proxypilot-tray"); err != nil {
return err
}
}
if runtime.GOOS == "windows" {
ico := trayicon.ProxyPilotICO()
if len(ico) > 0 {
_ = os.WriteFile(filepath.Join(binRoot, "ProxyPilot.ico"), ico, 0o644)
}
}
return nil
}
func packageZip(repoRoot, binRoot, distRoot string) error {
outZip := filepath.Join(distRoot, "ProxyPilot.zip")
_ = os.Remove(outZip)
files := []struct {
src string
dst string
}{
{src: filepath.Join(binRoot, "ProxyPilot.exe"), dst: "ProxyPilot.exe"},
{src: filepath.Join(binRoot, "ProxyPilot.ico"), dst: "ProxyPilot.ico"},
{src: filepath.Join(binRoot, "proxypilot-engine.exe"), dst: "proxypilot-engine.exe"},
// Back-compat: keep a copy under the legacy name for older launchers/scripts.
{src: filepath.Join(binRoot, "proxypilot-engine.exe"), dst: "cliproxyapi-latest.exe"},
}
cfg := filepath.Join(repoRoot, "config.example.yaml")
if _, err := os.Stat(cfg); err == nil {
files = append(files, struct {
src string
dst string
}{src: cfg, dst: "config.example.yaml"})
}
f, err := os.Create(outZip)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
zw := zip.NewWriter(f)
for _, it := range files {
b, err := os.ReadFile(it.src)
if err != nil {
return fmt.Errorf("missing %s (build first): %w", it.src, err)
}
w, err := zw.Create(it.dst)
if err != nil {
return err
}
if _, err := io.Copy(w, bytes.NewReader(b)); err != nil {
return err
}
}
if err := zw.Close(); err != nil {
return err
}
return nil
}
func packageSetup(repoRoot, binRoot, distRoot string) error {
iexpress := filepath.Join(os.Getenv("WINDIR"), "System32", "iexpress.exe")
if _, err := os.Stat(iexpress); err != nil {
return fmt.Errorf("IExpress not found at %s (use package-zip instead)", iexpress)
}
staging := filepath.Join(distRoot, "ProxyPilot-Staging")
_ = os.RemoveAll(staging)
if err := os.MkdirAll(staging, 0o755); err != nil {
return err
}
// Payload files
mgrExe := filepath.Join(binRoot, "ProxyPilot.exe")
srvExe := filepath.Join(binRoot, "proxypilot-engine.exe")
if err := copyFile(mgrExe, filepath.Join(staging, "ProxyPilot.exe")); err != nil {
return err
}
if err := copyFile(srvExe, filepath.Join(staging, "proxypilot-engine.exe")); err != nil {
return err
}
_ = copyFile(srvExe, filepath.Join(staging, "cliproxyapi-latest.exe"))
cfgSrc := filepath.Join(repoRoot, "config.example.yaml")
if _, err := os.Stat(cfgSrc); err == nil {
if err := copyFile(cfgSrc, filepath.Join(staging, "config.example.yaml")); err != nil {
return err
}
}
installCmd := filepath.Join(staging, "install.cmd")
installBody := "" +
"@echo off\r\n" +
"setlocal\r\n" +
"set \"SRC=%~dp0\"\r\n" +
"set \"DEST=%LOCALAPPDATA%\\ProxyPilot\"\r\n" +
"if not exist \"%DEST%\" mkdir \"%DEST%\" >nul 2>&1\r\n" +
"copy /Y \"%SRC%ProxyPilot.exe\" \"%DEST%\\ProxyPilot.exe\" >nul\r\n" +
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\proxypilot-engine.exe\" >nul\r\n" +
"copy /Y \"%SRC%proxypilot-engine.exe\" \"%DEST%\\cliproxyapi-latest.exe\" >nul\r\n" +
"if exist \"%SRC%config.example.yaml\" copy /Y \"%SRC%config.example.yaml\" \"%DEST%\\config.example.yaml\" >nul\r\n" +
"if not exist \"%DEST%\\config.yaml\" if exist \"%DEST%\\config.example.yaml\" copy /Y \"%DEST%\\config.example.yaml\" \"%DEST%\\config.yaml\" >nul\r\n" +
"\r\n" +
"REM Create Start Menu + Desktop shortcuts\r\n" +
"powershell -NoProfile -ExecutionPolicy Bypass -Command \"$dest=Join-Path $env:LOCALAPPDATA 'ProxyPilot'; $sm=Join-Path $env:APPDATA 'Microsoft\\\\Windows\\\\Start Menu\\\\Programs\\\\ProxyPilot'; New-Item -ItemType Directory -Force -Path $sm | Out-Null; $ws=New-Object -ComObject WScript.Shell; $lnk=$ws.CreateShortcut((Join-Path $sm 'ProxyPilot.lnk')); $lnk.TargetPath=(Join-Path $dest 'ProxyPilot.exe'); $lnk.WorkingDirectory=$dest; $lnk.IconLocation=$lnk.TargetPath+',0'; $lnk.Save(); $desk=[Environment]::GetFolderPath('Desktop'); $dlnk=$ws.CreateShortcut((Join-Path $desk 'ProxyPilot.lnk')); $dlnk.TargetPath=(Join-Path $dest 'ProxyPilot.exe'); $dlnk.WorkingDirectory=$dest; $dlnk.IconLocation=$dlnk.TargetPath+',0'; $dlnk.Save()\" >nul 2>&1\r\n" +
"\r\n" +
"start \"\" \"%DEST%\\ProxyPilot.exe\"\r\n"
if err := os.WriteFile(installCmd, []byte(installBody), 0o644); err != nil {
return err
}
outExe := filepath.Join(distRoot, "ProxyPilot-Setup.exe")
if err := os.Remove(outExe); err != nil && !errors.Is(err, os.ErrNotExist) {
// If the target is locked (common if the user just ran the installer), build to a unique name instead.
ext := filepath.Ext(outExe)
base := strings.TrimSuffix(filepath.Base(outExe), ext)
outExe = filepath.Join(distRoot, fmt.Sprintf("%s-%s%s", base, time.Now().Format("20060102-150405"), ext))
}
sedPath := filepath.Join(staging, "package.sed")
sed, err := buildIExpressSed(staging, outExe)
if err != nil {
return err
}
// If config.example.yaml is absent, omit it to avoid IExpress build failure.
if _, err := os.Stat(filepath.Join(staging, "config.example.yaml")); errors.Is(err, os.ErrNotExist) {
sed = strings.ReplaceAll(sed, "%FILE2%=config.example.yaml\r\n", "")
sed = strings.ReplaceAll(sed, "FILE2=config.example.yaml\r\n", "")
}
if err := os.WriteFile(sedPath, []byte(sed), 0o644); err != nil {
return err
}
if err := run(repoRoot, iexpress, "/n", "/q", sedPath); err != nil {
return err
}
if _, err := os.Stat(outExe); err != nil {
return fmt.Errorf("installer build failed; expected: %s", outExe)
}
return nil
}
func buildIExpressSed(staging string, outExe string) (string, error) {
stagingAbs, err := filepath.Abs(staging)
if err != nil {
return "", err
}
outAbs, err := filepath.Abs(outExe)
if err != nil {
return "", err
}
// IExpress SED wants backslashes escaped.
stagingEsc := strings.ReplaceAll(stagingAbs, `\`, `\\`)
outEsc := strings.ReplaceAll(outAbs, `\`, `\\`)
return fmt.Sprintf(`[Version]
Class=IExpress
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=0
HideExtractAnimation=1
UseLongFileName=1
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=
DisplayLicense=
FinishMessage=
TargetName=%s
FriendlyName=ProxyPilot
AppLaunched=cmd.exe /c install.cmd
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=%s
[SourceFiles0]
%%FILE0%%=ProxyPilot.exe
%%FILE1%%=proxypilot-engine.exe
%%FILE2%%=config.example.yaml
%%FILE3%%=install.cmd
[Strings]
FILE0=ProxyPilot.exe
FILE1=proxypilot-engine.exe
FILE2=config.example.yaml
FILE3=install.cmd
`, outEsc, stagingEsc), nil
}
func packageInno(repoRoot, distRoot string) error {
iscc, err := findISCC()
if err != nil {
return err
}
iss := filepath.Join(repoRoot, "installer", "proxypilot.iss")
if _, err := os.Stat(iss); err != nil {
return fmt.Errorf("missing inno script: %s", iss)
}
appVersion := resolveAppVersion(repoRoot)
repoAbs, _ := filepath.Abs(repoRoot)
outAbs, _ := filepath.Abs(distRoot)
args := []string{
"/Q",
"/DAppVersion=" + appVersion,
"/DRepoRoot=" + repoAbs,
"/DOutDir=" + outAbs,
iss,
}
return run(repoRoot, iscc, args...)
}
func findISCC() (string, error) {
if p, err := exec.LookPath("ISCC.exe"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
if p, err := exec.LookPath("ISCC"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
candidates := []string{
filepath.Join(os.Getenv("ProgramFiles(x86)"), "Inno Setup 6", "ISCC.exe"),
filepath.Join(os.Getenv("ProgramFiles"), "Inno Setup 6", "ISCC.exe"),
filepath.Join(os.Getenv("LOCALAPPDATA"), "Programs", "Inno Setup 6", "ISCC.exe"),
}
if reg := findInnoInstallLocationFromRegistry(); reg != "" {
candidates = append(candidates, filepath.Join(reg, "ISCC.exe"))
}
for _, c := range candidates {
if strings.TrimSpace(c) == "" {
continue
}
if _, err := os.Stat(c); err == nil {
return c, nil
}
}
return "", fmt.Errorf("Inno Setup compiler (ISCC.exe) not found; install Inno Setup 6 or add ISCC.exe to PATH")
}
func findInnoInstallLocationFromRegistry() string {
if runtime.GOOS != "windows" {
return ""
}
// Query uninstall entries for "Inno Setup" and read InstallLocation.
out, err := exec.Command("reg", "query", `HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall`, "/s", "/v", "InstallLocation").Output()
if err == nil {
if loc := parseRegInstallLocation(string(out)); loc != "" {
return loc
}
}
out, err = exec.Command("reg", "query", `HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall`, "/s", "/v", "InstallLocation").Output()
if err == nil {
if loc := parseRegInstallLocation(string(out)); loc != "" {
return loc
}
}
out, err = exec.Command("reg", "query", `HKLM\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall`, "/s", "/v", "InstallLocation").Output()
if err == nil {
if loc := parseRegInstallLocation(string(out)); loc != "" {
return loc
}
}
return ""
}
func parseRegInstallLocation(out string) string {
// reg.exe output lines look like:
// InstallLocation REG_SZ C:\Users\...\Inno Setup 6\
lines := strings.Split(out, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
if !strings.HasPrefix(strings.ToLower(line), "installlocation") {
continue
}
fields := strings.Fields(line)
if len(fields) < 3 {
continue
}
loc := strings.TrimSpace(strings.Join(fields[2:], " "))
loc = strings.Trim(loc, `"`)
loc = strings.TrimSpace(loc)
if loc == "" {
continue
}
if _, err := os.Stat(loc); err == nil {
return strings.TrimRight(loc, `\`)
}
}
return ""
}
func resolveAppVersion(repoRoot string) string {
// Prefer git sha if available. Keep it short and filesystem-safe.
out, err := exec.Command("git", "-C", repoRoot, "rev-parse", "--short", "HEAD").Output()
if err == nil {
sha := strings.TrimSpace(string(out))
if sha != "" {
return "dev-" + sha
}
}
return "dev-" + time.Now().Format("20060102-150405")
}
func run(dir string, name string, args ...string) error {
c := exec.Command(name, args...)
c.Dir = dir
c.Stdout = os.Stdout
c.Stderr = os.Stderr
return c.Run()
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
return err
}
out, err := os.Create(dst)
if err != nil {
return err
}
defer func() { _ = out.Close() }()
if _, err := io.Copy(out, in); err != nil {
return err
}
return nil
}
func die(msg string) {
_, _ = fmt.Fprintln(os.Stderr, msg)
os.Exit(2)
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
package assets
import "embed"
//go:embed index.html vite.svg logo.png assets/*
var FS embed.FS
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="pp-mgmt-key" content="test123" />
<title>ProxyPilot</title>
<!-- Google Fonts preconnect for performance -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<!-- Google Fonts: Space Grotesk (display/headers), JetBrains Mono (code), IBM Plex Sans (body) -->
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+396 -69
View File
@@ -8,6 +8,7 @@ import (
"errors"
"flag"
"fmt"
"io"
"io/fs"
"net/url"
"os"
@@ -16,18 +17,25 @@ import (
"time"
"github.com/joho/godotenv"
configaccess "github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access"
"github.com/router-for-me/CLIProxyAPI/v6/internal/cmd"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v6/internal/managementasset"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v6/internal/store"
_ "github.com/router-for-me/CLIProxyAPI/v6/internal/translator"
"github.com/router-for-me/CLIProxyAPI/v6/internal/usage"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
"github.com/router-for-me/CLIProxyAPI/v7/internal/buildinfo"
"github.com/router-for-me/CLIProxyAPI/v7/internal/cmd"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/home"
"github.com/router-for-me/CLIProxyAPI/v7/internal/homeplugins"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v7/internal/managementasset"
"github.com/router-for-me/CLIProxyAPI/v7/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v7/internal/pluginhost"
"github.com/router-for-me/CLIProxyAPI/v7/internal/redisqueue"
"github.com/router-for-me/CLIProxyAPI/v7/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v7/internal/safemode"
"github.com/router-for-me/CLIProxyAPI/v7/internal/store"
_ "github.com/router-for-me/CLIProxyAPI/v7/internal/translator"
"github.com/router-for-me/CLIProxyAPI/v7/internal/tui"
"github.com/router-for-me/CLIProxyAPI/v7/internal/util"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
coreauth "github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy/auth"
log "github.com/sirupsen/logrus"
)
@@ -41,35 +49,64 @@ var (
// init initializes the shared logger setup.
func init() {
logging.SetupBaseLogger()
buildinfo.Version = Version
buildinfo.Commit = Commit
buildinfo.BuildDate = BuildDate
}
func shouldStartExampleAPIKeyWarningServer(cfg *config.Config, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode bool) bool {
if cfg == nil || commandMode || homeMode || cloudConfigMissing {
return false
}
if tuiMode && !standalone {
return false
}
return safemode.HasExampleAPIKeys(cfg.APIKeys)
}
// main is the entry point of the application.
// It parses command-line flags, loads configuration, and starts the appropriate
// service based on the provided flags (login, codex-login, or server mode).
func main() {
fmt.Printf("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s\n", Version, Commit, BuildDate)
fmt.Printf("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
// Command-line flags to control the application's behavior.
var login bool
var codexLogin bool
var codexDeviceLogin bool
var claudeLogin bool
var qwenLogin bool
var iflowLogin bool
var noBrowser bool
var projectID string
var oauthCallbackPort int
var antigravityLogin bool
var kimiLogin bool
var xaiLogin bool
var vertexImport string
var vertexImportPrefix string
var configPath string
var password string
var homeJWT string
var homeDisableClusterDiscovery bool
var tuiMode bool
var standalone bool
var localModel bool
// Define command-line flags for different operation modes.
flag.BoolVar(&login, "login", false, "Login Google Account")
flag.BoolVar(&codexLogin, "codex-login", false, "Login to Codex using OAuth")
flag.BoolVar(&codexDeviceLogin, "codex-device-login", false, "Login to Codex using device code flow")
flag.BoolVar(&claudeLogin, "claude-login", false, "Login to Claude using OAuth")
flag.BoolVar(&qwenLogin, "qwen-login", false, "Login to Qwen using OAuth")
flag.BoolVar(&iflowLogin, "iflow-login", false, "Login to iFlow using OAuth")
flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
flag.IntVar(&oauthCallbackPort, "oauth-callback-port", 0, "Override OAuth callback port (defaults to provider-specific port)")
flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth")
flag.BoolVar(&kimiLogin, "kimi-login", false, "Login to Kimi using OAuth")
flag.BoolVar(&xaiLogin, "xai-login", false, "Login to xAI using OAuth")
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
flag.StringVar(&vertexImportPrefix, "vertex-import-prefix", "", "Prefix for Vertex model namespacing (use with -vertex-import)")
flag.StringVar(&password, "password", "", "")
flag.StringVar(&homeJWT, "home-jwt", "", "Home control plane JWT for mTLS certificate bootstrap and connection")
flag.BoolVar(&homeDisableClusterDiscovery, "home-disable-cluster-discovery", false, "Disable Home CLUSTER NODES discovery and keep using the configured -home-jwt address")
flag.BoolVar(&tuiMode, "tui", false, "Start with terminal management UI")
flag.BoolVar(&standalone, "standalone", false, "In TUI mode, start an embedded local server")
flag.BoolVar(&localModel, "local-model", false, "Use embedded model catalog only, skip remote model fetching")
flag.CommandLine.Usage = func() {
out := flag.CommandLine.Output()
@@ -98,6 +135,12 @@ func main() {
})
}
pluginHost := pluginhost.New()
if bootstrapCfg := loadPluginBootstrapConfig(pluginBootstrapConfigPath(os.Args[1:], DefaultConfigPath)); bootstrapCfg != nil {
pluginHost.ApplyConfig(context.Background(), bootstrapCfg)
pluginHost.RegisterCommandLineFlags(context.Background(), flag.CommandLine)
}
// Parse the command-line flags.
flag.Parse()
@@ -105,6 +148,9 @@ func main() {
var err error
var cfg *config.Config
var isCloudDeploy bool
var configLoadedFromHome bool
var homeClient *home.Client
var homePluginSyncReport homeplugins.SyncReport
var (
usePostgresStore bool
pgStoreDSN string
@@ -115,6 +161,7 @@ func main() {
gitStoreRemoteURL string
gitStoreUser string
gitStorePassword string
gitStoreBranch string
gitStoreLocalPath string
gitStoreInst *store.GitTokenStore
gitStoreRoot string
@@ -129,7 +176,8 @@ func main() {
wd, err := os.Getwd()
if err != nil {
log.Fatalf("failed to get working directory: %v", err)
log.Errorf("failed to get working directory: %v", err)
return
}
// Load environment variables from .env if present.
@@ -150,6 +198,13 @@ func main() {
return "", false
}
writableBase := util.WritablePath()
if strings.TrimSpace(homeJWT) == "" {
if v, ok := lookupEnv("HOME_JWT", "home_jwt"); ok {
homeJWT = v
}
}
if value, ok := lookupEnv("PGSTORE_DSN", "pgstore_dsn"); ok {
usePostgresStore = true
pgStoreDSN = value
@@ -183,6 +238,9 @@ func main() {
if value, ok := lookupEnv("GITSTORE_LOCAL_PATH", "gitstore_local_path"); ok {
gitStoreLocalPath = value
}
if value, ok := lookupEnv("GITSTORE_GIT_BRANCH", "gitstore_git_branch"); ok {
gitStoreBranch = value
}
if value, ok := lookupEnv("OBJECTSTORE_ENDPOINT", "objectstore_endpoint"); ok {
useObjectStore = true
objectStoreEndpoint = value
@@ -210,7 +268,69 @@ func main() {
// Determine and load the configuration file.
// Prefer the Postgres store when configured, otherwise fallback to git or local files.
var configFilePath string
if usePostgresStore {
if strings.TrimSpace(homeJWT) != "" {
configLoadedFromHome = true
ctxHome, cancelHome := context.WithTimeout(context.Background(), 30*time.Second)
homeCfg, errHomeCfg := home.ConfigFromJWT(ctxHome, homeJWT)
cancelHome()
if errHomeCfg != nil {
log.Errorf("invalid -home-jwt: %v", errHomeCfg)
return
}
if homeDisableClusterDiscovery {
homeCfg.DisableClusterDiscovery = true
}
homeClient = home.New(homeCfg)
defer homeClient.Close()
ctxHomeConfig, cancelHomeConfig := context.WithTimeout(context.Background(), 30*time.Second)
raw, errGetConfig := homeClient.GetConfig(ctxHomeConfig)
cancelHomeConfig()
if errGetConfig != nil {
log.Errorf("failed to fetch config from home: %v", errGetConfig)
return
}
parsed, errParseConfig := config.ParseConfigBytes(raw)
if errParseConfig != nil {
log.Errorf("failed to parse config payload from home: %v", errParseConfig)
return
}
if parsed == nil {
parsed = &config.Config{}
}
parsed.Home = homeCfg
parsed.Port = 8317 // Default to 8317 for home mode, can be overridden by home config
parsed.UsageStatisticsEnabled = true
ctxHomePlugins, cancelHomePlugins := context.WithTimeout(context.Background(), 30*time.Second)
var errHomePlugins error
homePluginSyncReport, errHomePlugins = homeplugins.SyncWithReport(ctxHomePlugins, parsed, pluginHost)
cancelHomePlugins()
errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, homeCfg.NodeID, homePluginSyncReport)
if errHomePlugins != nil {
log.Errorf("failed to fetch plugins from home: %v", errHomePlugins)
}
if errReportPlugins != nil {
log.Warnf("failed to report home plugin sync status: %v", errReportPlugins)
}
if errHomePlugins != nil {
return
}
cfg = parsed
// Keep a non-empty config path for downstream components (log paths, management assets, etc),
// but do not require the file to exist when loading config from home.
if strings.TrimSpace(configPath) != "" {
configFilePath = configPath
} else {
configFilePath = filepath.Join(wd, "config.yaml")
}
// Local stores are intentionally disabled when config is loaded from home.
usePostgresStore = false
useObjectStore = false
useGitStore = false
} else if usePostgresStore {
if pgStoreLocalPath == "" {
pgStoreLocalPath = wd
}
@@ -223,13 +343,15 @@ func main() {
})
cancel()
if err != nil {
log.Fatalf("failed to initialize postgres token store: %v", err)
log.Errorf("failed to initialize postgres token store: %v", err)
return
}
examplePath := filepath.Join(wd, "config.example.yaml")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
if errBootstrap := pgStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
cancel()
log.Fatalf("failed to bootstrap postgres-backed config: %v", errBootstrap)
log.Errorf("failed to bootstrap postgres-backed config: %v", errBootstrap)
return
}
cancel()
configFilePath = pgStoreInst.ConfigPath()
@@ -252,7 +374,8 @@ func main() {
if strings.Contains(resolvedEndpoint, "://") {
parsed, errParse := url.Parse(resolvedEndpoint)
if errParse != nil {
log.Fatalf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse)
log.Errorf("failed to parse object store endpoint %q: %v", objectStoreEndpoint, errParse)
return
}
switch strings.ToLower(parsed.Scheme) {
case "http":
@@ -260,10 +383,12 @@ func main() {
case "https":
useSSL = true
default:
log.Fatalf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme)
log.Errorf("unsupported object store scheme %q (only http and https are allowed)", parsed.Scheme)
return
}
if parsed.Host == "" {
log.Fatalf("object store endpoint %q is missing host information", objectStoreEndpoint)
log.Errorf("object store endpoint %q is missing host information", objectStoreEndpoint)
return
}
resolvedEndpoint = parsed.Host
if parsed.Path != "" && parsed.Path != "/" {
@@ -282,13 +407,15 @@ func main() {
}
objectStoreInst, err = store.NewObjectTokenStore(objCfg)
if err != nil {
log.Fatalf("failed to initialize object token store: %v", err)
log.Errorf("failed to initialize object token store: %v", err)
return
}
examplePath := filepath.Join(wd, "config.example.yaml")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
if errBootstrap := objectStoreInst.Bootstrap(ctx, examplePath); errBootstrap != nil {
cancel()
log.Fatalf("failed to bootstrap object-backed config: %v", errBootstrap)
log.Errorf("failed to bootstrap object-backed config: %v", errBootstrap)
return
}
cancel()
configFilePath = objectStoreInst.ConfigPath()
@@ -310,10 +437,11 @@ func main() {
}
gitStoreRoot = filepath.Join(gitStoreLocalPath, "gitstore")
authDir := filepath.Join(gitStoreRoot, "auths")
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword)
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword, gitStoreBranch)
gitStoreInst.SetBaseDir(authDir)
if errRepo := gitStoreInst.EnsureRepository(); errRepo != nil {
log.Fatalf("failed to prepare git token store: %v", errRepo)
log.Errorf("failed to prepare git token store: %v", errRepo)
return
}
configFilePath = gitStoreInst.ConfigPath()
if configFilePath == "" {
@@ -322,17 +450,21 @@ func main() {
if _, statErr := os.Stat(configFilePath); errors.Is(statErr, fs.ErrNotExist) {
examplePath := filepath.Join(wd, "config.example.yaml")
if _, errExample := os.Stat(examplePath); errExample != nil {
log.Fatalf("failed to find template config file: %v", errExample)
log.Errorf("failed to find template config file: %v", errExample)
return
}
if errCopy := misc.CopyConfigTemplate(examplePath, configFilePath); errCopy != nil {
log.Fatalf("failed to bootstrap git-backed config: %v", errCopy)
log.Errorf("failed to bootstrap git-backed config: %v", errCopy)
return
}
if errCommit := gitStoreInst.PersistConfig(context.Background()); errCommit != nil {
log.Fatalf("failed to commit initial git-backed config: %v", errCommit)
log.Errorf("failed to commit initial git-backed config: %v", errCommit)
return
}
log.Infof("git-backed config initialized from template: %s", configFilePath)
} else if statErr != nil {
log.Fatalf("failed to inspect git-backed config: %v", statErr)
log.Errorf("failed to inspect git-backed config: %v", statErr)
return
}
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
if err == nil {
@@ -345,13 +477,15 @@ func main() {
} else {
wd, err = os.Getwd()
if err != nil {
log.Fatalf("failed to get working directory: %v", err)
log.Errorf("failed to get working directory: %v", err)
return
}
configFilePath = filepath.Join(wd, "config.yaml")
cfg, err = config.LoadConfigOptional(configFilePath, isCloudDeploy)
}
if err != nil {
log.Fatalf("failed to load config: %v", err)
log.Errorf("failed to load config: %v", err)
return
}
if cfg == nil {
cfg = &config.Config{}
@@ -360,37 +494,45 @@ func main() {
// In cloud deploy mode, check if we have a valid configuration
var configFileExists bool
if isCloudDeploy {
if info, errStat := os.Stat(configFilePath); errStat != nil {
// Don't mislead: API server will not start until configuration is provided.
log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration")
configFileExists = false
} else if info.IsDir() {
log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration")
configFileExists = false
} else if cfg.Port == 0 {
// LoadConfigOptional returns empty config when file is empty or invalid.
// Config file exists but is empty or invalid; treat as missing config
log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration")
configFileExists = false
if configLoadedFromHome && cfg != nil {
configFileExists = cfg.Port != 0
} else {
log.Info("Cloud deploy mode: Configuration file detected; starting service")
configFileExists = true
if info, errStat := os.Stat(configFilePath); errStat != nil {
// Don't mislead: API server will not start until configuration is provided.
log.Info("Cloud deploy mode: No configuration file detected; standing by for configuration")
configFileExists = false
} else if info.IsDir() {
log.Info("Cloud deploy mode: Config path is a directory; standing by for configuration")
configFileExists = false
} else if cfg.Port == 0 {
// LoadConfigOptional returns empty config when file is empty or invalid.
// Config file exists but is empty or invalid; treat as missing config
log.Info("Cloud deploy mode: Configuration file is empty or invalid; standing by for valid configuration")
configFileExists = false
} else {
log.Info("Cloud deploy mode: Configuration file detected; starting service")
configFileExists = true
}
}
}
usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled)
redisqueue.SetUsageStatisticsEnabled(cfg.UsageStatisticsEnabled)
redisqueue.SetRetentionSeconds(cfg.RedisUsageQueueRetentionSeconds)
coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
coreauth.SetTransientErrorCooldownSeconds(cfg.TransientErrorCooldownSeconds)
if err = logging.ConfigureLogOutput(cfg.LoggingToFile); err != nil {
log.Fatalf("failed to configure log output: %v", err)
if err = logging.ConfigureLogOutput(cfg); err != nil {
log.Errorf("failed to configure log output: %v", err)
return
}
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", Version, Commit, BuildDate)
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate)
// Set the log level based on the configuration.
util.SetLogLevel(cfg)
if resolvedAuthDir, errResolveAuthDir := util.ResolveAuthDir(cfg.AuthDir); errResolveAuthDir != nil {
log.Fatalf("failed to resolve auth directory: %v", errResolveAuthDir)
log.Errorf("failed to resolve auth directory: %v", errResolveAuthDir)
return
} else {
cfg.AuthDir = resolvedAuthDir
}
@@ -398,7 +540,18 @@ func main() {
// Create login options to be used in authentication flows.
options := &cmd.LoginOptions{
NoBrowser: noBrowser,
NoBrowser: noBrowser,
CallbackPort: oauthCallbackPort,
}
commandMode := vertexImport != "" || antigravityLogin || codexLogin || codexDeviceLogin || claudeLogin || kimiLogin || xaiLogin
cloudConfigMissing := isCloudDeploy && !configFileExists
homeMode := configLoadedFromHome || (cfg != nil && cfg.Home.Enabled)
if shouldStartExampleAPIKeyWarningServer(cfg, commandMode, tuiMode, standalone, cloudConfigMissing, homeMode) {
matches := safemode.ExampleAPIKeys(cfg.APIKeys)
log.WithField("api_keys", strings.Join(matches, ",")).Error("unsafe example API key configured; starting warning-only server")
cmd.StartExampleAPIKeyWarningServer(cfg, configFilePath, matches)
return
}
// Register the shared token store once so all components use the same persistence backend.
@@ -413,23 +566,51 @@ func main() {
}
// Register built-in access providers before constructing services.
configaccess.Register()
configaccess.Register(&cfg.SDKConfig)
pluginHost.ApplyConfig(context.Background(), cfg)
if configLoadedFromHome {
errHomePluginLoad := homeplugins.MarkLoadResults(&homePluginSyncReport, pluginHost)
errReportPlugins := home.ReportPluginStatus(context.Background(), homeClient, cfg.Home.NodeID, homePluginSyncReport)
if errHomePluginLoad != nil {
log.Errorf("failed to load home plugins: %v", errHomePluginLoad)
}
if errReportPlugins != nil {
log.Warnf("failed to report home plugin load status: %v", errReportPlugins)
}
if errHomePluginLoad != nil {
return
}
}
if pluginHost.HasTriggeredCommandLineFlags() {
if exitCode, handled := pluginHost.ExecuteCommandLine(context.Background(), os.Args[0], os.Args[1:], configFilePath, flag.CommandLine); handled {
if exitCode != 0 {
os.Exit(exitCode)
}
return
}
}
// Handle different command modes based on the provided flags.
if login {
// Handle Google/Gemini login
cmd.DoLogin(cfg, projectID, options)
if vertexImport != "" {
// Handle Vertex service account import
cmd.DoVertexImport(cfg, vertexImport, vertexImportPrefix)
} else if antigravityLogin {
// Handle Antigravity login
cmd.DoAntigravityLogin(cfg, options)
} else if codexLogin {
// Handle Codex login
cmd.DoCodexLogin(cfg, options)
} else if codexDeviceLogin {
// Handle Codex device-code login
cmd.DoCodexDeviceLogin(cfg, options)
} else if claudeLogin {
// Handle Claude login
cmd.DoClaudeLogin(cfg, options)
} else if qwenLogin {
cmd.DoQwenLogin(cfg, options)
} else if iflowLogin {
cmd.DoIFlowLogin(cfg, options)
} else if kimiLogin {
cmd.DoKimiLogin(cfg, options)
} else if xaiLogin {
cmd.DoXAILogin(cfg, options)
} else {
// In cloud deploy mode without config file, just wait for shutdown signals
if isCloudDeploy && !configFileExists {
@@ -437,8 +618,154 @@ func main() {
cmd.WaitForCloudDeploy()
return
}
// Start the main proxy service
managementasset.StartAutoUpdater(context.Background(), configFilePath)
cmd.StartService(cfg, configFilePath, password)
if localModel && (!tuiMode || standalone) {
log.Info("Local model mode: using embedded model catalog, remote model updates disabled")
}
if tuiMode {
if standalone {
// Standalone mode: start an embedded local server and connect TUI client to it.
managementasset.StartAutoUpdater(context.Background(), configFilePath)
misc.StartAntigravityVersionUpdater(context.Background())
if !localModel && !cfg.Home.Enabled {
registry.StartModelsUpdater(context.Background())
} else if cfg.Home.Enabled {
log.Info("Home mode: remote model updates disabled")
}
hook := tui.NewLogHook(2000)
hook.SetFormatter(&logging.LogFormatter{})
log.AddHook(hook)
origStdout := os.Stdout
origStderr := os.Stderr
origLogOutput := log.StandardLogger().Out
log.SetOutput(io.Discard)
devNull, errOpenDevNull := os.Open(os.DevNull)
if errOpenDevNull == nil {
os.Stdout = devNull
os.Stderr = devNull
}
restoreIO := func() {
os.Stdout = origStdout
os.Stderr = origStderr
log.SetOutput(origLogOutput)
if devNull != nil {
_ = devNull.Close()
}
}
localMgmtPassword := fmt.Sprintf("tui-%d-%d", os.Getpid(), time.Now().UnixNano())
if password == "" {
password = localMgmtPassword
}
cancel, done := cmd.StartServiceBackgroundWithPluginHost(cfg, configFilePath, password, pluginHost)
client := tui.NewClient(cfg.Port, password)
ready := false
backoff := 100 * time.Millisecond
for i := 0; i < 30; i++ {
if _, errGetConfig := client.GetConfig(); errGetConfig == nil {
ready = true
break
}
time.Sleep(backoff)
if backoff < time.Second {
backoff = time.Duration(float64(backoff) * 1.5)
}
}
if !ready {
restoreIO()
cancel()
<-done
fmt.Fprintf(os.Stderr, "TUI error: embedded server is not ready\n")
return
}
if errRun := tui.Run(cfg.Port, password, hook, origStdout); errRun != nil {
restoreIO()
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
} else {
restoreIO()
}
cancel()
<-done
} else {
// Default TUI mode: pure management client.
// The proxy server must already be running.
if errRun := tui.Run(cfg.Port, password, nil, os.Stdout); errRun != nil {
fmt.Fprintf(os.Stderr, "TUI error: %v\n", errRun)
}
}
} else {
// Start the main proxy service
managementasset.StartAutoUpdater(context.Background(), configFilePath)
misc.StartAntigravityVersionUpdater(context.Background())
if !localModel && !cfg.Home.Enabled {
registry.StartModelsUpdater(context.Background())
} else if cfg.Home.Enabled {
log.Info("Home mode: remote model updates disabled")
}
cmd.StartServiceWithPluginHost(cfg, configFilePath, password, pluginHost)
}
}
}
func pluginBootstrapConfigPath(args []string, defaultPath string) string {
for i := 0; i < len(args); i++ {
arg := args[i]
switch {
case arg == "--":
return defaultPluginBootstrapConfigPath(defaultPath)
case arg == "-config" || arg == "--config":
if i+1 < len(args) {
return args[i+1]
}
return defaultPluginBootstrapConfigPath(defaultPath)
case strings.HasPrefix(arg, "-config="):
return strings.TrimPrefix(arg, "-config=")
case strings.HasPrefix(arg, "--config="):
return strings.TrimPrefix(arg, "--config=")
}
}
return defaultPluginBootstrapConfigPath(defaultPath)
}
func defaultPluginBootstrapConfigPath(defaultPath string) string {
if strings.TrimSpace(defaultPath) != "" {
return defaultPath
}
wd, errGetwd := os.Getwd()
if errGetwd != nil {
return "config.yaml"
}
return filepath.Join(wd, "config.yaml")
}
func loadPluginBootstrapConfig(path string) *config.Config {
raw, errReadFile := os.ReadFile(path)
if errReadFile != nil {
if !errors.Is(errReadFile, os.ErrNotExist) {
log.Warnf("failed to read plugin bootstrap config: %v", errReadFile)
}
cfg := &config.Config{}
cfg.NormalizePluginsConfig()
return cfg
}
if len(strings.TrimSpace(string(raw))) == 0 {
cfg := &config.Config{}
cfg.NormalizePluginsConfig()
return cfg
}
cfg, errParseConfig := config.ParseConfigBytes(raw)
if errParseConfig != nil {
log.Warnf("failed to parse plugin bootstrap config: %v", errParseConfig)
cfg = &config.Config{}
cfg.NormalizePluginsConfig()
return cfg
}
return cfg
}
+89
View File
@@ -0,0 +1,89 @@
package main
import (
"testing"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
)
func TestShouldStartExampleAPIKeyWarningServer(t *testing.T) {
cfgWithExampleKey := &config.Config{
SDKConfig: config.SDKConfig{
APIKeys: []string{"real-key", " your-api-key-1 "},
},
}
cfgWithRealKey := &config.Config{
SDKConfig: config.SDKConfig{
APIKeys: []string{"real-key"},
},
}
tests := []struct {
name string
cfg *config.Config
commandMode bool
tuiMode bool
standalone bool
cloudConfigMissing bool
homeMode bool
want bool
}{
{
name: "normal server with example key",
cfg: cfgWithExampleKey,
want: true,
},
{
name: "standalone tui with example key",
cfg: cfgWithExampleKey,
tuiMode: true,
standalone: true,
want: true,
},
{
name: "pure tui client is not blocked",
cfg: cfgWithExampleKey,
tuiMode: true,
standalone: false,
commandMode: false,
want: false,
},
{
name: "one-shot command is not blocked",
cfg: cfgWithExampleKey,
commandMode: true,
want: false,
},
{
name: "home mode is not blocked",
cfg: cfgWithExampleKey,
homeMode: true,
want: false,
},
{
name: "cloud standby without config is not blocked",
cfg: cfgWithExampleKey,
cloudConfigMissing: true,
want: false,
},
{
name: "normal server with real key",
cfg: cfgWithRealKey,
want: false,
},
{
name: "nil config",
cfg: nil,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldStartExampleAPIKeyWarningServer(tt.cfg, tt.commandMode, tt.tuiMode, tt.standalone, tt.cloudConfigMissing, tt.homeMode)
if got != tt.want {
t.Fatalf("shouldStartExampleAPIKeyWarningServer() = %t, want %t", got, tt.want)
}
})
}
}
+13
View File
@@ -0,0 +1,13 @@
//go:build !windows
package main
// Service stubs for non-Windows platforms
func runService(configPath string) error {
return nil
}
func handleServiceCommand(args []string) bool {
return false
}
+353
View File
@@ -0,0 +1,353 @@
//go:build windows
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"
configaccess "github.com/router-for-me/CLIProxyAPI/v7/internal/access/config_access"
"github.com/router-for-me/CLIProxyAPI/v7/internal/config"
"github.com/router-for-me/CLIProxyAPI/v7/internal/logging"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v7/sdk/auth"
"github.com/router-for-me/CLIProxyAPI/v7/sdk/cliproxy"
)
const serviceName = "ProxyPilot"
const serviceDisplayName = "ProxyPilot API Proxy"
const serviceDescription = "Local API proxy for AI coding tools"
// proxyService implements svc.Handler
type proxyService struct {
configPath string
cancelFunc context.CancelFunc
}
func (s *proxyService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown
changes <- svc.Status{State: svc.StartPending}
// Initialize logging
logging.SetupBaseLogger()
// Load config
cfg, err := config.LoadConfigOptional(s.configPath, false)
if err != nil {
elog, _ := eventlog.Open(serviceName)
if elog != nil {
elog.Error(1, fmt.Sprintf("Failed to load config: %v", err))
elog.Close()
}
return
}
if cfg == nil {
cfg = &config.Config{Port: 8318}
}
// Configure logging
logging.ConfigureLogOutput(cfg)
// Register token store
sdkAuth.RegisterTokenStore(sdkAuth.NewFileTokenStore())
// Register access providers
configaccess.Register(&cfg.SDKConfig)
// Build and start service using builder pattern
builder := cliproxy.NewBuilder().
WithConfig(cfg).
WithConfigPath(s.configPath)
service, err := builder.Build()
if err != nil {
elog, _ := eventlog.Open(serviceName)
if elog != nil {
elog.Error(1, fmt.Sprintf("Failed to build service: %v", err))
elog.Close()
}
return
}
// Create context for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
s.cancelFunc = cancel
// Start service in background
go func() {
if err := service.Run(ctx); err != nil && err != context.Canceled {
elog, _ := eventlog.Open(serviceName)
if elog != nil {
elog.Error(1, fmt.Sprintf("Service error: %v", err))
elog.Close()
}
}
}()
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
// Wait for stop signal
for {
select {
case c := <-r:
switch c.Cmd {
case svc.Stop, svc.Shutdown:
changes <- svc.Status{State: svc.StopPending}
cancel()
return
case svc.Interrogate:
changes <- c.CurrentStatus
}
}
}
}
// runService starts the Windows service
func runService(configPath string) error {
elog, err := eventlog.Open(serviceName)
if err != nil {
return err
}
defer elog.Close()
elog.Info(1, fmt.Sprintf("Starting %s service", serviceName))
err = svc.Run(serviceName, &proxyService{configPath: configPath})
if err != nil {
elog.Error(1, fmt.Sprintf("Service failed: %v", err))
return err
}
elog.Info(1, fmt.Sprintf("%s service stopped", serviceName))
return nil
}
// installService installs ProxyPilot as a Windows service
func installService(configPath string) error {
exePath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
exePath = filepath.Clean(exePath)
m, err := mgr.Connect()
if err != nil {
return fmt.Errorf("failed to connect to service manager: %w", err)
}
defer m.Disconnect()
// Check if service exists
s, err := m.OpenService(serviceName)
if err == nil {
s.Close()
return fmt.Errorf("service %s already exists", serviceName)
}
// Build service arguments
args := []string{"-service"}
if configPath != "" {
args = append(args, "-config", configPath)
}
s, err = m.CreateService(serviceName, exePath, mgr.Config{
DisplayName: serviceDisplayName,
Description: serviceDescription,
StartType: mgr.StartAutomatic,
ErrorControl: mgr.ErrorNormal,
}, args...)
if err != nil {
return fmt.Errorf("failed to create service: %w", err)
}
defer s.Close()
// Set recovery options (restart on failure)
err = s.SetRecoveryActions([]mgr.RecoveryAction{
{Type: mgr.ServiceRestart, Delay: 5 * time.Second},
{Type: mgr.ServiceRestart, Delay: 30 * time.Second},
{Type: mgr.ServiceRestart, Delay: 60 * time.Second},
}, 86400) // Reset failure count after 24 hours
if err != nil {
// Non-fatal
}
// Install event log source
err = eventlog.InstallAsEventCreate(serviceName, eventlog.Error|eventlog.Warning|eventlog.Info)
if err != nil {
// Non-fatal, may already exist
}
fmt.Printf("Service %s installed successfully\n", serviceName)
return nil
}
// uninstallService removes the Windows service
func uninstallService() error {
m, err := mgr.Connect()
if err != nil {
return fmt.Errorf("failed to connect to service manager: %w", err)
}
defer m.Disconnect()
s, err := m.OpenService(serviceName)
if err != nil {
return fmt.Errorf("service %s not found: %w", serviceName, err)
}
defer s.Close()
// Stop the service if running
status, err := s.Query()
if err == nil && status.State != svc.Stopped {
_, _ = s.Control(svc.Stop)
// Wait for stop
for i := 0; i < 10; i++ {
time.Sleep(500 * time.Millisecond)
status, err = s.Query()
if err != nil || status.State == svc.Stopped {
break
}
}
}
err = s.Delete()
if err != nil {
return fmt.Errorf("failed to delete service: %w", err)
}
// Remove event log source
_ = eventlog.Remove(serviceName)
fmt.Printf("Service %s uninstalled successfully\n", serviceName)
return nil
}
// startService starts the Windows service
func startService() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(serviceName)
if err != nil {
return fmt.Errorf("service %s not found: %w", serviceName, err)
}
defer s.Close()
return s.Start()
}
// stopService stops the Windows service
func stopService() error {
m, err := mgr.Connect()
if err != nil {
return err
}
defer m.Disconnect()
s, err := m.OpenService(serviceName)
if err != nil {
return fmt.Errorf("service %s not found: %w", serviceName, err)
}
defer s.Close()
_, err = s.Control(svc.Stop)
return err
}
// serviceStatus returns the current service status
func serviceStatus() string {
m, err := mgr.Connect()
if err != nil {
return "unknown"
}
defer m.Disconnect()
s, err := m.OpenService(serviceName)
if err != nil {
return "not installed"
}
defer s.Close()
status, err := s.Query()
if err != nil {
return "unknown"
}
switch status.State {
case svc.Stopped:
return "stopped"
case svc.StartPending:
return "starting"
case svc.StopPending:
return "stopping"
case svc.Running:
return "running"
case svc.ContinuePending:
return "resuming"
case svc.PausePending:
return "pausing"
case svc.Paused:
return "paused"
default:
return "unknown"
}
}
// handleServiceCommand handles service-related CLI commands
func handleServiceCommand(args []string) bool {
if len(args) == 0 {
return false
}
cmd := strings.ToLower(args[0])
switch cmd {
case "install":
configPath := ""
if len(args) > 1 {
configPath = args[1]
}
if err := installService(configPath); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return true
case "uninstall", "remove":
if err := uninstallService(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
return true
case "start":
if err := startService(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println("Service started")
return true
case "stop":
if err := stopService(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println("Service stopped")
return true
case "status":
fmt.Printf("Service status: %s\n", serviceStatus())
return true
default:
return false
}
}
+40
View File
@@ -0,0 +1,40 @@
{
"FixedFileInfo": {
"FileVersion": {
"Major": 0,
"Minor": 3,
"Patch": 0,
"Build": 0
},
"ProductVersion": {
"Major": 0,
"Minor": 3,
"Patch": 0,
"Build": 0
},
"FileFlagsMask": "3f",
"FileFlags ": "00",
"FileOS": "040004",
"FileType": "01",
"FileSubType": "00"
},
"StringFileInfo": {
"Comments": "Local AI Proxy Engine",
"CompanyName": "ProxyPilot",
"FileDescription": "ProxyPilot Engine",
"FileVersion": "0.3.0",
"InternalName": "proxypilot-engine",
"LegalCopyright": "MIT License",
"OriginalFilename": "proxypilot-engine.exe",
"ProductName": "ProxyPilot",
"ProductVersion": "0.3.0"
},
"VarFileInfo": {
"Translation": {
"LangID": "0409",
"CharsetID": "04B0"
}
},
"IconPath": "../../static/icon.ico",
"ManifestPath": ""
}
+413 -40
View File
@@ -1,6 +1,16 @@
# Server host/interface to bind to. Default is empty ("") to bind all interfaces (IPv4 + IPv6).
# Use "127.0.0.1" or "localhost" to restrict access to local machine only.
host: ""
# Server port
port: 8317
# TLS settings for HTTPS. When enabled, the server listens with the provided certificate and key.
tls:
enable: false
cert: ""
key: ""
# Management API settings
remote-management:
# Whether to allow remote (non-localhost) management access.
@@ -15,6 +25,13 @@ remote-management:
# Disable the bundled management control panel asset download and HTTP route when true.
disable-control-panel: false
# Disable automatic periodic background updates of the management panel from GitHub (default: false).
# When enabled, the panel is only downloaded on first access if missing, and never auto-updated afterward.
# disable-auto-update-panel: false
# GitHub repository for the management control panel. Accepts a repository URL or releases API URL.
panel-github-repository: "https://github.com/router-for-me/Cli-Proxy-API-Management-Center"
# Authentication directory (supports ~ for home directory)
auth-dir: "~/.cli-proxy-api"
@@ -22,73 +39,429 @@ auth-dir: "~/.cli-proxy-api"
api-keys:
- "your-api-key-1"
- "your-api-key-2"
- "your-api-key-3"
# Enable debug logging
debug: false
# Enable pprof HTTP debug server (host:port). Keep it bound to localhost for safety.
pprof:
enable: false
addr: "127.0.0.1:8316"
# Standard dynamic library plugins are trusted in-process code. They are disabled by default.
# Build Go examples with go build -buildmode=c-shared for the target GOOS/GOARCH.
# Other languages can implement the same C ABI and JSON method protocol.
# Plugin executors require a matching auth record with the same provider key.
# If the same provider is configured as OpenAI-compatible, the native executor wins.
# Plugin command-line flags and Management API routes are optional capabilities.
# Existing native flags/routes and higher-priority plugin flags/routes cannot be replaced.
# Plugin list Management API reads Logo and ConfigFields from plugin metadata for management UI display.
# Per-plugin enabled only controls plugins.configs.<pluginID>.enabled and does not implicitly change global plugins.enabled.
plugins:
enabled: false
dir: "plugins"
# Additional plugin store registries. The built-in official registry is always included.
# store-sources:
# - "https://example.com/cliproxy-plugins/registry.json"
configs:
example:
enabled: true
priority: 1
config1: true
config2: "string"
config3: 3
mode: "safe" # enum example: safe, fast
# When true, disable high-overhead request logging and HTTP middleware features to reduce per-request memory usage under high concurrency.
commercial-mode: false
# When true, write application logs to rotating files instead of stdout
logging-to-file: false
# Maximum total size (MB) of log files under the logs directory. When exceeded, the oldest log
# files are deleted until within the limit. Set to 0 to disable.
logs-max-total-size-mb: 0
# Maximum number of error log files retained when request logging is disabled.
# When exceeded, the oldest error log files are deleted. Default is 10. Set to 0 to disable cleanup.
error-logs-max-files: 10
# When false, disable in-memory usage statistics aggregation
usage-statistics-enabled: false
# How long (in seconds) usage queue items are retained in memory for the Management API.
# The local Redis RESP usage output is disabled.
# Default: 60. Max: 3600.
redis-usage-queue-retention-seconds: 60
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
# Per-entry proxy-url also supports "direct" or "none" to bypass both the global proxy-url and environment proxies explicitly.
proxy-url: ""
# When true, unprefixed model requests only use credentials without a prefix (except when prefix == model name).
force-model-prefix: false
# When true, forward filtered upstream response headers to downstream clients.
# Default is false (disabled).
passthrough-headers: false
# Number of times to retry a request. Retries will occur if the HTTP response code is 403, 408, 500, 502, 503, or 504.
request-retry: 3
# Maximum number of different credentials to try for one failed request.
# Set to 0 to keep legacy behavior (try all available credentials).
max-retry-credentials: 0
# Maximum wait time in seconds for a cooled-down credential before triggering a retry.
max-retry-interval: 30
# When true, disable auth/model cooldown scheduling globally (prevents blackout windows after failure states).
disable-cooling: false
# When true, persist per-auth cooldown status as .cds files next to auth files.
# Default is false; when false, cooldown status is kept in memory only.
save-cooldown-status: false
# Cooldown duration in seconds for transient upstream errors (408/500/502/503/504).
# Set to 0 to keep the legacy 60-second cooldown; set to -1 to disable transient error cooldowns.
transient-error-cooldown-seconds: 0
# When true, globally disable Claude request cloaking (the Claude Code CLI disguise and
# system prompt replacement), so the original system prompt is passed through to Claude as-is.
# Individual credentials can still override this: a claude-api-key entry via its "cloak.mode",
# or a Claude OAuth/token file via a "cloak_mode" value. Default false keeps the per-client
# "auto" behavior (cloak only non-Claude-Code clients).
disable-claude-cloak-mode: false
# disable-image-generation supports: false (default), true, "chat", or "passthrough".
# - true: disable image_generation everywhere (also returns 404 for /v1/images/generations and /v1/images/edits).
# - "chat": disable image_generation injection on non-images endpoints, but keep /v1/images/generations and /v1/images/edits enabled.
# - "passthrough": never inject or strip image_generation on non-images endpoints (forward the client payload unchanged); behaves like "chat" on /v1/images/* endpoints.
disable-image-generation: false
# Base model used by the legacy hosted image_generation tool path when a Codex image request is not proxied directly through the Image API.
# Must start with "gpt-" (case-insensitive). If unset or invalid, defaults to "gpt-5.4-mini".
# gpt-image-2-base-model: "gpt-5.4-mini"
# How long video IDs returned by /openai/v1/videos and xAI video creation stay bound
# to the credential that created them. Default: 3h.
video-result-auth-cache-ttl: "3h"
# Core auth auto-refresh worker pool size (OAuth/file-based auth token refresh).
# When > 0, overrides the default worker count (16).
# auth-auto-refresh-workers: 16
# Quota exceeded behavior
quota-exceeded:
switch-project: true # Whether to automatically switch to another project when a quota is exceeded
switch-preview-model: true # Whether to automatically switch to a preview model when a quota is exceeded
antigravity-credits: true # Whether to use credits as last-resort fallback when all free-tier auths are exhausted for Claude models
# Routing strategy for selecting credentials when multiple match.
routing:
strategy: "round-robin" # round-robin (default), fill-first
# Enable universal session-sticky routing for all clients.
# Session IDs are extracted from: metadata.user_id (Claude Code session format),
# X-Session-ID, Session_id (Codex), X-Client-Request-Id (PI), conversation_id,
# or first few messages hash.
# Automatic failover is always enabled when bound auth becomes unavailable.
session-affinity: false # default: false
# How long session-to-auth bindings are retained. Default: 1h
session-affinity-ttl: "1h"
# Codex provider behavior.
codex:
# When true, and routing.strategy is fill-first or routing.session-affinity is true,
# remap Codex prompt_cache_key and installation identity per selected auth.
# Some superstitious users believe request tracking identifiers can be used
# as evidence for TOS enforcement bans; this option only satisfies those odd concerns.
identity-confuse: false
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
ws-auth: true
# Gemini API keys (preferred)
#gemini-api-key:
# - api-key: "AIzaSy...01"
# # base-url: "https://generativelanguage.googleapis.com"
# # headers:
# # X-Custom-Header: "custom-value"
# # proxy-url: "socks5://proxy.example.com:1080"
# - api-key: "AIzaSy...02"
# When > 0, emit blank lines every N seconds for non-streaming responses to prevent idle timeouts.
nonstream-keepalive-interval: 0
# Streaming behavior (SSE keep-alives + safe bootstrap retries).
# streaming:
# keepalive-seconds: 15 # Default: 0 (disabled). <= 0 disables keep-alives.
# bootstrap-retries: 1 # Default: 0 (disabled). Retries before first byte is sent.
# API keys for official Generative Language API (legacy compatibility)
#generative-language-api-key:
# - "AIzaSy...01"
# - "AIzaSy...02"
# Signature cache validation for thinking blocks (Antigravity/Claude).
# When true (default), cached signatures are preferred and validated.
# When false, client signatures are used directly after normalization (bypass mode for testing).
# antigravity-signature-cache-enabled: true
# Bypass mode signature validation strictness (only applies when signature cache is disabled).
# When true, validates full Claude protobuf tree (Field 2 -> Field 1 structure).
# When false (default), only checks R/E prefix + base64 + first byte 0x12.
# antigravity-signature-bypass-strict: false
# Gemini API keys
# gemini-api-key:
# - api-key: "AIzaSy...01"
# prefix: "test" # optional: require calls like "test/gemini-3-pro-preview" to target this credential
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
# base-url: "https://generativelanguage.googleapis.com"
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080"
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "gemini-2.5-flash" # upstream model name
# alias: "gemini-flash" # client alias mapped to the upstream model
# excluded-models:
# - "gemini-2.5-pro" # exclude specific models from this provider (exact match)
# - "gemini-2.5-*" # wildcard matching prefix (e.g. gemini-2.5-flash, gemini-2.5-pro)
# - "*-preview" # wildcard matching suffix (e.g. gemini-3-pro-preview)
# - "*flash*" # wildcard matching substring (e.g. gemini-2.5-flash-lite)
# - api-key: "AIzaSy...02"
# Codex API keys
#codex-api-key:
# - api-key: "sk-atSM..."
# base-url: "https://www.example.com" # use the custom codex API endpoint
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# codex-api-key:
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/gpt-5-codex" to target this credential
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
# base-url: "https://www.example.com" # use the custom codex API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "gpt-5-codex" # upstream model name
# alias: "codex-latest" # client alias mapped to the upstream model
# excluded-models:
# - "gpt-5.1" # exclude specific models (exact match)
# - "gpt-5-*" # wildcard matching prefix (e.g. gpt-5-medium, gpt-5-codex)
# - "*-mini" # wildcard matching suffix (e.g. gpt-5-codex-mini)
# - "*codex*" # wildcard matching substring (e.g. gpt-5-codex-low)
# Claude API keys
#claude-api-key:
# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url
# - api-key: "sk-atSM..."
# base-url: "https://www.example.com" # use the custom claude API endpoint
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# models:
# - name: "claude-3-5-sonnet-20241022" # upstream model name
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
# claude-api-key:
# - api-key: "sk-atSM..." # use the official claude API key, no need to set the base url
# - api-key: "sk-atSM..."
# prefix: "test" # optional: require calls like "test/claude-sonnet-latest" to target this credential
# disable-cooling: false # optional: per-auth override for auth/model cooldown scheduling
# base-url: "https://www.example.com" # use the custom claude API endpoint
# headers:
# X-Custom-Header: "custom-value"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# models:
# - name: "claude-3-5-sonnet-20241022" # upstream model name
# alias: "claude-sonnet-latest" # client alias mapped to the upstream model
# excluded-models:
# - "claude-opus-4-5-20251101" # exclude specific models (exact match)
# - "claude-3-*" # wildcard matching prefix (e.g. claude-3-7-sonnet-20250219)
# - "*-thinking" # wildcard matching suffix (e.g. claude-opus-4-5-thinking)
# - "*haiku*" # wildcard matching substring (e.g. claude-3-5-haiku-20241022)
# rebuild-mid-system-message: false # optional: default is false; when true, move messages with role "system" into the top-level Claude system field
# cloak: # optional: request cloaking for non-Claude-Code clients
# mode: "auto" # "auto" (default): cloak only when client is not Claude Code
# # "always": always apply cloaking
# # "never": never apply cloaking
# # This "cloak" block applies to this claude-api-key entry only. For Claude OAuth
# # credentials, set the same options in the auth/token JSON file via "cloak_mode" /
# # "cloak_strict_mode" / "cloak_sensitive_words" / "cloak_cache_user_id". The top-level
# # "disable-claude-cloak-mode: true" disables cloaking for all Claude credentials at once.
# strict-mode: false # false (default): prepend Claude Code prompt to user system messages
# # true: strip all user system messages, keep only Claude Code prompt
# sensitive-words: # optional: words to obfuscate with zero-width characters
# - "API"
# - "proxy"
# cache-user-id: true # optional: default is false; set true to reuse cached user_id per API key instead of generating a random one each request
# experimental-cch-signing: false # optional: default is false; when true, sign the final /v1/messages body using the current Claude Code cch algorithm
# # keep this disabled unless you explicitly need the behavior, so upstream seed changes fall back to legacy proxy behavior
# Default headers for Claude API requests. Update when Claude Code releases new versions.
# In legacy mode, user-agent/package-version/runtime-version/timeout are used as fallbacks
# when the client omits them, while OS/arch remain runtime-derived. When
# stabilize-device-profile is enabled, OS/arch stay pinned to the baseline values below,
# while user-agent/package-version/runtime-version seed a software fingerprint that can
# still upgrade to newer official Claude client versions.
# claude-header-defaults:
# user-agent: "claude-cli/2.1.44 (external, sdk-cli)"
# package-version: "0.74.0"
# runtime-version: "v24.3.0"
# os: "MacOS"
# arch: "arm64"
# timeout: "600"
# stabilize-device-profile: false # optional, default false; set true to enable per-auth/API-key fingerprint pinning
# Default headers for Codex OAuth model requests.
# These are used only for file-backed/OAuth Codex requests when the client
# does not send the header. `user-agent` applies to HTTP and websocket requests;
# `beta-features` only applies to websocket requests. They do not apply to codex-api-key entries.
# codex-header-defaults:
# user-agent: "codex_cli_rs/0.114.0 (Mac OS 14.2.0; x86_64) vscode/1.111.0"
# beta-features: "multi_agent"
# OpenAI compatibility providers
#openai-compatibility:
# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.
# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.
# # New format with per-key proxy support (recommended):
# api-key-entries:
# - api-key: "sk-or-v1-...b780"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# - api-key: "sk-or-v1-...b781" # without proxy-url
# # Legacy format (still supported, but cannot specify proxy per key):
# # api-keys:
# # - "sk-or-v1-...b780"
# # - "sk-or-v1-...b781"
# models: # The models supported by the provider.
# - name: "moonshotai/kimi-k2:free" # The actual model name.
# alias: "kimi-k2" # The alias used in the API.
# openai-compatibility:
# - name: "openrouter" # The name of the provider; it will be used in the user agent and other places.
# disabled: false # optional: set to true to disable this provider without removing it
# prefix: "test" # optional: require calls like "test/kimi-k2" to target this provider's credentials
# base-url: "https://openrouter.ai/api/v1" # The base URL of the provider.
# disable-cooling: false # optional: per-provider override for auth/model cooldown scheduling
# headers:
# X-Custom-Header: "custom-value"
# api-key-entries:
# - api-key: "sk-or-v1-...b780"
# proxy-url: "socks5://proxy.example.com:1080" # optional: per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# - api-key: "sk-or-v1-...b781" # without proxy-url
# models: # The models supported by the provider.
# - name: "moonshotai/kimi-k2:free" # The actual model name.
# alias: "kimi-k2" # The alias used in the API.
# image: false # optional: set true to allow this model on /v1/images/generations and /v1/images/edits
# thinking: # optional: omit to default to levels ["low","medium","high"]
# levels: ["low", "medium", "high"]
# # You may repeat the same alias to build an internal model pool.
# # The client still sees only one alias in the model list.
# # Requests to that alias will round-robin across the upstream names below,
# # and if the chosen upstream fails before producing output, the request will
# # continue with the next upstream model in the same alias pool.
# - name: "deepseek-v3.1"
# alias: "claude-opus-4.66"
# - name: "glm-5"
# alias: "claude-opus-4.66"
# - name: "kimi-k2.5"
# alias: "claude-opus-4.66"
# Vertex API keys (Vertex-compatible endpoints, base-url is optional)
# vertex-api-key:
# - api-key: "vk-123..." # x-goog-api-key header
# prefix: "test" # optional: require calls like "test/vertex-pro" to target this credential
# base-url: "https://example.com/api" # optional, e.g. https://zenmux.ai/api; falls back to Google Vertex when omitted
# proxy-url: "socks5://proxy.example.com:1080" # optional per-key proxy override
# # proxy-url: "direct" # optional: explicit direct connect for this credential
# headers:
# X-Custom-Header: "custom-value"
# models: # optional: map aliases to upstream model names
# - name: "gemini-2.5-flash" # upstream model name
# alias: "vertex-flash" # client-visible alias
# - name: "gemini-2.5-pro"
# alias: "vertex-pro"
# excluded-models: # optional: models to exclude from listing
# - "imagen-3.0-generate-002"
# - "imagen-*"
# Global OAuth model name aliases (per channel)
# These aliases rename model IDs for both model listing and request routing.
# Supported channels: vertex, aistudio, antigravity, claude, codex, kimi, xai.
# NOTE: Aliases do not apply to gemini-api-key, codex-api-key, claude-api-key, openai-compatibility, or vertex-api-key.
# NOTE: Because aliases affect the merged /v1 model list and merged request routing, overlapping
# client-visible names can become ambiguous across providers. For strict backend pinning, use
# unique aliases/prefixes or avoid overlapping names.
# You can repeat the same name with different aliases to expose multiple client model names.
# Optional per-entry flags:
# fork: true # keep the upstream model and also expose the alias as a separate client-visible model
# force-mapping: true # optional: rewrite upstream response model fields back to the client-visible alias (example below uses antigravity only)
# Per-auth OAuth aliases can also be stored in an OAuth auth JSON file as "model-aliases".
# They apply only to that selected auth and take precedence over global aliases for the same client-visible alias.
# Example auth JSON:
# {
# "type": "codex",
# "email": "user@example.com",
# "model-aliases": [
# {"name": "gpt-5.3-codex-spark", "alias": "gpt-5.5"},
# {"name": "gpt-5.3-codex-spark", "alias": "gpt-5.4"}
# ]
# }
# oauth-model-alias:
# vertex:
# - name: "gemini-2.5-pro"
# alias: "g2.5p"
# aistudio:
# - name: "gemini-2.5-pro"
# alias: "g2.5p"
# antigravity:
# - name: "gemini-pro-agent" # upstream Antigravity model id
# alias: "gemini-3.1-pro-preview" # client-visible id (Gemini 3.1 Pro Preview)
# fork: true
# force-mapping: true
# claude:
# - name: "claude-sonnet-4-5-20250929"
# alias: "cs4.5"
# codex:
# - name: "gpt-5"
# alias: "g5"
# kimi:
# - name: "kimi-k2.5"
# alias: "k2.5"
# xai:
# - name: "grok-4.3"
# alias: "grok-latest"
# sample-provider: # plugin provider keys are supported for OAuth plugins
# - name: "sample-model-latest"
# alias: "sample-latest"
# OAuth provider excluded models
# oauth-excluded-models:
# vertex:
# - "gemini-3-pro-preview"
# aistudio:
# - "gemini-3-pro-preview"
# antigravity:
# - "gemini-3-pro-preview"
# claude:
# - "claude-3-5-haiku-20241022"
# codex:
# - "gpt-5-codex-mini"
# kimi:
# - "kimi-k2-thinking"
# xai:
# - "grok-3-mini"
# Optional payload configuration
# payload:
# default: # Default rules only set parameters when they are missing in the payload.
# - models:
# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")
# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity
# from-protocol: "responses" # restricts the rule to the source protocol, options: openai, responses, gemini, claude
# headers: # all configured request headers must match; values support "*" wildcards
# X-Client-Tier: "tenant-*-region-*"
# match: # all payload JSON paths must equal the configured values
# - "metadata.client": "codex"
# not-match: # payload JSON paths must not equal the configured values
# - "metadata.mode": "dev"
# exist: # all payload JSON paths must exist and not be null
# - "tools.#(type==\"web_search\").type"
# not-exist: # all payload JSON paths must be missing or null
# - "metadata.disable_payload"
# params: # JSON path (gjson/sjson syntax) -> value
# "generationConfig.thinkingConfig.thinkingBudget": 32768
# default-raw: # Default raw rules set parameters using raw JSON when missing (must be valid JSON).
# - models:
# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")
# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity
# params: # JSON path (gjson/sjson syntax) -> raw JSON value (strings are used as-is, must be valid JSON)
# "generationConfig.responseJsonSchema": "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}}}"
# override: # Override rules always set parameters, overwriting any existing values.
# - models:
# - name: "gpt-5.4-fast"
# protocol: "codex"
# - name: "gpt-5.5-fast"
# protocol: "codex"
# params:
# service_tier: priority
# - models:
# - name: "gpt-*" # Supports wildcards (e.g., "gpt-*")
# protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity
# params: # JSON path (gjson/sjson syntax) -> value
# "reasoning.effort": "high"
# override-raw: # Override raw rules always set parameters using raw JSON (must be valid JSON).
# - models:
# - name: "gpt-*" # Supports wildcards (e.g., "gpt-*")
# protocol: "codex" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity
# params: # JSON path (gjson/sjson syntax) -> raw JSON value (strings are used as-is, must be valid JSON)
# "response_format": "{\"type\":\"json_schema\",\"json_schema\":{\"name\":\"answer\",\"schema\":{\"type\":\"object\"}}}"
# filter: # Filter rules remove specified parameters from the payload.
# - models:
# - name: "gemini-2.5-pro" # Supports wildcards (e.g., "gemini-*")
# protocol: "gemini" # restricts the rule to a specific protocol, options: openai, gemini, claude, codex, antigravity
# params: # JSON paths (gjson/sjson syntax) to remove from the payload
# - "generationConfig.thinkingConfig.thinkingBudget"
# - "generationConfig.responseJsonSchema"
+29
View File
@@ -0,0 +1,29 @@
services:
cli-proxy-api:
image: ${CLI_PROXY_IMAGE:-eceasy/cli-proxy-api:latest}
pull_policy: always
build:
context: .
dockerfile: Dockerfile
args:
VERSION: ${VERSION:-dev}
COMMIT: ${COMMIT:-none}
BUILD_DATE: ${BUILD_DATE:-unknown}
container_name: cli-proxy-api-cluster
environment:
HOME_JWT: ${HOME_JWT:-}
ports:
- "8317:8317"
volumes:
- ./home:/root/.cli-proxy-api
- ./logs:/CLIProxyAPI/logs
command: >
sh -eu -c '
if [ -z "$$HOME_JWT" ]; then
echo "HOME_JWT is required" >&2
exit 1
fi
exec ./CLIProxyAPI -home-jwt "$$HOME_JWT"
'
restart: unless-stopped
+9 -8
View File
@@ -1,6 +1,6 @@
services:
cli-proxy-api:
image: ${CLI_PROXY_IMAGE:-eceasy/cli-proxy-api:latest}
image: ${CLI_PROXY_IMAGE:-eceasy/cli-proxy-api-plus:latest}
pull_policy: always
build:
context: .
@@ -9,7 +9,7 @@ services:
VERSION: ${VERSION:-dev}
COMMIT: ${COMMIT:-none}
BUILD_DATE: ${BUILD_DATE:-unknown}
container_name: cli-proxy-api
container_name: cli-proxy-api-plus
# env_file:
# - .env
environment:
@@ -17,11 +17,12 @@ services:
ports:
- "8317:8317"
- "8085:8085"
- "1455:1455"
- "54545:54545"
- "11451:11451"
- "127.0.0.1:1455:1455"
- "127.0.0.1:54545:54545"
- "127.0.0.1:51121:51121"
- "127.0.0.1:11451:11451"
volumes:
- ./config.yaml:/CLIProxyAPI/config.yaml
- ./auths:/root/.cli-proxy-api
- ./logs:/CLIProxyAPI/logs
- ${CLI_PROXY_CONFIG_PATH:-./config.yaml}:/ProxyPilot/config.yaml
- ${CLI_PROXY_AUTH_PATH:-./auths}:/root/.cli-proxy-api
- ${CLI_PROXY_LOG_PATH:-./logs}:/ProxyPilot/logs
restart: unless-stopped
+64
View File
@@ -0,0 +1,64 @@
# Agentic Harness Demo (ProxyPilot)
This is a static, copy-paste demo showing how the middleware rewrites requests.
## Responses API (Codex CLI style)
Input:
```json
{
"model": "gpt-5-codex",
"instructions": "Follow the user's request.",
"input": [
{ "role": "user", "content": [{ "type": "input_text", "text": "Build a todo app" }] }
]
}
```
Injected (INITIALIZER mode):
```json
{
"model": "gpt-5-codex",
"instructions": "Follow the user's request.\n\n<harness_mode>INITIALIZER</harness_mode>\nYou are the **Initializer Agent** in a Long-Running Agent Harness.\nYour ONLY goal is to set up the project environment for future Coding Agents.\n\n**CRITICAL INSTRUCTIONS**:\n1. **Analyze the User's Request**: Understand what feature or app needs to be built.\n2. **Create 'feature_list.json'**:\n - Write a JSON file listing ALL features/requirements as separate items.\n - Mark them all as \"passes\": false.\n - Format:\n Request: \"Build a todo app\"\n File Content:\n [\n { \"category\": \"core\", \"description\": \"User can add a todo\", \"steps\": [\"Open app\", \"Enter text\", \"Press enter\", \"See new item\"], \"passes\": false },\n { \"category\": \"core\", \"description\": \"User can delete a todo\", \"steps\": [\"Open app\", \"Click delete\", \"Item removed\"], \"passes\": false }\n ]\n3. **Create 'claude-progress.txt'**:\n - Create this file with a header \"## Progress Log\".\n - Add an initial entry: \"- [Initializer] Environment setup started.\"\n4. **Create 'init.sh' (Optional)**:\n - If a dev server is needed, create a script to start it (e.g., 'npm run dev').\n5. **Initial Commit**:\n - Initialize git if not present.\n - Commit these foundational files.\n\n**DO NOT** start implementing features yourself. Your job is ONLY to scaffold the harness.",
"input": [
{ "role": "user", "content": [{ "type": "input_text", "text": "Build a todo app" }] }
]
}
```
## Chat Completions (Claude / OAI chat)
Input:
```json
{
"model": "claude-sonnet-4-5-thinking",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "Set up the repo" }
]
}
```
Injected (INITIALIZER mode):
```json
{
"model": "claude-sonnet-4-5-thinking",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant.\n\n<harness_mode>INITIALIZER</harness_mode>\nYou are the **Initializer Agent** in a Long-Running Agent Harness.\nYour ONLY goal is to set up the project environment for future Coding Agents.\n\n**CRITICAL INSTRUCTIONS**:\n... (same initializer prompt) ..."
},
{ "role": "user", "content": "Set up the repo" }
]
}
```
## CODING mode trigger
If `feature_list.json` or `claude-progress.txt` exists under `harness-root-dir`,
the middleware switches to CODING mode and injects the Coding prompt instead.
The response header will include:
```
X-ProxyPilot-Harness-Mode: CODING
```
+108
View File
@@ -0,0 +1,108 @@
# Claude Code via CLIProxyAPI (local proxy)
This documents how to route Claude Code through CLIProxyAPI, and the related server changes made to improve model aliasing and auth error reporting.
## What we configured (Windows/macOS)
1. Run CLIProxyAPI locally (default in this repo uses `127.0.0.1:8318`).
2. Point Claude Code at the local proxy by setting Anthropic environment variables in your Claude Code user settings.
Claude Code reads settings from:
- Windows: `C:\Users\<you>\.claude\settings.json`
- macOS/Linux: `~/.claude/settings.json`
Example:
```json
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8318",
"ANTHROPIC_AUTH_TOKEN": "local-dev-key",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "gemini-3-pro-preview",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "antigravity-claude-sonnet-4-5-thinking",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "antigravity-claude-opus-4-5-thinking"
},
"model": "opus"
}
```
Important:
- Avoid Claude Code “Auth conflict”: do **not** set both `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the same time.
- Restart Claude Code after editing settings so the new env vars take effect.
## Account risk warning
Claude/Anthropic OAuth, Google/Gemini OAuth, Gemini CLI OAuth, and Antigravity OAuth are unofficial compatibility paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension.
Do not use production, billing-critical, school/work, or irreplaceable personal accounts with these OAuth paths unless you accept that risk. Prefer official API keys or officially supported developer access for important accounts.
## Claude OAuth quota limitation
Anthropic currently treats third-party app traffic differently from regular Claude.ai or Claude Code subscription usage. If a Claude OAuth request fails with:
```text
Third-party apps now draw from your extra usage, not your plan limits.
Add more at claude.ai/settings/usage and keep going.
```
that response is coming from Anthropic, not ProxyPilot. It means the OAuth credential is valid, but Anthropic is requiring paid extra usage for this third-party API path. ProxyPilot cannot make those requests draw from normal Claude.ai subscription quota.
For Claude through ProxyPilot, either add extra usage in Anthropic settings, use a supported API-key billing path, or route the client to another provider/model alias such as Antigravity, Codex, Gemini, or Kiro.
## Server-side model aliasing (Claude handler)
CLIProxyAPI rewrites common Claude Code model aliases to locally-available models before routing:
- `opus` / `claude-opus-*` → `antigravity-claude-opus-4-5-thinking`
- `sonnet` / `claude-sonnet-*` → `antigravity-claude-sonnet-4-5-thinking`
- `haiku` / `claude-haiku-*` → `gemini-3-pro-preview`
Implementation: `sdk/api/handlers/claude/code_handlers.go` (`mapClaudeCodeModel`).
## Auth error reporting improvements
When all credentials are blocked for a model, CLIProxyAPI now reports more informative HTTP statuses:
- Quota/rate cooldown: `429` with `code: model_cooldown` and `Retry-After`
- Temporarily blocked credentials (non-quota): `503` with `code: auth_unavailable`, `Retry-After`, and a JSON error body including blocked counts and recent upstream HTTP statuses (when known)
Implementation: `sdk/cliproxy/auth/selector.go`, `sdk/cliproxy/auth/manager.go`.
## Quick sanity checks
List models as Claude Code would see them:
```powershell
$hdr=@{ 'User-Agent'='claude-cli'; 'Authorization'='Bearer local-dev-key' }
Invoke-RestMethod -Headers $hdr -Uri 'http://127.0.0.1:8318/v1/models' -Method Get
```
Or with `curl` (macOS/Linux):
```bash
curl -s \
-H 'User-Agent: claude-cli' \
-H 'Authorization: Bearer local-dev-key' \
'http://127.0.0.1:8318/v1/models'
```
Send a minimal Claude Messages request through the proxy:
```powershell
$hdr=@{ 'User-Agent'='claude-cli'; 'Authorization'='Bearer local-dev-key'; 'Content-Type'='application/json' }
$body=@{ model='opus'; max_tokens=16; stream=$false; messages=@(@{ role='user'; content='hi' }) } | ConvertTo-Json -Depth 6
Invoke-RestMethod -Headers $hdr -Uri 'http://127.0.0.1:8318/v1/messages' -Method Post -Body $body
```
Or with `curl` (macOS/Linux):
```bash
curl -s \
-H 'User-Agent: claude-cli' \
-H 'Authorization: Bearer local-dev-key' \
-H 'Content-Type: application/json' \
-d '{"model":"opus","max_tokens":16,"stream":false,"messages":[{"role":"user","content":"hi"}]}' \
'http://127.0.0.1:8318/v1/messages'
```
+334
View File
@@ -0,0 +1,334 @@
# ProxyPilot CLI
**proxypilot** is the unified command-line interface for the ProxyPilot local AI proxy. It provides both **server** functionality (running the proxy server) and **switch** functionality (toggling AI agents between proxy mode and native mode).
## Installation
### Via bun (recommended)
```bash
bun install -g proxypilot
```
### Via npm
```bash
npm install -g proxypilot
```
### Via Go
```bash
go install github.com/Finesssee/ProxyPilot/cmd/server@latest
```
### Manual Download
Download pre-built binaries from [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases).
Available binaries:
- `proxypilot-darwin-amd64` - macOS Intel
- `proxypilot-darwin-arm64` - macOS Apple Silicon
- `proxypilot-linux-amd64` - Linux x64
- `proxypilot-linux-arm64` - Linux ARM64
- `proxypilot-windows-amd64.exe` - Windows x64
## Server Mode
Run ProxyPilot as a local proxy server:
```bash
proxypilot # Start server on default port (8317)
proxypilot -config /path/to/config # Use custom config file
```
### Server Features
- Routes AI requests through configured providers
- Automatic model aliasing and translation
- OAuth login helpers for various providers
- Agent configuration management
### Login Commands
```bash
proxypilot --login # Login to Google Account (Gemini)
proxypilot --codex-login # Login to Codex using OAuth
proxypilot --claude-login # Login to Claude using OAuth
proxypilot --qwen-login # Login to Qwen using OAuth
proxypilot --antigravity-login # Login to Antigravity using OAuth
proxypilot --kiro-login # Login to Kiro using AWS Builder ID
proxypilot --kiro-aws-login # Login to Kiro using AWS Builder ID device code
proxypilot --minimax-login # Add MiniMax API key
proxypilot --zhipu-login # Add Zhipu AI API key
```
Account risk warning: `--claude-login`, `--login` / Gemini, Gemini CLI OAuth, and `--antigravity-login` are unofficial compatibility login paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension. Prefer official API-key or officially supported developer access for accounts you cannot afford to lose.
Kiro Google/GitHub OAuth is not currently supported because AWS Cognito rejects third-party localhost callbacks. Use AWS Builder ID or import a token from the official Kiro IDE instead.
### Login Options
```bash
--no-browser # Don't open browser automatically for OAuth
--incognito # Use incognito/private mode (useful for multiple accounts)
--no-incognito # Force disable incognito mode
```
### Import Commands
```bash
proxypilot --vertex-import <file> # Import Vertex service account key JSON
proxypilot --kiro-import # Import Kiro token from Kiro IDE
```
## Agent Configuration
ProxyPilot can automatically configure AI CLI tools to use the proxy.
### Detect Installed Agents
```bash
proxypilot --detect-agents
```
Example output:
```
Detecting installed CLI agents...
Claude Code: [+] Installed
Binary: /usr/local/bin/claude
Config: ~/.claude/settings.json
Codex CLI: [+] Installed
Binary: /usr/local/bin/codex
Config: ~/.codex
Gemini CLI: [-] Not found
```
### Setup Commands
```bash
proxypilot --setup-all # Configure all detected agents
proxypilot --setup-claude # Configure Claude Code
proxypilot --setup-codex # Configure Codex CLI
proxypilot --setup-droid # Configure Factory Droid
proxypilot --setup-opencode # Configure OpenCode
proxypilot --setup-gemini # Configure Gemini CLI
proxypilot --setup-cursor # Configure Cursor
proxypilot --setup-kilo # Configure Kilo Code CLI
proxypilot --setup-roocode # Configure RooCode (VS Code)
```
## Switch Mode
Switch AI agents between proxy mode (through ProxyPilot) and native mode (direct API access). Think of it like `nvm` for Node versions, but for AI agent configurations.
### Usage
```bash
proxypilot --switch <agent> # Show status of specific agent
proxypilot --switch <agent> --mode proxy # Switch agent to proxy mode
proxypilot --switch <agent> --mode native # Switch agent to native mode
proxypilot --switch <agent> --mode status # Show current mode (default)
```
### Supported Agents
| Agent | CLI Tool | Config Location |
|-------|----------|-----------------|
| `claude` | Claude Code | `~/.claude/settings.json` |
| `gemini` | Gemini CLI | `~/.gemini/settings.json` |
| `codex` | Codex CLI | `~/.codex/config.toml` |
| `opencode` | OpenCode | `~/.opencode/config.json` |
| `droid` | Factory Droid | `~/.factory/settings.json` |
| `cursor` | Cursor IDE | `~/.cursor/config.json` |
| `kilo` | Kilo Code* | VS Code settings |
| `roocode` | RooCode* | VS Code settings |
*VS Code extensions require manual configuration - proxypilot will display instructions.
### Modes
| Mode | Description |
|------|-------------|
| `proxy` | Route through ProxyPilot (`http://127.0.0.1:8317`) |
| `native` | Use direct API access (restore original config) |
| `status` | Show current mode (default) |
### Examples
#### Check single agent status
```bash
$ proxypilot --switch claude
Claude Code: proxy
Config: ~/.claude/settings.json
```
#### Switch Claude to proxy mode
```bash
$ proxypilot --switch claude --mode proxy
Switched Claude Code to proxy mode
Config: ~/.claude/settings.json
Backup: ~/.claude/settings.json.native.json
```
#### Switch Gemini back to native mode
```bash
$ proxypilot --switch gemini --mode native
Switched Gemini CLI to native mode
Restored from: ~/.gemini/settings.json.native.json
```
### How Switch Works
#### Switching to proxy mode
1. Backs up current config to `<config>.native.json`
2. Updates config to point to `http://127.0.0.1:8317`
3. Preserves all other settings (API keys, preferences, etc.)
#### Switching to native mode
1. Restores config from `<config>.native.json` backup
2. Removes backup file after successful restore
3. Original API keys and settings are restored
#### Config Detection
ProxyPilot automatically detects which mode an agent is in by checking:
- If config contains `127.0.0.1:8317` -> proxy mode
- If backup file exists -> was previously in proxy mode
- Otherwise -> native mode
## Agent-Specific Notes
### Claude Code
Config location: `~/.claude/settings.json`
Proxy mode sets:
```json
{
"env": {
"ANTHROPIC_BASE_URL": "http://127.0.0.1:8317"
}
}
```
### Codex CLI
Config location: `~/.codex/config.toml`
Proxy mode sets:
```toml
[openai]
api_base_url = "http://127.0.0.1:8317"
```
### Gemini CLI
Config location: `~/.gemini/settings.json`
Proxy mode sets the API endpoint to ProxyPilot.
### Kilo Code & RooCode
These are VS Code extensions that require manual configuration:
1. Open VS Code Settings (Ctrl+,)
2. Search for the extension settings
3. Update the API base URL to `http://127.0.0.1:8317`
ProxyPilot will display these instructions when you run:
```bash
proxypilot --setup-kilo
proxypilot --setup-roocode
```
## Backup System
Before modifying any configuration file, ProxyPilot creates a timestamped backup:
```
~/.claude/.proxypilot-backups/
settings.json.20251228-221853.bak
~/.codex/.proxypilot-backups/
config.toml.20251228-221853.bak
```
### Restoring Backups
```bash
# List backups
ls ~/.claude/.proxypilot-backups/
# Restore
cp ~/.claude/.proxypilot-backups/settings.json.<timestamp>.bak ~/.claude/settings.json
```
## Troubleshooting
### "Config not found"
The agent's config file doesn't exist. Run the agent once to create it, or create the config manually.
### "Failed to backup config"
Check file permissions on the config directory.
### "Already in proxy/native mode"
The agent is already configured for the requested mode. No changes made.
### CLI not detected
If a CLI tool is installed but not detected:
1. Ensure the binary is in your `PATH`
2. Try running the tool directly to verify it's installed
3. Check if the config directory exists
### Configuration not applied
1. Restart the CLI tool after running setup
2. Verify ProxyPilot is running on port 8317
3. Check the backup directory for the original config
## Full Usage Reference
```bash
proxypilot -h, --help # Show help
proxypilot -v, --version # Show version
# Server
proxypilot # Start proxy server
proxypilot -config <path> # Use custom config file
# OAuth Logins
proxypilot --login # Google/Gemini login
proxypilot --codex-login # Codex OAuth
proxypilot --claude-login # Claude OAuth
proxypilot --qwen-login # Qwen OAuth
proxypilot --antigravity-login # Antigravity OAuth
proxypilot --kiro-login # Kiro AWS Builder ID
proxypilot --kiro-aws-login # Kiro AWS Builder ID device code
# Agent Detection & Setup
proxypilot --detect-agents # Detect installed agents
proxypilot --setup-all # Configure all agents
proxypilot --setup-<agent> # Configure specific agent
# Agent Switching
proxypilot --switch <agent> # Show agent status
proxypilot --switch <agent> --mode proxy # Switch to proxy
proxypilot --switch <agent> --mode native # Switch to native
```
## Links
- [npm package](https://www.npmjs.com/package/proxypilot)
- [GitHub Releases](https://github.com/Finesssee/ProxyPilot/releases)
- [Source Code](https://github.com/Finesssee/ProxyPilot)
+79
View File
@@ -0,0 +1,79 @@
# Compatibility Matrix (Quick Reference)
This project proxies multiple “OpenAI-compatible” clients to multiple upstreams. Small schema differences matter.
## Clients
### Codex CLI (`codex_cli_rs/...`)
- Endpoint: `POST /v1/responses`
- Streaming: SSE (`text/event-stream`)
- Notes:
- `data: [DONE]` sentinel is tolerated/expected by many Codex/OpenAI clients.
- Response output ordering and `output_text` fields must be stable.
- Routing transparency:
- Responses from localhost include:
- `X-ProxyPilot-Requested-Model`
- `X-ProxyPilot-Resolved-Model`
- `X-ProxyPilot-Provider-Candidates`
- `X-ProxyPilot-Resolved-Provider`
- Add `X-CLIProxyAPI-Debug-Auth: 1` (localhost only) to also receive:
- `X-CLIProxyAPI-Selected-Provider`, `X-CLIProxyAPI-Selected-Auth`, `X-CLIProxyAPI-Selected-Label`, `X-CLIProxyAPI-Selected-Account`.
### Droid / Factory CLI (`factory-cli/...`, Stainless headers)
- Endpoint: `POST /v1/responses`
- Streaming behavior:
- Sends `stream: true` but typically uses `Accept: application/json`
- CLIProxyAPI uses a non-stream upstream call and **synthesizes SSE** for reliability.
- Notes:
- Droid attempts to JSON-parse each SSE `data:` line, so `data: [DONE]` must **not** be emitted for this client.
- Routing transparency:
- For localhost requests, the same headers as Codex apply for underlying routing.
- The `/v0/management/routing/preview?model=...` endpoint is the easiest way to debug which provider a `model` will map to before sending a turn from Droid/Factory.
### OpenAI-compatible SDKs (`openai`, `azure-openai`, etc.)
- Endpoints: `POST /v1/chat/completions`, `POST /v1/completions`.
- Streaming behavior:
- If body has `"stream": true` and `Accept` includes `text/event-stream`, ProxyPilot streams SSE.
- If `Accept: application/json` **without** `text/event-stream`, ProxyPilot automatically downgrades to non-streaming and returns JSON, even when `stream: true`.
- Notes:
- Responses from localhost include routing headers as above.
- For debugging, you can issue a test request and inspect:
- `X-ProxyPilot-Requested-Model` vs `X-ProxyPilot-Resolved-Model` to see alias/`auto`/thinking normalisation.
- `X-ProxyPilot-Provider-Candidates` and `X-ProxyPilot-Resolved-Provider` to see which upstream(s) and which provider actually ran.
## Upstreams
### Antigravity (`cloudcode-pa.googleapis.com`)
- Endpoints:
- `v1internal:generateContent` (non-stream)
- `v1internal:streamGenerateContent?alt=sse` (stream)
- Notes:
- `request.contents[].parts[].text` must be a **string** (`"text":"..."`), not an object.
## Model routing rules
- Quick debugging helpers:
- `GET /v0/management/routing/preview?model=<name>`
- Returns JSON describing how a given model name will be normalised and which provider candidates will be used.
- `POST /v0/management/routing/preview`
- Accepts a full request JSON body (OpenAI/OpenAIResponses-compatible), extracts the `model` field, and returns the same routing preview for that model.
- `/v0/management/routing/recent`
- Returns a small in-memory list of the last few routed requests (timestamp, path, requested/resolved model, provider + candidates).
- Both endpoints require a management key and are intended for localhost use.
### `gemini-3-*` provider preference
- Primary: `antigravity`
- Fallback: `gemini-cli` (only used if antigravity is unavailable/cooling)
- Rotation: disabled between these two providers to keep the primary stable.
## Regression tests
- Droid SSE parsing: `sdk/api/handlers/openai/openai_responses_handlers_sse_done_test.go`
- Codex SSE done sentinel: `sdk/api/handlers/openai/openai_responses_handlers_sse_json_compat_test.go`
- Antigravity request shape: `internal/runtime/executor/antigravity_executor_shape_test.go`
- Gemini-3-* provider ordering: `internal/util/provider_test.go` and `sdk/cliproxy/auth/provider_rotation_test.go`
+25
View File
@@ -0,0 +1,25 @@
# Cursor IDE Integration
CLIProxyAPI can be used as a local OpenAI-compatible endpoint for Cursor.
## 1) Start CLIProxyAPI
Run the server and note the listening address (default: `http://localhost:8318`).
## 2) Configure Cursor
In Cursor settings:
- **API base URL**: `http://localhost:8318` (recommended)
- Alternatively: `http://localhost:8318/v1` (CLIProxyAPI also provides non-`/v1` aliases for this case)
- **API key**: use one of the keys from `config.yaml` under `api-keys`
- Example: `your-cli-proxy-api-key`
## 3) Model selection
Cursor will query `GET /v1/models` (or `/models` when base URL ends with `/v1`).
Pick any model exposed by your configured providers.
## Notes
- `POST /v1/embeddings` is implemented and returns deterministic synthetic embeddings to keep IDE features working even when an embeddings backend is not configured.
+300
View File
@@ -0,0 +1,300 @@
# ProxyPilot CLI + Tray Build Process
Documentation of the CLI and system tray application build and release process.
## Overview
ProxyPilot uses a **CLI + system tray architecture**:
- **proxypilot.exe** - CLI executable with all proxy functionality
- **ProxyPilot.exe** - System tray app that manages the CLI process and provides quick access to controls
The dashboard is accessed via web browser at `http://127.0.0.1:<port>/proxypilot.html`.
## Architecture
```
┌─────────────────────────────────────────────────────────────────┐
│ ProxyPilot System │
│ │
│ ┌─────────────────────┐ ┌─────────────────────────────┐ │
│ │ ProxyPilot.exe │ │ proxypilot.exe │ │
│ │ (System Tray) │─────▶│ (CLI / Engine) │ │
│ │ │ │ │ │
│ │ - Start/Stop │ │ - Proxy Engine (port 8317) │ │
│ │ - Open Dashboard │ │ - Web Dashboard Server │ │
│ │ - Copy API URL │ │ - Provider Auth Mgmt │ │
│ │ - Autostart toggle │ │ - Routing Engine │ │
│ └─────────────────────┘ └─────────────────────────────┘ │
│ │
│ ┌─────────────────────┐ │
│ │ Web Browser │ │
│ │ (Dashboard UI) │ │
│ │ proxypilot.html │ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────────┘
```
### CLI + Tray Separation
The architecture separates concerns:
**proxypilot.exe (CLI)**:
- All proxy engine functionality
- Serves web dashboard at `/proxypilot.html`
- Can run standalone from command line
- Supports all CLI flags (`--help`, `--setup-claude`, etc.)
**ProxyPilot.exe (Tray)**:
- Lightweight system tray wrapper
- Manages CLI process lifecycle (start/stop/restart)
- Opens dashboard in default browser
- Provides quick-access menu
Benefits of CLI + tray architecture:
- **Flexibility**: Use CLI directly or via tray app
- **No WebView2 dependency**: Dashboard runs in any browser
- **Simpler debugging**: Inspect network/console in browser DevTools
- **Cross-platform dashboard**: Same web UI works on all platforms
## Build Process
### Prerequisites
```bash
# Required tools
go install github.com/josephspurrier/goversioninfo/cmd/goversioninfo@latest
```
Inno Setup 6 must be installed for creating the Windows installer.
### Step 1: Build Web UI Assets
```bash
cd webui
npm install
npm run build
```
This generates `webui/dist/` with the dashboard assets that are served by the CLI at `/proxypilot.html`.
### Step 2: Create Multi-Resolution Icon
The icon must have multiple sizes for proper Windows display (16px to 256px):
```python
from PIL import Image
img = Image.open('static/icon.png')
if img.mode != 'RGBA':
img = img.convert('RGBA')
sizes = [(16,16), (24,24), (32,32), (48,48), (64,64), (128,128), (256,256)]
img.save('static/icon.ico', format='ICO', sizes=sizes)
```
Copy to tray icon location:
```bash
cp static/icon.ico internal/trayicon/icon.ico
```
### Step 3: Generate Windows Resource Files
Generate `.syso` files for embedding icons in executables:
```bash
cd cmd/proxypilot-tray
goversioninfo -icon="../../static/icon.ico"
```
This creates `resource.syso` files that Go automatically includes during build.
### Step 4: Build Executables
```bash
# Build CLI executable
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o dist/proxypilot.exe ./cmd/server
# Build tray app (with -H windowsgui to hide console)
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H windowsgui" -o dist/ProxyPilot.exe ./cmd/proxypilot-tray
```
### Step 5: Build Installer
```bash
# Using Inno Setup
"C:\Users\FSOS\AppData\Local\Programs\Inno Setup 6\ISCC.exe" installer/proxypilot.iss
```
Output: `dist/ProxyPilot-0.1.0-Setup.exe`
## Key Files
### Version Info Configuration
**cmd/proxypilot-tray/versioninfo.json**
```json
{
"FixedFileInfo": {
"FileVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0},
"ProductVersion": {"Major": 0, "Minor": 1, "Patch": 0, "Build": 0}
},
"StringFileInfo": {
"FileDescription": "ProxyPilot System Tray",
"ProductName": "ProxyPilot",
"ProductVersion": "0.1.0"
},
"IconPath": "../../static/icon.ico"
}
```
### Tray Process Manager
**cmd/proxypilot-tray/engine.go** - Manages the CLI process:
- Spawns/stops `proxypilot.exe` subprocess
- Monitors process health
- Passes configuration and management password
### Tray Icon Embedding
**internal/trayicon/ico.go**
```go
package trayicon
import (
_ "embed"
)
//go:embed icon.ico
var proxyPilotICO []byte
func ProxyPilotICO() []byte {
return proxyPilotICO
}
```
### Installer Script
**installer/proxypilot.iss** - Inno Setup script that:
- Installs `proxypilot.exe` and `ProxyPilot.exe` to `%LOCALAPPDATA%\ProxyPilot`
- Creates Start Menu shortcut
- Adds optional Windows startup entry
- Copies config.example.yaml and creates config.yaml on first install
- Uses ProxyPilot icon for installer and shortcuts
## System Tray Menu
Simplified flat menu structure:
```
┌─────────────────────┐
│ Open Dashboard │ → Opens browser to proxypilot.html
├─────────────────────┤
│ Start/Stop │ → Toggle proxy engine (CLI process)
│ Copy API URL │ → Copies http://127.0.0.1:8317/v1
├─────────────────────┤
│ Quit │ → Stop engine and exit
└─────────────────────┘
```
## Release Process
### Create Release on GitHub
```bash
# Tag the release
git tag v0.1.0
git push origin v0.1.0
# Create release with assets
gh release create v0.1.0 \
--title "ProxyPilot v0.1.0" \
--notes "Release notes here" \
dist/ProxyPilot-0.1.0-Setup.exe \
dist/ProxyPilot.exe \
config.example.yaml
```
### Update Existing Release
```bash
# Delete old asset
gh release delete-asset v0.1.0 ProxyPilot.exe --yes
# Upload new asset
gh release upload v0.1.0 dist/ProxyPilot.exe
```
## Troubleshooting
### Icon Not Showing in File Explorer
1. Ensure icon.ico has 256x256 size (required for Windows)
2. Clear Windows icon cache: `ie4uinit.exe -show`
3. Verify resource.syso was generated after icon update
4. Rebuild the executable
### Dashboard Not Loading in Browser
1. Ensure the CLI process is running (check tray status)
2. Verify the port is correct: `http://127.0.0.1:8317/proxypilot.html`
3. Check for port conflicts with another application
### Tray Icon Shows Wrong Image
1. Check internal/trayicon/icon.ico is the correct file
2. Rebuild the tray app to re-embed the icon
3. Restart the application
### Engine Not Starting
1. Check if port 8317/8318 are already in use
2. Review logs in `%LOCALAPPDATA%\ProxyPilot\logs\`
3. Ensure config.yaml is valid YAML
## File Structure
```
ProxyPilot/
├── cmd/
│ ├── server/
│ │ └── main.go # CLI entry point
│ └── proxypilot-tray/
│ ├── main_windows.go # Tray app entry point
│ ├── engine.go # CLI process manager
│ ├── versioninfo.json # Version/icon config
│ └── resource.syso # Compiled resources
├── internal/
│ └── trayicon/
│ ├── ico.go # Embeds icon.ico
│ └── icon.ico # ProxyPilot logo (multi-res)
├── static/
│ ├── icon.ico # Source icon (7 sizes)
│ └── icon.png # Original PNG logo
├── webui/
│ ├── src/ # React dashboard source
│ └── dist/ # Built assets (served by CLI)
├── installer/
│ └── proxypilot.iss # Inno Setup script
└── dist/ # Distribution files
├── proxypilot.exe # CLI executable
└── ProxyPilot.exe # Tray app
```
## Version History
- **v0.3.0** (2025-12-30) - CLI + Tray architecture
- Removed WebView2 dependency
- Dashboard served by CLI, opened in browser
- Tray app manages CLI subprocess
- Simplified deployment and debugging
- **v0.2.0** (2025-12-27) - Single-binary architecture
- Embedded proxy engine runs in-process
- Removed separate proxypilot-engine.exe
- Reduced total size from ~46MB to ~29MB
- Faster startup with no process spawning
- **v0.1.0** (2025-12-27) - Initial release
- System tray with minimal menu
- Multi-resolution icon support
- Single-file Windows installer
+97
View File
@@ -0,0 +1,97 @@
# Hindsight (Optional) Agent Memory Sidecar
Hindsight is an **agent memory system** (retain/recall/reflect) that can run locally and expose an **MCP server**. It can help reduce “context rot” and repeated “prompt too long” failures by moving long-term memory out of the chat history and into a separate store the agent can query.
CLIProxyAPI is a **proxy + translator**. It is not the “agent brain”, so the best integration is to run Hindsight as a **sidecar** and let your CLI agent call it via MCP tools.
Repo: https://github.com/vectorize-io/hindsight
## Recommended architecture
- Keep CLIProxyAPI focused on: auth, routing, translation, compatibility fixes, and request trimming.
- Run Hindsight separately (Docker or `pip install hindsight-api`).
- Add Hindsight as an MCP server to your agentic client (Droid/Factory CLI, Claude Code, etc.).
- Teach the agent (via your system prompt) to:
- `retain` stable preferences and project facts
- `recall` before large context dumps
- `reflect` after successes/failures to improve consistency
## Run Hindsight locally
### Docker (easy)
```bash
# Provide an LLM key/model for Hindsight’s internal reasoning (separate from CLIProxyAPI)
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_API_KEY=sk-...
export HINDSIGHT_API_LLM_MODEL=gpt-4o-mini
docker run --rm -it -p 8888:8888 -p 9999:9999 \
-e HINDSIGHT_API_LLM_PROVIDER \
-e HINDSIGHT_API_LLM_API_KEY \
-e HINDSIGHT_API_LLM_MODEL \
-v $HOME/.hindsight-docker:/home/hindsight/.pg0 \
ghcr.io/vectorize-io/hindsight:latest
```
- REST API: `http://localhost:8888`
- MCP server: `http://localhost:8888/mcp`
- UI: `http://localhost:9999`
### Python (no Docker)
```bash
pip install hindsight-api -U
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_API_KEY=sk-...
hindsight-api
```
## Connect your agent via MCP
Hindsight exposes MCP two ways:
- **HTTP MCP**: `http://localhost:8888/mcp`
- **stdio MCP**: `hindsight-local-mcp`
How you register an MCP server depends on the client. Many clients use a `.mcp.json` file. Typical patterns:
### Option A: stdio MCP (most portable)
```json
{
"mcpServers": {
"hindsight": {
"command": "hindsight-local-mcp",
"args": [],
"env": {
"HINDSIGHT_API_LLM_PROVIDER": "openai",
"HINDSIGHT_API_LLM_API_KEY": "sk-..."
}
}
}
}
```
### Option B: HTTP MCP
If your client supports HTTP MCP servers, point it at:
- `http://localhost:8888/mcp`
## Operational notes / gotchas
- **Privacy**: Hindsight stores memory content (and may call its own LLM). Treat it like a database of user data.
- **Tool-call correctness**: If you see tool sequencing errors in Claude/Vertex, check `docs/tool-calling-and-cli-compat.md`.
- **Keep it optional**: Don’t enable or inject memory tools by default from CLIProxyAPI; different clients have different tool behaviors, and tool injection can increase prompt size.
## Next step (if you want deeper integration)
If you want CLIProxyAPI to “own” the Hindsight lifecycle, we can spec a thin optional module:
- `config.yaml`:
- `hindsight.enabled`
- `hindsight.base_url`
- `hindsight.auth_header` (optional)
- A small “memory helper” doc + scripts to start/stop the Hindsight sidecar alongside CLIProxyAPI.
+352
View File
@@ -0,0 +1,352 @@
# Long-Context Features in ProxyPilot
ProxyPilot implements two research-backed features for handling long-running AI agent sessions:
1. **Context Compression** - Based on Factory.ai research
2. **Agentic Harness** - Based on Anthropic's "Building Effective Agents" blog
Both are enabled by default and can be toggled via environment variables.
---
## Sources
| Feature | Source | Link |
|---------|--------|------|
| Context Compression | Factory.ai Research | [Context Compression for Long-Running Agents](https://www.factory.ai/news/context-compression) |
| Agentic Harness | Anthropic Blog | [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) |
---
## 1. Context Compression (Factory.ai)
### What Factory.ai Found
Factory.ai researched how to handle long coding sessions where conversation context exceeds model limits. Their key findings:
- **Naive truncation fails** - Cutting old messages loses critical context
- **Structured summarization works** - Preserving key information in a specific format maintains continuity
- **Anchored approach is best** - Merging new info into existing summaries beats creating fresh ones
### How ProxyPilot Implements It
When conversation exceeds 75% of the model's context window:
1. **Trigger**: Token count check detects threshold exceeded
2. **Summarize**: LLM generates structured summary of older messages
3. **Inject**: Summary replaces compressed messages in subsequent requests
### Structured Summary Format
```
## Session Intent
[High-level goal of the conversation]
## File Modifications
- path/to/file1.go: Added function X, modified Y
- path/to/file2.ts: Refactored component Z
## Decisions Made
- Chose approach A over B because...
- Confirmed that X should use pattern Y
## Next Steps
1. Implement feature X
2. Add tests for Y
## Technical Details
- Key code snippets or patterns
- Important variable names or function signatures
```
### Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CLIPROXY_TOKEN_AWARE_ENABLED` | `true` | Enable token-based compression |
| `CLIPROXY_LLM_SUMMARY_ENABLED` | `true` | Use LLM for summaries (vs regex fallback) |
| `CLIPROXY_COMPRESSION_THRESHOLD` | `0.75` | Trigger at this % of context |
| `CLIPROXY_SUMMARY_MODEL` | `gemini-3-flash` | Model used for summarization |
### Summary Model Selection
ProxyPilot uses a dedicated model for context summarization:
- **Primary**: `gemini-3-flash` via Antigravity provider
- **Fallback**: `gemini-3-flash-preview` (on model-not-found errors)
- **Final fallback**: Regex-based extraction (on any LLM failure)
This separation keeps summarization costs low while maintaining quality. The fallback chain ensures summarization never blocks the main request.
### Disable
```bash
export CLIPROXY_LLM_SUMMARY_ENABLED=false
```
---
## 2. Agentic Harness (Anthropic)
### What Anthropic Found
Anthropic's research on long-running agents identified key failure modes:
- Agents try to do everything at once and fail
- Agents don't track state between turns
- Agents skip verification ("the code looks correct")
- Agents lose context of what was already done
Their solution: **Structured harness with explicit state files and disciplined workflow.**
### How ProxyPilot Implements It
ProxyPilot injects prompts based on conversation state:
#### INITIALIZER Mode (First Request)
Injected when agentic client sends first request:
```
You are the Initializer Agent. Your ONLY goal is to set up the project environment.
1. Create 'feature_list.json' - List ALL features with:
- id, category, description, steps, passes: false, priority
2. Create 'claude-progress.txt' - Session log with:
- [Initializer] Environment setup started
3. Create 'init.sh' - Dev server startup script
DO NOT implement features. Only scaffold the harness files.
```
#### CODING Mode (After Harness Files Exist)
Injected when `feature_list.json` or `claude-progress.txt` detected:
```
You are a Coding Agent. Follow this workflow:
STEP 1: GET BEARINGS (MANDATORY)
- pwd, git log, cat claude-progress.txt, cat feature_list.json
STEP 2: SANITY CHECK
- Verify existing features work
- Fix regressions before new work
STEP 3: PICK ONE TASK
- Find highest-priority feature where passes: false
- Announce: "I will implement: [description]"
STEP 4: IMPLEMENT & VERIFY
- Write code for ONE feature only
- Run tests to verify it works
- Do NOT mark complete without actual testing
STEP 5: UPDATE STATE
- Set passes: true in feature_list.json
- Append to claude-progress.txt
STEP 6: COMMIT
- Git commit with feature ID in message
```
#### PASSIVE Mode
For non-agentic clients (browsers, curl), no prompts injected.
### Client Detection
Harness activates for these User-Agents:
- `claude-cli`
- `codex`
- `droid`
Or when header `X-ProxyPilot-Harness: true` is set.
### Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CLIPROXY_HARNESS_ENABLED` | `true` | Enable agentic harness |
| `CLIPROXY_MEMORY_DIR` | `~/.proxypilot/memory` | Session storage location |
### Disable
```bash
export CLIPROXY_HARNESS_ENABLED=false
```
---
## Implementation Details
### Files Modified
| File | Change |
|------|--------|
| `internal/memory/summarizer_executor.go` | Added `CoreManagerExecutor` interface and `ManagerAuthAdapter` |
| `internal/api/middleware/codex_prompt_budget.go` | Added `InitSummarizerWithAuthManager()` |
| `sdk/cliproxy/service.go` | Added `coreManagerWrapper`, wired up compression |
| `internal/api/server.go` | Registered `AgenticHarnessMiddleware()` |
### Files Created
| File | Purpose |
|------|---------|
| `internal/memory/summarizer_executor_test.go` | 12 unit tests for adapter |
| `internal/api/features_integration_test.go` | 3 integration tests |
### Architecture
```
Request Flow (Context Compression):
Client Request
│
▼
┌─────────────────────┐
│ PromptBudget │
│ Middleware │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Token Count Check │──── < 75% ────▶ Pass through
└─────────────────────┘
│
│ > 75%
▼
┌─────────────────────┐
│ PipelineSummarizer │
│ Executor │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ ManagerAuthAdapter │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ coreManagerWrapper │
└─────────────────────┘
│
▼
┌─────────────────────┐
│ Auth Manager │
│ (claude/codex/ │
│ gemini) │
└─────────────────────┘
```
```
Request Flow (Agentic Harness):
Client Request
│
▼
┌─────────────────────┐
│ Check User-Agent │──── Not agentic ────▶ Pass through
└─────────────────────┘
│
│ Agentic client
▼
┌─────────────────────┐
│ Detect Harness │
│ State │
└─────────────────────┘
│
├── No harness files + short convo ──▶ INITIALIZER prompt
│
├── Harness files exist ──────────────▶ CODING prompt
│
└── Long convo, no files ─────────────▶ PASSIVE (no injection)
```
---
## What Was NOT Implemented
During implementation, we removed features that were added by a previous session but **not from the original sources**:
| Removed | Reason |
|---------|--------|
| Puppeteer MCP detection | Not in Factory.ai or Anthropic sources |
| Browser automation reminders | Made up, not from research |
The current implementation is pure to the original Factory.ai and Anthropic research.
---
## Testing
```bash
# Run all tests
go test ./...
# Run specific feature tests
go test ./internal/memory/... -v # Compression adapter
go test ./internal/api/middleware/... -v -run Harness # Harness middleware
go test ./internal/api/... -v -run Integration # Integration tests
```
### Test Coverage
| Test File | Tests | Coverage |
|-----------|-------|----------|
| `summarizer_executor_test.go` | 12 | Adapter, pipeline, edge cases |
| `agentic_harness_test.go` | 10 | All modes, injection, session storage |
| `features_integration_test.go` | 3 | Combined feature validation |
---
## Quick Reference
### Enable/Disable Features
```bash
# Disable context compression
export CLIPROXY_LLM_SUMMARY_ENABLED=false
# Disable agentic harness
export CLIPROXY_HARNESS_ENABLED=false
# Disable both
export CLIPROXY_TOKEN_AWARE_ENABLED=false
export CLIPROXY_HARNESS_ENABLED=false
```
### Key Integration Points
```go
// Context Compression - sdk/cliproxy/service.go:516
middleware.InitSummarizerWithAuthManager(wrapper, providers)
// Agentic Harness - internal/api/server.go:224
engine.Use(middleware.AgenticHarnessMiddleware())
```
---
## Changelog
### 2025-12-31
- **Enhanced**: Multi-format response parsing (OpenAI, Claude, Gemini)
- **Added**: `SummaryModelFallbackExecutor` for model fallback (`gemini-3-flash` → `gemini-3-flash-preview`)
- **Added**: `CLIPROXY_SUMMARY_MODEL` env var for custom summary model
- **Added**: Dual output format (`summary.md` + `summary.json`)
- **Added**: 30+ unit tests for response parsing and model fallback
### 2025-12-27
- **Implemented**: Factory.ai-style context compression with LLM summarization
- **Implemented**: Anthropic-style agentic harness (INITIALIZER/CODING modes)
- **Added**: `ManagerAuthAdapter` to bridge auth manager types
- **Added**: `coreManagerWrapper` to adapt concrete types to interfaces
- **Added**: `InitSummarizerWithAuthManager()` for initialization
- **Added**: Session-based harness file storage
- **Added**: Comprehensive test coverage (25+ tests)
- **Removed**: Puppeteer MCP detection (not from original sources)
+186
View File
@@ -0,0 +1,186 @@
# Long-Session Memory (ProxyPilot / CLIProxyAPI)
CLIProxyAPI can keep long agentic CLI sessions running without manual `/compact` by:
- Persisting trimmed/dropped history to disk (external memory)
- Retrieving relevant snippets and injecting them back into the prompt when the request must be trimmed
This is **not** a 7M-token context window. It is a store + retrieval loop.
## When it activates
The memory flow runs inside `internal/api/middleware/codex_prompt_budget.go` for agentic CLIs:
- `OpenAI Codex`
- `factory-cli` / `droid`
- `warp`
- Stainless SDK clients (`X-Stainless-*` headers)
It only injects memory when a request is oversized and must be trimmed.
## Where memory is stored
Default directory:
- If `util.WritablePath()` is set: `<WritablePath>/.proxypilot/memory`
- Otherwise: `./.proxypilot/memory`
Per-session logs:
- `.proxypilot/memory/sessions/<sessionKey>/events.jsonl`
The session key is chosen in this order:
1. `X-CLIProxyAPI-Session` header (preferred)
2. `X-Session-Id` header
3. JSON `prompt_cache_key`
4. JSON `metadata.session_id` / `session_id`
5. Fallback hash of `Authorization + User-Agent` (hashed; raw values are not stored)
## Retrieval / injection
- Dropped items are appended as JSONL events (`dropped_chat` / `dropped_responses`)
- Retrieval is a lightweight keyword scorer over the last ~2MB of stored events
- Up to 8 snippets (~6k chars) are injected by appending to the **last user message** (best-effort).
## Anchored summaries (heuristic)
When history is trimmed, ProxyPilot writes a lightweight anchor summary based on **heuristic extraction**
(latest user intent + file/command hits). It does not use an LLM to summarize old turns.
Key behaviors:
- No LLM-based summarization of old turns. The anchored summary is generated by heuristic extraction (latest user intent + file/command hits) from dropped messages, not a model-produced summary.
- No explicit “~140k sweet spot” threshold or scheduled compression cycle. The memory flow only kicks in when a request exceeds budget and must be trimmed.
- No explicit cache-aware anchoring beyond append-only scaffold (we preserve append-only, but we don’t do Droid’s full anchored compression pipeline).
Environment variables:
- `CLIPROXY_ANCHOR_SUMMARY_MAX_CHARS` (default: `14000`)
- `CLIPROXY_ANCHOR_APPEND_ONLY` (default: enabled)
- `CLIPROXY_MEMORY_MAX_WRITES_PER_MIN` (default: `120`)
- `CLIPROXY_MEMORY_EXPORT_MAX_BYTES` (default: `262144000` / 250MB)
When append-only anchoring is on, the new anchor is appended once and then preserved in subsequent turns by the client.
If disabled, the anchor is included in the scaffold on every request (legacy behavior).
## Environment variables
- `CLIPROXY_MEMORY_ENABLED`:
- default: enabled
- set to `0`, `false`, `off`, or `no` to disable persistence + retrieval
- `CLIPROXY_MEMORY_DIR`: override the base directory used to store memory
## Persistent TODO (never dropped)
CLIProxyAPI maintains an optional per-session TODO file:
- `.proxypilot/memory/sessions/<sessionKey>/todo.md`
If present, it is injected on **every** agentic request (before any trimming). This keeps the agent aligned even across many compression cycles.
Ways to set it:
- Write the file directly
- Or send a request header `X-CLIProxyAPI-Todo` (the proxy stores it to `todo.md` and strips the header before forwarding upstream)
Environment variables:
- `CLIPROXY_TODO_ENABLED` (default: enabled)
- `CLIPROXY_TODO_MAX_CHARS` (default: `4000`)
## Prompt-cache friendly scaffolding (append-only)
To preserve stable prompt prefixes for long sessions, CLIProxyAPI injects session state as an **append-only scaffold** by default (it appends a new system message/input entry instead of mutating prior content).
Packed block format:
- `<proxypilot_state>`
- `<pinned>` from `pinned.md`
- `<anchor>` from `summary.md`
- `<todo>` from `todo.md`
- `<spec>` when Spec Mode is enabled
## Text normalization
Some clients (notably PowerShell `ConvertTo-Json`) can store TODO/pinned state with escaped sequences like `\\n` / `\\u2019`.
CLIProxyAPI normalizes common escape sequences when reading/writing `todo.md`, `pinned.md`, and `summary.md` so the injected state stays readable.
## AGENTS.md pinning
If `harness-root-dir` is set (or provided to the middleware), CLIProxyAPI will read `AGENTS.md` from that directory and merge it into pinned context.
## Spec Mode (optional)
Spec Mode can be enabled to require a spec/plan before any code changes:
- Header: `X-CLIProxyAPI-Spec-Mode: true`
- Env: `CLIPROXY_SPEC_MODE=1`
When enabled and not yet approved, the scaffold injects a spec prompt that asks the agent to produce a reviewable specification and wait for approval.
## Semantic memory (local embeddings)
ProxyPilot can optionally embed and retrieve semantic memory using a local Ollama embed model.
This runs fully local and is **always-on** when enabled.
Embedding of dropped history is queued in the background to keep request latency low.
Environment variables:
- `CLIPROXY_SEMANTIC_ENABLED` (default: enabled)
- `CLIPROXY_SEMANTIC_MODEL` (default: `embeddinggemma`; also supports `nomic-embed-text`)
- `CLIPROXY_SEMANTIC_BASE_URL` (default: `http://127.0.0.1:11434`)
- `CLIPROXY_SEMANTIC_MAX_SNIPS` (default: `4`)
- `CLIPROXY_SEMANTIC_MAX_CHARS` (default: `3000`)
- `CLIPROXY_SEMANTIC_RERANK` (default: enabled)
- `CLIPROXY_SEMANTIC_KEYWORD_BOOST` (default: `0.25`)
- `CLIPROXY_SEMANTIC_RECENCY_BOOST` (default: `0.15`)
- `CLIPROXY_SEMANTIC_MAX_AGE_DAYS` (default: disabled)
- `CLIPROXY_SEMANTIC_MAX_NAMESPACES` (default: disabled)
- `CLIPROXY_SEMANTIC_MAX_BYTES_PER_NAMESPACE` (default: disabled)
- `CLIPROXY_SEMANTIC_MAX_WRITES_PER_MIN` (default: `120`)
- `CLIPROXY_SEMANTIC_QUERY_MAX_CHARS` (default: `512`)
Namespace:
- `X-CLIProxyAPI-Repo` / `X-Repo-Path` / `X-Workspace-Root` / `X-Project-Root`
- or request `metadata.repo`
- fallback: session key
## Memory hygiene (prune / size caps)
You can set guardrails to keep memory from growing without bound. When configured,
ProxyPilot will prune on a best-effort interval (every ~10 minutes after writes).
- `CLIPROXY_MEMORY_MAX_AGE_DAYS` (default: disabled)
- `CLIPROXY_MEMORY_MAX_SESSIONS` (default: disabled)
- `CLIPROXY_MEMORY_MAX_BYTES_PER_SESSION` (default: disabled)
The management UI also exposes manual prune + import/export tools.
## Per-session semantic toggle
You can disable semantic memory per session (stored in `semantic_disabled` in the session folder).
This stops embeddings/retrieval for that session without disabling global semantic memory.
Management endpoints (local only):
- `GET /v0/management/memory/sessions`
- `GET /v0/management/memory/session?session=...`
- `GET /v0/management/memory/events?session=...`
- `GET /v0/management/memory/anchors?session=...`
- `POST /v0/management/memory/todo|pinned|summary`
- `POST /v0/management/memory/semantic` (enable/disable per-session semantic)
- `POST /v0/management/memory/prune`
- `GET /v0/management/memory/export?session=...`
- `GET /v0/management/memory/export-all`
- `POST /v0/management/memory/import?session=...`
- `POST /v0/management/memory/delete-all`
## LLM-Based Context Compression
For advanced context compression using LLM-generated structured summaries and token-aware proactive trimming, see [Context Compression](context-compression.md).
## Agentic Harness
For structured incremental development workflows (INITIALIZER/CODING modes, feature tracking, progress logging), see [Agentic Harness](agentic-harness.md).
@@ -0,0 +1,223 @@
# Provider Migration: iFlow → MiniMax + Zhipu AI
**Date:** 2025-12-28
**Version:** 0.1.6
## Summary
Removed the iFlow provider (complex OAuth/cookie authentication) and replaced it with two new direct API providers:
- **MiniMax** - `https://api.minimax.io/v1` (OpenAI-compatible, API key auth)
- **Zhipu AI** - `https://open.bigmodel.cn/api/paas/v4/` (OpenAI-compatible, API key auth)
Both new providers are significantly simpler than iFlow because they use API keys instead of OAuth.
---
## Changes Overview
### Providers Before
| Provider | Auth Method |
|----------|-------------|
| Claude | OAuth2 |
| Codex | OAuth2 |
| Gemini | OAuth2 |
| Gemini CLI | OAuth2 |
| Kiro | OAuth2 + AWS SSO |
| Qwen | OAuth2 |
| iFlow | OAuth + Cookie |
| **Total: 7** | |
### Providers After
| Provider | Auth Method |
|----------|-------------|
| Claude | OAuth2 |
| Codex | OAuth2 |
| Gemini | OAuth2 |
| Gemini CLI | OAuth2 |
| Kiro | OAuth2 + AWS SSO |
| Qwen | OAuth2 |
| MiniMax | API Key |
| Zhipu AI | API Key |
| **Total: 8** | |
---
## Files Deleted (iFlow Removal)
```
internal/auth/iflow/iflow_auth.go
internal/auth/iflow/iflow_token.go
internal/auth/iflow/oauth_server.go
internal/auth/iflow/cookie_helpers.go
internal/cmd/iflow_login.go
internal/cmd/iflow_cookie.go
internal/runtime/executor/iflow_executor.go
internal/api/handlers/management/iflow_import.go
internal/api/handlers/management/iflow_import_test.go
sdk/auth/iflow.go
```
---
## Files Created (New Providers)
### MiniMax Provider
```
internal/runtime/executor/minimax_executor.go # OpenAI-compatible executor
sdk/auth/minimax.go # API key authenticator
```
### Zhipu AI Provider
```
internal/runtime/executor/zhipu_executor.go # OpenAI-compatible executor
sdk/auth/zhipu.go # API key authenticator
```
---
## Files Modified
### Core Registration Files
| File | Changes |
|------|---------|
| `sdk/auth/refresh_registry.go` | Removed iFlow, added MiniMax + Zhipu registrations |
| `sdk/cliproxy/service.go` | Removed iFlow executor/model cases, added MiniMax + Zhipu |
| `internal/registry/model_definitions.go` | Removed `GetIFlowModels()`, added `GetMiniMaxModels()` + `GetZhipuModels()` |
| `internal/cmd/auth_manager.go` | Removed iFlow authenticator, added MiniMax + Zhipu |
### API/Server Files
| File | Changes |
|------|---------|
| `internal/api/server.go` | Removed iFlow OAuth routes |
| `internal/api/handlers/management/auth_files.go` | Removed iFlow import, removed `RequestIFlowToken` + `RequestIFlowCookieToken` handlers |
| `internal/api/handlers/management/oauth_sessions.go` | Removed iFlow case from provider normalization |
| `internal/api/handlers/management/generic_import.go` | Removed iFlow import, added `importResult` type definition |
### CLI Files
| File | Changes |
|------|---------|
| `cmd/server/main.go` | Removed `--iflow-login` and `--iflow-cookie` flags |
| `cmd/proxypilotui/main_windows.go` | Removed iFlow button and handler |
| `cmd/cliproxytray/main_windows.go` | Removed iFlow endpoint case |
### UI Files
| File | Changes |
|------|---------|
| `webui/src/components/layout/StatusBar.tsx` | Removed iFlow from provider list |
| `webui/src/components/dashboard/ProviderLogins.tsx` | Removed iFlow from provider list and auth detection |
### Documentation
| File | Changes |
|------|---------|
| `README.md` | Updated provider count (7→8), updated provider table |
| `docs/proxypilot.md` | Removed iFlow from one-click login list |
| `config.example.yaml` | Removed iFlow example |
| `cmd/installer/bundle/config.example.yaml` | Removed iFlow example |
---
## New Model Definitions
### MiniMax Models
| Model ID | Display Name | Description |
|----------|--------------|-------------|
| `minimax-m2` | MiniMax-M2 | Base model |
| `minimax-m2.1` | MiniMax-M2.1 | With reasoning support |
| `minimax-m2.1-lightning` | MiniMax-M2.1-Lightning | Fast variant |
### Zhipu AI Models
| Model ID | Display Name | Description |
|----------|--------------|-------------|
| `glm-4.7` | GLM-4.7 | Flagship model with thinking |
| `glm-4.6` | GLM-4.6 | High performance |
| `glm-4.5` | GLM-4.5 | Excellent for coding |
| `glm-4-long` | GLM-4-Long | 1M context window |
| `glm-4.6v` | GLM-4.6V | Vision model |
---
## API Details
### MiniMax
- **Base URL:** `https://api.minimax.io/v1`
- **Auth:** `Authorization: Bearer <API_KEY>`
- **Format:** OpenAI-compatible
- **Thinking:** M2.1 models support reasoning via `reasoning_split=true`
### Zhipu AI
- **Base URL:** `https://open.bigmodel.cn/api/paas/v4/`
- **Auth:** `Authorization: Bearer <API_KEY>`
- **Format:** OpenAI-compatible
- **Thinking:** GLM-4.6/4.7 support via `extra_body={"thinking": {"type": "enabled"}}`
---
## Auth File Format
Both providers use simple JSON with API key (no OAuth tokens needed):
```json
{
"type": "minimax",
"api_key": "sk-xxx",
"label": "my-account",
"created_at": "2025-12-28T12:00:00Z"
}
```
```json
{
"type": "zhipu",
"api_key": "xxx.yyy",
"label": "my-account",
"created_at": "2025-12-28T12:00:00Z"
}
```
---
## Usage
### Adding MiniMax API Key
Create a file `auth/minimax-myaccount.json`:
```json
{
"type": "minimax",
"api_key": "YOUR_MINIMAX_API_KEY",
"label": "myaccount"
}
```
### Adding Zhipu AI API Key
Create a file `auth/zhipu-myaccount.json`:
```json
{
"type": "zhipu",
"api_key": "YOUR_ZHIPU_API_KEY",
"label": "myaccount"
}
```
---
## Build Verification
```bash
go build ./...
# ✓ Build successful
```
---
## Migration Notes
1. **iFlow users:** If you have existing iFlow auth files, they will no longer work. Remove them from your `auth/` directory.
2. **Model mapping:** If you had model mappings pointing to iFlow models, update them to use the new providers:
- `glm-4.6` → Use Zhipu provider directly
- `glm-4.7` → Use Zhipu provider directly
- `minimax-m2` → Use MiniMax provider directly
3. **API keys:** Both MiniMax and Zhipu require API keys from their respective platforms:
- MiniMax: https://www.minimax.io/
- Zhipu AI: https://open.bigmodel.cn/
+72
View File
@@ -0,0 +1,72 @@
# ProxyPilot
ProxyPilot is a local AI proxy with CLI + system tray interface for agentic tools (Droid/Factory, Codex CLI, Warp).
This repo started as a fork of CLIProxyAPI, but is now branded as ProxyPilot. For compatibility, some internal names and headers still use `CLIProxyAPI` (e.g. `X-CLIProxyAPI-*`).
## What’s included
- ProxyPilot tray app (Windows) to start/stop/restart the proxy engine, open the web dashboard in browser, open logs, and toggle autostart.
- Prompt-budget middleware to reduce “prompt too long” failures in strict CLIs.
- Long-session memory with pinned state + persistent TODO (local disk).
- Optional auth debugging and cooldown reset endpoints for local troubleshooting.
## Install / uninstall (Windows)
- Install: run `dist\\ProxyPilot-Setup.exe`
- Launch: Start Menu → ProxyPilot
- Uninstall: Settings → Apps → Installed apps → ProxyPilot → Uninstall
## Build / package
If you have Go installed:
- Build binaries: `go run .\\cmd\\proxypilotpack build`
- Package zip: `go run .\\cmd\\proxypilotpack package-zip` → `dist\\ProxyPilot.zip`
- Package installer (recommended): `go run .\\cmd\\proxypilotpack package-inno` (requires Inno Setup `ISCC.exe`) → `dist\\ProxyPilot-Setup.exe`
## Endpoints / health
- `GET /healthz` (no auth)
- `GET /v1/models` (requires API key)
- `GET /proxypilot.html` (local-only ProxyPilot dashboard; no manual key entry)
Example:
- `curl -H "Authorization: Bearer local-dev-key" http://127.0.0.1:<port>/v1/models`
## Autostart toggles (tray)
ProxyPilot tray app can toggle:
- `Launch on login` (starts ProxyPilot)
- `Auto-start proxy` (starts the proxy engine when ProxyPilot launches)
On Windows this uses a per-user Run entry (no admin required).
## Local management (Dashboard / tray)
When the proxy is started by the ProxyPilot tray app, it sets a per-user `MANAGEMENT_PASSWORD` for the engine process so `/v0/management/*` endpoints are enabled for local use.
The password is stored in the ProxyPilot UI state file:
- `%LOCALAPPDATA%\\ProxyPilot\\ui-state.json` (preferred)
- legacy fallback: `%LOCALAPPDATA%\\CLIProxyAPI\\ui-state.json` (migrates to `%LOCALAPPDATA%\\ProxyPilot\\ui-state.json`)
## OAuth helpers (tray)
ProxyPilot tray app includes:
- `Private OAuth window` toggle (opens Edge `--inprivate` when available)
- One-click login launchers: Antigravity, Gemini CLI, Codex, Claude, Qwen
- `Open Auth Folder` shortcut
Account risk warning: Antigravity, Gemini/Gemini CLI, and Claude login launchers use unofficial compatibility OAuth paths. Providers may treat proxy, automation, shared-token, or third-party OAuth traffic as abnormal usage or a policy violation. These flows can risk quota loss, account restriction, or account suspension. Use disposable or non-critical accounts only if you accept that risk; prefer official API keys or officially supported developer access for important accounts.
## Logs / diagnostics
Useful paths:
- `logs/proxypilot-engine.out.log`
- `logs/proxypilot-engine.err.log`
- `logs/v1-responses-*.log` / `logs/v1-chat-completions-*.log` (request logs, if enabled)
+53 -75
View File
@@ -7,80 +7,71 @@ The `github.com/router-for-me/CLIProxyAPI/v6/sdk/access` package centralizes inb
```go
import (
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
```
Add the module with `go get github.com/router-for-me/CLIProxyAPI/v6/sdk/access`.
## Provider Registry
Providers are registered globally and then attached to a `Manager` as a snapshot:
- `RegisterProvider(type, provider)` installs a pre-initialized provider instance.
- Registration order is preserved the first time each `type` is seen.
- `RegisteredProviders()` returns the providers in that order.
## Manager Lifecycle
```go
manager := sdkaccess.NewManager()
providers, err := sdkaccess.BuildProviders(cfg)
if err != nil {
return err
}
manager.SetProviders(providers)
manager.SetProviders(sdkaccess.RegisteredProviders())
```
* `NewManager` constructs an empty manager.
* `SetProviders` replaces the provider slice using a defensive copy.
* `Providers` retrieves a snapshot that can be iterated safely from other goroutines.
* `BuildProviders` translates `config.Config` access declarations into runnable providers. When the config omits explicit providers but defines inline API keys, the helper auto-installs the built-in `config-api-key` provider.
If the manager itself is `nil` or no providers are configured, the call returns `nil, nil`, allowing callers to treat access control as disabled.
## Authenticating Requests
```go
result, err := manager.Authenticate(ctx, req)
result, authErr := manager.Authenticate(ctx, req)
switch {
case err == nil:
case authErr == nil:
// Authentication succeeded; result describes the provider and principal.
case errors.Is(err, sdkaccess.ErrNoCredentials):
case sdkaccess.IsAuthErrorCode(authErr, sdkaccess.AuthErrorCodeNoCredentials):
// No recognizable credentials were supplied.
case errors.Is(err, sdkaccess.ErrInvalidCredential):
case sdkaccess.IsAuthErrorCode(authErr, sdkaccess.AuthErrorCodeInvalidCredential):
// Supplied credentials were present but rejected.
default:
// Transport-level failure was returned by a provider.
// Internal/transport failure was returned by a provider.
}
```
`Manager.Authenticate` walks the configured providers in order. It returns on the first success, skips providers that surface `ErrNotHandled`, and tracks whether any provider reported `ErrNoCredentials` or `ErrInvalidCredential` for downstream error reporting.
If the manager itself is `nil` or no providers are registered, the call returns `nil, nil`, allowing callers to treat access control as disabled without branching on errors.
`Manager.Authenticate` walks the configured providers in order. It returns on the first success, skips providers that return `AuthErrorCodeNotHandled`, and aggregates `AuthErrorCodeNoCredentials` / `AuthErrorCodeInvalidCredential` for a final result.
Each `Result` includes the provider identifier, the resolved principal, and optional metadata (for example, which header carried the credential).
## Configuration Layout
## Built-in `config-api-key` Provider
The manager expects access providers under the `auth.providers` key inside `config.yaml`:
The proxy includes one built-in access provider:
- `config-api-key`: Validates API keys declared under top-level `api-keys`.
- Credential sources: `Authorization: Bearer`, `X-Goog-Api-Key`, `X-Api-Key`, `?key=`, `?auth_token=`
- Metadata: `Result.Metadata["source"]` is set to the matched source label.
In the CLI server and `sdk/cliproxy`, this provider is registered automatically based on the loaded configuration.
```yaml
auth:
providers:
- name: inline-api
type: config-api-key
api-keys:
- sk-test-123
- sk-prod-456
api-keys:
- sk-test-123
- sk-prod-456
```
Fields map directly to `config.AccessProvider`: `name` labels the provider, `type` selects the registered factory, `sdk` can name an external module, `api-keys` seeds inline credentials, and `config` passes provider-specific options.
## Loading Providers from External Go Modules
### Loading providers from external SDK modules
To consume a provider shipped in another Go module, point the `sdk` field at the module path and import it for its registration side effect:
```yaml
auth:
providers:
- name: partner-auth
type: partner-token
sdk: github.com/acme/xplatform/sdk/access/providers/partner
config:
region: us-west-2
audience: cli-proxy
```
To consume a provider shipped in another Go module, import it for its registration side effect:
```go
import (
@@ -89,19 +80,11 @@ import (
)
```
The blank identifier import ensures `init` runs so `sdkaccess.RegisterProvider` executes before `BuildProviders` is called.
## Built-in Providers
The SDK ships with one provider out of the box:
- `config-api-key`: Validates API keys declared inline or under top-level `api-keys`. It accepts the key from `Authorization: Bearer`, `X-Goog-Api-Key`, `X-Api-Key`, or the `?key=` query string and reports `ErrInvalidCredential` when no match is found.
Additional providers can be delivered by third-party packages. When a provider package is imported, it registers itself with `sdkaccess.RegisterProvider`.
The blank identifier import ensures `init` runs so `sdkaccess.RegisterProvider` executes before you call `RegisteredProviders()` (or before `cliproxy.NewBuilder().Build()`).
### Metadata and auditing
`Result.Metadata` carries provider-specific context. The built-in `config-api-key` provider, for example, stores the credential source (`authorization`, `x-goog-api-key`, `x-api-key`, or `query-key`). Populate this map in custom providers to enrich logs and downstream auditing.
`Result.Metadata` carries provider-specific context. The built-in `config-api-key` provider, for example, stores the credential source (`authorization`, `x-goog-api-key`, `x-api-key`, `query-key`, `query-auth-token`). Populate this map in custom providers to enrich logs and downstream auditing.
## Writing Custom Providers
@@ -110,13 +93,13 @@ type customProvider struct{}
func (p *customProvider) Identifier() string { return "my-provider" }
func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sdkaccess.Result, error) {
func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sdkaccess.Result, *sdkaccess.AuthError) {
token := r.Header.Get("X-Custom")
if token == "" {
return nil, sdkaccess.ErrNoCredentials
return nil, sdkaccess.NewNotHandledError()
}
if token != "expected" {
return nil, sdkaccess.ErrInvalidCredential
return nil, sdkaccess.NewInvalidCredentialError()
}
return &sdkaccess.Result{
Provider: p.Identifier(),
@@ -126,51 +109,46 @@ func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sd
}
func init() {
sdkaccess.RegisterProvider("custom", func(cfg *config.AccessProvider, root *config.Config) (sdkaccess.Provider, error) {
return &customProvider{}, nil
})
sdkaccess.RegisterProvider("custom", &customProvider{})
}
```
A provider must implement `Identifier()` and `Authenticate()`. To expose it to configuration, call `RegisterProvider` inside `init`. Provider factories receive the specific `AccessProvider` block plus the full root configuration for contextual needs.
A provider must implement `Identifier()` and `Authenticate()`. To make it available to the access manager, call `RegisterProvider` inside `init` with an initialized provider instance.
## Error Semantics
- `ErrNoCredentials`: no credentials were present or recognized by any provider.
- `ErrInvalidCredential`: at least one provider processed the credentials but rejected them.
- `ErrNotHandled`: instructs the manager to fall through to the next provider without affecting aggregate error reporting.
- `NewNoCredentialsError()` (`AuthErrorCodeNoCredentials`): no credentials were present or recognized. (HTTP 401)
- `NewInvalidCredentialError()` (`AuthErrorCodeInvalidCredential`): credentials were present but rejected. (HTTP 401)
- `NewNotHandledError()` (`AuthErrorCodeNotHandled`): fall through to the next provider.
- `NewInternalAuthError(message, cause)` (`AuthErrorCodeInternal`): transport/system failure. (HTTP 500)
Return custom errors to surface transport failures; they propagate immediately to the caller instead of being masked.
Errors propagate immediately to the caller unless they are classified as `not_handled` / `no_credentials` / `invalid_credential` and can be aggregated by the manager.
## Integration with cliproxy Service
`sdk/cliproxy` wires `@sdk/access` automatically when you build a CLI service via `cliproxy.NewBuilder`. Supplying a preconfigured manager allows you to extend or override the default providers:
`sdk/cliproxy` wires `@sdk/access` automatically when you build a CLI service via `cliproxy.NewBuilder`. Supplying a manager lets you reuse the same instance in your host process:
```go
coreCfg, _ := config.LoadConfig("config.yaml")
providers, _ := sdkaccess.BuildProviders(coreCfg)
manager := sdkaccess.NewManager()
manager.SetProviders(providers)
accessManager := sdkaccess.NewManager()
svc, _ := cliproxy.NewBuilder().
WithConfig(coreCfg).
WithAccessManager(manager).
WithConfigPath("config.yaml").
WithRequestAccessManager(accessManager).
Build()
```
The service reuses the manager for every inbound request, ensuring consistent authentication across embedded deployments and the canonical CLI binary.
Register any custom providers (typically via blank imports) before calling `Build()` so they are present in the global registry snapshot.
### Hot reloading providers
### Hot reloading
When configuration changes, rebuild providers and swap them into the manager:
When configuration changes, refresh any config-backed providers and then reset the manager's provider chain:
```go
providers, err := sdkaccess.BuildProviders(newCfg)
if err != nil {
log.Errorf("reload auth providers failed: %v", err)
return
}
accessManager.SetProviders(providers)
// configaccess is github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access
configaccess.Register(&newCfg.SDKConfig)
accessManager.SetProviders(sdkaccess.RegisteredProviders())
```
This mirrors the behaviour in `cliproxy.Service.refreshAccessProviders` and `api.Server.applyAccessConfig`, enabling runtime updates without restarting the process.
This mirrors the behaviour in `internal/access.ApplyAccessProviders`, enabling runtime updates without restarting the process.
+51 -73
View File
@@ -7,80 +7,71 @@
```go
import (
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
)
```
通过 `go get github.com/router-for-me/CLIProxyAPI/v6/sdk/access` 添加依赖。
## Provider Registry
访问提供者是全局注册,然后以快照形式挂到 `Manager` 上:
- `RegisterProvider(type, provider)` 注册一个已经初始化好的 provider 实例。
- 每个 `type` 第一次出现时会记录其注册顺序。
- `RegisteredProviders()` 会按该顺序返回 provider 列表。
## 管理器生命周期
```go
manager := sdkaccess.NewManager()
providers, err := sdkaccess.BuildProviders(cfg)
if err != nil {
return err
}
manager.SetProviders(providers)
manager.SetProviders(sdkaccess.RegisteredProviders())
```
- `NewManager` 创建空管理器。
- `SetProviders` 替换提供者切片并做防御性拷贝。
- `Providers` 返回适合并发读取的快照。
- `BuildProviders` 将 `config.Config` 中的访问配置转换成可运行的提供者。当配置没有显式声明但包含顶层 `api-keys` 时,会自动挂载内建的 `config-api-key` 提供者。
如果管理器本身为 `nil` 或未配置任何 provider,调用会返回 `nil, nil`,可视为关闭访问控制。
## 认证请求
```go
result, err := manager.Authenticate(ctx, req)
result, authErr := manager.Authenticate(ctx, req)
switch {
case err == nil:
case authErr == nil:
// Authentication succeeded; result carries provider and principal.
case errors.Is(err, sdkaccess.ErrNoCredentials):
case sdkaccess.IsAuthErrorCode(authErr, sdkaccess.AuthErrorCodeNoCredentials):
// No recognizable credentials were supplied.
case errors.Is(err, sdkaccess.ErrInvalidCredential):
case sdkaccess.IsAuthErrorCode(authErr, sdkaccess.AuthErrorCodeInvalidCredential):
// Credentials were present but rejected.
default:
// Provider surfaced a transport-level failure.
}
```
`Manager.Authenticate` 按配置顺序遍历提供者。遇到成功立即返回,`ErrNotHandled` 会继续尝试下一个;若发现 `ErrNoCredentials` 或 `ErrInvalidCredential`,会在遍历结束后汇总给调用方。
若管理器本身为 `nil` 或尚未注册提供者,调用会返回 `nil, nil`,让调用方无需针对错误做额外分支即可关闭访问控制。
`Manager.Authenticate` 会按顺序遍历 provider:遇到成功立即返回,`AuthErrorCodeNotHandled` 会继续尝试下一个;`AuthErrorCodeNoCredentials` / `AuthErrorCodeInvalidCredential` 会在遍历结束后汇总给调用方。
`Result` 提供认证提供者标识、解析出的主体以及可选元数据(例如凭证来源)。
## 配置结构
## 内建 `config-api-key` Provider
在 `config.yaml` 的 `auth.providers` 下定义访问提供者:
代理内置一个访问提供者:
- `config-api-key`:校验 `config.yaml` 顶层的 `api-keys`。
- 凭证来源:`Authorization: Bearer`、`X-Goog-Api-Key`、`X-Api-Key`、`?key=`、`?auth_token=`
- 元数据:`Result.Metadata["source"]` 会写入匹配到的来源标识
在 CLI 服务端与 `sdk/cliproxy` 中,该 provider 会根据加载到的配置自动注册。
```yaml
auth:
providers:
- name: inline-api
type: config-api-key
api-keys:
- sk-test-123
- sk-prod-456
api-keys:
- sk-test-123
- sk-prod-456
```
条目映射到 `config.AccessProvider`:`name` 指定实例名,`type` 选择注册的工厂,`sdk` 可引用第三方模块,`api-keys` 提供内联凭证,`config` 用于传递特定选项。
## 引入外部 Go 模块提供者
### 引入外部 SDK 提供者
若要消费其它 Go 模块输出的访问提供者,可在配置里填写 `sdk` 字段并在代码中引入该包,利用其 `init` 注册过程:
```yaml
auth:
providers:
- name: partner-auth
type: partner-token
sdk: github.com/acme/xplatform/sdk/access/providers/partner
config:
region: us-west-2
audience: cli-proxy
```
若要消费其它 Go 模块输出的访问提供者,直接用空白标识符导入以触发其 `init` 注册即可:
```go
import (
@@ -89,19 +80,11 @@ import (
)
```
通过空白标识符导入即可确保 `init` 调用,先于 `BuildProviders` 完成 `sdkaccess.RegisterProvider`。
## 内建提供者
当前 SDK 默认内置:
- `config-api-key`:校验配置中的 API Key。它从 `Authorization: Bearer`、`X-Goog-Api-Key`、`X-Api-Key` 以及查询参数 `?key=` 提取凭证,不匹配时抛出 `ErrInvalidCredential`。
导入第三方包即可通过 `sdkaccess.RegisterProvider` 注册更多类型。
空白导入可确保 `init` 先执行,从而在你调用 `RegisteredProviders()`(或 `cliproxy.NewBuilder().Build()`)之前完成 `sdkaccess.RegisterProvider`。
### 元数据与审计
`Result.Metadata` 用于携带提供者特定的上下文信息。内建的 `config-api-key` 会记录凭证来源(`authorization`、`x-goog-api-key`、`x-api-key` 或 `query-key`)。自定义提供者同样可以填充该 Map,以便丰富日志与审计场景。
`Result.Metadata` 用于携带提供者特定的上下文信息。内建的 `config-api-key` 会记录凭证来源(`authorization`、`x-goog-api-key`、`x-api-key`、`query-key`、`query-auth-token`)。自定义提供者同样可以填充该 Map,以便丰富日志与审计场景。
## 编写自定义提供者
@@ -110,13 +93,13 @@ type customProvider struct{}
func (p *customProvider) Identifier() string { return "my-provider" }
func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sdkaccess.Result, error) {
func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sdkaccess.Result, *sdkaccess.AuthError) {
token := r.Header.Get("X-Custom")
if token == "" {
return nil, sdkaccess.ErrNoCredentials
return nil, sdkaccess.NewNotHandledError()
}
if token != "expected" {
return nil, sdkaccess.ErrInvalidCredential
return nil, sdkaccess.NewInvalidCredentialError()
}
return &sdkaccess.Result{
Provider: p.Identifier(),
@@ -126,51 +109,46 @@ func (p *customProvider) Authenticate(ctx context.Context, r *http.Request) (*sd
}
func init() {
sdkaccess.RegisterProvider("custom", func(cfg *config.AccessProvider, root *config.Config) (sdkaccess.Provider, error) {
return &customProvider{}, nil
})
sdkaccess.RegisterProvider("custom", &customProvider{})
}
```
自定义提供者需要实现 `Identifier()` 与 `Authenticate()`。在 `init` 中调用 `RegisterProvider` 暴露给配置层,工厂函数既能读取当前条目,也能访问完整根配置。
自定义提供者需要实现 `Identifier()` 与 `Authenticate()`。在 `init` 中用已初始化实例调用 `RegisterProvider` 注册到全局 registry。
## 错误语义
- `ErrNoCredentials`:任何提供者都未识别到凭证。
- `ErrInvalidCredential`:至少一个提供者处理了凭证但判定无效。
- `ErrNotHandled`:告诉管理器跳到下一个提供者,不影响最终错误统计。
- `NewNoCredentialsError()`(`AuthErrorCodeNoCredentials`):未提供或未识别到凭证。(HTTP 401)
- `NewInvalidCredentialError()`(`AuthErrorCodeInvalidCredential`):凭证存在但校验失败。(HTTP 401)
- `NewNotHandledError()`(`AuthErrorCodeNotHandled`):告诉管理器跳到下一个 provider。
- `NewInternalAuthError(message, cause)`(`AuthErrorCodeInternal`):网络/系统错误。(HTTP 500)
自定义错误(例如网络异常)会马上冒泡返回。
除可汇总的 `not_handled` / `no_credentials` / `invalid_credential` 外,其它错误会立即冒泡返回。
## 与 cliproxy 集成
使用 `sdk/cliproxy` 构建服务时会自动接入 `@sdk/access`。如果需要扩展内置行为,可传入自定义管理器:
使用 `sdk/cliproxy` 构建服务时会自动接入 `@sdk/access`。如果希望在宿主进程里复用同一个 `Manager` 实例,可传入自定义管理器:
```go
coreCfg, _ := config.LoadConfig("config.yaml")
providers, _ := sdkaccess.BuildProviders(coreCfg)
manager := sdkaccess.NewManager()
manager.SetProviders(providers)
accessManager := sdkaccess.NewManager()
svc, _ := cliproxy.NewBuilder().
WithConfig(coreCfg).
WithAccessManager(manager).
WithConfigPath("config.yaml").
WithRequestAccessManager(accessManager).
Build()
```
服务会复用该管理器处理每一个入站请求,实现与 CLI 二进制一致的访问控制体验。
请在调用 `Build()` 之前完成自定义 provider 的注册(通常通过空白导入触发 `init`),以确保它们被包含在全局 registry 的快照中。
### 动态热更新提供者
当配置发生变化时,可以重新构建提供者并替换当前列表:
当配置发生变化时,刷新依赖配置的 provider,然后重置 manager 的 provider 链:
```go
providers, err := sdkaccess.BuildProviders(newCfg)
if err != nil {
log.Errorf("reload auth providers failed: %v", err)
return
}
accessManager.SetProviders(providers)
// configaccess is github.com/router-for-me/CLIProxyAPI/v6/internal/access/config_access
configaccess.Register(&newCfg.SDKConfig)
accessManager.SetProviders(sdkaccess.RegisteredProviders())
```
这一流程与 `cliproxy.Service.refreshAccessProviders` 和 `api.Server.applyAccessConfig` 保持一致,避免为更新访问策略而重启进程。
这一流程与 `internal/access.ApplyAccessProviders` 保持一致,避免为更新访问策略而重启进程。
+29
View File
@@ -0,0 +1,29 @@
# Session Progress - 2026-03-07
## Summary
Merged upstream CLIProxyAPI releases `v6.8.40` through `v6.8.46` into ProxyPilot on branch `sync-upstream-v6.8.40-to-v6.8.46` and prepared the next dev release tag `v0.3.0-dev-0.40`.
## Upstream Releases Included
- `v6.8.40` - adaptive thinking updates across Claude, Codex, OpenAI, and Antigravity flows
- `v6.8.41` - auth file handling follow-ups, Antigravity effort mapping, watcher synth changes
- `v6.8.42` - excluded Vertex models support, `defer_loading` stripping, Gemini schema cleanup
- `v6.8.43` - Claude SSE decompression fixes, watcher debounce fixes, codex response cleanup
- `v6.8.44` - watcher timer fix and initial GPT-5.4 registry entry
- `v6.8.45` - GPT-5.4 description cleanup and conditional `service_tier` handling
- `v6.8.46` - Gemini 3.1 Flash Lite Preview registry support and Codex websocket `response.create` cleanup
## Conflict Resolution Notes
- Kept ProxyPilot branding in `README.md` during the `v6.8.41` merge.
- Preserved deletion of `README_CN.md` when upstream tried to reintroduce it.
- Accepted upstream behavior in translator, watcher, executor, and registry paths unless the fork already had a stronger ProxyPilot-specific customization.
## Verification
- Clean `origin/main` baseline still fails `go test ./sdk/cliproxy/auth` in `TestFileStore_Delete_RemovesFile`; treated as a pre-existing failure.
- Targeted subsystem checks passed after each upstream merge for thinking, translators, watcher, registry, executor, and OpenAI websocket paths.
- Final full-suite verification should still record the pre-existing `sdk/cliproxy/auth` failure explicitly if it remains on the final release commit.
## Release Notes
- Next dev tag: `v0.3.0-dev-0.40`
- Upstream marker files updated:
- `UPSTREAM_VERSION` -> `v6.8.46`
- `features.json.upstream` -> `CLIProxyAPI v6.8.46`
+36
View File
@@ -0,0 +1,36 @@
# Session Progress - 2026-03-09
## Summary
Merged upstream CLIProxyAPI releases `v6.8.47` through `v6.8.49` into ProxyPilot on branch `sync-upstream-v6.8.47-to-v6.8.49`, fixed fork-specific release lookup drift, and prepared the next dev release tag `v0.3.0-dev-0.41`.
## Upstream Releases Included
- `v6.8.47` - watcher incremental auth-file changes, websocket follow-ups, and OpenAI-to-Claude request coverage
- `v6.8.48` - auth scheduler implementation, registry safety fixes, adaptive thinking pass-through, and Gemini/Vertex/model updates
- `v6.8.49` - scheduler refresh regression fix and OpenAI-to-Gemini `systemInstruction` camelCase correction
## Conflict Resolution Notes
- Kept ProxyPilot branding and structure in `README.md` during the `v6.8.49` merge.
- Preserved deletion of `README_CN.md` when upstream tried to reintroduce it.
- Accepted upstream behavior in watcher, registry, auth scheduler, translator, and executor paths unless the fork already had a stronger ProxyPilot-specific customization.
## Fork-Specific Follow-Ups
- Updated `UPSTREAM_VERSION` to `v6.8.49`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.49`.
- Fixed `.github/workflows/check-upstream.yml` so it compares the tracked `UPSTREAM_VERSION` tag against the latest upstream release tag instead of comparing upstream HEAD to itself.
- Switched fork-facing release lookups in `internal/api/handlers/management/config_basic.go` and `internal/proxypilotupdate/github.go` to `Finesssee/ProxyPilot` releases.
## Verification
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
- `go vet ./...` - PASS
- `go test ./...` - FAIL, but only on the pre-existing baseline failure in `sdk/cliproxy/auth`:
- `TestFileStore_Delete_RemovesFile/deletes_file_in_subdirectory`
- Spot-checked changed packages through the full test sweep:
- `internal/api/handlers/management` - PASS
- `internal/proxypilotupdate` - no test files
- `internal/registry` - PASS
- `internal/runtime/executor` - PASS
- `internal/watcher` - PASS
## Release Notes
- Next dev tag: `v0.3.0-dev-0.41`
- Latest upstream target at merge time: `CLIProxyAPI v6.8.49`
+84
View File
@@ -0,0 +1,84 @@
# Session Progress - 2026-03-12
## Summary
Merged upstream CLIProxyAPI releases `v6.8.50` and `v6.8.51` directly into ProxyPilot `main`, resolved fork-specific conflicts in startup and Docker publishing paths, prepared the next dev release tag `v0.3.0-dev-0.42`, then switched release publishing to a local/manual flow and uploaded the release assets outside GitHub Actions.
## Upstream Releases Included
- `v6.8.50` - preserve string-form system prompts, cap websocket body log growth, and extend scheduler / executor coverage
- `v6.8.51` - refresh model catalog from network on startup, register Codex models by plan tier, and refresh release / workflow paths
## Conflict Resolution Notes
- Kept ProxyPilot Docker publishing identity in `.github/workflows/docker-image.yml` and added the upstream models catalog refresh step before image builds.
- Kept ProxyPilot's management-password startup flow in `cmd/server/main.go` and added `registry.StartModelsUpdater(...)` before service startup.
- Accepted the upstream move from generated static registry data to embedded `internal/registry/models/models.json`, including deletion of `internal/registry/model_definitions_static_data.go`.
## Fork-Specific Follow-Ups
- Updated `internal/cmd/list_models.go` to use the new Codex plan-tier model getters instead of the removed `registry.GetOpenAIModels`.
- Fixed `sdk/auth/filestore.go` delete-path resolution so nested relative auth IDs delete under the configured base dir, absolute paths still work for the management API, and traversal outside the base dir is rejected.
- Updated `UPSTREAM_VERSION` to `v6.8.51`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.51`.
- Changed `.github/workflows/proxypilot-release.yml` and `.github/workflows/docker-image.yml` from tag-triggered runs to manual dispatch so releases can be built locally and uploaded manually instead of consuming GitHub Actions minutes.
- Built the `v0.3.0-dev-0.42` release assets locally from the tag snapshot and uploaded:
- `proxypilot-darwin-amd64`
- `proxypilot-darwin-arm64`
- `proxypilot-linux-amd64`
- `proxypilot-linux-arm64`
- `proxypilot-windows-amd64.exe`
- `checksums.txt`
## Verification
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
- `go vet ./...` - PASS
- `go test ./internal/runtime/executor/...` - PASS
- `go test ./internal/registry/...` - PASS
- `go test ./sdk/api/handlers/openai/...` - PASS
- `go test ./sdk/cliproxy/auth -run 'TestFileStore_Delete_(RemovesFile|NotFound|AbsolutePath|RejectsTraversalOutsideBaseDir)' -v` - PASS
- `go test ./sdk/cliproxy/auth` - PASS
- `go test ./sdk/cliproxy/...` - PASS
- `go test ./...` - PASS
## Release Notes
- Next dev tag: `v0.3.0-dev-0.42`
- Latest upstream target at merge time: `CLIProxyAPI v6.8.51`
## Maintenance Review
- Completed parallel findings-first review of `internal/auth/*`, `internal/translator/*`, and `internal/api/handlers/*` on 2026-03-12 12:01:40 +07.
- Auth review findings:
- `internal/auth/kiro/token_repository.go` only queues `auth_method` values `idc` and `builder-id` for background refresh even though `internal/auth/kiro/oauth.go` persists social logins as `auth_method: "social"` and the refresher has a default OAuth refresh path for non-SSO methods. Result: Google/GitHub Kiro tokens are skipped by auto-refresh.
- `internal/auth/kiro/token_repository.go` walks nested token files but rewrites refreshed tokens back to `filepath.Join(baseDir, token.ID)` after truncating IDs to `filepath.Base(path)`. Result: nested Kiro token files would be rewritten into the auth root instead of their original directory.
- Translator review findings:
- `internal/translator/kiro/openai` can emit streamed tool-call argument deltas with the wrong OpenAI tool index.
- `internal/translator/kiro/openai` does not actually enforce `tool_choice`; it still forwards tools when callers request `none` or pin a specific function.
- `internal/translator/openai/openai/responses` downgrades `developer` messages to `user`.
- `internal/translator/gemini/openai/chat-completions` reads/mapping finish reasons incorrectly for some response shapes.
- `internal/translator/gemini/openai/responses` can send `functionResponse.name = "unknown"` on follow-up tool-output requests.
- API handler review findings:
- `internal/api/handlers/management/memory.go` uses raw `session` query values to build filesystem paths for delete/export/import instead of the memory store's sanitized session path helper, allowing traversal outside the memory store root.
- `internal/api/handlers/management/generic_import.go` derives auth filenames from the first characters of imported API keys, exposing secret prefixes in filenames and management responses.
- `internal/api/handlers/management/auth_files.go` writes uploaded auth files to disk before validation and leaves invalid files behind on registration failure.
- `internal/api/handlers/management/config_basic.go` returns a zero-value config from `GetConfig` because it serializes `new(*h.cfg)` instead of the current config.
- `internal/api/handlers/management/auth_priority.go` and `internal/api/handlers/management/auth_files.go` update priority in places the runtime selector does not read, so management-set auth priority does not affect routing and does not persist reliably for file-backed auths.
- Config mutation helpers in `internal/api/handlers/management/handler.go` mutate `h.cfg` before persistence succeeds, so failed writes can leave runtime config diverged from disk until restart.
- Review validation:
- `go test ./internal/auth/... ./internal/translator/... ./internal/api/handlers/...` - PASS
## Maintenance Fixes
- Hardened management memory delete/export/import so session names are validated before resolving filesystem paths, blocking traversal attempts outside the memory store root.
- Changed bulk API-key import filenames to opaque `provider-import-...` names so credential prefixes are no longer exposed in filenames or management responses.
- Changed auth upload handling to validate uploaded JSON before committing it to disk and to roll back failed registrations instead of leaving broken auth files behind.
- Fixed `GetConfig` to return the live in-memory config and changed the simple config mutation helpers to persist cloned config state instead of mutating runtime config before the file write succeeds.
- Fixed file-backed auth persistence so `priority`, `prefix`, and `proxy_url` survive saves, reloads, and management edits, and so runtime selection prefers `Auth.Priority` with a legacy attribute fallback.
- Changed token writers across codex, claude, gemini, kimi, qwen, iflow, copilot, and vertex to use atomic `0600` JSON writes.
- Fixed Kiro background refresh so blank refresh responses do not erase the existing refresh token, nested token paths refresh in place, and social auth token files participate in the refresh scan.
- Fixed Kiro OAuth callback servers so shutdown waits on a dedicated completion signal instead of racing the login flow for the only callback result.
- Fixed Kiro/OpenAI tool streaming to keep a stable mapping from content-block indexes to OpenAI tool ordinals.
- Fixed Kiro/OpenAI request translation so `tool_choice=none|required|function` is enforced instead of treated as a prompt-only hint.
- Fixed OpenAI Responses to Chat Completions conversion to preserve `developer` role messages.
- Fixed Gemini/OpenAI finish-reason mapping so OpenAI receives valid enums while the original Gemini reason is preserved in `native_finish_reason`.
- Added a bounded Gemini function-call name cache so `previous_response_id` follow-up tool outputs resolve the original function name and fail closed when they cannot.
## Maintenance Fix Verification
- `go test ./internal/auth/... ./sdk/auth ./sdk/cliproxy/auth ./internal/translator/... ./internal/api/handlers/...` - PASS
- `go test ./internal/api/handlers/management` - PASS
- `go test ./...` - PASS
- `go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
+28
View File
@@ -0,0 +1,28 @@
# Session Progress - 2026-03-17
## Summary
Merged upstream CLIProxyAPI release `v6.8.55` into ProxyPilot `main`, carrying forward the fork's workflow and branding decisions while absorbing upstream changes from `v6.8.52` through `v6.8.55`.
Built the release assets locally and published `v0.3.0-dev-0.43` on GitHub as the latest ProxyPilot release.
## Upstream Releases Included
- `v6.8.52` - Codex websocket header defaults and related compatibility updates
- `v6.8.53` - Antigravity model refresh and proxy helper improvements
- `v6.8.54` - auth file metadata exposure and management API test coverage
- `v6.8.55` - auth list priority/note support, Gemini responses tool-output fixes, and proxy utility additions
## Conflict Resolution Notes
- Kept the fork versions of `.github/workflows/docker-image.yml`, `.github/workflows/release.yaml`, `.github/workflows/pr-test-build.yml`, and `.goreleaser.yml` so this sync does not alter CI or release automation.
- Kept ProxyPilot README branding and deleted the upstream `README_CN.md` revival because this fork intentionally does not ship that file.
- Merged `internal/api/handlers/management/auth_files.go` semantically so ProxyPilot keeps its `Auth.Priority` persistence while also adding upstream `note` support and priority/note exposure in the auth-file API.
- Kept the stricter Gemini Responses JSON validation in `internal/translator/gemini/openai/responses/gemini_openai-responses_request.go` so partial JSON strings are not embedded as structured results.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.8.55`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.8.55`.
- Published dev release: `v0.3.0-dev-0.43`.
## Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack` - PASS
- `mise exec go@1.26.0 -- go vet ./...` - PASS
- `mise exec go@1.26.0 -- go test ./...` - PASS
- `gh release list -R Finesssee/ProxyPilot --limit 5` - PASS (`v0.3.0-dev-0.43` is `Latest`)
+26
View File
@@ -0,0 +1,26 @@
# Session Progress - 2026-04-01
## Summary
Merged upstream CLIProxyAPI release `v6.9.7` into ProxyPilot on a dedicated sync branch, carrying forward ProxyPilot branding and local-manual release workflow choices while absorbing the upstream changes from `v6.9.6` and `v6.9.7`.
Re-established a fully local Windows installer build path on Linux using a repo-scoped Wine prefix plus Inno Setup so the `Setup.exe` can be built without CI/CD.
## Upstream Releases Included
- `v6.9.6` - intermediate upstream changes now included through the `v6.9.7` merge
- `v6.9.7` - Codex executor/cache behavior updates, Amp response rewriting improvements, scheduler/auth updates, and related tests
## Conflict Resolution Notes
- Kept the ProxyPilot README and removed upstream `README_CN.md` and `README_JA.md` revivals because this fork intentionally does not ship those translation files.
- Followed upstream on the Codex continuity revert by deleting `internal/runtime/executor/codex_continuity.go` and aligning the Codex cache tests with `v6.9.7`, since upstream explicitly reverted that helper rather than evolving it.
- Preserved the existing fork policy of local/manual releases instead of changing CI or workflow behavior as part of this sync.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.7`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.7`.
- Prepared a local Windows installer toolchain using Wine + Inno Setup for the upcoming `v0.3.0-dev-0.47` release build.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.47`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+28
View File
@@ -0,0 +1,28 @@
# Session Progress - 2026-04-03
## Summary
Merged upstream CLIProxyAPI release `v6.9.10` into ProxyPilot on a dedicated sync branch and preserved the fork's local/manual release workflow.
Reconciled upstream's executor helper-package move with ProxyPilot's existing executor call sites by keeping the new `internal/runtime/executor/helps/` layout while restoring compatibility entrypoints in `internal/runtime/executor/`.
## Upstream Releases Included
- `v6.9.8` - intermediate upstream changes now included through the `v6.9.10` merge
- `v6.9.9` - intermediate upstream changes now included through the `v6.9.10` merge
- `v6.9.10` - latest upstream sync target for this release cycle
## Conflict Resolution Notes
- Kept the ProxyPilot README and continued to omit upstream `README_CN.md` and `README_JA.md` revivals because this fork does not ship those translation files.
- Preserved ProxyPilot's auth-file persistence behavior, including `prefix`, `proxy_url`, `priority`, and last-refresh handling, while also bringing in upstream custom-header hydration and patch support.
- Kept upstream's `internal/runtime/executor/helps/` reorganization, but restored executor-package compatibility wrappers/files so existing fork-specific executors still compile without a larger refactor in the same release pass.
- Continued to omit the upstream TUI translation/usage-tab files because ProxyPilot's current TUI surface does not carry those forked files.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.10`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.10`.
- Recorded the merge commit `chore: merge upstream CLIProxyAPI v6.9.10` before starting validation and release assembly.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.48`
- `gh release list -R Finesssee/ProxyPilot --limit 5`
+26
View File
@@ -0,0 +1,26 @@
# Session Progress - 2026-04-04
## Summary
Merged upstream CLIProxyAPI release `v6.9.12` into ProxyPilot on a dedicated sync branch and kept the existing local/manual release workflow unchanged.
This catch-up pull included the upstream delta from `v6.9.11` through `v6.9.12` and merged cleanly without any fork-specific conflict resolution work.
## Upstream Releases Included
- `v6.9.11` - intermediate upstream changes now included through the `v6.9.12` merge
- `v6.9.12` - latest upstream sync target for this release cycle
## Merge Notes
- The merge applied cleanly with upstream changes concentrated in `config.example.yaml`, `internal/config/sdk_config.go`, `internal/runtime/executor/qwen_executor.go`, and `sdk/api/handlers/gemini/gemini-cli_handlers.go`.
- No additional ProxyPilot compatibility shims were needed beyond the executor-wrapper structure restored in the prior sync.
- ProxyPilot branding, release routing, and local-build release flow remain unchanged.
## Repo State Updates
- Updated `UPSTREAM_VERSION` to `v6.9.12`.
- Updated `features.json` upstream marker to `CLIProxyAPI v6.9.12`.
- Prepared the repo for the next local/manual release: `v0.3.0-dev-0.49`.
## Pending Verification
- `mise exec go@1.26.0 -- go build ./cmd/server ./cmd/proxypilot-tray ./cmd/proxypilotpack`
- `mise exec go@1.26.0 -- go vet ./...`
- `mise exec go@1.26.0 -- go test ./...`
- full local release asset build for `v0.3.0-dev-0.49`
- `gh release list -R Finesssee/ProxyPilot --limit 5`

Some files were not shown because too many files have changed in this diff Show More