Compare commits

...
Author SHA1 Message Date
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
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
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
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
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
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
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
Luis Pater e18e288fda fix(registry): Remove gemini-2.5-flash-image Gemini models from gemini cli and add gemini-2.5-flash-image preview to AIStudio
These models were likely for internal preview or testing and are no longer relevant for public use.
2025-11-04 03:02:16 +08:00
Luis Pater 38cfbac8f0 fix(executor): adjust Anthropic-Beta header handling for consistent API requests 2025-11-03 20:49:01 +08:00
Luis Pater 5be4d22b9b fix(executor): ensure consistent header application in Claude API requests 2025-11-03 17:57:20 +08:00
Luis Pater 64774a5786 fix(executor): remove safetySettings from payload in token counting request 2025-11-03 17:31:43 +08:00
Luis Pater 16b0a561d7 docs: remove MANAGEMENT_API documentation files (EN and CN)
- Deleted `MANAGEMENT_API.md` and `MANAGEMENT_API_CN.md` as they are no longer necessary.
- Streamlined project documentation by removing redundant API details already covered elsewhere.
2025-11-03 11:17:31 +08:00
Luis Pater 21dde0e352 docs: expand MANAGEMENT_API documentation with new endpoints and fields
- Added detailed descriptions for new `/config.yaml` endpoints (GET/PUT).
- Documented API responses, error codes, and enhancements for log management, usage statistics, and OAuth flows.
- Updated examples and notes for better clarity across both EN and CN versions.
2025-11-03 09:59:54 +08:00
Luis Pater b040a43b81 docs: minimalize and clean README content
- Streamlined Chinese README by reducing redundancy and unnecessary sections.
- Added a concise link to CLIProxyAPI user manual for detailed instructions.
- Reorganized the original README with a simplified overview.
2025-11-03 09:27:18 +08:00
Luis Pater bccefb2905 docs: minimalize and clean README content
- Streamlined Chinese README by reducing redundancy and unnecessary sections.
- Added a concise link to CLIProxyAPI user manual for detailed instructions.
- Reorganized the original README with a simplified overview.
2025-11-03 09:22:31 +08:00
Luis Pater b26ec8162d docs: minimalize and clean README content
- Streamlined Chinese README by reducing redundancy and unnecessary sections.
- Added a concise link to CLIProxyAPI user manual for detailed instructions.
- Reorganized the original README with a simplified overview.
2025-11-03 09:21:23 +08:00
Luis Pater ee0a91f539 Update GitHub funding model with username 2025-11-03 08:57:08 +08:00
Luis Pater 89b0d53a09 fix(executor): remove safetySettings from payload for Gemini requests 2025-11-01 16:53:48 +08:00
Luis Pater fd2b23592e Fixed: #193
fix(translator): consolidate temperature and top_p conditionals in OpenAI Claude request

Fixed: #169

fix(translator): adjust instruction strings in Codex Claude and OpenAI responses
2025-11-01 15:37:51 +08:00
Luis Pater 4d0804687c Merge pull request #194 from router-for-me/gemini-key
Add Gemini API key endpoints
2025-10-31 19:18:54 +08:00
hkfires 2021ae3891 fix(config): skip persisting empty API key and compat entries 2025-10-31 15:56:47 +08:00
hkfires 4883349795 Update doc 2025-10-31 15:22:09 +08:00
hkfires 5c65938113 fix(config): stabilize YAML sequence merges by reordering items 2025-10-31 15:21:58 +08:00
hkfires 16be3f0a12 fix(config): dedupe and normalize Gemini keys and headers 2025-10-31 13:20:10 +08:00
hkfires 7c1c4ee60b feat(gemini): add Gemini API key endpoints 2025-10-31 11:09:28 +08:00
Luis Pater 96c7271448 Merge pull request #191 from router-for-me/gemini
Add safety settings for gemini models
2025-10-31 09:24:37 +08:00
Luis Pater 07da781336 feat(registry): add client model support check for executor filtering
- Introduced `ClientSupportsModel` function to `ModelRegistry` for verifying client support for specific models.
- Integrated model support validation into executor candidate filtering logic.
- Updated CLIProxy registry interface to include the new support check method.
2025-10-31 09:15:14 +08:00
hkfires a53c84d0d1 feat(gemini): apply default safety settings across request translators 2025-10-31 08:22:16 +08:00
hkfires a517290726 refactor(executor): summarize API error bodies of html in debug logs 2025-10-31 06:58:38 +08:00
Luis Pater af3fbd134d fix(translator): remove strict key from function declaration to prevent errors during schema transformation 2025-10-30 13:14:26 +08:00
Luis Pater 2f477df97e feat(translator): add built-in translator registry and helpers
- Introduced `builtin` package exposing a default registry and pipeline for built-in translators.
- Added format constants for common schemas (e.g., OpenAI, Gemini, Codex).
- Implemented helper functions for schema translation using format name strings.
- Provided example usage for integration with translator helpers.
2025-10-30 12:20:46 +08:00
Luis Pater 3e7b645346 Merge pull request #186 from router-for-me/doc
docs: add AI Studio setup
2025-10-29 21:53:49 +08:00
hkfires 24446a4dc4 feat(cliproxy): skip persisting runtime-only websocket auths 2025-10-29 21:49:35 +08:00
hkfires 475f473dab docs: add AI Studio setup 2025-10-29 21:10:14 +08:00
Luis Pater 8dba32a077 Merge pull request #185 from router-for-me/thinking
Feat: Add reasoning effort support for Gemini models
2025-10-29 20:27:07 +08:00
hkfires 1bbbd16df6 chore(logging): clarify 429 rate-limit retries in Gemini executor 2025-10-29 19:19:18 +08:00
hkfires 5cb378256b feat(gemini-translators): set include_thoughts when mapping thinking 2025-10-29 19:19:18 +08:00
hkfires 3ac5f05e8c feat(gemini): prefer official reasoning fields, add extra_body(cherry studio) fallback 2025-10-29 19:19:18 +08:00
hkfires 58d30369b4 fix(gemini-cli): correctly strip/normalize thinking config by model 2025-10-29 19:19:18 +08:00
hkfires 7dd93a4a25 fix(executor): only apply thinking config to supported models 2025-10-29 19:19:17 +08:00
hkfires 2a3ee8d0e3 fix(translators): normalize thinking budgets 2025-10-29 19:19:17 +08:00
hkfires 41577bce07 feat(claude): map Anthropic 'thinking' to Gemini thinkingBudget 2025-10-29 19:19:17 +08:00
hkfires 3d7aca22c0 feat(registry): add thinking budget support; populate Gemini models 2025-10-29 19:19:17 +08:00
hkfires 680b3f5010 fix(translator): avoid default thinkingConfig in Gemini requests 2025-10-29 19:19:17 +08:00
Luis Pater 9d42e4b239 feat(runtime): add User-Agent headers to codex and claude executors
- Standardized User-Agent strings for Codex and Claude executors to improve request tracing and compatibility.
- Updated header insertion logic in both executors for consistency.
2025-10-29 12:57:37 +08:00
Luis Pater 97af785aad docs(readme): add CLIProxyAPI Linux installer instructions
- Updated `README.md` and `README_CN.md` with steps to install via the Linux installer.
- Acknowledged [brokechubb](https://github.com/brokechubb) for building the installer.
2025-10-28 23:17:08 +08:00
453 changed files with 72418 additions and 12672 deletions
+4
View File
@@ -27,4 +27,8 @@ config.yaml
bin/*
.claude/*
.vscode/*
.gemini/*
.serena/*
.agent/*
.bmad/*
_bmad/*
+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
# ------------------------------------------------------------------------------
+1
View File
@@ -0,0 +1 @@
github: [router-for-me]
+1 -1
View File
@@ -7,7 +7,7 @@ on:
env:
APP_NAME: CLIProxyAPI
DOCKERHUB_REPO: eceasy/cli-proxy-api
DOCKERHUB_REPO: eceasy/cli-proxy-api-plus
jobs:
docker:
+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
+23
View File
@@ -0,0 +1,23 @@
name: pr-test-build
on:
pull_request:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- 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
+2 -1
View File
@@ -23,7 +23,8 @@ jobs:
cache: true
- name: Generate Build Metadata
run: |
echo VERSION=`git describe --tags --always --dirty` >> $GITHUB_ENV
VERSION=$(git describe --tags --always --dirty)
echo "VERSION=${VERSION}" >> $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
+33
View File
@@ -1,5 +1,6 @@
# Binaries
cli-proxy-api
cliproxy
*.exe
# Configuration
@@ -15,6 +16,10 @@ pgstore/*
gitstore/*
objectstore/*
static/*
refs/*
dist/*
.proxypilot/*
memory/*
# Authentication data
auths/*
@@ -22,6 +27,15 @@ auths/*
# 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
AGENTS.md
CLAUDE.md
GEMINI.md
@@ -29,4 +43,23 @@ GEMINI.md
# Tooling metadata
.vscode/*
.claude/*
.gemini/*
.serena/*
.agent/*
.bmad/*
_bmad/*
.mcp/cache/
# macOS
.DS_Store
._*
*.log
*_out.txt
# Added by Gemini CLI fix
node_modules/
dist/
.turbo/
.env
+7 -5
View File
@@ -1,5 +1,7 @@
builds:
- id: "cli-proxy-api"
- id: "cli-proxy-api-plus"
env:
- CGO_ENABLED=0
goos:
- linux
- windows
@@ -8,11 +10,11 @@ builds:
- amd64
- 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
format_overrides:
- goos: windows
@@ -34,4 +36,4 @@ changelog:
filters:
exclude:
- '^docs:'
- '^test:'
- '^test:'
+6 -6
View File
@@ -12,19 +12,19 @@ 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=0 GOOS=linux go build -ldflags="-s -w -X 'main.Version=${VERSION}-plus' -X 'main.Commit=${COMMIT}' -X 'main.BuildDate=${BUILD_DATE}'" -o ./CLIProxyAPIPlus ./cmd/server/
FROM alpine:3.22.0
RUN apk add --no-cache tzdata
RUN mkdir /CLIProxyAPI
RUN mkdir /ProxyPilot
COPY --from=builder ./app/CLIProxyAPI /CLIProxyAPI/CLIProxyAPI
COPY --from=builder ./app/CLIProxyAPIPlus /CLIProxyAPI/CLIProxyAPIPlus
COPY config.example.yaml /CLIProxyAPI/config.example.yaml
COPY config.example.yaml /ProxyPilot/config.example.yaml
WORKDIR /CLIProxyAPI
WORKDIR /ProxyPilot
EXPOSE 8317
@@ -32,4 +32,4 @@ ENV TZ=Asia/Shanghai
RUN cp /usr/share/zoneinfo/${TZ} /etc/localtime && echo "${TZ}" > /etc/timezone
CMD ["./CLIProxyAPI"]
CMD ["./CLIProxyAPIPlus"]
-689
View File
@@ -1,689 +0,0 @@
# Management API
Base path: `http://localhost:8317/v0/management`
This API manages the CLI Proxy API’s runtime configuration and authentication files. All changes are persisted to the YAML config file and hot‑reloaded by the service.
Note: The following options cannot be modified via API and must be set in the config file (restart if needed):
- `allow-remote-management`
- `remote-management-key` (if plaintext is detected at startup, it is automatically bcrypt‑hashed and written back to the config)
## Authentication
- All requests (including localhost) must provide a valid management key.
- Remote access requires enabling remote management in the config: `allow-remote-management: true`.
- Provide the management key (in plaintext) via either:
- `Authorization: Bearer <plaintext-key>`
- `X-Management-Key: <plaintext-key>`
Additional notes:
- If `remote-management.secret-key` is empty, the entire Management API is disabled (all `/v0/management` routes return 404).
- For remote IPs, 5 consecutive authentication failures trigger a temporary ban (~30 minutes) before further attempts are allowed.
If a plaintext key is detected in the config at startup, it will be bcrypt‑hashed and written back to the config file automatically.
## Request/Response Conventions
- Content-Type: `application/json` (unless otherwise noted).
- Boolean/int/string updates: request body is `{ "value": <type> }`.
- Array PUT: either a raw array (e.g. `["a","b"]`) or `{ "items": [ ... ] }`.
- Array PATCH: supports `{ "old": "k1", "new": "k2" }` or `{ "index": 0, "value": "k2" }`.
- Object-array PATCH: supports matching by index or by key field (specified per endpoint).
## Endpoints
### Usage Statistics
- GET `/usage` — Retrieve aggregated in-memory request metrics
- Response:
```json
{
"usage": {
"total_requests": 24,
"success_count": 22,
"failure_count": 2,
"total_tokens": 13890,
"requests_by_day": {
"2024-05-20": 12
},
"requests_by_hour": {
"09": 4,
"18": 8
},
"tokens_by_day": {
"2024-05-20": 9876
},
"tokens_by_hour": {
"09": 1234,
"18": 865
},
"apis": {
"POST /v1/chat/completions": {
"total_requests": 12,
"total_tokens": 9021,
"models": {
"gpt-4o-mini": {
"total_requests": 8,
"total_tokens": 7123,
"details": [
{
"timestamp": "2024-05-20T09:15:04.123456Z",
"tokens": {
"input_tokens": 523,
"output_tokens": 308,
"reasoning_tokens": 0,
"cached_tokens": 0,
"total_tokens": 831
}
}
]
}
}
}
}
}
}
```
- Notes:
- Statistics are recalculated for every request that reports token usage; data resets when the server restarts.
- Hourly counters fold all days into the same hour bucket (`00`–`23`).
### Config
- GET `/config` — Get the full config
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/config
```
- Response:
```json
{"debug":true,"proxy-url":"","api-keys":["1...5","JS...W"],"quota-exceeded":{"switch-project":true,"switch-preview-model":true},"generative-language-api-key":["AI...01","AI...02","AI...03"],"request-log":true,"request-retry":3,"claude-api-key":[{"api-key":"cr...56","base-url":"https://example.com/api","proxy-url":"socks5://proxy.example.com:1080","models":[{"name":"claude-3-5-sonnet-20241022","alias":"claude-sonnet-latest"}]},{"api-key":"cr...e3","base-url":"http://example.com:3000/api","proxy-url":""},{"api-key":"sk-...q2","base-url":"https://example.com","proxy-url":""}],"codex-api-key":[{"api-key":"sk...01","base-url":"https://example/v1","proxy-url":""}],"openai-compatibility":[{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk...01","proxy-url":""}],"models":[{"name":"moonshotai/kimi-k2:free","alias":"kimi-k2"}]},{"name":"iflow","base-url":"https://apis.iflow.cn/v1","api-key-entries":[{"api-key":"sk...7e","proxy-url":"socks5://proxy.example.com:1080"}],"models":[{"name":"deepseek-v3.1","alias":"deepseek-v3.1"},{"name":"glm-4.5","alias":"glm-4.5"},{"name":"kimi-k2","alias":"kimi-k2"}]}]}
```
### Debug
- GET `/debug` — Get the current debug state
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/debug
```
- Response:
```json
{ "debug": false }
```
- PUT/PATCH `/debug` — Set debug (boolean)
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/debug
```
- Response:
```json
{ "status": "ok" }
```
### Force GPT-5 Codex
- GET `/force-gpt-5-codex` — Get current flag
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/force-gpt-5-codex
```
- Response:
```json
{ "gpt-5-codex": false }
```
- PUT/PATCH `/force-gpt-5-codex` — Set boolean
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/force-gpt-5-codex
```
- Response:
```json
{ "status": "ok" }
```
### Proxy Server URL
- GET `/proxy-url` — Get the proxy URL string
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/proxy-url
```
- Response:
```json
{ "proxy-url": "socks5://user:pass@127.0.0.1:1080/" }
```
- PUT/PATCH `/proxy-url` — Set the proxy URL string
- Request (PUT):
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":"socks5://user:pass@127.0.0.1:1080/"}' \
http://localhost:8317/v0/management/proxy-url
```
- Request (PATCH):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":"http://127.0.0.1:8080"}' \
http://localhost:8317/v0/management/proxy-url
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/proxy-url` — Clear the proxy URL
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE http://localhost:8317/v0/management/proxy-url
```
- Response:
```json
{ "status": "ok" }
```
### Quota Exceeded Behavior
- GET `/quota-exceeded/switch-project`
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/quota-exceeded/switch-project
```
- Response:
```json
{ "switch-project": true }
```
- PUT/PATCH `/quota-exceeded/switch-project` — Boolean
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":false}' \
http://localhost:8317/v0/management/quota-exceeded/switch-project
```
- Response:
```json
{ "status": "ok" }
```
- GET `/quota-exceeded/switch-preview-model`
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/quota-exceeded/switch-preview-model
```
- Response:
```json
{ "switch-preview-model": true }
```
- PUT/PATCH `/quota-exceeded/switch-preview-model` — Boolean
- Request:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/quota-exceeded/switch-preview-model
```
- Response:
```json
{ "status": "ok" }
```
### API Keys (proxy service auth)
These endpoints update the inline `config-api-key` provider inside the `auth.providers` section of the configuration. Legacy top-level `api-keys` remain in sync automatically.
- GET `/api-keys` — Return the full list
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/api-keys
```
- Response:
```json
{ "api-keys": ["k1","k2","k3"] }
```
- PUT `/api-keys` — Replace the full list
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '["k1","k2","k3"]' \
http://localhost:8317/v0/management/api-keys
```
- Response:
```json
{ "status": "ok" }
```
- PATCH `/api-keys` — Modify one item (`old/new` or `index/value`)
- Request (by old/new):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"old":"k2","new":"k2b"}' \
http://localhost:8317/v0/management/api-keys
```
- Request (by index/value):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":0,"value":"k1b"}' \
http://localhost:8317/v0/management/api-keys
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/api-keys` — Delete one (`?value=` or `?index=`)
- Request (by value):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/api-keys?value=k1'
```
- Request (by index):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/api-keys?index=0'
```
- Response:
```json
{ "status": "ok" }
```
### Gemini API Key (Generative Language)
- GET `/generative-language-api-key`
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/generative-language-api-key
```
- Response:
```json
{ "generative-language-api-key": ["AIzaSy...01","AIzaSy...02"] }
```
- PUT `/generative-language-api-key`
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '["AIzaSy-1","AIzaSy-2"]' \
http://localhost:8317/v0/management/generative-language-api-key
```
- Response:
```json
{ "status": "ok" }
```
- PATCH `/generative-language-api-key`
- Request:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"old":"AIzaSy-1","new":"AIzaSy-1b"}' \
http://localhost:8317/v0/management/generative-language-api-key
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/generative-language-api-key`
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/generative-language-api-key?value=AIzaSy-2'
```
- Response:
```json
{ "status": "ok" }
```
### Codex API KEY (object array)
- GET `/codex-api-key` — List all
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/codex-api-key
```
- Response:
```json
{ "codex-api-key": [ { "api-key": "sk-a", "base-url": "", "proxy-url": "" } ] }
```
- PUT `/codex-api-key` — Replace the list
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"api-key":"sk-a","proxy-url":"socks5://proxy.example.com:1080"},{"api-key":"sk-b","base-url":"https://c.example.com","proxy-url":""}]' \
http://localhost:8317/v0/management/codex-api-key
```
- Response:
```json
{ "status": "ok" }
```
- PATCH `/codex-api-key` — Modify one (by `index` or `match`)
- Request (by index):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":1,"value":{"api-key":"sk-b2","base-url":"https://c.example.com","proxy-url":""}}' \
http://localhost:8317/v0/management/codex-api-key
```
- Request (by match):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"match":"sk-a","value":{"api-key":"sk-a","base-url":"","proxy-url":"socks5://proxy.example.com:1080"}}' \
http://localhost:8317/v0/management/codex-api-key
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/codex-api-key` — Delete one (`?api-key=` or `?index=`)
- Request (by api-key):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/codex-api-key?api-key=sk-b2'
```
- Request (by index):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/codex-api-key?index=0'
```
- Response:
```json
{ "status": "ok" }
```
### Request Retry Count
- GET `/request-retry` — Get integer
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/request-retry
```
- Response:
```json
{ "request-retry": 3 }
```
- PUT/PATCH `/request-retry` — Set integer
- Request:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":5}' \
http://localhost:8317/v0/management/request-retry
```
- Response:
```json
{ "status": "ok" }
```
### Request Log
- GET `/request-log` — Get boolean
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/request-log
```
- Response:
```json
{ "request-log": false }
```
- PUT/PATCH `/request-log` — Set boolean
- Request:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/request-log
```
- Response:
```json
{ "status": "ok" }
```
### Claude API KEY (object array)
- GET `/claude-api-key` — List all
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/claude-api-key
```
- Response:
```json
{ "claude-api-key": [ { "api-key": "sk-a", "base-url": "", "proxy-url": "" } ] }
```
- PUT `/claude-api-key` — Replace the list
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"api-key":"sk-a","proxy-url":"socks5://proxy.example.com:1080"},{"api-key":"sk-b","base-url":"https://c.example.com","proxy-url":""}]' \
http://localhost:8317/v0/management/claude-api-key
```
- Response:
```json
{ "status": "ok" }
```
- PATCH `/claude-api-key` — Modify one (by `index` or `match`)
- Request (by index):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":1,"value":{"api-key":"sk-b2","base-url":"https://c.example.com","proxy-url":""}}' \
http://localhost:8317/v0/management/claude-api-key
```
- Request (by match):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"match":"sk-a","value":{"api-key":"sk-a","base-url":"","proxy-url":"socks5://proxy.example.com:1080"}}' \
http://localhost:8317/v0/management/claude-api-key
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/claude-api-key` — Delete one (`?api-key=` or `?index=`)
- Request (by api-key):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/claude-api-key?api-key=sk-b2'
```
- Request (by index):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/claude-api-key?index=0'
```
- Response:
```json
{ "status": "ok" }
```
### OpenAI Compatibility Providers (object array)
- GET `/openai-compatibility` — List all
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/openai-compatibility
```
- Response:
```json
{ "openai-compatibility": [ { "name": "openrouter", "base-url": "https://openrouter.ai/api/v1", "api-key-entries": [ { "api-key": "sk", "proxy-url": "" } ], "models": [] } ] }
```
- PUT `/openai-compatibility` — Replace the list
- Request:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[{"name":"m","alias":"a"}]}]' \
http://localhost:8317/v0/management/openai-compatibility
```
- Response:
```json
{ "status": "ok" }
```
- PATCH `/openai-compatibility` — Modify one (by `index` or `name`)
- Request (by name):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"name":"openrouter","value":{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[]}}' \
http://localhost:8317/v0/management/openai-compatibility
```
- Request (by index):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":0,"value":{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[]}}' \
http://localhost:8317/v0/management/openai-compatibility
```
- Response:
```json
{ "status": "ok" }
```
- Notes:
- Legacy `api-keys` input remains accepted; keys are migrated into `api-key-entries` automatically so the legacy field will eventually remain empty in responses.
- DELETE `/openai-compatibility` — Delete (`?name=` or `?index=`)
- Request (by name):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/openai-compatibility?name=openrouter'
```
- Request (by index):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/openai-compatibility?index=0'
```
- Response:
```json
{ "status": "ok" }
```
### Auth File Management
Manage JSON token files under `auth-dir`: list, download, upload, delete.
- GET `/auth-files` — List
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/auth-files
```
- Response:
```json
{ "files": [ { "name": "acc1.json", "size": 1234, "modtime": "2025-08-30T12:34:56Z", "type": "google" } ] }
```
- GET `/auth-files/download?name=<file.json>` — Download a single file
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -OJ 'http://localhost:8317/v0/management/auth-files/download?name=acc1.json'
```
- POST `/auth-files` — Upload
- Request (multipart):
```bash
curl -X POST -F 'file=@/path/to/acc1.json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/auth-files
```
- Request (raw JSON):
```bash
curl -X POST -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d @/path/to/acc1.json \
'http://localhost:8317/v0/management/auth-files?name=acc1.json'
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/auth-files?name=<file.json>` — Delete a single file
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/auth-files?name=acc1.json'
```
- Response:
```json
{ "status": "ok" }
```
- DELETE `/auth-files?all=true` — Delete all `.json` files under `auth-dir`
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/auth-files?all=true'
```
- Response:
```json
{ "status": "ok", "deleted": 3 }
```
### Login/OAuth URLs
These endpoints initiate provider login flows and return a URL to open in a browser. Tokens are saved under `auths/` once the flow completes.
- GET `/anthropic-auth-url` — Start Anthropic (Claude) login
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/anthropic-auth-url
```
- Response:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/codex-auth-url` — Start Codex login
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/codex-auth-url
```
- Response:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/gemini-cli-auth-url` — Start Google (Gemini CLI) login
- Query params:
- `project_id` (optional): Google Cloud project ID.
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
'http://localhost:8317/v0/management/gemini-cli-auth-url?project_id=<PROJECT_ID>'
```
- Response:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/qwen-auth-url` — Start Qwen login (device flow)
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/qwen-auth-url
```
- Response:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/iflow-auth-url` — Start iFlow login
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/iflow-auth-url
```
- Response:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/get-auth-status?state=<state>` — Poll OAuth flow status
- Request:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
'http://localhost:8317/v0/management/get-auth-status?state=<STATE_FROM_AUTH_URL>'
```
- Response examples:
```json
{ "status": "wait" }
{ "status": "ok" }
{ "status": "error", "error": "Authentication failed" }
```
## Error Responses
Generic error format:
- 400 Bad Request: `{ "error": "invalid body" }`
- 401 Unauthorized: `{ "error": "missing management key" }` or `{ "error": "invalid management key" }`
- 403 Forbidden: `{ "error": "remote management disabled" }`
- 404 Not Found: `{ "error": "item not found" }` or `{ "error": "file not found" }`
- 500 Internal Server Error: `{ "error": "failed to save config: ..." }`
## Notes
- Changes are written back to the YAML config file and hot‑reloaded by the file watcher and clients.
- `allow-remote-management` and `remote-management-key` cannot be changed via the API; configure them in the config file.
-689
View File
@@ -1,689 +0,0 @@
# 管理 API
基础路径:`http://localhost:8317/v0/management`
该 API 用于管理 CLI Proxy API 的运行时配置与认证文件。所有变更会持久化写入 YAML 配置文件,并由服务自动热重载。
注意:以下选项不能通过 API 修改,需在配置文件中设置(如有必要可重启):
- `allow-remote-management`
- `remote-management-key`(若在启动时检测到明文,会自动进行 bcrypt 加密并写回配置)
## 认证
- 所有请求(包括本地访问)都必须提供有效的管理密钥.
- 远程访问需要在配置文件中开启远程访问: `allow-remote-management: true`
- 通过以下任意方式提供管理密钥(明文):
- `Authorization: Bearer <plaintext-key>`
- `X-Management-Key: <plaintext-key>`
若在启动时检测到配置中的管理密钥为明文,会自动使用 bcrypt 加密并回写到配置文件中。
其它说明:
- 若 `remote-management.secret-key` 为空,则管理 API 整体被禁用(所有 `/v0/management` 路由均返回 404)。
- 对于远程 IP,连续 5 次认证失败会触发临时封禁(约 30 分钟)。
## 请求/响应约定
- Content-Type:`application/json`(除非另有说明)。
- 布尔/整数/字符串更新:请求体为 `{ "value": <type> }`。
- 数组 PUT:既可使用原始数组(如 `["a","b"]`),也可使用 `{ "items": [ ... ] }`。
- 数组 PATCH:支持 `{ "old": "k1", "new": "k2" }` 或 `{ "index": 0, "value": "k2" }`。
- 对象数组 PATCH:支持按索引或按关键字段匹配(各端点中单独说明)。
## 端点说明
### Usage(请求统计)
- GET `/usage` — 获取内存中的请求统计
- 响应:
```json
{
"usage": {
"total_requests": 24,
"success_count": 22,
"failure_count": 2,
"total_tokens": 13890,
"requests_by_day": {
"2024-05-20": 12
},
"requests_by_hour": {
"09": 4,
"18": 8
},
"tokens_by_day": {
"2024-05-20": 9876
},
"tokens_by_hour": {
"09": 1234,
"18": 865
},
"apis": {
"POST /v1/chat/completions": {
"total_requests": 12,
"total_tokens": 9021,
"models": {
"gpt-4o-mini": {
"total_requests": 8,
"total_tokens": 7123,
"details": [
{
"timestamp": "2024-05-20T09:15:04.123456Z",
"tokens": {
"input_tokens": 523,
"output_tokens": 308,
"reasoning_tokens": 0,
"cached_tokens": 0,
"total_tokens": 831
}
}
]
}
}
}
}
}
}
```
- 说明:
- 仅统计带有 token 使用信息的请求,服务重启后数据会被清空。
- 小时维度会将所有日期折叠到 `00`–`23` 的统一小时桶中。
### Config
- GET `/config` — 获取完整的配置
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/config
```
- 响应:
```json
{"debug":true,"proxy-url":"","api-keys":["1...5","JS...W"],"quota-exceeded":{"switch-project":true,"switch-preview-model":true},"generative-language-api-key":["AI...01","AI...02","AI...03"],"request-log":true,"request-retry":3,"claude-api-key":[{"api-key":"cr...56","base-url":"https://example.com/api","proxy-url":"socks5://proxy.example.com:1080","models":[{"name":"claude-3-5-sonnet-20241022","alias":"claude-sonnet-latest"}]},{"api-key":"cr...e3","base-url":"http://example.com:3000/api","proxy-url":""},{"api-key":"sk-...q2","base-url":"https://example.com","proxy-url":""}],"codex-api-key":[{"api-key":"sk...01","base-url":"https://example/v1","proxy-url":""}],"openai-compatibility":[{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk...01","proxy-url":""}],"models":[{"name":"moonshotai/kimi-k2:free","alias":"kimi-k2"}]},{"name":"iflow","base-url":"https://apis.iflow.cn/v1","api-key-entries":[{"api-key":"sk...7e","proxy-url":"socks5://proxy.example.com:1080"}],"models":[{"name":"deepseek-v3.1","alias":"deepseek-v3.1"},{"name":"glm-4.5","alias":"glm-4.5"},{"name":"kimi-k2","alias":"kimi-k2"}]}]}
```
### Debug
- GET `/debug` — 获取当前 debug 状态
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/debug
```
- 响应:
```json
{ "debug": false }
```
- PUT/PATCH `/debug` — 设置 debug(布尔值)
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/debug
```
- 响应:
```json
{ "status": "ok" }
```
### 强制 GPT-5 Codex
- GET `/force-gpt-5-codex` — 获取当前标志
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/force-gpt-5-codex
```
- 响应:
```json
{ "gpt-5-codex": false }
```
- PUT/PATCH `/force-gpt-5-codex` — 设置布尔值
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/force-gpt-5-codex
```
- 响应:
```json
{ "status": "ok" }
```
### 代理服务器 URL
- GET `/proxy-url` — 获取代理 URL 字符串
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/proxy-url
```
- 响应:
```json
{ "proxy-url": "socks5://user:pass@127.0.0.1:1080/" }
```
- PUT/PATCH `/proxy-url` — 设置代理 URL 字符串
- 请求(PUT):
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":"socks5://user:pass@127.0.0.1:1080/"}' \
http://localhost:8317/v0/management/proxy-url
```
- 请求(PATCH):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":"http://127.0.0.1:8080"}' \
http://localhost:8317/v0/management/proxy-url
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/proxy-url` — 清空代理 URL
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE http://localhost:8317/v0/management/proxy-url
```
- 响应:
```json
{ "status": "ok" }
```
### 超出配额行为
- GET `/quota-exceeded/switch-project`
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/quota-exceeded/switch-project
```
- 响应:
```json
{ "switch-project": true }
```
- PUT/PATCH `/quota-exceeded/switch-project` — 布尔值
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":false}' \
http://localhost:8317/v0/management/quota-exceeded/switch-project
```
- 响应:
```json
{ "status": "ok" }
```
- GET `/quota-exceeded/switch-preview-model`
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/quota-exceeded/switch-preview-model
```
- 响应:
```json
{ "switch-preview-model": true }
```
- PUT/PATCH `/quota-exceeded/switch-preview-model` — 布尔值
- 请求:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/quota-exceeded/switch-preview-model
```
- 响应:
```json
{ "status": "ok" }
```
### API Keys(代理服务认证)
这些接口会更新配置中 `auth.providers` 内置的 `config-api-key` 提供方,旧版顶层 `api-keys` 会自动保持同步。
- GET `/api-keys` — 返回完整列表
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/api-keys
```
- 响应:
```json
{ "api-keys": ["k1","k2","k3"] }
```
- PUT `/api-keys` — 完整改写列表
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '["k1","k2","k3"]' \
http://localhost:8317/v0/management/api-keys
```
- 响应:
```json
{ "status": "ok" }
```
- PATCH `/api-keys` — 修改其中一个(`old/new` 或 `index/value`)
- 请求(按 old/new):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"old":"k2","new":"k2b"}' \
http://localhost:8317/v0/management/api-keys
```
- 请求(按 index/value):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":0,"value":"k1b"}' \
http://localhost:8317/v0/management/api-keys
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/api-keys` — 删除其中一个(`?value=` 或 `?index=`)
- 请求(按值删除):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/api-keys?value=k1'
```
- 请求(按索引删除):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/api-keys?index=0'
```
- 响应:
```json
{ "status": "ok" }
```
### Gemini API Key(生成式语言)
- GET `/generative-language-api-key`
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/generative-language-api-key
```
- 响应:
```json
{ "generative-language-api-key": ["AIzaSy...01","AIzaSy...02"] }
```
- PUT `/generative-language-api-key`
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '["AIzaSy-1","AIzaSy-2"]' \
http://localhost:8317/v0/management/generative-language-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- PATCH `/generative-language-api-key`
- 请求:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"old":"AIzaSy-1","new":"AIzaSy-1b"}' \
http://localhost:8317/v0/management/generative-language-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/generative-language-api-key`
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/generative-language-api-key?value=AIzaSy-2'
```
- 响应:
```json
{ "status": "ok" }
```
### Codex API KEY(对象数组)
- GET `/codex-api-key` — 列出全部
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/codex-api-key
```
- 响应:
```json
{ "codex-api-key": [ { "api-key": "sk-a", "base-url": "", "proxy-url": "" } ] }
```
- PUT `/codex-api-key` — 完整改写列表
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"api-key":"sk-a","proxy-url":"socks5://proxy.example.com:1080"},{"api-key":"sk-b","base-url":"https://c.example.com","proxy-url":""}]' \
http://localhost:8317/v0/management/codex-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- PATCH `/codex-api-key` — 修改其中一个(按 `index` 或 `match`)
- 请求(按索引):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":1,"value":{"api-key":"sk-b2","base-url":"https://c.example.com","proxy-url":""}}' \
http://localhost:8317/v0/management/codex-api-key
```
- 请求(按匹配):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"match":"sk-a","value":{"api-key":"sk-a","base-url":"","proxy-url":"socks5://proxy.example.com:1080"}}' \
http://localhost:8317/v0/management/codex-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/codex-api-key` — 删除其中一个(`?api-key=` 或 `?index=`)
- 请求(按 api-key):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/codex-api-key?api-key=sk-b2'
```
- 请求(按索引):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/codex-api-key?index=0'
```
- 响应:
```json
{ "status": "ok" }
```
### 请求重试次数
- GET `/request-retry` — 获取整数
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/request-retry
```
- 响应:
```json
{ "request-retry": 3 }
```
- PUT/PATCH `/request-retry` — 设置整数
- 请求:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":5}' \
http://localhost:8317/v0/management/request-retry
```
- 响应:
```json
{ "status": "ok" }
```
### 请求日志开关
- GET `/request-log` — 获取布尔值
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/request-log
```
- 响应:
```json
{ "request-log": false }
```
- PUT/PATCH `/request-log` — 设置布尔值
- 请求:
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"value":true}' \
http://localhost:8317/v0/management/request-log
```
- 响应:
```json
{ "status": "ok" }
```
### Claude API KEY(对象数组)
- GET `/claude-api-key` — 列出全部
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/claude-api-key
```
- 响应:
```json
{ "claude-api-key": [ { "api-key": "sk-a", "base-url": "", "proxy-url": "" } ] }
```
- PUT `/claude-api-key` — 完整改写列表
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"api-key":"sk-a","proxy-url":"socks5://proxy.example.com:1080"},{"api-key":"sk-b","base-url":"https://c.example.com","proxy-url":""}]' \
http://localhost:8317/v0/management/claude-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- PATCH `/claude-api-key` — 修改其中一个(按 `index` 或 `match`)
- 请求(按索引):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":1,"value":{"api-key":"sk-b2","base-url":"https://c.example.com","proxy-url":""}}' \
http://localhost:8317/v0/management/claude-api-key
```
- 请求(按匹配):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"match":"sk-a","value":{"api-key":"sk-a","base-url":"","proxy-url":"socks5://proxy.example.com:1080"}}' \
http://localhost:8317/v0/management/claude-api-key
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/claude-api-key` — 删除其中一个(`?api-key=` 或 `?index=`)
- 请求(按 api-key):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/claude-api-key?api-key=sk-b2'
```
- 请求(按索引):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/claude-api-key?index=0'
```
- 响应:
```json
{ "status": "ok" }
```
### OpenAI 兼容提供商(对象数组)
- GET `/openai-compatibility` — 列出全部
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/openai-compatibility
```
- 响应:
```json
{ "openai-compatibility": [ { "name": "openrouter", "base-url": "https://openrouter.ai/api/v1", "api-key-entries": [ { "api-key": "sk", "proxy-url": "" } ], "models": [] } ] }
```
- PUT `/openai-compatibility` — 完整改写列表
- 请求:
```bash
curl -X PUT -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '[{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[{"name":"m","alias":"a"}]}]' \
http://localhost:8317/v0/management/openai-compatibility
```
- 响应:
```json
{ "status": "ok" }
```
- PATCH `/openai-compatibility` — 修改其中一个(按 `index` 或 `name`)
- 请求(按名称):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"name":"openrouter","value":{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[]}}' \
http://localhost:8317/v0/management/openai-compatibility
```
- 请求(按索引):
```bash
curl -X PATCH -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d '{"index":0,"value":{"name":"openrouter","base-url":"https://openrouter.ai/api/v1","api-key-entries":[{"api-key":"sk","proxy-url":""}],"models":[]}}' \
http://localhost:8317/v0/management/openai-compatibility
```
- 响应:
```json
{ "status": "ok" }
```
- 说明:
- 仍可提交遗留的 `api-keys` 字段,但所有密钥会自动迁移到 `api-key-entries` 中,返回结果中的 `api-keys` 会逐步留空。
- DELETE `/openai-compatibility` — 删除(`?name=` 或 `?index=`)
- 请求(按名称):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/openai-compatibility?name=openrouter'
```
- 请求(按索引):
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/openai-compatibility?index=0'
```
- 响应:
```json
{ "status": "ok" }
```
### 认证文件管理
管理 `auth-dir` 下的 JSON 令牌文件:列出、下载、上传、删除。
- GET `/auth-files` — 列表
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' http://localhost:8317/v0/management/auth-files
```
- 响应:
```json
{ "files": [ { "name": "acc1.json", "size": 1234, "modtime": "2025-08-30T12:34:56Z", "type": "google" } ] }
```
- GET `/auth-files/download?name=<file.json>` — 下载单个文件
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -OJ 'http://localhost:8317/v0/management/auth-files/download?name=acc1.json'
```
- POST `/auth-files` — 上传
- 请求(multipart):
```bash
curl -X POST -F 'file=@/path/to/acc1.json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/auth-files
```
- 请求(原始 JSON):
```bash
curl -X POST -H 'Content-Type: application/json' \
-H 'Authorization: Bearer <MANAGEMENT_KEY>' \
-d @/path/to/acc1.json \
'http://localhost:8317/v0/management/auth-files?name=acc1.json'
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/auth-files?name=<file.json>` — 删除单个文件
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/auth-files?name=acc1.json'
```
- 响应:
```json
{ "status": "ok" }
```
- DELETE `/auth-files?all=true` — 删除 `auth-dir` 下所有 `.json` 文件
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' -X DELETE 'http://localhost:8317/v0/management/auth-files?all=true'
```
- 响应:
```json
{ "status": "ok", "deleted": 3 }
```
### 登录/授权 URL
以下端点用于发起各提供商的登录流程,并返回需要在浏览器中打开的 URL。流程完成后,令牌会保存到 `auths/` 目录。
- GET `/anthropic-auth-url` — 开始 Anthropic(Claude)登录
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/anthropic-auth-url
```
- 响应:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/codex-auth-url` — 开始 Codex 登录
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/codex-auth-url
```
- 响应:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/gemini-cli-auth-url` — 开始 Google(Gemini CLI)登录
- 查询参数:
- `project_id`(可选):Google Cloud 项目 ID。
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
'http://localhost:8317/v0/management/gemini-cli-auth-url?project_id=<PROJECT_ID>'
```
- 响应:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/qwen-auth-url` — 开始 Qwen 登录(设备授权流程)
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/qwen-auth-url
```
- 响应:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/iflow-auth-url` — 开始 iFlow 登录
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
http://localhost:8317/v0/management/iflow-auth-url
```
- 响应:
```json
{ "status": "ok", "url": "https://..." }
```
- GET `/get-auth-status?state=<state>` — 轮询 OAuth 流程状态
- 请求:
```bash
curl -H 'Authorization: Bearer <MANAGEMENT_KEY>' \
'http://localhost:8317/v0/management/get-auth-status?state=<STATE_FROM_AUTH_URL>'
```
- 响应示例:
```json
{ "status": "wait" }
{ "status": "ok" }
{ "status": "error", "error": "Authentication failed" }
```
## 错误响应
通用错误格式:
- 400 Bad Request: `{ "error": "invalid body" }`
- 401 Unauthorized: `{ "error": "missing management key" }` 或 `{ "error": "invalid management key" }`
- 403 Forbidden: `{ "error": "remote management disabled" }`
- 404 Not Found: `{ "error": "item not found" }` 或 `{ "error": "file not found" }`
- 500 Internal Server Error: `{ "error": "failed to save config: ..." }`
## 说明
- 变更会写回 YAML 配置文件,并由文件监控器热重载配置与客户端。
- `allow-remote-management` 与 `remote-management-key` 不能通过 API 修改,需在配置文件中设置。
+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.
+18 -831
View File
@@ -1,844 +1,31 @@
# CLI Proxy API
# CLIProxyAPI Plus
English | [中文](README_CN.md)
English | [Chinese](README_CN.md)
A proxy server that provides OpenAI/Gemini/Claude/Codex compatible API interfaces for CLI.
This is the Plus version of [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI), adding support for third-party providers on top of the mainline project.
It now also supports OpenAI Codex (GPT models) and Claude Code via OAuth.
All third-party provider support is maintained by community contributors; CLIProxyAPI does not provide technical support. Please contact the corresponding community maintainer if you need assistance.
So you can use local or multi-account CLI access with OpenAI(include Responses)/Gemini/Claude-compatible clients and SDKs.
The Plus release stays in lockstep with the mainline features.
Chinese providers have now been added: [Qwen Code](https://github.com/QwenLM/qwen-code), [iFlow](https://iflow.cn/).
## Differences from the Mainline
## Features
- OpenAI/Gemini/Claude 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
- 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)
- Generative Language API Key support
- 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
- OpenAI-compatible upstream providers via config (e.g., OpenRouter)
- Reusable Go SDK for embedding the proxy (see `docs/sdk-usage.md`)
## Installation
### Prerequisites
- Go 1.24 or higher
- A Google account with access to Gemini CLI models (optional)
- An OpenAI account for Codex/GPT access (optional)
- An Anthropic account for Claude Code access (optional)
- A Qwen Chat account for Qwen Code access (optional)
- An iFlow account for iFlow access (optional)
### Building from Source
1. Clone the repository:
```bash
git clone https://github.com/luispater/CLIProxyAPI.git
cd CLIProxyAPI
```
2. Build the application:
Linux, macOS:
```bash
go build -o cli-proxy-api ./cmd/server
```
Windows:
```bash
go build -o cli-proxy-api.exe ./cmd/server
```
### Installation via Homebrew
```bash
brew install cliproxyapi
brew services start cliproxyapi
```
## Usage
### GUI Client & Official WebUI
#### [EasyCLI](https://github.com/router-for-me/EasyCLI)
A cross-platform desktop GUI client for CLIProxyAPI.
#### [Cli-Proxy-API-Management-Center](https://github.com/router-for-me/Cli-Proxy-API-Management-Center)
A web-based management center for CLIProxyAPI.
Set `remote-management.disable-control-panel` to `true` if you prefer to host the management UI elsewhere; the server will skip downloading `management.html` and `/management.html` will return 404.
You can set the `MANAGEMENT_STATIC_PATH` environment variable to choose the directory where `management.html` is stored.
### Authentication
You can authenticate for Gemini, OpenAI, Claude, Qwen, and/or iFlow. All can coexist in the same `auth-dir` and will be load balanced.
- Gemini (Google):
```bash
./cli-proxy-api --login
```
If you are an existing Gemini Code user, you may need to specify a project ID:
```bash
./cli-proxy-api --login --project_id <your_project_id>
```
The local OAuth callback uses port `8085`.
Options: add `--no-browser` to print the login URL instead of opening a browser. The local OAuth callback uses port `8085`.
- OpenAI (Codex/GPT via OAuth):
```bash
./cli-proxy-api --codex-login
```
Options: add `--no-browser` to print the login URL instead of opening a browser. The local OAuth callback uses port `1455`.
- Claude (Anthropic via OAuth):
```bash
./cli-proxy-api --claude-login
```
Options: add `--no-browser` to print the login URL instead of opening a browser. The local OAuth callback uses port `54545`.
- Qwen (Qwen Chat via OAuth):
```bash
./cli-proxy-api --qwen-login
```
Options: add `--no-browser` to print the login URL instead of opening a browser. Use the Qwen Chat's OAuth device flow.
- iFlow (iFlow via OAuth):
```bash
./cli-proxy-api --iflow-login
```
Options: add `--no-browser` to print the login URL instead of opening a browser. The local OAuth callback uses port `11451`.
### Starting the Server
Once authenticated, start the server:
```bash
./cli-proxy-api
```
By default, the server runs on port 8317.
### API Endpoints
#### List Models
```
GET http://localhost:8317/v1/models
```
#### Chat Completions
```
POST http://localhost:8317/v1/chat/completions
```
Request body example:
```json
{
"model": "gemini-2.5-pro",
"messages": [
{
"role": "user",
"content": "Hello, how are you?"
}
],
"stream": true
}
```
Notes:
- Use a `gemini-*` model for Gemini (e.g., "gemini-2.5-pro"), a `gpt-*` model for OpenAI (e.g., "gpt-5"), a `claude-*` model for Claude (e.g., "claude-3-5-sonnet-20241022"), a `qwen-*` model for Qwen (e.g., "qwen3-coder-plus"), or an iFlow-supported model (e.g., "tstars2.0", "deepseek-v3.1", "kimi-k2", etc.). The proxy will route to the correct provider automatically.
#### Claude Messages (SSE-compatible)
```
POST http://localhost:8317/v1/messages
```
### Using with OpenAI Libraries
You can use this proxy with any OpenAI-compatible library by setting the base URL to your local server:
#### Python (with OpenAI library)
```python
from openai import OpenAI
client = OpenAI(
api_key="dummy", # Not used but required
base_url="http://localhost:8317/v1"
)
# Gemini example
gemini = client.chat.completions.create(
model="gemini-2.5-pro",
messages=[{"role": "user", "content": "Hello, how are you?"}]
)
# Codex/GPT example
gpt = client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "Summarize this project in one sentence."}]
)
# Claude example (using messages endpoint)
import requests
claude_response = requests.post(
"http://localhost:8317/v1/messages",
json={
"model": "claude-3-5-sonnet-20241022",
"messages": [{"role": "user", "content": "Summarize this project in one sentence."}],
"max_tokens": 1000
}
)
print(gemini.choices[0].message.content)
print(gpt.choices[0].message.content)
print(claude_response.json())
```
#### JavaScript/TypeScript
```javascript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: 'dummy', // Not used but required
baseURL: 'http://localhost:8317/v1',
});
// Gemini
const gemini = await openai.chat.completions.create({
model: 'gemini-2.5-pro',
messages: [{ role: 'user', content: 'Hello, how are you?' }],
});
// Codex/GPT
const gpt = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: 'Summarize this project in one sentence.' }],
});
// Claude example (using messages endpoint)
const claudeResponse = await fetch('http://localhost:8317/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: 'Summarize this project in one sentence.' }],
max_tokens: 1000
})
});
console.log(gemini.choices[0].message.content);
console.log(gpt.choices[0].message.content);
console.log(await claudeResponse.json());
```
## Supported Models
- gemini-2.5-pro
- gemini-2.5-flash
- gemini-2.5-flash-lite
- gemini-2.5-flash-image
- gemini-2.5-flash-image-preview
- gpt-5
- gpt-5-codex
- claude-opus-4-1-20250805
- claude-opus-4-20250514
- claude-sonnet-4-20250514
- claude-sonnet-4-5-20250929
- claude-3-7-sonnet-20250219
- claude-3-5-haiku-20241022
- qwen3-coder-plus
- qwen3-coder-flash
- qwen3-max
- qwen3-vl-plus
- deepseek-v3.2
- deepseek-v3.1
- deepseek-r1
- deepseek-v3
- kimi-k2
- glm-4.5
- glm-4.6
- tstars2.0
- And other iFlow-supported models
- Gemini models auto-switch to preview variants when needed
## Configuration
The server uses a YAML configuration file (`config.yaml`) located in the project root directory by default. You can specify a different configuration file path using the `--config` flag:
```bash
./cli-proxy-api --config /path/to/your/config.yaml
```
### Configuration Options
| Parameter | Type | Default | Description |
|-----------------------------------------|----------|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `port` | integer | 8317 | The port number on which the server will listen. |
| `auth-dir` | string | "~/.cli-proxy-api" | Directory where authentication tokens are stored. Supports using `~` for the home directory. If you use Windows, please set the directory like this: `C:/cli-proxy-api/` |
| `proxy-url` | string | "" | Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/ |
| `request-retry` | integer | 0 | Number of times to retry a request. Retries will occur if the HTTP response code is 403, 408, 500, 502, 503, or 504. |
| `remote-management.allow-remote` | boolean | false | Whether to allow remote (non-localhost) access to the management API. If false, only localhost can access. A management key is still required for localhost. |
| `remote-management.secret-key` | string | "" | Management key. If a plaintext value is provided, it will be hashed on startup using bcrypt and persisted back to the config file. If empty, the entire management API is disabled (404). |
| `remote-management.disable-control-panel` | boolean | false | When true, skip downloading `management.html` and return 404 for `/management.html`, effectively disabling the bundled management UI. |
| `quota-exceeded` | object | {} | Configuration for handling quota exceeded. |
| `quota-exceeded.switch-project` | boolean | true | Whether to automatically switch to another project when a quota is exceeded. |
| `quota-exceeded.switch-preview-model` | boolean | true | Whether to automatically switch to a preview model when a quota is exceeded. |
| `debug` | boolean | false | Enable debug mode for verbose logging. |
| `logging-to-file` | boolean | true | Write application logs to rotating files instead of stdout. Set to `false` to log to stdout/stderr. |
| `usage-statistics-enabled` | boolean | true | Enable in-memory usage aggregation for management APIs. Disable to drop all collected usage metrics. |
| `api-keys` | string[] | [] | Legacy shorthand for inline API keys. Values are mirrored into the `config-api-key` provider for backwards compatibility. |
| `generative-language-api-key` | string[] | [] | List of Generative Language API keys. |
| `codex-api-key` | object | {} | List of Codex API keys. |
| `codex-api-key.api-key` | string | "" | Codex API key. |
| `codex-api-key.base-url` | string | "" | Custom Codex API endpoint, if you use a third-party API endpoint. |
| `codex-api-key.proxy-url` | string | "" | Proxy URL for this specific API key. Overrides the global proxy-url setting. Supports socks5/http/https protocols. |
| `claude-api-key` | object | {} | List of Claude API keys. |
| `claude-api-key.api-key` | string | "" | Claude API key. |
| `claude-api-key.base-url` | string | "" | Custom Claude API endpoint, if you use a third-party API endpoint. |
| `claude-api-key.proxy-url` | string | "" | Proxy URL for this specific API key. Overrides the global proxy-url setting. Supports socks5/http/https protocols. |
| `claude-api-key.models` | object[] | [] | Model alias entries for this key. |
| `claude-api-key.models.*.name` | string | "" | Upstream Claude model name invoked against the API. |
| `claude-api-key.models.*.alias` | string | "" | Client-facing alias that maps to the upstream model name. |
| `openai-compatibility` | object[] | [] | Upstream OpenAI-compatible providers configuration (name, base-url, api-keys, models). |
| `openai-compatibility.*.name` | string | "" | The name of the provider. It will be used in the user agent and other places. |
| `openai-compatibility.*.base-url` | string | "" | The base URL of the provider. |
| `openai-compatibility.*.api-keys` | string[] | [] | (Deprecated) The API keys for the provider. Use api-key-entries instead for per-key proxy support. |
| `openai-compatibility.*.api-key-entries` | object[] | [] | API key entries with optional per-key proxy configuration. Preferred over api-keys. |
| `openai-compatibility.*.api-key-entries.*.api-key` | string | "" | The API key for this entry. |
| `openai-compatibility.*.api-key-entries.*.proxy-url` | string | "" | Proxy URL for this specific API key. Overrides the global proxy-url setting. Supports socks5/http/https protocols. |
| `openai-compatibility.*.models` | object[] | [] | Model alias definitions routing client aliases to upstream names. |
| `openai-compatibility.*.models.*.name` | string | "" | Upstream model name invoked against the provider. |
| `openai-compatibility.*.models.*.alias` | string | "" | Client alias routed to the upstream model. |
When `claude-api-key.models` is specified, only the provided aliases are registered in the model registry (mirroring OpenAI compatibility behaviour), and the default Claude catalog is suppressed for that credential.
### Example Configuration File
```yaml
# Server port
port: 8317
# 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: ""
# Disable the bundled management control panel asset download and HTTP route when true.
disable-control-panel: false
# Authentication directory (supports ~ for home directory). If you use Windows, please set the directory like this: `C:/cli-proxy-api/`
auth-dir: "~/.cli-proxy-api"
# API keys for authentication
api-keys:
- "your-api-key-1"
- "your-api-key-2"
# Enable debug logging
debug: false
# When true, write application logs to rotating files instead of stdout
logging-to-file: true
# When false, disable in-memory usage statistics aggregation
usage-statistics-enabled: true
# Proxy URL. Supports socks5/http/https protocols. Example: socks5://user:pass@192.168.1.1:1080/
proxy-url: ""
# 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
# 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
# API keys for official Generative Language API
generative-language-api-key:
- "AIzaSy...01"
- "AIzaSy...02"
- "AIzaSy...03"
- "AIzaSy...04"
# 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
# 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
# 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. Or you can use a format such as openrouter://moonshotai/kimi-k2:free to request undefined models
- name: "moonshotai/kimi-k2:free" # The actual model name.
alias: "kimi-k2" # The alias used in the API.
```
### Git-backed Configuration and Token Store
The application can be configured to use a Git repository as a backend for storing both the `config.yaml` file and the authentication tokens from the `auth-dir`. This allows for centralized management and versioning of your configuration.
To enable this feature, set the `GITSTORE_GIT_URL` environment variable to the URL of your Git repository.
**Environment Variables**
| Variable | Required | Default | Description |
|-------------------------|----------|---------------------------|---------------------------------------------------------------------------------------------------------|
| `MANAGEMENT_PASSWORD` | Yes | | The password for management webui. |
| `GITSTORE_GIT_URL` | Yes | | The HTTPS URL of the Git repository to use. |
| `GITSTORE_LOCAL_PATH` | No | Current working directory | The local path where the Git repository will be cloned. Inside Docker, this defaults to `/CLIProxyAPI`. |
| `GITSTORE_GIT_USERNAME` | No | | The username for Git authentication. |
| `GITSTORE_GIT_TOKEN` | No | | The personal access token (or password) for Git authentication. |
**How it Works**
1. **Cloning:** On startup, the application clones the remote Git repository to the `GITSTORE_LOCAL_PATH`.
2. **Configuration:** It then looks for a `config.yaml` inside a `config` directory within the cloned repository.
3. **Bootstrapping:** If `config/config.yaml` does not exist in the repository, the application will copy the local `config.example.yaml` to that location, commit, and push it to the remote repository as an initial configuration. You must have `config.example.yaml` available.
4. **Token Sync:** The `auth-dir` is also managed within this repository. Any changes to authentication tokens (e.g., through a new login) are automatically committed and pushed to the remote Git repository.
### PostgreSQL-backed Configuration and Token Store
You can also persist configuration and authentication data in PostgreSQL when running CLIProxyAPI in hosted environments that favor managed databases over local files.
**Environment Variables**
| Variable | Required | Default | Description |
|-----------------------|----------|-----------------------|---------------------------------------------------------------------------------------------------------------|
| `MANAGEMENT_PASSWORD` | Yes | | Password for the management web UI (required when remote management is enabled). |
| `PGSTORE_DSN` | Yes | | PostgreSQL connection string (e.g. `postgresql://user:pass@host:5432/db`). |
| `PGSTORE_SCHEMA` | No | public | Schema where the tables will be created. Leave empty to use the default schema. |
| `PGSTORE_LOCAL_PATH` | No | Current working directory | Root directory for the local mirror; the server writes to `<value>/pgstore`. If unset and CWD is unavailable, `/tmp/pgstore` is used. |
**How it Works**
1. **Initialization:** On startup the server connects via `PGSTORE_DSN`, ensures the schema exists, and creates the `config_store` / `auth_store` tables when missing.
2. **Local Mirror:** A writable cache at `<PGSTORE_LOCAL_PATH or CWD>/pgstore` mirrors `config/config.yaml` and `auths/` so the rest of the application can reuse the existing file-based logic.
3. **Bootstrapping:** If no configuration row exists, `config.example.yaml` seeds the database using the fixed identifier `config`.
4. **Token Sync:** Changes flow both ways—file updates are written to PostgreSQL and database records are mirrored back to disk so watchers and management APIs continue to operate.
### Object Storage-backed Configuration and Token Store
An S3-compatible object storage service can host configuration and authentication records.
**Environment Variables**
| Variable | Required | Default | Description |
|--------------------------|----------|--------------------------------|--------------------------------------------------------------------------------------------------------------------------|
| `MANAGEMENT_PASSWORD` | Yes | | Password for the management web UI (required when remote management is enabled). |
| `OBJECTSTORE_ENDPOINT` | Yes | | Object storage endpoint. Include `http://` or `https://` to force the protocol (omitted scheme → HTTPS). |
| `OBJECTSTORE_BUCKET` | Yes | | Bucket that stores `config/config.yaml` and `auths/*.json`. |
| `OBJECTSTORE_ACCESS_KEY` | Yes | | Access key ID for the object storage account. |
| `OBJECTSTORE_SECRET_KEY` | Yes | | Secret key for the object storage account. |
| `OBJECTSTORE_LOCAL_PATH` | No | Current working directory | Root directory for the local mirror; the server writes to `<value>/objectstore`. If unset, defaults to current CWD. |
**How it Works**
1. **Startup:** The endpoint is parsed (respecting any scheme prefix), a MinIO-compatible client is created in path-style mode, and the bucket is created when missing.
2. **Local Mirror:** A writable cache at `<OBJECTSTORE_LOCAL_PATH or CWD>/objectstore` mirrors `config/config.yaml` and `auths/`.
3. **Bootstrapping:** When `config/config.yaml` is absent in the bucket, the server copies `config.example.yaml`, uploads it, and uses it as the initial configuration.
4. **Sync:** Changes to configuration or auth files are uploaded to the bucket, and remote updates are mirrored back to disk, keeping watchers and management APIs in sync.
### OpenAI Compatibility Providers
Configure upstream OpenAI-compatible providers (e.g., OpenRouter) via `openai-compatibility`.
- name: provider identifier used internally
- base-url: provider base URL
- api-key-entries: list of API key entries with optional per-key proxy configuration (recommended)
- api-keys: (deprecated) simple list of API keys without proxy support
- models: list of mappings from upstream model `name` to local `alias`
Example with per-key proxy support:
```yaml
openai-compatibility:
- name: "openrouter"
base-url: "https://openrouter.ai/api/v1"
api-key-entries:
- api-key: "sk-or-v1-...b780"
proxy-url: "socks5://proxy.example.com:1080"
- api-key: "sk-or-v1-...b781"
models:
- name: "moonshotai/kimi-k2:free"
alias: "kimi-k2"
```
Legacy format (still supported):
```yaml
openai-compatibility:
- name: "openrouter"
base-url: "https://openrouter.ai/api/v1"
api-keys:
- "sk-or-v1-...b780"
- "sk-or-v1-...b781"
models:
- name: "moonshotai/kimi-k2:free"
alias: "kimi-k2"
```
Usage:
Call OpenAI's endpoint `/v1/chat/completions` with `model` set to the alias (e.g., `kimi-k2`). The proxy routes to the configured provider/model automatically.
Also, you may call Claude's endpoint `/v1/messages`, Gemini's `/v1beta/models/model-name:streamGenerateContent` or `/v1beta/models/model-name:generateContent`.
And you can always use Gemini CLI with `CODE_ASSIST_ENDPOINT` set to `http://127.0.0.1:8317` for these OpenAI-compatible provider's models.
### Authentication Directory
The `auth-dir` parameter specifies where authentication tokens are stored. When you run the login command, the application will create JSON files in this directory containing the authentication tokens for your Google accounts. Multiple accounts can be used for load balancing.
### Official Generative Language API
The `generative-language-api-key` parameter allows you to define a list of API keys that can be used to authenticate requests to the official Generative Language API.
## Hot Reloading
The server watches the config file and the `auth-dir` for changes and reloads clients and settings automatically. You can add or remove Gemini/OpenAI token JSON files while the server is running; no restart is required.
## Gemini CLI with multiple account load balancing
Start CLI Proxy API server, and then set the `CODE_ASSIST_ENDPOINT` environment variable to the URL of the CLI Proxy API server.
```bash
export CODE_ASSIST_ENDPOINT="http://127.0.0.1:8317"
```
The server will relay the `loadCodeAssist`, `onboardUser`, and `countTokens` requests. And automatically load balance the text generation requests between the multiple accounts.
> [!NOTE]
> This feature only allows local access because there is currently no way to authenticate the requests.
> 127.0.0.1 is hardcoded for load balancing.
## Claude Code with multiple account load balancing
Start CLI Proxy API server, and then set the `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL` (or `ANTHROPIC_MODEL`, `ANTHROPIC_SMALL_FAST_MODEL` for version 1.x.x) environment variables.
Using Gemini models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=gemini-2.5-pro
export ANTHROPIC_DEFAULT_SONNET_MODEL=gemini-2.5-flash
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gemini-2.5-flash-lite
# version 1.x.x
export ANTHROPIC_MODEL=gemini-2.5-pro
export ANTHROPIC_SMALL_FAST_MODEL=gemini-2.5-flash
```
Using OpenAI GPT 5 models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=gpt-5-high
export ANTHROPIC_DEFAULT_SONNET_MODEL=gpt-5-medium
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gpt-5-minimal
# version 1.x.x
export ANTHROPIC_MODEL=gpt-5
export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-minimal
```
Using OpenAI GPT 5 Codex models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=gpt-5-codex-high
export ANTHROPIC_DEFAULT_SONNET_MODEL=gpt-5-codex-medium
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gpt-5-codex-low
# version 1.x.x
export ANTHROPIC_MODEL=gpt-5-codex
export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-codex-low
```
Using Claude models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-1-20250805
export ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-4-5-20250929
export ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-3-5-haiku-20241022
# version 1.x.x
export ANTHROPIC_MODEL=claude-sonnet-4-20250514
export ANTHROPIC_SMALL_FAST_MODEL=claude-3-5-haiku-20241022
```
Using Qwen models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_HAIKU_MODEL=qwen3-coder-flash
# version 1.x.x
export ANTHROPIC_MODEL=qwen3-coder-plus
export ANTHROPIC_SMALL_FAST_MODEL=qwen3-coder-flash
```
Using iFlow models:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# version 2.x.x
export ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3-max
export ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_HAIKU_MODEL=qwen3-235b-a22b-instruct
# version 1.x.x
export ANTHROPIC_MODEL=qwen3-max
export ANTHROPIC_SMALL_FAST_MODEL=qwen3-235b-a22b-instruct
```
## Codex with multiple account load balancing
Start CLI Proxy API server, and then edit the `~/.codex/config.toml` and `~/.codex/auth.json` files.
config.toml:
```toml
model_provider = "cliproxyapi"
model = "gpt-5-codex" # Or gpt-5, you can also use any of the models that we support.
model_reasoning_effort = "high"
[model_providers.cliproxyapi]
name = "cliproxyapi"
base_url = "http://127.0.0.1:8317/v1"
wire_api = "responses"
```
auth.json:
```json
{
"OPENAI_API_KEY": "sk-dummy"
}
```
## Run with Docker
Run the following command to login (Gemini OAuth on port 8085):
```bash
docker run --rm -p 8085:8085 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --login
```
Run the following command to login (OpenAI OAuth on port 1455):
```bash
docker run --rm -p 1455:1455 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --codex-login
```
Run the following command to logi (Claude OAuth on port 54545):
```bash
docker run -rm -p 54545:54545 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --claude-login
```
Run the following command to login (Qwen OAuth):
```bash
docker run -it -rm -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --qwen-login
```
Run the following command to login (iFlow OAuth on port 11451):
```bash
docker run --rm -p 11451:11451 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --iflow-login
```
Run the following command to start the server:
```bash
docker run --rm -p 8317:8317 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest
```
> [!NOTE]
> To use the Git-backed configuration store with Docker, you can pass the `GITSTORE_*` environment variables using the `-e` flag. For example:
>
> ```bash
> docker run --rm -p 8317:8317 \
> -e GITSTORE_GIT_URL="https://github.com/your/config-repo.git" \
> -e GITSTORE_GIT_TOKEN="your_personal_access_token" \
> -v /path/to/your/git-store:/CLIProxyAPI/remote \
> eceasy/cli-proxy-api:latest
> ```
> In this case, you may not need to mount `config.yaml` or `auth-dir` directly, as they will be managed by the Git store inside the container at the `GITSTORE_LOCAL_PATH` (which defaults to `/CLIProxyAPI` and we are setting it to `/CLIProxyAPI/remote` in this example).
## Run with Docker Compose
1. Clone the repository and navigate into the directory:
```bash
git clone https://github.com/luispater/CLIProxyAPI.git
cd CLIProxyAPI
```
2. Prepare the configuration file:
Create a `config.yaml` file by copying the example and customize it to your needs.
```bash
cp config.example.yaml config.yaml
```
*(Note for Windows users: You can use `copy config.example.yaml config.yaml` in CMD or PowerShell.)*
To use the Git-backed configuration store, you can add the `GITSTORE_*` environment variables to your `docker-compose.yml` file under the `cli-proxy-api` service definition. For example:
```yaml
services:
cli-proxy-api:
image: eceasy/cli-proxy-api:latest
container_name: cli-proxy-api
ports:
- "8317:8317"
- "8085:8085"
- "1455:1455"
- "54545:54545"
- "11451:11451"
environment:
- GITSTORE_GIT_URL=https://github.com/your/config-repo.git
- GITSTORE_GIT_TOKEN=your_personal_access_token
volumes:
- ./git-store:/CLIProxyAPI/remote # GITSTORE_LOCAL_PATH
restart: unless-stopped
```
When using the Git store, you may not need to mount `config.yaml` or `auth-dir` directly.
3. Start the service:
- **For most users (recommended):**
Run the following command to start the service using the pre-built image from Docker Hub. The service will run in the background.
```bash
docker compose up -d
```
- **For advanced users:**
If you have modified the source code and need to build a new image, use the interactive helper scripts:
- For Windows (PowerShell):
```powershell
.\docker-build.ps1
```
- For Linux/macOS:
```bash
bash docker-build.sh
```
The script will prompt you to choose how to run the application:
- **Option 1: Run using Pre-built Image (Recommended)**: Pulls the latest official image from the registry and starts the container. This is the easiest way to get started.
- **Option 2: Build from Source and Run (For Developers)**: Builds the image from the local source code, tags it as `cli-proxy-api:local`, and then starts the container. This is useful if you are making changes to the source code.
4. To authenticate with providers, run the login command inside the container:
- **Gemini**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --login
```
- **OpenAI (Codex)**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --codex-login
```
- **Claude**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --claude-login
```
- **Qwen**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --qwen-login
```
- **iFlow**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --iflow-login
```
5. To view the server logs:
```bash
docker compose logs -f
```
6. To stop the application:
```bash
docker compose down
```
## Management API
see [MANAGEMENT_API.md](MANAGEMENT_API.md)
## SDK Docs
- Usage: [docs/sdk-usage.md](docs/sdk-usage.md)
- Advanced (executors & translators): [docs/sdk-advanced.md](docs/sdk-advanced.md)
- Access: [docs/sdk-access.md](docs/sdk-access.md)
- Watcher: [docs/sdk-watcher.md](docs/sdk-watcher.md)
- Custom Provider Example: `examples/custom-provider`
- Added Kiro (AWS CodeWhisperer) support (OAuth login), provided by [fuko2935](https://github.com/fuko2935/CLIProxyAPI/tree/feature/kiro-integration), [Ravens2121](https://github.com/Ravens2121/CLIProxyAPIPlus/)
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
This project only accepts pull requests that relate to third-party provider support. Any pull requests unrelated to third-party provider support will be rejected.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## Who is with us?
Those projects are based on CLIProxyAPI:
### [vibeproxy](https://github.com/automazeio/vibeproxy)
Native macOS menu bar app to use your Claude Code & ChatGPT subscriptions with AI coding tools - no API keys needed
### [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
> [!NOTE]
> If you developed a project based on CLIProxyAPI, please open a PR to add it to this list.
If you need to submit any non-third-party provider changes, please open them against the mainline repository.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
This project is licensed under the MIT License - see `LICENSE`.
## Disclaimer
This project is intended for educational and interoperability research purposes only. It interacts with various internal or undocumented APIs (such as Google's `v1internal`) to provide compatibility layers.
- **Use at your own risk.** The authors are not responsible for any consequences arising from the use of this software, including but not limited to account suspensions or service interruptions.
- This project is **not** affiliated with, endorsed by, or associated with Google, OpenAI, Anthropic, or any other service provider mentioned.
- Users are expected to comply with the Terms of Service of the respective platforms they connect to.
+9 -840
View File
@@ -1,854 +1,23 @@
# 写给所有中国网友的
对于项目前期的确有很多用户使用上遇到各种各样的奇怪问题,大部分是因为配置或我说明文档不全导致的。
对说明文档我已经尽可能的修补,有些重要的地方我甚至已经写到了打包的配置文件里。
已经写在 README 中的功能,都是**可用**的,经过**验证**的,并且我自己**每天**都在使用的。
可能在某些场景中使用上效果并不是很出色,但那基本上是模型和工具的原因,比如用 Claude Code 的时候,有的模型就无法正确使用工具,比如 Gemini,就在 Claude Code 和 Codex 的下使用的相当扭捏,有时能完成大部分工作,但有时候却只说不做。
目前来说 Claude 和 GPT-5 是目前使用各种第三方CLI工具运用的最好的模型,我自己也是多个账号做均衡负载使用。
实事求是的说,最初的几个版本我根本就没有中文文档,我至今所有文档也都是使用英文更新让后让 Gemini 翻译成中文的。但是无论如何都不会出现中文文档无法理解的问题。因为所有的中英文文档我都是再三校对,并且发现未及时更改的更新的地方都快速更新掉了。
最后,烦请在发 Issue 之前请认真阅读这篇文档。
另外中文需要交流的用户可以加 QQ 群:188637136
或 Telegram 群:https://t.me/CLIProxyAPI
# CLI 代理 API
# CLIProxyAPI Plus
[English](README.md) | 中文
一个为 CLI 提供 OpenAI/Gemini/Claude/Codex 兼容 API 接口的代理服务器。
这是 [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) 的 Plus 版本,在原有基础上增加了第三方供应商的支持。
现已支持通过 OAuth 登录接入 OpenAI Codex(GPT 系列)和 Claude Code。
所有的第三方供应商支持都由第三方社区维护者提供,CLIProxyAPI 不提供技术支持。如需取得支持,请与对应的社区维护者联系。
您可以使用本地或多账户的CLI方式,通过任何与 OpenAI(包括Responses)/Gemini/Claude 兼容的客户端和SDK进行访问。
该 Plus 版本的主线功能与主线功能强制同步。
现已新增国内提供商:[Qwen Code](https://github.com/QwenLM/qwen-code)、[iFlow](https://iflow.cn/)。
## 与主线版本版本差异
## 功能特性
- 为 CLI 模型提供 OpenAI/Gemini/Claude/Codex 兼容的 API 端点
- 新增 OpenAI Codex(GPT 系列)支持(OAuth 登录)
- 新增 Claude Code 支持(OAuth 登录)
- 新增 Qwen Code 支持(OAuth 登录)
- 新增 iFlow 支持(OAuth 登录)
- 支持流式与非流式响应
- 函数调用/工具支持
- 多模态输入(文本、图片)
- 多账户支持与轮询负载均衡(Gemini、OpenAI、Claude、Qwen 与 iFlow)
- 简单的 CLI 身份验证流程(Gemini、OpenAI、Claude、Qwen 与 iFlow)
- 支持 Gemini AIStudio API 密钥
- 支持 Gemini CLI 多账户轮询
- 支持 Claude Code 多账户轮询
- 支持 Qwen Code 多账户轮询
- 支持 iFlow 多账户轮询
- 支持 OpenAI Codex 多账户轮询
- 通过配置接入上游 OpenAI 兼容提供商(例如 OpenRouter)
- 可复用的 Go SDK(见 `docs/sdk-usage_CN.md`)
## 安装
### 前置要求
- Go 1.24 或更高版本
- 有权访问 Gemini CLI 模型的 Google 账户(可选)
- 有权访问 OpenAI Codex/GPT 的 OpenAI 账户(可选)
- 有权访问 Claude Code 的 Anthropic 账户(可选)
- 有权访问 Qwen Code 的 Qwen Chat 账户(可选)
- 有权访问 iFlow 的 iFlow 账户(可选)
### 从源码构建
1. 克隆仓库:
```bash
git clone https://github.com/luispater/CLIProxyAPI.git
cd CLIProxyAPI
```
2. 构建应用程序:
```bash
go build -o cli-proxy-api ./cmd/server
```
### 通过 Homebrew 安装
```bash
brew install cliproxyapi
brew services start cliproxyapi
```
## 使用方法
### 图形客户端与官方 WebUI
#### [EasyCLI](https://github.com/router-for-me/EasyCLI)
CLIProxyAPI 的跨平台桌面图形客户端。
#### [Cli-Proxy-API-Management-Center](https://github.com/router-for-me/Cli-Proxy-API-Management-Center)
CLIProxyAPI 的基于 Web 的管理中心。
如果希望自行托管管理页面,可在配置中将 `remote-management.disable-control-panel` 设为 `true`,服务器将停止下载 `management.html`,并让 `/management.html` 返回 404。
可以通过设置环境变量 `MANAGEMENT_STATIC_PATH` 来指定 `management.html` 的存储目录。
### 身份验证
您可以分别为 Gemini、OpenAI、Claude、Qwen 和 iFlow 进行身份验证,它们可同时存在于同一个 `auth-dir` 中并参与负载均衡。
- Gemini(Google):
```bash
./cli-proxy-api --login
```
如果您是现有的 Gemini Code 用户,可能需要指定一个项目ID:
```bash
./cli-proxy-api --login --project_id <your_project_id>
```
本地 OAuth 回调端口为 `8085`。
选项:加上 `--no-browser` 可打印登录地址而不自动打开浏览器。本地 OAuth 回调端口为 `8085`。
- OpenAI(Codex/GPT,OAuth):
```bash
./cli-proxy-api --codex-login
```
选项:加上 `--no-browser` 可打印登录地址而不自动打开浏览器。本地 OAuth 回调端口为 `1455`。
- Claude(Anthropic,OAuth):
```bash
./cli-proxy-api --claude-login
```
选项:加上 `--no-browser` 可打印登录地址而不自动打开浏览器。本地 OAuth 回调端口为 `54545`。
- Qwen(Qwen Chat,OAuth):
```bash
./cli-proxy-api --qwen-login
```
选项:加上 `--no-browser` 可打印登录地址而不自动打开浏览器。使用 Qwen Chat 的 OAuth 设备登录流程。
- iFlow(iFlow,OAuth):
```bash
./cli-proxy-api --iflow-login
```
选项:加上 `--no-browser` 可打印登录地址而不自动打开浏览器。本地 OAuth 回调端口为 `11451`。
### 启动服务器
身份验证完成后,启动服务器:
```bash
./cli-proxy-api
```
默认情况下,服务器在端口 8317 上运行。
### API 端点
#### 列出模型
```
GET http://localhost:8317/v1/models
```
#### 聊天补全
```
POST http://localhost:8317/v1/chat/completions
```
请求体示例:
```json
{
"model": "gemini-2.5-pro",
"messages": [
{
"role": "user",
"content": "你好,你好吗?"
}
],
"stream": true
}
```
说明:
- 使用 "gemini-*" 模型(例如 "gemini-2.5-pro")来调用 Gemini,使用 "gpt-*" 模型(例如 "gpt-5")来调用 OpenAI,使用 "claude-*" 模型(例如 "claude-3-5-sonnet-20241022")来调用 Claude,使用 "qwen-*" 模型(例如 "qwen3-coder-plus")来调用 Qwen,或者使用 iFlow 支持的模型(例如 "tstars2.0"、"deepseek-v3.1"、"kimi-k2" 等)来调用 iFlow。代理服务会自动将请求路由到相应的提供商。
#### Claude 消息(SSE 兼容)
```
POST http://localhost:8317/v1/messages
```
### 与 OpenAI 库一起使用
您可以通过将基础 URL 设置为本地服务器来将此代理与任何 OpenAI 兼容的库一起使用:
#### Python(使用 OpenAI 库)
```python
from openai import OpenAI
client = OpenAI(
api_key="dummy", # 不使用但必需
base_url="http://localhost:8317/v1"
)
# Gemini 示例
gemini = client.chat.completions.create(
model="gemini-2.5-pro",
messages=[{"role": "user", "content": "你好,你好吗?"}]
)
# Codex/GPT 示例
gpt = client.chat.completions.create(
model="gpt-5",
messages=[{"role": "user", "content": "用一句话总结这个项目"}]
)
# Claude 示例(使用 messages 端点)
import requests
claude_response = requests.post(
"http://localhost:8317/v1/messages",
json={
"model": "claude-3-5-sonnet-20241022",
"messages": [{"role": "user", "content": "用一句话总结这个项目"}],
"max_tokens": 1000
}
)
print(gemini.choices[0].message.content)
print(gpt.choices[0].message.content)
print(claude_response.json())
```
#### JavaScript/TypeScript
```javascript
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: 'dummy', // 不使用但必需
baseURL: 'http://localhost:8317/v1',
});
// Gemini
const gemini = await openai.chat.completions.create({
model: 'gemini-2.5-pro',
messages: [{ role: 'user', content: '你好,你好吗?' }],
});
// Codex/GPT
const gpt = await openai.chat.completions.create({
model: 'gpt-5',
messages: [{ role: 'user', content: '用一句话总结这个项目' }],
});
// Claude 示例(使用 messages 端点)
const claudeResponse = await fetch('http://localhost:8317/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'claude-3-5-sonnet-20241022',
messages: [{ role: 'user', content: '用一句话总结这个项目' }],
max_tokens: 1000
})
});
console.log(gemini.choices[0].message.content);
console.log(gpt.choices[0].message.content);
console.log(await claudeResponse.json());
```
## 支持的模型
- gemini-2.5-pro
- gemini-2.5-flash
- gemini-2.5-flash-lite
- gemini-2.5-flash-image
- gemini-2.5-flash-image-preview
- gpt-5
- gpt-5-codex
- claude-opus-4-1-20250805
- claude-opus-4-20250514
- claude-sonnet-4-20250514
- claude-sonnet-4-5-20250929
- claude-3-7-sonnet-20250219
- claude-3-5-haiku-20241022
- qwen3-coder-plus
- qwen3-coder-flash
- qwen3-max
- qwen3-vl-plus
- deepseek-v3.2
- deepseek-v3.1
- deepseek-r1
- deepseek-v3
- kimi-k2
- glm-4.5
- glm-4.6
- tstars2.0
- 以及其他 iFlow 支持的模型
- Gemini 模型在需要时自动切换到对应的 preview 版本
## 配置
服务器默认使用位于项目根目录的 YAML 配置文件(`config.yaml`)。您可以使用 `--config` 标志指定不同的配置文件路径:
```bash
./cli-proxy-api --config /path/to/your/config.yaml
```
### 配置选项
| 参数 | 类型 | 默认值 | 描述 |
|-----------------------------------------|----------|--------------------|---------------------------------------------------------------------|
| `port` | integer | 8317 | 服务器将监听的端口号。 |
| `auth-dir` | string | "~/.cli-proxy-api" | 存储身份验证令牌的目录。支持使用 `~` 来表示主目录。如果你使用Windows,建议设置成`C:/cli-proxy-api/`。 |
| `proxy-url` | string | "" | 代理URL。支持socks5/http/https协议。例如:socks5://user:pass@192.168.1.1:1080/ |
| `request-retry` | integer | 0 | 请求重试次数。如果HTTP响应码为403、408、500、502、503或504,将会触发重试。 |
| `remote-management.allow-remote` | boolean | false | 是否允许远程(非localhost)访问管理接口。为false时仅允许本地访问;本地访问同样需要管理密钥。 |
| `remote-management.secret-key` | string | "" | 管理密钥。若配置为明文,启动时会自动进行bcrypt加密并写回配置文件。若为空,管理接口整体不可用(404)。 |
| `remote-management.disable-control-panel` | boolean | false | 当为 true 时,不再下载 `management.html`,且 `/management.html` 会返回 404,从而禁用内置管理界面。 |
| `quota-exceeded` | object | {} | 用于处理配额超限的配置。 |
| `quota-exceeded.switch-project` | boolean | true | 当配额超限时,是否自动切换到另一个项目。 |
| `quota-exceeded.switch-preview-model` | boolean | true | 当配额超限时,是否自动切换到预览模型。 |
| `debug` | boolean | false | 启用调试模式以获取详细日志。 |
| `logging-to-file` | boolean | true | 是否将应用日志写入滚动文件;设为 false 时输出到 stdout/stderr。 |
| `usage-statistics-enabled` | boolean | true | 是否启用内存中的使用统计;设为 false 时直接丢弃所有统计数据。 |
| `api-keys` | string[] | [] | 兼容旧配置的简写,会自动同步到默认 `config-api-key` 提供方。 |
| `generative-language-api-key` | string[] | [] | 生成式语言API密钥列表。 |
| `codex-api-key` | object | {} | Codex API密钥列表。 |
| `codex-api-key.api-key` | string | "" | Codex API密钥。 |
| `codex-api-key.base-url` | string | "" | 自定义的Codex API端点 |
| `codex-api-key.proxy-url` | string | "" | 针对该API密钥的代理URL。会覆盖全局proxy-url设置。支持socks5/http/https协议。 |
| `claude-api-key` | object | {} | Claude API密钥列表。 |
| `claude-api-key.api-key` | string | "" | Claude API密钥。 |
| `claude-api-key.base-url` | string | "" | 自定义的Claude API端点,如果您使用第三方的API端点。 |
| `claude-api-key.proxy-url` | string | "" | 针对该API密钥的代理URL。会覆盖全局proxy-url设置。支持socks5/http/https协议。 |
| `claude-api-key.models` | object[] | [] | Model alias entries for this key. |
| `claude-api-key.models.*.name` | string | "" | Upstream Claude model name invoked against the API. |
| `claude-api-key.models.*.alias` | string | "" | Client-facing alias that maps to the upstream model name. |
| `openai-compatibility` | object[] | [] | 上游OpenAI兼容提供商的配置(名称、基础URL、API密钥、模型)。 |
| `openai-compatibility.*.name` | string | "" | 提供商的名称。它将被用于用户代理(User Agent)和其他地方。 |
| `openai-compatibility.*.base-url` | string | "" | 提供商的基础URL。 |
| `openai-compatibility.*.api-keys` | string[] | [] | (已弃用) 提供商的API密钥。建议改用api-key-entries以获得每密钥代理支持。 |
| `openai-compatibility.*.api-key-entries` | object[] | [] | API密钥条目,支持可选的每密钥代理配置。优先于api-keys。 |
| `openai-compatibility.*.api-key-entries.*.api-key` | string | "" | 该条目的API密钥。 |
| `openai-compatibility.*.api-key-entries.*.proxy-url` | string | "" | 针对该API密钥的代理URL。会覆盖全局proxy-url设置。支持socks5/http/https协议。 |
| `openai-compatibility.*.models` | object[] | [] | Model alias definitions routing client aliases to upstream names. |
| `openai-compatibility.*.models.*.name` | string | "" | Upstream model name invoked against the provider. |
| `openai-compatibility.*.models.*.alias` | string | "" | Client alias routed to the upstream model. |
When `claude-api-key.models` is provided, only the listed aliases are registered for that credential, and the default Claude model catalog is skipped.
### 配置文件示例
```yaml
# 服务器端口
port: 8317
# 管理 API 设置
remote-management:
# 是否允许远程(非localhost)访问管理接口。为false时仅允许本地访问(但本地访问同样需要管理密钥)。
allow-remote: false
# 管理密钥。若配置为明文,启动时会自动进行bcrypt加密并写回配置文件。
# 所有管理请求(包括本地)都需要该密钥。
# 若为空,/v0/management 整体处于 404(禁用)。
secret-key: ""
# 当设为 true 时,不下载管理面板文件,/management.html 将直接返回 404。
disable-control-panel: false
# 身份验证目录(支持 ~ 表示主目录)。如果你使用Windows,建议设置成`C:/cli-proxy-api/`。
auth-dir: "~/.cli-proxy-api"
# 请求认证使用的API密钥
api-keys:
- "your-api-key-1"
- "your-api-key-2"
# 启用调试日志
debug: false
# 为 true 时将应用日志写入滚动文件而不是 stdout
logging-to-file: true
# 为 false 时禁用内存中的使用统计并直接丢弃所有数据
usage-statistics-enabled: true
# 代理URL。支持socks5/http/https协议。例如:socks5://user:pass@192.168.1.1:1080/
proxy-url: ""
# 请求重试次数。如果HTTP响应码为403、408、500、502、503或504,将会触发重试。
request-retry: 3
# 配额超限行为
quota-exceeded:
switch-project: true # 当配额超限时是否自动切换到另一个项目
switch-preview-model: true # 当配额超限时是否自动切换到预览模型
# AIStduio Gemini API 的 API 密钥
generative-language-api-key:
- "AIzaSy...01"
- "AIzaSy...02"
- "AIzaSy...03"
- "AIzaSy...04"
# Codex API 密钥
codex-api-key:
- api-key: "sk-atSM..."
base-url: "https://www.example.com" # 第三方 Codex API 中转服务端点
proxy-url: "socks5://proxy.example.com:1080" # 可选:针对该密钥的代理设置
# Claude API 密钥
claude-api-key:
- api-key: "sk-atSM..." # 如果使用官方 Claude API,无需设置 base-url
- api-key: "sk-atSM..."
base-url: "https://www.example.com" # 第三方 Claude API 中转服务端点
proxy-url: "socks5://proxy.example.com:1080" # 可选:针对该密钥的代理设置
# OpenAI 兼容提供商
openai-compatibility:
- name: "openrouter" # 提供商的名称;它将被用于用户代理和其它地方。
base-url: "https://openrouter.ai/api/v1" # 提供商的基础URL。
# 新格式:支持每密钥代理配置(推荐):
api-key-entries:
- api-key: "sk-or-v1-...b780"
proxy-url: "socks5://proxy.example.com:1080" # 可选:针对该密钥的代理设置
- api-key: "sk-or-v1-...b781" # 不进行额外代理设置
# 旧格式(仍支持,但无法为每个密钥指定代理):
# api-keys:
# - "sk-or-v1-...b780"
# - "sk-or-v1-...b781"
models: # 提供商支持的模型。或者你可以使用类似 openrouter://moonshotai/kimi-k2:free 这样的格式来请求未在这里定义的模型
- name: "moonshotai/kimi-k2:free" # 实际的模型名称。
alias: "kimi-k2" # 在API中使用的别名。
```
### Git 支持的配置与令牌存储
应用程序可配置为使用 Git 仓库作为后端,用于存储 `config.yaml` 配置文件和来自 `auth-dir` 目录的身份验证令牌。这允许对您的配置进行集中管理和版本控制。
要启用此功能,请将 `GITSTORE_GIT_URL` 环境变量设置为您的 Git 仓库的 URL。
**环境变量**
| 变量 | 必需 | 默认值 | 描述 |
|-------------------------|----|--------|----------------------------------------------------|
| `MANAGEMENT_PASSWORD` | 是 | | 管理面板密码 |
| `GITSTORE_GIT_URL` | 是 | | 要使用的 Git 仓库的 HTTPS URL。 |
| `GITSTORE_LOCAL_PATH` | 否 | 当前工作目录 | 将克隆 Git 仓库的本地路径。在 Docker 内部,此路径默认为 `/CLIProxyAPI`。 |
| `GITSTORE_GIT_USERNAME` | 否 | | 用于 Git 身份验证的用户名。 |
| `GITSTORE_GIT_TOKEN` | 否 | | 用于 Git 身份验证的个人访问令牌(或密码)。 |
**工作原理**
1. **克隆:** 启动时,应用程序会将远程 Git 仓库克隆到 `GITSTORE_LOCAL_PATH`。
2. **配置:** 然后,它会在克隆的仓库内的 `config` 目录中查找 `config.yaml` 文件。
3. **引导:** 如果仓库中不存在 `config/config.yaml`,应用程序会将本地的 `config.example.yaml` 复制到该位置,然后提交并推送到远程仓库作为初始配置。您必须确保 `config.example.yaml` 文件可用。
4. **令牌同步:** `auth-dir` 也在此仓库中管理。对身份验证令牌的任何更改(例如,通过新的登录)都会自动提交并推送到远程 Git 仓库。
### PostgreSQL 支持的配置与令牌存储
在托管环境中运行服务时,可以选择使用 PostgreSQL 来保存配置与令牌,借助托管数据库减轻本地文件管理压力。
**环境变量**
| 变量 | 必需 | 默认值 | 描述 |
|-------------------------|----|---------------|----------------------------------------------------------------------|
| `MANAGEMENT_PASSWORD` | 是 | | 管理面板密码(启用远程管理时必需)。 |
| `PGSTORE_DSN` | 是 | | PostgreSQL 连接串,例如 `postgresql://user:pass@host:5432/db`。 |
| `PGSTORE_SCHEMA` | 否 | public | 创建表时使用的 schema;留空则使用默认 schema。 |
| `PGSTORE_LOCAL_PATH` | 否 | 当前工作目录 | 本地镜像根目录,服务将在 `<值>/pgstore` 下写入缓存;若无法获取工作目录则退回 `/tmp/pgstore`。 |
**工作原理**
1. **初始化:** 启动时通过 `PGSTORE_DSN` 连接数据库,确保 schema 存在,并在缺失时创建 `config_store` 与 `auth_store`。
2. **本地镜像:** 在 `<PGSTORE_LOCAL_PATH 或当前工作目录>/pgstore` 下建立可写缓存,复用 `config/config.yaml` 与 `auths/` 目录。
3. **引导:** 若数据库中无配置记录,会使用 `config.example.yaml` 初始化,并以固定标识 `config` 写入。
4. **令牌同步:** 配置与令牌的更改会写入 PostgreSQL,同时数据库中的内容也会反向同步至本地镜像,便于文件监听与管理接口继续工作。
### 对象存储驱动的配置与令牌存储
可以选择使用 S3 兼容的对象存储来托管配置与鉴权数据。
**环境变量**
| 变量 | 是否必填 | 默认值 | 说明 |
|--------------------------|----------|--------------------|--------------------------------------------------------------------------------------------------------------------------|
| `MANAGEMENT_PASSWORD` | 是 | | 管理面板密码(启用远程管理时必需)。 |
| `OBJECTSTORE_ENDPOINT` | 是 | | 对象存储访问端点。可带 `http://` 或 `https://` 前缀指定协议(省略则默认 HTTPS)。 |
| `OBJECTSTORE_BUCKET` | 是 | | 用于存放 `config/config.yaml` 与 `auths/*.json` 的 Bucket 名称。 |
| `OBJECTSTORE_ACCESS_KEY` | 是 | | 对象存储账号的访问密钥 ID。 |
| `OBJECTSTORE_SECRET_KEY` | 是 | | 对象存储账号的访问密钥 Secret。 |
| `OBJECTSTORE_LOCAL_PATH` | 否 | 当前工作目录 (CWD) | 本地镜像根目录;服务会写入到 `<值>/objectstore`。 |
**工作流程**
1. **启动阶段:** 解析端点地址(识别协议前缀),创建 MinIO 兼容客户端并使用 Path-Style 模式,如 Bucket 不存在会自动创建。
2. **本地镜像:** 在 `<OBJECTSTORE_LOCAL_PATH 或当前工作目录>/objectstore` 维护可写缓存,同步 `config/config.yaml` 与 `auths/`。
3. **初始化:** 若 Bucket 中缺少配置文件,将以 `config.example.yaml` 为模板生成 `config/config.yaml` 并上传。
4. **双向同步:** 本地变更会上传到对象存储,同时远端对象也会拉回到本地,保证文件监听、管理 API 与 CLI 命令行为一致。
### OpenAI 兼容上游提供商
通过 `openai-compatibility` 配置上游 OpenAI 兼容提供商(例如 OpenRouter)。
- name:内部识别名
- base-url:提供商基础地址
- api-key-entries:API密钥条目列表,支持可选的每密钥代理配置(推荐)
- api-keys:(已弃用) 简单的API密钥列表,不支持代理配置
- models:将上游模型 `name` 映射为本地可用 `alias`
支持每密钥代理配置的示例:
```yaml
openai-compatibility:
- name: "openrouter"
base-url: "https://openrouter.ai/api/v1"
api-key-entries:
- api-key: "sk-or-v1-...b780"
proxy-url: "socks5://proxy.example.com:1080"
- api-key: "sk-or-v1-...b781"
models:
- name: "moonshotai/kimi-k2:free"
alias: "kimi-k2"
```
旧格式(仍支持):
```yaml
openai-compatibility:
- name: "openrouter"
base-url: "https://openrouter.ai/api/v1"
api-keys:
- "sk-or-v1-...b780"
- "sk-or-v1-...b781"
models:
- name: "moonshotai/kimi-k2:free"
alias: "kimi-k2"
```
使用方式:在 `/v1/chat/completions` 中将 `model` 设为别名(如 `kimi-k2`),代理将自动路由到对应提供商与模型。
并且,对于这些与OpenAI兼容的提供商模型,您始终可以通过将CODE_ASSIST_ENDPOINT设置为 http://127.0.0.1:8317 来使用Gemini CLI。
### 身份验证目录
`auth-dir` 参数指定身份验证令牌的存储位置。当您运行登录命令时,应用程序将在此目录中创建包含 Google 账户身份验证令牌的 JSON 文件。多个账户可用于轮询。
### 官方生成式语言 API
`generative-language-api-key` 参数允许您定义可用于验证对官方 AIStudio Gemini API 请求的 API 密钥列表。
## 热更新
服务会监听配置文件与 `auth-dir` 目录的变化并自动重新加载客户端与配置。您可以在运行中新增/移除 Gemini/OpenAI 的令牌 JSON 文件,无需重启服务。
## Gemini CLI 多账户负载均衡
启动 CLI 代理 API 服务器,然后将 `CODE_ASSIST_ENDPOINT` 环境变量设置为 CLI 代理 API 服务器的 URL。
```bash
export CODE_ASSIST_ENDPOINT="http://127.0.0.1:8317"
```
服务器将中继 `loadCodeAssist`、`onboardUser` 和 `countTokens` 请求。并自动在多个账户之间轮询文本生成请求。
> [!NOTE]
> 此功能仅允许本地访问,因为找不到一个可以验证请求的方法。
> 所以只能强制只有 `127.0.0.1` 可以访问。
## Claude Code 的使用方法
启动 CLI Proxy API 服务器, 设置如下系统环境变量 `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_DEFAULT_OPUS_MODEL`, `ANTHROPIC_DEFAULT_SONNET_MODEL`, `ANTHROPIC_DEFAULT_HAIKU_MODEL` (或 `ANTHROPIC_MODEL`, `ANTHROPIC_SMALL_FAST_MODEL` 对应 1.x.x 版本)
使用 Gemini 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=gemini-2.5-pro
export ANTHROPIC_DEFAULT_SONNET_MODEL=gemini-2.5-flash
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gemini-2.5-flash-lite
# 1.x.x 版本
export ANTHROPIC_MODEL=gemini-2.5-pro
export ANTHROPIC_SMALL_FAST_MODEL=gemini-2.5-flash
```
使用 OpenAI GPT 5 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=gpt-5-high
export ANTHROPIC_DEFAULT_SONNET_MODEL=gpt-5-medium
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gpt-5-minimal
# 1.x.x 版本
export ANTHROPIC_MODEL=gpt-5
export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-minimal
```
使用 OpenAI GPT 5 Codex 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=gpt-5-codex-high
export ANTHROPIC_DEFAULT_SONNET_MODEL=gpt-5-codex-medium
export ANTHROPIC_DEFAULT_HAIKU_MODEL=gpt-5-codex-low
# 1.x.x 版本
export ANTHROPIC_MODEL=gpt-5-codex
export ANTHROPIC_SMALL_FAST_MODEL=gpt-5-codex-low
```
使用 Claude 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=claude-opus-4-1-20250805
export ANTHROPIC_DEFAULT_SONNET_MODEL=claude-sonnet-4-5-20250929
export ANTHROPIC_DEFAULT_HAIKU_MODEL=claude-3-5-haiku-20241022
# 1.x.x 版本
export ANTHROPIC_MODEL=claude-sonnet-4-20250514
export ANTHROPIC_SMALL_FAST_MODEL=claude-3-5-haiku-20241022
```
使用 Qwen 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_HAIKU_MODEL=qwen3-coder-flash
# 1.x.x 版本
export ANTHROPIC_MODEL=qwen3-coder-plus
export ANTHROPIC_SMALL_FAST_MODEL=qwen3-coder-flash
```
使用 iFlow 模型:
```bash
export ANTHROPIC_BASE_URL=http://127.0.0.1:8317
export ANTHROPIC_AUTH_TOKEN=sk-dummy
# 2.x.x 版本
export ANTHROPIC_DEFAULT_OPUS_MODEL=qwen3-max
export ANTHROPIC_DEFAULT_SONNET_MODEL=qwen3-coder-plus
export ANTHROPIC_DEFAULT_HAIKU_MODEL=qwen3-235b-a22b-instruct
# 1.x.x 版本
export ANTHROPIC_MODEL=qwen3-max
export ANTHROPIC_SMALL_FAST_MODEL=qwen3-235b-a22b-instruct
```
## Codex 多账户负载均衡
启动 CLI Proxy API 服务器, 修改 `~/.codex/config.toml` 和 `~/.codex/auth.json` 文件。
config.toml:
```toml
model_provider = "cliproxyapi"
model = "gpt-5-codex" # 或者是gpt-5,你也可以使用任何我们支持的模型
model_reasoning_effort = "high"
[model_providers.cliproxyapi]
name = "cliproxyapi"
base_url = "http://127.0.0.1:8317/v1"
wire_api = "responses"
```
auth.json:
```json
{
"OPENAI_API_KEY": "sk-dummy"
}
```
## 使用 Docker 运行
运行以下命令进行登录(Gemini OAuth,端口 8085):
```bash
docker run --rm -p 8085:8085 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --login
```
运行以下命令进行登录(OpenAI OAuth,端口 1455):
```bash
docker run --rm -p 1455:1455 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --codex-login
```
运行以下命令进行登录(Claude OAuth,端口 54545):
```bash
docker run --rm -p 54545:54545 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --claude-login
```
运行以下命令进行登录(Qwen OAuth):
```bash
docker run -it -rm -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --qwen-login
```
运行以下命令进行登录(iFlow OAuth,端口 11451):
```bash
docker run --rm -p 11451:11451 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest /CLIProxyAPI/CLIProxyAPI --iflow-login
```
运行以下命令启动服务器:
```bash
docker run --rm -p 8317:8317 -v /path/to/your/config.yaml:/CLIProxyAPI/config.yaml -v /path/to/your/auth-dir:/root/.cli-proxy-api eceasy/cli-proxy-api:latest
```
> [!NOTE]
> 要在 Docker 中使用 Git 支持的配置存储,您可以使用 `-e` 标志传递 `GITSTORE_*` 环境变量。例如:
>
> ```bash
> docker run --rm -p 8317:8317 \
> -e GITSTORE_GIT_URL="https://github.com/your/config-repo.git" \
> -e GITSTORE_GIT_TOKEN="your_personal_access_token" \
> -v /path/to/your/git-store:/CLIProxyAPI/remote \
> eceasy/cli-proxy-api:latest
> ```
> 在这种情况下,您可能不需要直接挂载 `config.yaml` 或 `auth-dir`,因为它们将由容器内的 Git 存储在 `GITSTORE_LOCAL_PATH`(默认为 `/CLIProxyAPI`,在此示例中我们将其设置为 `/CLIProxyAPI/remote`)进行管理。
## 使用 Docker Compose 运行
1. 克隆仓库并进入目录:
```bash
git clone https://github.com/luispater/CLIProxyAPI.git
cd CLIProxyAPI
```
2. 准备配置文件:
通过复制示例文件来创建 `config.yaml` 文件,并根据您的需求进行自定义。
```bash
cp config.example.yaml config.yaml
```
*(Windows 用户请注意:您可以在 CMD 或 PowerShell 中使用 `copy config.example.yaml config.yaml`。)*
要在 Docker Compose 中使用 Git 支持的配置存储,您可以将 `GITSTORE_*` 环境变量添加到 `docker-compose.yml` 文件中的 `cli-proxy-api` 服务定义下。例如:
```yaml
services:
cli-proxy-api:
image: eceasy/cli-proxy-api:latest
container_name: cli-proxy-api
ports:
- "8317:8317"
- "8085:8085"
- "1455:1455"
- "54545:54545"
- "11451:11451"
environment:
- GITSTORE_GIT_URL=https://github.com/your/config-repo.git
- GITSTORE_GIT_TOKEN=your_personal_access_token
volumes:
- ./git-store:/CLIProxyAPI/remote # GITSTORE_LOCAL_PATH
restart: unless-stopped
```
在使用 Git 存储时,您可能不需要直接挂载 `config.yaml` 或 `auth-dir`。
3. 启动服务:
- **适用于大多数用户(推荐):**
运行以下命令,使用 Docker Hub 上的预构建镜像启动服务。服务将在后台运行。
```bash
docker compose up -d
```
- **适用于进阶用户:**
如果您修改了源代码并需要构建新镜像,请使用交互式辅助脚本:
- 对于 Windows (PowerShell):
```powershell
.\docker-build.ps1
```
- 对于 Linux/macOS:
```bash
bash docker-build.sh
```
脚本将提示您选择运行方式:
- **选项 1:使用预构建的镜像运行 (推荐)**:从镜像仓库拉取最新的官方镜像并启动容器。这是最简单的开始方式。
- **选项 2:从源码构建并运行 (适用于开发者)**:从本地源代码构建镜像,将其标记为 `cli-proxy-api:local`,然后启动容器。如果您需要修改源代码,此选项很有用。
4. 要在容器内运行登录命令进行身份验证:
- **Gemini**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --login
```
- **OpenAI (Codex)**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --codex-login
```
- **Claude**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --claude-login
```
- **Qwen**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --qwen-login
```
- **iFlow**:
```bash
docker compose exec cli-proxy-api /CLIProxyAPI/CLIProxyAPI -no-browser --iflow-login
```
5. 查看服务器日志:
```bash
docker compose logs -f
```
6. 停止应用程序:
```bash
docker compose down
```
## 管理 API 文档
请参见 [MANAGEMENT_API_CN.md](MANAGEMENT_API_CN.md)
## SDK 文档
- 使用文档:[docs/sdk-usage_CN.md](docs/sdk-usage_CN.md)
- 高级(执行器与翻译器):[docs/sdk-advanced_CN.md](docs/sdk-advanced_CN.md)
- 认证: [docs/sdk-access_CN.md](docs/sdk-access_CN.md)
- 凭据加载/更新: [docs/sdk-watcher_CN.md](docs/sdk-watcher_CN.md)
- 自定义 Provider 示例:`examples/custom-provider`
- 新增 Kiro (AWS CodeWhisperer) 支持 (OAuth 登录), 由[fuko2935](https://github.com/fuko2935/CLIProxyAPI/tree/feature/kiro-integration)、[Ravens2121](https://github.com/Ravens2121/CLIProxyAPIPlus/)提供
## 贡献
欢迎贡献!请随时提交 Pull Request。
1. Fork 仓库
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)
一款基于浏览器的 SRT 字幕翻译工具,可通过 CLI 代理 API 使用您的 Gemini 订阅。内置自动验证与错误修正功能,无需 API 密钥。
> [!NOTE]
> 如果你开发了基于 CLIProxyAPI 的项目,请提交一个 PR(拉取请求)将其添加到此列表中。
该项目仅接受第三方供应商支持的 Pull Request。任何非第三方供应商支持的 Pull Request 都将被拒绝。
如果需要提交任何非第三方供应商支持的 Pull Request,请提交到主线版本。
## 许可证
此项目根据 MIT 许可证授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
此项目根据 MIT 许可证授权 - 有关详细信息,请参阅 [LICENSE](LICENSE) 文件。
+74
View File
@@ -0,0 +1,74 @@
# ProxyPilot & Droid CLI Troubleshooting Log
**Date:** 2025-12-19
**Subject:** Gemini/Antigravity API Key & Quota Issues
## 1. Issue Summary
The user encountered `[HTTP 400] API key not valid` and `[HTTP 429] Resource Exhausted` errors when using the `droid` CLI with the `gemini-3-pro-preview` model.
## 2. Root Causes Identified
### A. Wrong Model Routing (Primary Cause of Quota Error)
* **Symbol:** `gemini-3-pro-preview`
* **Issue:** In ProxyPilot's registry, `gemini-3-pro-preview` is defined as a **Google/Gemini CLI** model, not an Antigravity model. Requests were routing directly to Google using personal CLI keys/quota, which were exhausted (429).
* **Fix:** Switched Droid configuration to use **`gemini-3-pro-high`** (or `low`), which are the correct aliases for Antigravity-routed models. These are now confirmed working.
### B. Antigravity Account Rotation Failure
* **Issue:** Even when using Antigravity, only 1 of the 3 available accounts was being utilized.
* **Cause:** The Auth Selector (`selector.go`) uses a "Strict Fallback" heuristic. If exactly *one* auth file contains a `project_id` field, it is designated as the "Primary" account, and others are ignored until the primary is effectively invalid.
* **Discovery:** Only the account `truongnamphong8` had a `project_id`.
* **Fix:** Removed the `project_id` field from the auth file so all 3 accounts are treated as "peers" and rotated via Round Robin.
### C. "API Key Not Valid" Startup Error
* **Issue:** ProxyPilot server logs showed API key errors on startup.
* **Cause:** `config.yaml` contained a placeholder line: `api-key: "YOUR_LEGIT_API_KEY_HERE"`.
* **Fix:** Commented out the invalid line in `config.yaml`.
### D. Droid CLI Config Corruption
* **Issue:** Droid failed to load with "Failed to parse custom models config".
* **Cause:** The `config.json` file was saved with a UTF-8 **BOM** (Byte Order Mark) by PowerShell during debugging/editing.
* **Fix:** Rewrote `config.json` with UTF-8 (No BOM) encoding.
## 3. Preventative Measures & Best Practices
### Model Naming
**ALWAYS** use the Antigravity-specific model IDs to ensure requests route through the shared pool rather than personal quota:
* ✅ `gemini-3-pro-high`
* ✅ `gemini-3-pro-low`
* ✅ `gemini-3-flash` (if available via Antigravity)
* ✅ `antigravity-claude-sonnet-4-5-thinking`
* ❌ `gemini-3-pro-preview` (Routes to Google CLI)
### Auth File Management
When adding new Antigravity accounts (`.json` files in `~/.cli-proxy-api/`):
* Ensure **uniformity**. Either *all* files should have a `project_id`, or *none* should.
* If mixed, the one with `project_id` will monopolize traffic.
### Configuration
* Do not leave placeholder values (like "YOUR_KEY_HERE") in `config.yaml`; comment them out.
* When editing JSON configuration files on Windows, ensure your editor saves as **UTF-8 (No BOM)**.
## 4. Current Configuration (Verified)
* **Droid Config:** `~/.factory/config.json` updated with correct Antigravity model names.
* **ProxyPilot Config:** `d:\code\ProxyPilot\config.yaml` cleaned of invalid keys.
* **Auth Status:** 3 Antigravity accounts active and rotating.
## 5. Issue: Rate Limit Rotation "Stuck" on One Account
**Date:** 2025-12-20
**Subject:** HTTP 429 Handling in Antigravity Executor & Manager
### A. Issue Summary
The user experienced repeated 429 Too Many Requests errors from the *same* account (yuhh0704@gmail.com) despite having multiple healthy backup accounts (nnq2366) available. The rotation logic refused to switch to the backup, effectively blocking the user.
### B. Root Causes
1. **Missing Retry-After Parsing:** The AntigravityExecutor was receiving a Retry-After header (e.g., 1 hour) from the upstream API but was ignoring it. It only returned a generic error message.
* **Effect:** The AuthManager used a default backoff of only **1 second**.
2. **Model State Not Updated:** When the global Auth object was marked as "Rate Limited", the specific ModelState for the requested model (e.g., claude-opus-4-5-thinking) remained "Active".
* **Effect:** The RoundRobinSelector checked the *model* state, saw it was valid, and re-selected the same "Primary Fallback" account (due to strict fallback logic preferences) immediately after the 1-second backoff expired.
### C. The Fix
1. **Updated AntigravityExecutor:** Added logic to parse the Retry-After header (supporting both integer seconds and HTTP date formats) and pass it to the statusErr struct.
2. **Updated AuthManager (MarkResult):** Modified the result handling to explicitly update the ModelState with the error and cooldown info, not just the parent Auth object.
3. **Updated Selector (isAuthBlockedForModel):** Added a defensive check to respect NextRetryAfter timestamps even if the Unavailable boolean flag wasn't explicitly set, ensuring blocked models are strictly filtered out.
### D. Result
System now respects long cooldowns (e.g., 3 hours) and correctly skips the blocked "Primary" account to use the "Secondary" backups like nnq2366.
+156
View File
@@ -0,0 +1,156 @@
# WARP.md
This file provides guidance to WARP (warp.dev) when working with code in this repository.
## Common commands
### Go (engine + desktop binaries)
Build the main deliverables into `bin/`:
```pwsh
# Builds:
# - bin\proxypilot-engine.exe (engine)
# - bin\ProxyPilot.exe (tray app)
# - bin\ProxyPilotUI.exe (desktop dashboard)
go run .\cmd\proxypilotpack build
```
Run the engine directly:
```pwsh
# Uses config.yaml in the repo root by default
# (or pass -config <path>)
go run .\cmd\server -config .\config.yaml
```
Windows helpers (used for local development and Droid/Factory CLI integration):
```pwsh
# build engine (writes bin\proxypilot-engine.exe)
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\build-cliproxyapi.ps1
# start/stop/restart engine (writes logs\proxypilot-engine.{out,err}.log)
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\start-cliproxy.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\stop-cliproxy.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\restart-cliproxy.ps1
```
Package artifacts:
```pwsh
# Zip bundle -> dist\ProxyPilot.zip
# (includes tray, UI, engine, and config.example.yaml)
go run .\cmd\proxypilotpack package-zip
# Windows installer (Inno Setup) -> dist\ProxyPilot-Setup.exe
# Requires ISCC.exe (Inno Setup 6) available on PATH.
go run .\cmd\proxypilotpack package-inno
```
Docker (engine in a container):
```pwsh
docker compose up --build
```
### Web UI (Vite)
The web UI lives in `webui/`:
```pwsh
cd .\webui
npm install
npm run dev # local dev server
npm run build # typecheck + build
npm run lint
```
### Tests
Run all Go tests:
```pwsh
go test ./...
```
Run a single package:
```pwsh
go test .\internal\api -run TestName
```
Run a single test across all packages:
```pwsh
go test ./... -run TestName
```
Regression tests called out in docs:
- 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`
## High-level architecture
### Binaries (`cmd/`)
This repo produces multiple Go binaries:
- `cmd/server` (engine): HTTP proxy server exposing OpenAI/Gemini/Claude-compatible endpoints; also hosts OAuth callback endpoints.
- `cmd/cliproxytray` (Windows tray app): starts/stops the engine, opens UI, toggles autostart, checks for updates.
- `cmd/proxypilotui` (Windows desktop UI): WebView2 desktop window for the Control Center; talks to the running engine and uses management endpoints.
- `cmd/proxypilotpack`: build/packaging orchestrator (build binaries into `bin/`, create `dist/` artifacts).
### Engine request path (big picture)
1. `cmd/server/main.go` loads config (`config.yaml` or a store-backed config), decides whether to run login flows or start the server.
2. `internal/cmd/StartService` builds the service via the exported SDK (`sdk/cliproxy.NewBuilder()`) and runs it.
3. The HTTP server is implemented in `internal/api/server.go` using Gin:
- `/v1/*` OpenAI-compatible endpoints (plus non-`/v1` aliases for clients that set base URL to `/v1`).
- `/v1/responses` has special streaming/SSE behavior for strict CLIs (see `docs/compat-matrix.md`).
- `/v1beta/*` Gemini-compatible endpoints.
- `/v1internal:method` Gemini CLI compatibility endpoint.
- OAuth callbacks like `/codex/callback`, `/google/callback`, etc. persist short-lived state for the login goroutines.
Core handler layer:
- `sdk/api/handlers/*` contains provider-specific API adapters (OpenAI/Gemini/Claude) and schema/streaming shims.
- `internal/api/handlers/management/*` contains management endpoints mounted under `/v0/management/*`.
### Management + desktop UX
- Management endpoints are only enabled when a secret is configured:
- `remote-management.secret-key` in `config.yaml`, or
- environment `MANAGEMENT_PASSWORD`.
- The tray app starts the engine via `internal/desktopctl.Start()` and injects a per-user `MANAGEMENT_PASSWORD` so the desktop UX can use `/v0/management/*` locally.
- The ProxyPilot dashboard page (`/proxypilot.html`) is served **localhost-only** and injects the management key into the HTML so users don’t paste keys manually.
Key components:
- `internal/desktopctl`: process management (start/stop/status), log file locations, and per-user UI state.
- `internal/api/proxypilot_dashboard.go`: local-only ProxyPilot dashboard HTML.
- `internal/managementasset`: downloads/serves the upstream management UI bundle and applies runtime text replacements for ProxyPilot branding.
### Config + persistence
- Default config is `config.yaml` (template: `config.example.yaml`).
- The engine can optionally use different config/auth persistence backends based on env vars (selected in `cmd/server/main.go`):
- Postgres-backed store (`PGSTORE_*`)
- Git-backed token store (`GITSTORE_*`)
- Object store (`OBJECTSTORE_*`)
### SDK embedding
The proxy can be embedded as a Go library:
- `sdk/cliproxy` exposes a builder (`NewBuilder`) that wires config watching, auth, translators, and the HTTP server.
- `docs/sdk-usage.md` shows the supported server options (middleware/router hooks, request logging overrides, management enablement).
## Docs worth reading first
- `docs/proxypilot.md` (Windows packaging + local management key behavior)
- `docs/compat-matrix.md` (client/upstream quirks; streaming/SSE gotchas; tests to protect)
- `docs/cursor-ide.md` (how Cursor expects base URL and API key behavior)
- `docs/sdk-usage.md` (how the engine is composed when embedded)
Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

+9
View File
@@ -0,0 +1,9 @@
//go:build !windows
package main
import "fmt"
func main() {
fmt.Println("cliproxytray is currently supported on Windows only.")
}
+700
View File
@@ -0,0 +1,700 @@
//go:build windows
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/getlantern/systray"
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
"github.com/router-for-me/CLIProxyAPI/v6/internal/proxypilotupdate"
"github.com/router-for-me/CLIProxyAPI/v6/internal/trayicon"
)
const autostartAppName = "ProxyPilot"
const thinkingProxyPort = 8317
func main() {
var repoRoot string
var configPath string
var exePath string
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
flag.StringVar(&exePath, "exe", "", "Path to ProxyPilot Engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
flag.Parse()
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
run(repoRoot, configPath, exePath)
}
func run(repoRoot, configPath, exePath string) {
systray.Run(func() {
thinkingProxy := startThinkingProxy(configPath)
defer thinkingProxy.Close()
if ico := trayicon.ProxyPilotICO(); len(ico) > 0 {
systray.SetIcon(ico)
}
systray.SetTitle("ProxyPilot")
systray.SetTooltip("ProxyPilot")
statusItem := systray.AddMenuItem("Status: ...", "Current status")
statusItem.Disable()
systray.AddSeparator()
openProxyUI := systray.AddMenuItem("Open Dashboard", "Open ProxyPilot Control Center")
systray.AddSeparator()
// Engine submenu
engineMenu := systray.AddMenuItem("Engine", "Engine controls")
startItem := engineMenu.AddSubMenuItem("Start", "Start the ProxyPilot engine")
stopItem := engineMenu.AddSubMenuItem("Stop", "Stop the ProxyPilot engine")
restartItem := engineMenu.AddSubMenuItem("Restart", "Restart the ProxyPilot engine")
// Connect submenu (VibeProxy-style easy setup)
connectMenu := systray.AddMenuItem("Connect", "Environment variables")
copyAnthropicEnv := connectMenu.AddSubMenuItem("Copy ANTHROPIC_BASE_URL", "Copy export ANTHROPIC_BASE_URL=http://127.0.0.1:8317/v1")
copyOpenAIEnv := connectMenu.AddSubMenuItem("Copy OPENAI_BASE_URL", "Copy export OPENAI_BASE_URL=http://127.0.0.1:8317/v1")
// Settings submenu
settingsMenu := systray.AddMenuItem("Settings", "ProxyPilot settings")
autoOn, _, _ := desktopctl.IsWindowsRunAutostartEnabled(autostartAppName)
autoStartItem := settingsMenu.AddSubMenuItemCheckbox("Launch on login", "Start this tray app when you log in", autoOn)
autoProxyOn, _ := desktopctl.GetAutoStartProxy()
autoStartProxyItem := settingsMenu.AddSubMenuItemCheckbox("Auto-start proxy", "Start the proxy server automatically", autoProxyOn)
// Tools submenu
toolsMenu := systray.AddMenuItem("Tools", "ProxyPilot tools")
openLogs := toolsMenu.AddSubMenuItem("Open Logs", "Open logs folder")
copyDiagnostics := toolsMenu.AddSubMenuItem("Copy Diagnostics", "Copy a support bundle to clipboard")
openLegacyUI := toolsMenu.AddSubMenuItem("Advanced UI", "Open management UI (advanced)")
// Updates submenu
updatesMenu := systray.AddMenuItem("Updates", "Check for updates")
checkUpdates := updatesMenu.AddSubMenuItem("Check for Updates", "Check GitHub Releases for a newer ProxyPilot")
updateNow := updatesMenu.AddSubMenuItem("Update ProxyPilot...", "Download and run the latest installer")
updateNow.Disable()
systray.AddSeparator()
quitItem := systray.AddMenuItem("Quit", "Quit")
lastErr := ""
var (
latestVersion string
assetName string
assetURL string
)
refresh := func() {
st, _ := desktopctl.StatusFor(configPath)
title := "Stopped"
if st.Running {
title = fmt.Sprintf("Running (:%d)", st.Port)
}
if st.LastError != "" && lastErr == "" {
lastErr = st.LastError
}
if lastErr != "" {
title = title + " - " + shorten(lastErr, 80)
}
statusItem.SetTitle("Status: " + title)
systray.SetTooltip("ProxyPilot - " + title)
if st.Running {
startItem.Disable()
stopItem.Enable()
restartItem.Enable()
} else {
startItem.Enable()
stopItem.Disable()
restartItem.Disable()
}
}
refresh()
// Optional: auto-start the proxy server on launch.
if autoProxyOn {
go func() {
st, _ := desktopctl.StatusFor(configPath)
if st.Running {
return
}
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
} else {
lastErr = ""
}
refresh()
}()
}
go func() {
t := time.NewTicker(2 * time.Second)
defer t.Stop()
for range t.C {
refresh()
}
}()
go func() {
for {
select {
case <-startItem.ClickedCh:
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-stopItem.ClickedCh:
if err := desktopctl.Stop(desktopctl.StopOptions{}); err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-restartItem.ClickedCh:
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
if err != nil {
lastErr = err.Error()
refresh()
continue
}
lastErr = ""
refresh()
case <-copyAnthropicEnv.ClickedCh:
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
case <-copyOpenAIEnv.ClickedCh:
_ = copyToClipboard(fmt.Sprintf("http://127.0.0.1:%d/v1", thinkingProxyPort))
case <-autoStartItem.ClickedCh:
if autoStartItem.Checked() {
_ = desktopctl.DisableWindowsRunAutostart(autostartAppName)
autoStartItem.Uncheck()
lastErr = ""
refresh()
continue
}
cmd, err := autostartCommand(repoRoot, configPath, exePath)
if err != nil {
lastErr = err.Error()
refresh()
continue
}
if err := desktopctl.EnableWindowsRunAutostart(autostartAppName, cmd); err != nil {
lastErr = err.Error()
refresh()
continue
}
autoStartItem.Check()
lastErr = ""
refresh()
case <-autoStartProxyItem.ClickedCh:
if autoStartProxyItem.Checked() {
_ = desktopctl.SetAutoStartProxy(false)
autoStartProxyItem.Uncheck()
lastErr = ""
refresh()
continue
}
_ = desktopctl.SetAutoStartProxy(true)
autoStartProxyItem.Check()
lastErr = ""
refresh()
case <-openProxyUI.ClickedCh:
if err := openProxyUIWithAutostart(repoRoot, configPath, exePath); err != nil {
lastErr = err.Error()
refresh()
} else {
lastErr = ""
refresh()
}
case <-openLegacyUI.ClickedCh:
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
lastErr = "proxy is not running"
refresh()
continue
}
_ = desktopctl.OpenBrowser(st.BaseURL + "/management.html?legacy=1")
case <-openLogs.ClickedCh:
if err := desktopctl.OpenLogsFolder(repoRoot, configPath); err != nil {
lastErr = err.Error()
refresh()
}
case <-copyDiagnostics.ClickedCh:
if err := copyDiagnosticsToClipboard(configPath); err != nil {
lastErr = err.Error()
} else {
lastErr = "Diagnostics copied"
}
refresh()
case <-checkUpdates.ClickedCh:
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
rel, err := proxypilotupdate.FetchLatestRelease(ctx)
if err != nil {
lastErr = err.Error()
refresh()
return
}
latestVersion = rel.Version()
assetName, assetURL = rel.FindPreferredAsset()
if strings.TrimSpace(assetURL) == "" {
lastErr = "no ProxyPilot asset found in latest release"
refresh()
return
}
// If this build is already tagged, avoid prompting unnecessarily.
if buildinfo.Version != "" && buildinfo.Version != "dev" && strings.EqualFold(buildinfo.Version, latestVersion) {
lastErr = "Up to date (" + latestVersion + ")"
updateNow.Disable()
refresh()
return
}
updateNow.SetTitle("Update ProxyPilot... (" + latestVersion + ")")
updateNow.Enable()
lastErr = "Update available (" + latestVersion + ")"
refresh()
}()
case <-updateNow.ClickedCh:
if strings.TrimSpace(assetURL) == "" {
lastErr = "no update asset URL (run Check for Updates)"
refresh()
continue
}
go func() {
dest := filepath.Join(os.TempDir(), "ProxyPilot-"+sanitizeFileName(latestVersion)+"-"+sanitizeFileName(assetName))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
updateNow.SetTitle("Updating...")
lastErr = "Downloading update..."
refresh()
if err := proxypilotupdate.DownloadToFile(ctx, assetURL, dest); err != nil {
lastErr = err.Error()
updateNow.SetTitle("Update ProxyPilot...")
refresh()
return
}
// Run installer/zip handler and exit ProxyPilot so files can be replaced.
lastErr = "Launching installer..."
refresh()
_ = launchUpdate(dest)
systray.Quit()
}()
case <-quitItem.ClickedCh:
systray.Quit()
return
}
}
}()
}, func() {})
}
type closeFn func() error
func (c closeFn) Close() error { return c() }
func startThinkingProxy(configPath string) ioCloser {
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", thinkingProxyPort))
if err != nil {
// Best effort: don't crash the tray app if the port is already taken.
return closeFn(func() error { return nil })
}
var (
mu sync.Mutex
lastPort int
lastProxy *httputil.ReverseProxy
lastTarget *url.URL
)
getProxy := func() (*httputil.ReverseProxy, *url.URL) {
st, _ := desktopctl.StatusFor(configPath)
port := st.Port
if port <= 0 {
port = 8318
}
target, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port))
mu.Lock()
defer mu.Unlock()
if lastProxy != nil && lastTarget != nil && lastPort == port {
return lastProxy, lastTarget
}
rp := httputil.NewSingleHostReverseProxy(target)
rp.FlushInterval = 50 * time.Millisecond
origDirector := rp.Director
rp.Director = func(r *http.Request) {
origDirector(r)
// Preserve original Host header behavior for local forwarding.
r.Host = target.Host
}
rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadGateway)
_, _ = w.Write([]byte(`{"error":{"message":"engine unavailable","type":"server_error"}}`))
}
lastPort = port
lastProxy = rp
lastTarget = target
return rp, target
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Only allow localhost clients to use the thinking proxy.
host, _, _ := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
if host != "127.0.0.1" && host != "::1" && !strings.EqualFold(host, "localhost") {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
rp, _ := getProxy()
rp.ServeHTTP(w, r)
})
srv := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
go func() { _ = srv.Serve(ln) }()
return closeFn(func() error {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
return ln.Close()
})
}
type ioCloser interface {
Close() error
}
func openProxyUIWithAutostart(repoRoot, configPath, exePath string) error {
// Prefer opening the desktop window if the UI binary exists next to this tray app.
if exe, err := os.Executable(); err == nil && strings.TrimSpace(exe) != "" {
dir := filepath.Dir(filepath.Clean(exe))
uiExe := filepath.Join(dir, "ProxyPilotUI.exe")
if _, err := os.Stat(uiExe); err == nil {
args := []string{}
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return exec.Command(uiExe, args...).Start()
}
}
// Fallback: open browser to the management UI (starts proxy if needed).
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
if _, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath}); err != nil {
return err
}
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
st2, _ := desktopctl.StatusFor(configPath)
if st2.Running {
break
}
time.Sleep(150 * time.Millisecond)
}
}
st, _ = desktopctl.StatusFor(configPath)
if strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy base URL not available")
}
return desktopctl.OpenBrowser(st.BaseURL + "/proxypilot.html")
}
func shorten(s string, max int) string {
s = strings.TrimSpace(s)
if len(s) <= max {
return s
}
return s[:max] + "..."
}
func sanitizeFileName(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return "unknown"
}
repl := strings.NewReplacer(
"\\", "_", "/", "_", ":", "_", "*", "_", "?", "_", "\"", "_", "<", "_", ">", "_", "|", "_", " ", "_",
)
return repl.Replace(s)
}
func launchUpdate(path string) error {
ext := strings.ToLower(filepath.Ext(path))
switch ext {
case ".exe":
// Inno installer (silent, per-user).
return exec.Command(path, "/SILENT", "/NORESTART", "/CLOSEAPPLICATIONS", "/RESTARTAPPLICATIONS").Start()
default:
// Fallback: let Windows handle the file (zip, etc.)
return exec.Command("rundll32", "url.dll,FileProtocolHandler", path).Start()
}
}
type authURLResponse struct {
Status string `json:"status"`
URL string `json:"url"`
State string `json:"state"`
Error string `json:"error"`
}
func startOAuthFlow(configPath string, endpointPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+endpointPath, nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var out authURLResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
if strings.TrimSpace(out.Error) != "" {
return fmt.Errorf("%s", out.Error)
}
return fmt.Errorf("auth url request failed: %s", resp.Status)
}
if strings.TrimSpace(out.URL) == "" {
return fmt.Errorf("missing auth url")
}
private, _ := desktopctl.GetOAuthPrivate()
return openOAuthURL(out.URL, private)
}
func copyDiagnosticsToClipboard(configPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+"/v0/management/proxypilot/diagnostics?lines=200", nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var payload struct {
Text string `json:"text"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("diagnostics failed: %s", resp.Status)
}
if strings.TrimSpace(payload.Text) == "" {
return fmt.Errorf("empty diagnostics")
}
return copyToClipboard(payload.Text)
}
func copyToClipboard(text string) error {
cmd := exec.Command("cmd", "/c", "clip")
cmd.Stdin = strings.NewReader(text)
return cmd.Run()
}
func openOAuthURL(url string, private bool) error {
if !private {
return desktopctl.OpenBrowser(url)
}
edge, err := findEdge()
if err != nil {
return desktopctl.OpenBrowser(url)
}
return exec.Command(edge, "--inprivate", url).Start()
}
func findEdge() (string, error) {
if p, err := exec.LookPath("msedge.exe"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
if p, err := exec.LookPath("msedge"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
candidates := []string{
filepath.Join(os.Getenv("ProgramFiles(x86)"), "Microsoft", "Edge", "Application", "msedge.exe"),
filepath.Join(os.Getenv("ProgramFiles"), "Microsoft", "Edge", "Application", "msedge.exe"),
}
for _, c := range candidates {
if strings.TrimSpace(c) == "" {
continue
}
if _, err := os.Stat(c); err == nil {
return c, nil
}
}
return "", fmt.Errorf("msedge.exe not found")
}
func autostartCommand(repoRoot, configPath, exePath string) (string, error) {
exe, err := os.Executable()
if err == nil && strings.TrimSpace(exe) != "" {
exe = filepath.Clean(exe)
} else {
exe = ""
}
if exe == "" {
return "", fmt.Errorf("unable to resolve tray executable path")
}
args := make([]string, 0, 6)
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return quoteWindowsCommand(exe, args), nil
}
func applyDefaults(repoRoot, configPath, exePath string) (string, string, string) {
repoRoot = strings.TrimSpace(repoRoot)
configPath = strings.TrimSpace(configPath)
exePath = strings.TrimSpace(exePath)
exe, _ := os.Executable()
exeDir := ""
if strings.TrimSpace(exe) != "" {
exeDir = filepath.Dir(filepath.Clean(exe))
}
// If launched from a repo/app "bin" directory, treat its parent as the root.
defaultRoot := exeDir
if strings.EqualFold(filepath.Base(defaultRoot), "bin") {
defaultRoot = filepath.Dir(defaultRoot)
}
if repoRoot == "" && defaultRoot != "" {
repoRoot = defaultRoot
}
if configPath == "" && repoRoot != "" {
configPath = filepath.Join(repoRoot, "config.yaml")
}
if configPath != "" {
ensureConfig(configPath)
}
if exePath == "" && exeDir != "" {
for _, name := range []string{"proxypilot-engine.exe", "cliproxyapi-latest.exe"} {
cand := filepath.Join(exeDir, name)
if _, err := os.Stat(cand); err == nil {
exePath = cand
break
}
}
}
return repoRoot, configPath, exePath
}
func ensureConfig(configPath string) {
if _, err := os.Stat(configPath); err == nil {
return
}
dir := filepath.Dir(configPath)
example := filepath.Join(dir, "config.example.yaml")
if _, err := os.Stat(example); err != nil {
return
}
b, err := os.ReadFile(example)
if err != nil {
return
}
b = bootstrapLocalConfig(b)
_ = os.WriteFile(configPath, b, 0o644)
}
func bootstrapLocalConfig(b []byte) []byte {
// Best-effort: make the packaged default usable without editing.
// Keep it simple (string-based) so we don't need YAML parsing in the tray binary.
s := string(b)
s = strings.ReplaceAll(s, "- \"your-api-key-1\"", "- \"local-dev-key\"")
s = strings.ReplaceAll(s, "- \"your-api-key-2\"\r\n", "")
s = strings.ReplaceAll(s, "- \"your-api-key-2\"\n", "")
s = strings.ReplaceAll(s, "secret-key: \"\"\r\n", "secret-key: \"local-dev-key\"\r\n")
s = strings.ReplaceAll(s, "secret-key: \"\"\n", "secret-key: \"local-dev-key\"\n")
return []byte(s)
}
func quoteWindowsCommand(exe string, args []string) string {
quoted := make([]string, 0, 1+len(args))
quoted = append(quoted, `"`+strings.ReplaceAll(exe, `"`, `\"`)+`"`)
for _, a := range args {
a = strings.TrimSpace(a)
if a == "" {
continue
}
if strings.ContainsAny(a, " \t") {
quoted = append(quoted, `"`+strings.ReplaceAll(a, `"`, `\"`)+`"`)
} else {
quoted = append(quoted, a)
}
}
return strings.Join(quoted, " ")
}
+498
View File
@@ -0,0 +1,498 @@
package main
import (
"archive/zip"
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/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")
}
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
if runtime.GOOS != "windows" {
uiExe = filepath.Join(binRoot, "ProxyPilotUI")
}
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/cliproxytray"); err != nil {
return err
}
} else {
if err := run(repoRoot, "go", "build", "-o", trayExe, "./cmd/cliproxytray"); err != nil {
return err
}
}
if runtime.GOOS == "windows" {
if err := run(repoRoot, "go", "build", "-ldflags", "-H=windowsgui", "-o", uiExe, "./cmd/proxypilotui"); err != nil {
return err
}
} else {
// The UI binary is only supported on Windows for now; skip on other OSes.
}
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, "ProxyPilotUI.exe"), dst: "ProxyPilotUI.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")
uiExe := filepath.Join(binRoot, "ProxyPilotUI.exe")
srvExe := filepath.Join(binRoot, "proxypilot-engine.exe")
if err := copyFile(mgrExe, filepath.Join(staging, "ProxyPilot.exe")); err != nil {
return err
}
if err := copyFile(uiExe, filepath.Join(staging, "ProxyPilotUI.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%ProxyPilotUI.exe\" \"%DEST%\\ProxyPilotUI.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, "%FILE3%=config.example.yaml\r\n", "")
sed = strings.ReplaceAll(sed, "FILE3=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%%=ProxyPilotUI.exe
%%FILE2%%=proxypilot-engine.exe
%%FILE3%%=config.example.yaml
%%FILE4%%=install.cmd
[Strings]
FILE0=ProxyPilot.exe
FILE1=ProxyPilotUI.exe
FILE2=proxypilot-engine.exe
FILE3=config.example.yaml
FILE4=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 assets/*
var FS embed.FS
+14
View File
@@ -0,0 +1,14 @@
<!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" />
<title>webui</title>
<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>
+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

+753
View File
@@ -0,0 +1,753 @@
//go:build windows
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"unsafe"
"github.com/jchv/go-webview2"
"github.com/router-for-me/CLIProxyAPI/v6/cmd/proxypilotui/assets"
"github.com/router-for-me/CLIProxyAPI/v6/internal/desktopctl"
)
func main() {
var repoRoot string
var configPath string
var exePath string
var url string
var standalone bool
flag.StringVar(&repoRoot, "repo", "", "Repo root (used to locate bin/ and logs/)")
flag.StringVar(&configPath, "config", "", "Path to config.yaml (defaults to <repo>/config.yaml)")
flag.StringVar(&exePath, "exe", "", "Path to proxy engine binary (defaults to <repo>/bin/proxypilot-engine.exe)")
flag.StringVar(&url, "url", "", "Open a specific URL in-app (advanced)")
flag.BoolVar(&standalone, "standalone", false, "Run standalone UI without connecting to proxy server")
flag.Parse()
repoRoot, configPath, exePath = applyDefaults(repoRoot, configPath, exePath)
var assetServerURL string
if standalone {
// Start embedded asset server
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
_ = messageBox("ProxyPilot", "Failed to start asset server: "+err.Error())
os.Exit(1)
}
assetServerURL = "http://" + ln.Addr().String()
go func() {
fsys, _ := fs.Sub(assets.FS, ".")
http.Serve(ln, http.FileServer(http.FS(fsys)))
}()
} else {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
_, _ = desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
st, _ = desktopctl.StatusFor(configPath)
if st.Running {
break
}
time.Sleep(200 * time.Millisecond)
}
}
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
_ = messageBox("ProxyPilot", "Proxy is not running.\n\nClick Start in the ProxyPilot tray menu, then try again.")
os.Exit(1)
}
}
if strings.TrimSpace(url) == "" {
url = "control"
}
var target string
if standalone {
if strings.EqualFold(strings.TrimSpace(url), "control") {
target = assetServerURL + "/index.html"
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
target = strings.TrimSpace(url)
} else {
target = assetServerURL + "/index.html"
}
} else {
st, _ := desktopctl.StatusFor(configPath)
if strings.EqualFold(strings.TrimSpace(url), "control") {
target = st.BaseURL + "/proxypilot.html"
} else if strings.HasPrefix(strings.TrimSpace(url), "http://") || strings.HasPrefix(strings.TrimSpace(url), "https://") {
target = strings.TrimSpace(url)
}
}
// Prefer an in-app window (WebView2) so this behaves like a native dashboard app.
w := webview2.NewWithOptions(webview2.WebViewOptions{
Debug: true,
AutoFocus: true,
WindowOptions: webview2.WindowOptions{
Title: "ProxyPilot",
Width: 1200,
Height: 850,
Center: true,
},
})
if w == nil {
// Fallback: Edge app mode or default browser.
if target == "" {
if standalone {
target = assetServerURL + "/index.html"
} else {
st, _ := desktopctl.StatusFor(configPath)
target = st.BaseURL + "/proxypilot.html"
}
}
edge, err := findEdge()
if err != nil {
_ = exec.Command("rundll32", "url.dll,FileProtocolHandler", target).Start()
return
}
_ = exec.Command(edge, "--app="+target, "--window-size=1200,850", "--lang=en-US").Start()
return
}
defer w.Destroy()
w.SetSize(1200, 850, webview2.HintNone)
// Bindings used by the Control Center UI.
_ = w.Bind("pp_status", func() (map[string]any, error) {
cur, _ := desktopctl.StatusFor(configPath)
return map[string]any{
"running": cur.Running,
"port": cur.Port,
"thinking_port": cur.ThinkingPort,
"thinking_running": cur.ThinkingRunning,
"base_url": cur.BaseURL,
"last_error": cur.LastError,
}, nil
})
_ = w.Bind("pp_start", func() error {
_, err := desktopctl.Start(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
return err
})
_ = w.Bind("pp_stop", func() error { return desktopctl.Stop(desktopctl.StopOptions{}) })
_ = w.Bind("pp_restart", func() error {
_, err := desktopctl.Restart(desktopctl.StartOptions{RepoRoot: repoRoot, ConfigPath: configPath, ExePath: exePath})
return err
})
_ = w.Bind("pp_open_logs", func() error { return desktopctl.OpenLogsFolder(repoRoot, configPath) })
_ = w.Bind("pp_open_auth_folder", func() error {
dir, err := desktopctl.AuthDirFor(configPath)
if err != nil {
return err
}
return desktopctl.OpenFolder(dir)
})
_ = w.Bind("pp_open_legacy_ui", func() error {
cur, _ := desktopctl.StatusFor(configPath)
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/management.html?legacy=1")
})
_ = w.Bind("pp_open_diagnostics", func() error {
cur, _ := desktopctl.StatusFor(configPath)
if !cur.Running || strings.TrimSpace(cur.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
return openNewWindow(repoRoot, configPath, exePath, cur.BaseURL+"/proxypilot.html")
})
_ = w.Bind("pp_get_oauth_private", func() (bool, error) { return desktopctl.GetOAuthPrivate() })
_ = w.Bind("pp_set_oauth_private", func(enabled bool) error { return desktopctl.SetOAuthPrivate(enabled) })
_ = w.Bind("pp_oauth", func(provider string) error {
endpoint := ""
switch strings.ToLower(strings.TrimSpace(provider)) {
case "antigravity":
endpoint = "/v0/management/antigravity-auth-url"
case "gemini-cli", "geminicli":
endpoint = "/v0/management/gemini-cli-auth-url"
case "codex":
endpoint = "/v0/management/codex-auth-url"
case "claude", "anthropic":
endpoint = "/v0/management/anthropic-auth-url"
case "qwen":
endpoint = "/v0/management/qwen-auth-url"
case "iflow":
endpoint = "/v0/management/iflow-auth-url"
default:
return fmt.Errorf("unknown provider: %s", provider)
}
return startOAuthFlow(configPath, endpoint)
})
_ = w.Bind("pp_copy_diagnostics", func() error { return copyDiagnosticsToClipboard(configPath) })
_ = w.Bind("pp_get_management_key", func() (string, error) { return desktopctl.GetManagementPassword() })
// Integration bindings
_ = w.Bind("pp_get_integrations", func() ([]map[string]any, error) {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
return nil, fmt.Errorf("proxy not running")
}
key, _ := desktopctl.GetManagementPassword()
client := &http.Client{Timeout: 5 * time.Second}
req, _ := http.NewRequest("GET", st.BaseURL+"/v0/management/integrations", nil)
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var res struct {
Integrations []map[string]any `json:"integrations"`
}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res.Integrations, nil
})
_ = w.Bind("pp_configure_integration", func(id string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running {
return fmt.Errorf("proxy not running")
}
key, _ := desktopctl.GetManagementPassword()
client := &http.Client{Timeout: 10 * time.Second}
req, _ := http.NewRequest("POST", st.BaseURL+"/v0/management/integrations/"+id, nil)
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
b, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed: %s", string(b))
}
return nil
})
if target != "" {
w.Navigate(target)
w.Run()
return
}
w.SetHtml(controlCenterHTML())
w.Run()
}
func findEdge() (string, error) {
if p, err := exec.LookPath("msedge.exe"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
if p, err := exec.LookPath("msedge"); err == nil && strings.TrimSpace(p) != "" {
return p, nil
}
candidates := []string{
filepath.Join(os.Getenv("ProgramFiles(x86)"), "Microsoft", "Edge", "Application", "msedge.exe"),
filepath.Join(os.Getenv("ProgramFiles"), "Microsoft", "Edge", "Application", "msedge.exe"),
}
for _, c := range candidates {
if strings.TrimSpace(c) == "" {
continue
}
if _, err := os.Stat(c); err == nil {
return c, nil
}
}
return "", fmt.Errorf("msedge.exe not found")
}
func applyDefaults(repoRoot, configPath, exePath string) (string, string, string) {
repoRoot = strings.TrimSpace(repoRoot)
configPath = strings.TrimSpace(configPath)
exePath = strings.TrimSpace(exePath)
exe, _ := os.Executable()
exeDir := ""
if strings.TrimSpace(exe) != "" {
exeDir = filepath.Dir(filepath.Clean(exe))
}
// If launched from a repo/app "bin" directory, treat its parent as the root.
defaultRoot := exeDir
if strings.EqualFold(filepath.Base(defaultRoot), "bin") {
defaultRoot = filepath.Dir(defaultRoot)
}
if repoRoot == "" && defaultRoot != "" {
repoRoot = defaultRoot
}
if configPath == "" && exeDir != "" {
configPath = filepath.Join(repoRoot, "config.yaml")
}
if exePath == "" && exeDir != "" {
for _, name := range []string{"proxypilot-engine.exe", "cliproxyapi-latest.exe"} {
cand := filepath.Join(exeDir, name)
if _, err := os.Stat(cand); err == nil {
exePath = cand
break
}
}
}
return repoRoot, configPath, exePath
}
func openNewWindow(repoRoot, configPath, exePath, url string) error {
exe, err := os.Executable()
if err != nil || strings.TrimSpace(exe) == "" {
return desktopctl.OpenBrowser(url)
}
args := []string{"-url", url}
if strings.TrimSpace(repoRoot) != "" {
args = append(args, "-repo", repoRoot)
}
if strings.TrimSpace(configPath) != "" {
args = append(args, "-config", configPath)
}
if strings.TrimSpace(exePath) != "" {
args = append(args, "-exe", exePath)
}
return exec.Command(exe, args...).Start()
}
type authURLResponse struct {
Status string `json:"status"`
URL string `json:"url"`
State string `json:"state"`
Error string `json:"error"`
}
func startOAuthFlow(configPath string, endpointPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+endpointPath, nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
var out authURLResponse
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
if strings.TrimSpace(out.Error) != "" {
return fmt.Errorf("%s", out.Error)
}
return fmt.Errorf("auth url request failed: %s", resp.Status)
}
if strings.TrimSpace(out.URL) == "" {
return fmt.Errorf("missing auth url")
}
private, _ := desktopctl.GetOAuthPrivate()
return openOAuthURL(out.URL, private)
}
func openOAuthURL(url string, private bool) error {
if !private {
return desktopctl.OpenBrowser(url)
}
edge, err := findEdge()
if err != nil {
return desktopctl.OpenBrowser(url)
}
return exec.Command(edge, "--inprivate", url).Start()
}
func copyDiagnosticsToClipboard(configPath string) error {
st, _ := desktopctl.StatusFor(configPath)
if !st.Running || strings.TrimSpace(st.BaseURL) == "" {
return fmt.Errorf("proxy is not running")
}
key, err := desktopctl.GetManagementPassword()
if err != nil {
return err
}
client := &http.Client{Timeout: 15 * time.Second}
req, err := http.NewRequest(http.MethodGet, st.BaseURL+"/v0/management/proxypilot/diagnostics?lines=200", nil)
if err != nil {
return err
}
req.Header.Set("X-Management-Key", key)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
b, _ := io.ReadAll(resp.Body)
msg := strings.TrimSpace(string(b))
if msg == "" {
msg = resp.Status
}
return fmt.Errorf("diagnostics failed: %s", msg)
}
var payload struct {
Text string `json:"text"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return err
}
if strings.TrimSpace(payload.Text) == "" {
return fmt.Errorf("empty diagnostics")
}
return copyToClipboard(payload.Text)
}
func copyToClipboard(text string) error {
cmd := exec.Command("cmd", "/c", "clip")
cmd.Stdin = strings.NewReader(text)
return cmd.Run()
}
func controlCenterHTML() string {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ProxyPilot</title>
<style>
:root{
--bg:#0b0f17;
--panel:#0f172a;
--panel2:#111c33;
--text:#e5e7eb;
--muted:#9ca3af;
--line:#1f2a44;
--brand:#60a5fa;
--good:#34d399;
--bad:#f87171;
--warn:#fbbf24;
--btn:#1f2a44;
--btn2:#243152;
}
*{box-sizing:border-box}
body{
margin:0;
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial;
background: radial-gradient(1000px 600px at 20% 0%, rgba(96,165,250,.18), transparent 60%),
radial-gradient(1000px 700px at 80% 10%, rgba(52,211,153,.12), transparent 55%),
var(--bg);
color:var(--text);
}
.wrap{max-width:1040px;margin:0 auto;padding:28px 22px 40px}
.top{display:flex;gap:14px;align-items:center;justify-content:space-between;margin-bottom:18px}
.brand{display:flex;align-items:center;gap:12px}
.logo{
width:42px;height:42px;border-radius:12px;
background: linear-gradient(135deg, rgba(96,165,250,.95), rgba(34,211,238,.75));
box-shadow: 0 10px 30px rgba(96,165,250,.18);
}
h1{font-size:22px;margin:0}
.sub{font-size:13px;color:var(--muted);margin-top:3px}
.pill{
display:inline-flex;align-items:center;gap:8px;
padding:8px 12px;border:1px solid var(--line);border-radius:999px;
background: rgba(15,23,42,.65);
font-size:13px;color:var(--muted)
}
.dot{width:9px;height:9px;border-radius:50%}
.card{
border:1px solid var(--line);
background: linear-gradient(180deg, rgba(15,23,42,.92), rgba(15,23,42,.78));
border-radius:16px;
padding:16px;
box-shadow: 0 20px 60px rgba(0,0,0,.35);
}
.grid{display:grid;grid-template-columns:1.4fr .9fr;gap:16px}
@media (max-width: 980px){.grid{grid-template-columns:1fr}}
.row{display:flex;flex-wrap:wrap;gap:10px}
button,.btn{
appearance:none;border:1px solid var(--line);background:var(--btn);color:var(--text);
border-radius:12px;padding:10px 12px;font-size:13px;cursor:pointer;
transition: transform .06s ease, background .12s ease, border-color .12s ease;
user-select:none;
}
button:hover{background:var(--btn2);border-color:#2c3a60}
button:active{transform: translateY(1px)}
button[disabled]{opacity:.45;cursor:not-allowed}
.btnPrimary{background: rgba(96,165,250,.18);border-color: rgba(96,165,250,.45)}
.btnPrimary:hover{background: rgba(96,165,250,.25);border-color: rgba(96,165,250,.65)}
.btnDanger{background: rgba(248,113,113,.14);border-color: rgba(248,113,113,.4)}
.btnDanger:hover{background: rgba(248,113,113,.2);border-color: rgba(248,113,113,.6)}
.btnGood{background: rgba(52,211,153,.14);border-color: rgba(52,211,153,.38)}
.btnGood:hover{background: rgba(52,211,153,.2);border-color: rgba(52,211,153,.55)}
.sectionTitle{font-size:13px;color:var(--muted);margin:0 0 10px}
.kv{display:grid;grid-template-columns:120px 1fr;gap:8px 10px;font-size:13px;margin-top:8px}
.k{color:var(--muted)}
.v{color:var(--text);word-break:break-word}
.note{font-size:12px;color:var(--muted);margin-top:10px;line-height:1.4}
.toggle{display:flex;align-items:center;gap:10px;margin-top:10px}
input[type="checkbox"]{width:16px;height:16px}
.toast{position:fixed;left:22px;bottom:18px;padding:10px 12px;border-radius:12px;border:1px solid var(--line);background:rgba(15,23,42,.88);color:var(--text);font-size:13px;display:none;max-width: min(620px, calc(100vw - 44px));}
.toast.show{display:block}
.hint{font-size:12px;color:var(--muted);margin-top:8px}
</style>
</head>
<body>
<div class="wrap">
<div class="top">
<div class="brand">
<div class="logo"></div>
<div>
<h1>ProxyPilot</h1>
<div class="sub">Local proxy controller + dashboard (Windows)</div>
</div>
</div>
<div class="pill" id="statusPill">
<span class="dot" id="statusDot" style="background: var(--warn)"></span>
<span id="statusText">Checking…</span>
</div>
</div>
<div class="grid">
<div class="card">
<div class="sectionTitle">Engine</div>
<div class="row">
<button class="btnGood" id="startBtn">Start</button>
<button class="btnDanger" id="stopBtn">Stop</button>
<button id="restartBtn">Restart</button>
<button class="btnPrimary" id="diagBtn">Open Diagnostics</button>
<button id="legacyBtn">Advanced UI</button>
</div>
<div class="kv">
<div class="k">Base URL</div><div class="v" id="baseUrl">-</div>
<div class="k">Port</div><div class="v" id="port">-</div>
<div class="k">Thinking Port</div><div class="v" id="thinkingPort">-</div>
<div class="k">Last error</div><div class="v" id="lastErr">-</div>
</div>
<div class="row" style="margin-top:12px">
<button id="logsBtn">Open Logs Folder</button>
<button id="authBtn">Open Auth Folder</button>
<button id="copyDiagBtn">Copy Diagnostics</button>
</div>
<div class="toggle">
<input id="privateOAuth" type="checkbox" />
<label for="privateOAuth">Open OAuth in a private (InPrivate) window</label>
</div>
<div class="note">
Tip: keep the tray menu minimal — use this Control Center for day-to-day actions.
</div>
</div>
<div class="card">
<div class="sectionTitle">Logins</div>
<div class="row">
<button id="oauthAntigravity">Antigravity</button>
<button id="oauthGeminiCli">Gemini CLI</button>
<button id="oauthCodex">Codex</button>
<button id="oauthClaude">Claude</button>
<button id="oauthQwen">Qwen</button>
<button id="oauthIflow">iFlow</button>
</div>
<div class="hint">These open the provider login flow in your browser and save auth files for ProxyPilot.</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Integrations</div>
<div class="row" id="integrationsList">
<div style="color:var(--muted);font-size:13px">Loading integrations...</div>
</div>
<div class="note">
Automatically configure local tools to use ProxyPilot.
</div>
</div>
<div class="card" style="grid-column: 1 / -1">
<div class="sectionTitle">Live Logs</div>
<div id="logContent" style="height:240px;overflow-y:auto;background:rgba(0,0,0,.3);padding:10px;font-family:monospace;font-size:12px;border-radius:8px;border:1px solid var(--line);white-space:pre-wrap;color:var(--muted)">Waiting for logs...</div>
<div class="row" style="margin-top:10px">
<button id="toggleLogsBtn">Pause Updates</button>
<button id="clearLogsBtn">Clear View</button>
</div>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script>
const $ = (id) => document.getElementById(id);
let logPaused = false;
const toast = (msg) => {
const el = $('toast');
el.textContent = msg;
el.classList.add('show');
clearTimeout(window.__toastTimer);
window.__toastTimer = setTimeout(()=> el.classList.remove('show'), 2400);
};
const setRunningUI = (running) => {
$('startBtn').disabled = !!running;
$('stopBtn').disabled = !running;
$('restartBtn').disabled = !running;
$('diagBtn').disabled = !running;
$('legacyBtn').disabled = !running;
const dot = $('statusDot');
dot.style.background = running ? 'var(--good)' : 'var(--warn)';
if(running) refreshIntegrations();
};
async function refreshStatus() {
try{
const s = await window.pp_status();
$('baseUrl').textContent = s.base_url || '-';
$('port').textContent = s.port ? String(s.port) : '-';
const tp = $('thinkingPort');
if (s.thinking_port) {
tp.textContent = s.thinking_port + (s.thinking_running ? ' (Active)' : ' (Inactive)');
tp.style.color = s.thinking_running ? 'var(--good)' : 'var(--muted)';
} else {
tp.textContent = '-';
tp.style.color = 'var(--muted)';
}
$('lastErr').textContent = (s.last_error && s.last_error.trim()) ? s.last_error : '-';
$('statusText').textContent = s.running ? ('Running (:' + s.port + ')') : 'Stopped';
setRunningUI(!!s.running);
if(!logPaused && s.running) refreshLogs();
}catch(e){
$('statusText').textContent = 'Error';
$('lastErr').textContent = (e && e.message) ? e.message : String(e);
setRunningUI(false);
}
}
async function refreshLogs() {
const logEl = $('logContent');
const key = await window.pp_get_management_key();
const s = await window.pp_status();
if(!s.base_url) return;
try {
const resp = await fetch(s.base_url + '/v0/management/proxypilot/logs/tail?file=stdout&lines=50', {
headers: { 'X-Management-Key': key }
});
const data = await resp.json();
if(data.lines) {
logEl.textContent = data.lines.join('\n');
logEl.scrollTop = logEl.scrollHeight;
}
} catch(e) {}
}
async function refreshIntegrations() {
const list = $('integrationsList');
try {
const items = await window.pp_get_integrations();
if(!items || items.length === 0) {
list.innerHTML = '<div style="color:var(--muted);font-size:13px">No integrations available</div>';
return;
}
list.innerHTML = '';
items.forEach(i => {
const btn = document.createElement('button');
btn.className = i.configured ? 'btnGood' : 'btn';
btn.textContent = i.name + (i.configured ? ' (Active)' : '');
btn.onclick = async () => {
try {
await window.pp_configure_integration(i.id);
toast('Configured ' + i.name);
refreshIntegrations();
} catch(e) { toast(e.message||String(e)); }
};
if(!i.installed) {
btn.disabled = true;
btn.textContent += ' (Not Installed)';
}
list.appendChild(btn);
});
} catch(e) {
// quiet fail if proxy not ready
}
}
async function init() {
try{
const priv = await window.pp_get_oauth_private();
$('privateOAuth').checked = !!priv;
}catch(e){}
await refreshStatus();
setInterval(refreshStatus, 1200);
}
$('startBtn').addEventListener('click', async () => { try{ await window.pp_start(); toast('Started'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('stopBtn').addEventListener('click', async () => { try{ await window.pp_stop(); toast('Stopped'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('restartBtn').addEventListener('click', async () => { try{ await window.pp_restart(); toast('Restarted'); }catch(e){ toast(e.message||String(e)); } await refreshStatus(); });
$('logsBtn').addEventListener('click', async () => { try{ await window.pp_open_logs(); toast('Opened logs'); }catch(e){ toast(e.message||String(e)); } });
$('authBtn').addEventListener('click', async () => { try{ await window.pp_open_auth_folder(); toast('Opened auth folder'); }catch(e){ toast(e.message||String(e)); } });
$('copyDiagBtn').addEventListener('click', async () => { try{ await window.pp_copy_diagnostics(); toast('Copied'); }catch(e){ toast(e.message||String(e)); } });
$('diagBtn').addEventListener('click', async () => { try{ await window.pp_open_diagnostics(); }catch(e){ toast(e.message||String(e)); } });
$('legacyBtn').addEventListener('click', async () => { try{ await window.pp_open_legacy_ui(); }catch(e){ toast(e.message||String(e)); } });
$('toggleLogsBtn').addEventListener('click', () => {
logPaused = !logPaused;
$('toggleLogsBtn').textContent = logPaused ? 'Resume Updates' : 'Pause Updates';
});
$('clearLogsBtn').addEventListener('click', () => { $('logContent').textContent = ''; });
$('privateOAuth').addEventListener('change', async (ev) => {
try{ await window.pp_set_oauth_private(!!ev.target.checked); toast('Saved'); }catch(e){ toast(e.message||String(e)); }
});
const oauth = (provider) => async () => { try{ await window.pp_oauth(provider); toast('Opened login'); }catch(e){ toast(e.message||String(e)); } };
$('oauthAntigravity').addEventListener('click', oauth('antigravity'));
$('oauthGeminiCli').addEventListener('click', oauth('gemini-cli'));
$('oauthCodex').addEventListener('click', oauth('codex'));
$('oauthClaude').addEventListener('click', oauth('claude'));
$('oauthQwen').addEventListener('click', oauth('qwen'));
$('oauthIflow').addEventListener('click', oauth('iflow'));
init();
</script>
</body>
</html>`
}
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
}
+128 -25
View File
@@ -1,4 +1,4 @@
// Package main provides the entry point for the CLI Proxy API server.
// Package main provides the entry point for the ProxyPilot engine.
// This server acts as a proxy that provides OpenAI/Gemini/Claude compatible API interfaces
// for CLI models, allowing CLI models to be used with tools and libraries designed for standard AI APIs.
package main
@@ -16,7 +16,7 @@ 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/buildinfo"
"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"
@@ -27,6 +27,7 @@ import (
"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"
configaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access/config"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
log "github.com/sirupsen/logrus"
)
@@ -41,13 +42,29 @@ var (
// init initializes the shared logger setup.
func init() {
logging.SetupBaseLogger()
buildinfo.Version = Version
buildinfo.Commit = Commit
buildinfo.BuildDate = BuildDate
}
// setKiroIncognitoMode sets the incognito browser mode for Kiro authentication.
// Kiro defaults to incognito mode for multi-account support.
// Users can explicitly override with --incognito or --no-incognito flags.
func setKiroIncognitoMode(cfg *config.Config, useIncognito, noIncognito bool) {
if useIncognito {
cfg.IncognitoBrowser = true
} else if noIncognito {
cfg.IncognitoBrowser = false
} else {
cfg.IncognitoBrowser = true // Kiro default
}
}
// 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("ProxyPilot Engine 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
@@ -55,10 +72,21 @@ func main() {
var claudeLogin bool
var qwenLogin bool
var iflowLogin bool
var iflowCookie bool
var noBrowser bool
var antigravityLogin bool
var kiroLogin bool
var kiroGoogleLogin bool
var kiroAWSLogin bool
var kiroAWSAuthCode bool
var kiroImport bool
// var githubCopilotLogin bool // REMOVED - GitHub Copilot excluded
var projectID string
var vertexImport string
var configPath string
var password string
var noIncognito bool
var useIncognito bool
// Define command-line flags for different operation modes.
flag.BoolVar(&login, "login", false, "Login Google Account")
@@ -66,9 +94,20 @@ func main() {
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(&iflowCookie, "iflow-cookie", false, "Login to iFlow using Cookie")
flag.BoolVar(&noBrowser, "no-browser", false, "Don't open browser automatically for OAuth")
flag.BoolVar(&useIncognito, "incognito", false, "Open browser in incognito/private mode for OAuth (useful for multiple accounts)")
flag.BoolVar(&noIncognito, "no-incognito", false, "Force disable incognito mode (uses existing browser session)")
flag.BoolVar(&antigravityLogin, "antigravity-login", false, "Login to Antigravity using OAuth")
flag.BoolVar(&kiroLogin, "kiro-login", false, "Login to Kiro using Google OAuth")
flag.BoolVar(&kiroGoogleLogin, "kiro-google-login", false, "Login to Kiro using Google OAuth (same as --kiro-login)")
flag.BoolVar(&kiroAWSLogin, "kiro-aws-login", false, "Login to Kiro using AWS Builder ID (device code flow)")
flag.BoolVar(&kiroAWSAuthCode, "kiro-aws-authcode", false, "Login to Kiro using AWS Builder ID (authorization code flow, better UX)")
flag.BoolVar(&kiroImport, "kiro-import", false, "Import Kiro token from Kiro IDE (~/.aws/sso/cache/kiro-auth-token.json)")
// GitHub Copilot login removed
flag.StringVar(&projectID, "project_id", "", "Project ID (Gemini only, not required)")
flag.StringVar(&configPath, "config", DefaultConfigPath, "Configure File Path")
flag.StringVar(&vertexImport, "vertex-import", "", "Import Vertex service account key JSON file")
flag.StringVar(&password, "password", "", "")
flag.CommandLine.Usage = func() {
@@ -129,7 +168,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.
@@ -223,13 +263,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 +294,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 +303,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 +327,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()
@@ -313,7 +360,8 @@ func main() {
gitStoreInst = store.NewGitTokenStore(gitStoreRemoteURL, gitStoreUser, gitStorePassword)
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 +370,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 +397,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{}
@@ -377,20 +431,34 @@ func main() {
configFileExists = true
}
}
usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled)
coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
if err = logging.ConfigureLogOutput(cfg.LoggingToFile); err != nil {
log.Fatalf("failed to configure log output: %v", err)
// Perform basic semantic validation of the loaded configuration.
if warnings, errValidate := config.ValidateConfig(cfg); errValidate != nil {
log.Errorf("invalid configuration: %v", errValidate)
return
} else if len(warnings) > 0 {
for _, w := range warnings {
log.Warnf("config warning: %s", w)
}
}
log.Infof("CLIProxyAPI Version: %s, Commit: %s, BuiltAt: %s", Version, Commit, BuildDate)
usage.SetStatisticsEnabled(cfg.UsageStatisticsEnabled)
coreauth.SetQuotaCooldownDisabled(cfg.DisableCooling)
// AntigravityPrimaryEmail removed - field does not exist
if err = logging.ConfigureLogOutput(cfg.LoggingToFile, cfg.LogsMaxTotalSizeMB); err != nil {
log.Errorf("failed to configure log output: %v", err)
return
}
log.Infof("ProxyPilot Engine 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
}
@@ -417,9 +485,18 @@ func main() {
// Handle different command modes based on the provided flags.
if login {
if vertexImport != "" {
// Handle Vertex service account import
cmd.DoVertexImport(cfg, vertexImport)
} else if login {
// Handle Google/Gemini login
cmd.DoLogin(cfg, projectID, options)
} else if antigravityLogin {
// Handle Antigravity login
cmd.DoAntigravityLogin(cfg, options)
} else if false { // GitHub Copilot removed
// Handle GitHub Copilot login
// GitHub Copilot login removed
} else if codexLogin {
// Handle Codex login
cmd.DoCodexLogin(cfg, options)
@@ -430,6 +507,32 @@ func main() {
cmd.DoQwenLogin(cfg, options)
} else if iflowLogin {
cmd.DoIFlowLogin(cfg, options)
} else if iflowCookie {
cmd.DoIFlowCookieAuth(cfg, options)
} else if kiroLogin {
// For Kiro auth, default to incognito mode for multi-account support
// Users can explicitly override with --no-incognito
// Note: This config mutation is safe - auth commands exit after completion
// and don't share config with StartService (which is in the else branch)
setKiroIncognitoMode(cfg, useIncognito, noIncognito)
cmd.DoKiroLogin(cfg, options)
} else if kiroGoogleLogin {
// For Kiro auth, default to incognito mode for multi-account support
// Users can explicitly override with --no-incognito
// Note: This config mutation is safe - auth commands exit after completion
setKiroIncognitoMode(cfg, useIncognito, noIncognito)
cmd.DoKiroGoogleLogin(cfg, options)
} else if kiroAWSLogin {
// For Kiro auth, default to incognito mode for multi-account support
// Users can explicitly override with --no-incognito
setKiroIncognitoMode(cfg, useIncognito, noIncognito)
cmd.DoKiroAWSLogin(cfg, options)
} else if kiroAWSAuthCode {
// For Kiro auth with authorization code flow (better UX)
setKiroIncognitoMode(cfg, useIncognito, noIncognito)
cmd.DoKiroAWSAuthCodeLogin(cfg, options)
} else if kiroImport {
cmd.DoKiroImport(cfg, options)
} else {
// In cloud deploy mode without config file, just wait for shutdown signals
if isCloudDeploy && !configFileExists {
+176 -48
View File
@@ -1,87 +1,215 @@
# 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).
# 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: ""
# Disable the bundled management control panel asset download and HTTP route when true.
# 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).
# Defaults to the server working directory when empty.
# harness-root-dir: ""
# API keys for authentication
api-keys:
- "your-api-key-1"
- "your-api-key-2"
- "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
# When true, enable authentication for the WebSocket API (/v1/ws).
ws-auth: false
# API keys for official Generative Language API
#generative-language-api-key:
# - "AIzaSy...01"
# - "AIzaSy...02"
# - "AIzaSy...03"
# - "AIzaSy...04"
# 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.
# 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..."
# 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
# 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
# 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..."
# 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
# 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.
# 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.
# 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"
# iflow:
# - "tstars2.0"
# 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"
+5 -4
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:
@@ -19,9 +19,10 @@ services:
- "8085:8085"
- "1455:1455"
- "54545:54545"
- "51121:51121"
- "11451:11451"
volumes:
- ./config.yaml:/CLIProxyAPI/config.yaml
- ./config.yaml:/ProxyPilot/config.yaml
- ./auths:/root/.cli-proxy-api
- ./logs:/CLIProxyAPI/logs
- ./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
```
+89
View File
@@ -0,0 +1,89 @@
# 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.
## 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'
```
+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.
+128
View File
@@ -0,0 +1,128 @@
# Desktop UI (ProxyPilot) — Shared Spec (Windows first)
This doc captures shared architecture and product decisions for a desktop “controller app” that manages a local `ProxyPilot` instance.
OS-specific details live in:
- Windows: `docs/windows-ui-spec.md`
- macOS (future): `docs/macos-ui-spec.md` (not yet)
## What we’re building
A small tray-first desktop app that can:
- start/stop/restart the local proxy engine (ProxyPilot Engine)
- show health + port + “copy base URL” snippets for IDE/agentic CLIs
- surface logs/request diagnostics to debug issues like 400/429, “prompt too long”, streaming quirks
It is not a full replacement for the server’s Management UI; it’s a launcher + diagnostics tool.
## Two-shell strategy (Wails + Tauri)
We can support both Wails and Tauri without forking business logic by standardizing on a single control interface.
### Primary shell: Wails (Go)
- Pros: simplest integration with existing Go codebase, easiest to ship v1 fast.
- Architecture: Wails UI ↔ Go control layer (in-process).
### Secondary shell: Tauri (Rust)
- Pros: smaller footprint, strong native tray/window tooling, good distribution story.
- Architecture (recommended): Tauri UI ↔ helper CLI ↔ Go control layer.
- Tauri calls `cliproxyctl` (or similar) as a subprocess.
- Benefits: no Rust↔Go FFI, no duplicated process logic, easy testing.
## Shared control interface
### Go package
- `internal/desktopctl`
- Pure Go logic for process management, config reading/writing, health, logs, autostart primitives.
- No UI dependencies.
### Suggested helper CLI (used by Tauri and power users)
- `cmd/cliproxyctl`
- `cliproxyctl status --config <path>`
- `cliproxyctl start --config <path>`
- `cliproxyctl stop`
- `cliproxyctl restart --config <path>`
- `cliproxyctl diag --config <path> --out <file|clipboard>`
Wails can call `internal/desktopctl` directly; Tauri can call `cliproxyctl`.
## Feature scope (v1)
### Core controls
- Start/Stop/Restart the proxy engine.
- Detect if a proxy is already running:
- If owned by UI: show as “Managed”.
- If not owned: show as “External” and offer “Attach” (read-only) vs “Stop anyway” behind a confirmation.
### Health
- Health check: `GET http://127.0.0.1:<port>/healthz`.
- Show last successful check time and last error message.
### Config
- Config path chooser + remember last choice.
- “Open config” action (external editor).
- Validate YAML on save (or show parse error).
### Logs / request diagnostics
- Open logs folder.
- Tail last N lines of `proxypilot-engine.out.log` and `proxypilot-engine.err.log`.
- “Copy diagnostics” button that includes:
- app version, proxy version
- config path, port, pid
- last error + last N log lines
- pointers to recent request logs
### Quick-copy snippets
- `OPENAI_BASE_URL=http://127.0.0.1:<port>/v1`
- `OPENAI_API_KEY=<your local key>`
- Minimal curl sanity checks.
## Nice-to-haves (v1.1+)
- “Recent requests” viewer (parse `logs/v1-*.log`):
- list request IDs, status, provider, model, auth label, latency
- click to open the log file at the relevant section
- Surface auth status:
- list loaded auth files + provider + account email (when available)
- show “cooling down” vs “active”
- optionally display primary/backup preference (e.g. `antigravity`)
- “Safe config wizard”:
- toggle localhost-only management
- add/generate local dev API key
- Update mechanism (self-update) and server binary update strategy.
## Security / safety rules
- Default to localhost-only assumptions.
- Don’t display or log API keys unless user explicitly reveals/copies them.
- Autostart toggles must show exactly what command will run.
- Avoid writing outside user profile by default.
## Cross-platform notes
Split OS-specific operations behind small interfaces in `internal/desktopctl`:
- Process operations (spawn, signal/terminate, pid discovery)
- Autostart
- “Open folder” / “Open URL”
Windows and macOS implementations can live in separate files via Go build tags:
- `*_windows.go`
- `*_darwin.go`
## Open questions
- Should the desktop app bundle the engine binary, or manage an existing install?
- Do we want a dedicated “desktop control” HTTP endpoint in the proxy (vs local process control only)?
+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.
+178
View File
@@ -0,0 +1,178 @@
# 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`
+70
View File
@@ -0,0 +1,70 @@
# ProxyPilot
ProxyPilot is a local “AI proxy + desktop UX” for agentic CLIs (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 dashboard, 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, iFlow
- `Open Auth Folder` shortcut
## 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)
+171
View File
@@ -0,0 +1,171 @@
# Windows UI for ProxyPilot — Spec (Wails + Tauri)
This is the Windows-specific portion of the desktop UI plan. Shared (cross-platform) decisions and architecture live in `docs/desktop-ui-spec.md`.
## Goals
- Provide a Windows-friendly way to run and manage `ProxyPilot` without PowerShell.
- Surface request/log diagnostics to reduce “prompt too long” + debugging pain.
- Support two desktop shells over time:
- Primary: Wails (Go backend + web UI)
- Secondary/experimental: Tauri (Rust + web UI)
- Share logic via a Go control layer so features don’t fork.
## Non-goals (v1)
- Replacing the existing Management API UI shipped with the server.
- Full cross-platform parity (macOS/Linux can come later).
- Full OAuth flows inside the desktop UI (v1 can “open browser” and show status).
- Becoming an agent/IDE: this is a small controller + diagnostics utility.
## Product decisions (to avoid bikeshedding)
- v1 ships as Wails.
- Tauri is optional later; it should reuse the same control layer via a helper CLI.
- The UI controls an existing `proxypilot-engine.exe` (built by the UI or already present).
- The UI should not require elevated privileges and should default to localhost-only behavior.
## Personas / Use-cases
- “I just want it running”: start/stop, see port, see health.
- “I need to debug”: view logs, open request logs, copy diagnostics.
- “I’m configuring tools”: show local base URL, API key hints, and quick-copy snippets.
- “I want it to launch on login”: enable/disable autostart (per-user).
## UX requirements
- Tray-first: app sits in the system tray with minimal friction.
- Single click status: Running/Stopped + port + quick actions.
- No admin required for normal operation.
- Clear failure reasons: missing config, port in use, binary missing, auth dir missing.
## Functional requirements (v1)
### Process control
- Build (optional): build `cmd/server` into `bin/proxypilot-engine.exe`.
- Start:
- Uses a selectable config path (default: repo `config.yaml` if present).
- Writes logs to `logs/proxypilot-engine.out.log` and `logs/proxypilot-engine.err.log`.
- Stop:
- Prefer graceful stop; fallback to kill process if needed.
- Restart.
- Detect running instance:
- PID-based if started by UI, plus best-effort discovery by listening port.
- If an instance is running but not owned by the UI, show “External” and offer read-only “Attach” (don’t blindly kill it).
### Status & health
- Show:
- port (from config or detection)
- reachable status via `GET http://127.0.0.1:<port>/v1/models` (or a future `/healthz`)
- last start time and PID (when known)
- Buttons:
- Open Management UI (browser)
- Open logs folder
- Copy base URL (`http://127.0.0.1:<port>` and optionally `/v1`)
### Config
- Config path selector (browse + remember last choice).
- Validate YAML on save (or warn on parse failure).
- Minimal editor:
- open in external editor, and/or inline text editor with Save.
- Safe defaults:
- warn if management routes are remotely accessible.
### Autostart (Windows)
- Enable/disable per-user startup on Windows.
- Backend supports:
- registry `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`
- scheduled task fallback (optional; clearly labeled)
### Quick-copy snippets (v1)
- Show ready-to-paste snippets:
- `OPENAI_BASE_URL=http://127.0.0.1:<port>/v1`
- `OPENAI_API_KEY=<your local key>`
- curl sanity check for `GET /v1/models`
### Diagnostics / support bundle (v1.1)
- One-click “Copy diagnostics”:
- version, config path, port, PID, last 200 lines of logs
- recent request logs list (or last N request IDs)
## Shared Go control layer (Windows notes)
Wails and Tauri should both call the same operations (process management, config, logs, autostart, health checks). See `docs/desktop-ui-spec.md` for the proposed package/API shape.
Windows-specific notes:
- Persist UI state in `%LOCALAPPDATA%/ProxyPilot/ui-state.json`.
- Prefer discover-by-port over discover-by-process-name.
- When opening folders/URLs, use native Windows shell APIs (no admin).
## Wails app (primary) — MVP
### Packaging
- Ship `ProxyPilot.exe` with embedded web UI assets.
- Bundle or download `proxypilot-engine.exe` (open decision).
### Screens
- Tray menu:
- Start / Stop / Restart
- Open UI
- Open logs
- Quit
- Main window:
- Status card (Running/Stopped, port, last error)
- Buttons: Start/Stop/Restart, Open Management UI, Open Logs
- Config path selector + Open config
- Autostart toggle
- Copy snippets section (base URL + key + curl check)
### First-run UX
- If no config path is set:
- Detect `config.yaml` in common locations (repo root, `%LOCALAPPDATA%/ProxyPilot/`, user home).
- Offer “Use detected config” or “Browse…”.
- If no API key is configured:
- Offer “Generate local key” (writes to config) or “Open config” guidance.
## Tauri app (secondary) — MVP
### Purpose
- Evaluate smaller footprint distribution vs Wails.
- Prototype a more native-feeling tray + notifications.
### Integration options
- Option A (recommended): Tauri calls a helper CLI (`cliproxyctl.exe`).
- Option B: Tauri starts a small local HTTP control server.
## Security considerations
- Default to localhost-only assumptions.
- Don’t display or log API keys unless explicitly requested.
- When enabling autostart, show what command will run.
- Avoid writing outside the user profile unless configured.
## Open decisions
- Where config lives by default (repo-local vs user config dir).
- Whether UI bundles the server binary or manages an existing install.
- Whether to add a stable `/healthz` endpoint for fast health checks.
- Whether “Generate local key” should mutate `config.yaml` or use a UI-only key store.
- Whether the UI should surface auth selection state (primary/backup) for providers like `antigravity`.
## Acceptance criteria (v1)
- Installing and launching the app shows a tray icon and a status window.
- Start/Stop/Restart works reliably across app restarts (PID state persisted).
- Health check distinguishes:
- process running but endpoint not reachable
- endpoint reachable with `GET /v1/models` returning 200
- Open logs opens the correct folder.
- Copy base URL copies `http://127.0.0.1:<port>` (and optionally `/v1`).
+11 -7
View File
@@ -23,13 +23,13 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/api"
"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/sdk/api"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
clipexec "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/executor"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/logging"
sdktr "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
)
@@ -137,6 +137,14 @@ func (MyExecutor) Execute(ctx context.Context, a *coreauth.Auth, req clipexec.Re
return clipexec.Response{Payload: body}, nil
}
func (MyExecutor) CountTokens(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("count tokens not implemented")
}
func (MyExecutor) Embed(context.Context, *coreauth.Auth, clipexec.Request, clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("embeddings not implemented")
}
func (MyExecutor) ExecuteStream(ctx context.Context, a *coreauth.Auth, req clipexec.Request, opts clipexec.Options) (<-chan clipexec.StreamChunk, error) {
ch := make(chan clipexec.StreamChunk, 1)
go func() {
@@ -146,10 +154,6 @@ func (MyExecutor) ExecuteStream(ctx context.Context, a *coreauth.Auth, req clipe
return ch, nil
}
func (MyExecutor) CountTokens(ctx context.Context, a *coreauth.Auth, req clipexec.Request, opts clipexec.Options) (clipexec.Response, error) {
return clipexec.Response{}, errors.New("not implemented")
}
func (MyExecutor) Refresh(ctx context.Context, a *coreauth.Auth) (*coreauth.Auth, error) {
return a, nil
}
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"context"
"fmt"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/translator"
_ "github.com/router-for-me/CLIProxyAPI/v6/sdk/translator/builtin"
)
func main() {
rawRequest := []byte(`{"messages":[{"content":[{"text":"Hello! Gemini","type":"text"}],"role":"user"}],"model":"gemini-2.5-pro","stream":false}`)
fmt.Println("Has gemini->openai response translator:", translator.HasResponseTransformerByFormatName(
translator.FormatGemini,
translator.FormatOpenAI,
))
translatedRequest := translator.TranslateRequestByFormatName(
translator.FormatOpenAI,
translator.FormatGemini,
"gemini-2.5-pro",
rawRequest,
false,
)
fmt.Printf("Translated request to Gemini format:\n%s\n\n", translatedRequest)
claudeResponse := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thought":true,"text":"Okay, here's what's going through my mind. I need to schedule a meeting"},{"thoughtSignature":"","functionCall":{"name":"schedule_meeting","args":{"topic":"Q3 planning","attendees":["Bob","Alice"],"time":"10:00","date":"2025-03-27"}}}]},"finishReason":"STOP","avgLogprobs":-0.50018133435930523}],"usageMetadata":{"promptTokenCount":117,"candidatesTokenCount":28,"totalTokenCount":474,"trafficType":"PROVISIONED_THROUGHPUT","promptTokensDetails":[{"modality":"TEXT","tokenCount":117}],"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":28}],"thoughtsTokenCount":329},"modelVersion":"gemini-2.5-pro","createTime":"2025-08-15T04:12:55.249090Z","responseId":"x7OeaIKaD6CU48APvNXDyA4"}`)
convertedResponse := translator.TranslateNonStreamByFormatName(
context.Background(),
translator.FormatGemini,
translator.FormatOpenAI,
"gemini-2.5-pro",
rawRequest,
translatedRequest,
claudeResponse,
nil,
)
fmt.Printf("Converted response for OpenAI clients:\n%s\n", convertedResponse)
}
+22 -7
View File
@@ -3,23 +3,29 @@ module github.com/router-for-me/CLIProxyAPI/v6
go 1.24.0
require (
github.com/andybalholm/brotli v1.0.6
github.com/fsnotify/fsnotify v1.9.0
github.com/getlantern/systray v1.2.2
github.com/gin-gonic/gin v1.10.1
github.com/go-git/go-git/v6 v6.0.0-20251009132922-75a182125145
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/jackc/pgx/v5 v5.7.6
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047
github.com/joho/godotenv v1.5.1
github.com/klauspost/compress v1.17.4
github.com/minio/minio-go/v7 v7.0.66
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/sirupsen/logrus v1.9.3
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
github.com/stretchr/testify v1.11.1
github.com/tidwall/gjson v1.18.0
github.com/tidwall/sjson v1.2.5
github.com/tiktoken-go/tokenizer v0.7.0
golang.org/x/crypto v0.43.0
golang.org/x/net v0.46.0
golang.org/x/crypto v0.45.0
golang.org/x/net v0.47.0
golang.org/x/oauth2 v0.30.0
golang.org/x/sys v0.38.0
golang.org/x/term v0.37.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gopkg.in/yaml.v3 v3.0.1
)
@@ -28,28 +34,36 @@ require (
cloud.google.com/go/compute/metadata v0.3.0 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/ProtonMail/go-crypto v1.3.0 // indirect
github.com/andybalholm/brotli v1.0.6 // indirect
github.com/bytedance/sonic v1.11.6 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudflare/circl v1.6.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/cyphar/filepath-securejoin v0.4.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dlclark/regexp2 v1.11.5 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 // indirect
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 // indirect
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7 // indirect
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7 // indirect
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 // indirect
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-git/gcfg/v2 v2.0.2 // indirect
github.com/go-git/go-billy/v6 v6.0.0-20250627091229-31e2a16eef30 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/go-stack/stack v1.8.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kevinburke/ssh_config v1.4.0 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
@@ -59,8 +73,10 @@ require (
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pjbgf/sha1cd v0.5.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rs/xid v1.5.0 // indirect
github.com/sergi/go-diff v1.4.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
@@ -68,9 +84,8 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.37.0 // indirect
golang.org/x/text v0.30.0 // indirect
golang.org/x/sync v0.18.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
+43 -13
View File
@@ -37,6 +37,20 @@ github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 h1:NRUJuo3v3WGC/g5YiyF790gut6oQr5f3FBI88Wv0dx4=
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520/go.mod h1:L+mq6/vvYHKjCX2oez0CgEAJmbq1fbb/oNJIWQkBybY=
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 h1:6uJ+sZ/e03gkbqZ0kUG6mfKoqDb4XMAzMIwlajq19So=
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7/go.mod h1:l+xpFBrCtDLpK9qNjxs+cHU6+BAdlBaxHqikB6Lku3A=
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7 h1:guBYzEaLz0Vfc/jv0czrr2z7qyzTOGC9hiQ0VC+hKjk=
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7/go.mod h1:zx/1xUUeYPy3Pcmet8OSXLbF47l+3y6hIPpyLWoR9oc=
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7 h1:micT5vkcr9tOVk1FiH8SWKID8ultN44Z+yzd2y/Vyb0=
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7/go.mod h1:dD3CgOrwlzca8ed61CsZouQS5h5jIzkK9ZWrTcf0s+o=
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 h1:XYzSdCbkzOC0FDNrgJqGRo8PCMFOBFL9py72DRs7bmc=
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55/go.mod h1:6mmzY2kW1TOOrVy+r41Za2MxXM+hhqTtY3oBKd2AgFA=
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f h1:wrYrQttPS8FHIRSlsrcuKazukx/xqO/PpLZzZXsF+EA=
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f/go.mod h1:D5ao98qkA6pxftxoqzibIBBrLSUli+kYnJqrgBf9cIA=
github.com/getlantern/systray v1.2.2 h1:dCEHtfmvkJG7HZ8lS/sLklTH4RKUcIsKrAD9sThoEBE=
github.com/getlantern/systray v1.2.2/go.mod h1:pXFOI1wwqwYXEhLPm9ZGjS2u/vVELeIgNMY5HvhHhcE=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
@@ -59,6 +73,8 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=
@@ -78,6 +94,10 @@ github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047 h1:oQmbCpoIo/BQCUWzmMYR6hyq9Awgx0ingJHy4gWijTI=
github.com/jchv/go-webview2 v0.0.0-20250406165304-0bcfea011047/go.mod h1:rWifBlzkgrvd7zUqlfq91sWt3473OikgnglnIILx/Jo=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1 h1:njuLRcjAuMKr7kI3D85AXWkw6/+v9PwtV6M6o11sWHQ=
github.com/jchv/go-winloader v0.0.0-20250406163304-c1995be93bd1/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
@@ -99,6 +119,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lxn/walk v0.0.0-20210112085537-c389da54e794/go.mod h1:E23UucZGqpuUANJooIbHWCufXvOcT6E7Stq81gU+CSQ=
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
@@ -112,10 +134,14 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=
github.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -126,7 +152,6 @@ github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
@@ -160,26 +185,31 @@ github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZ
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210218145245-beda7e5e158e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/Knetic/govaluate.v3 v3.0.0/go.mod h1:csKLBORsPbafmSCGTEh3U7Ozmsuq8ZSIlKk1bcqph0E=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+71
View File
@@ -0,0 +1,71 @@
#define AppName "ProxyPilot"
#ifndef AppVersion
#define AppVersion "0.0.0-dev"
#endif
#ifndef RepoRoot
#define RepoRoot ".."
#endif
#ifndef OutDir
#define OutDir "..\\dist"
#endif
[Setup]
AppId={{3D9053A0-3F6A-47D7-9D91-8BB1D1CC2A4E}
AppName={#AppName}
AppVersion={#AppVersion}
AppPublisher=ProxyPilot
SetupIconFile={#RepoRoot}\\bin\\ProxyPilot.ico
DefaultDirName={localappdata}\\{#AppName}
DefaultGroupName={#AppName}
DisableProgramGroupPage=yes
PrivilegesRequired=lowest
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
ArchitecturesInstallIn64BitMode=x64
OutputDir={#OutDir}
OutputBaseFilename=ProxyPilot-Setup
UninstallDisplayIcon={app}\\ProxyPilot.ico
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
Name: "desktopicon"; Description: "Create a &desktop icon"; GroupDescription: "Additional icons:"
[Files]
Source: "{#RepoRoot}\\bin\\ProxyPilot.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\ProxyPilotUI.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\proxypilot-engine.exe"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\bin\\ProxyPilot.ico"; DestDir: "{app}"; Flags: ignoreversion
Source: "{#RepoRoot}\\config.example.yaml"; DestDir: "{app}"; Flags: ignoreversion
[Icons]
Name: "{autoprograms}\\{#AppName}"; Filename: "{app}\\ProxyPilot.exe"; WorkingDir: "{app}"; IconFilename: "{app}\\ProxyPilot.ico"
Name: "{autodesktop}\\{#AppName}"; Filename: "{app}\\ProxyPilot.exe"; Tasks: desktopicon; WorkingDir: "{app}"; IconFilename: "{app}\\ProxyPilot.ico"
[Run]
Filename: "{app}\\ProxyPilot.exe"; Description: "Launch {#AppName}"; Flags: nowait postinstall skipifsilent
[UninstallRun]
Filename: "cmd.exe"; Parameters: "/c reg delete HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v ProxyPilot /f >nul 2>nul"; Flags: runhidden
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ConfigYaml: string;
ExampleYaml: string;
begin
if CurStep = ssPostInstall then
begin
ConfigYaml := ExpandConstant('{app}\\config.yaml');
ExampleYaml := ExpandConstant('{app}\\config.example.yaml');
if (not FileExists(ConfigYaml)) and FileExists(ExampleYaml) then
begin
FileCopy(ExampleYaml, ConfigYaml, False);
end;
end;
end;
+83
View File
@@ -0,0 +1,83 @@
package agentdebug
import (
"encoding/json"
"os"
"runtime"
"sync/atomic"
"time"
)
const defaultWindowsLogPath = `d:\code\ProxyPilot\.cursor\debug.log`
var seq uint64
type entry struct {
ID string `json:"id,omitempty"`
Timestamp int64 `json:"timestamp"`
Location string `json:"location"`
Message string `json:"message"`
Data map[string]any `json:"data,omitempty"`
SessionID string `json:"sessionId"`
RunID string `json:"runId"`
HypothesisID string `json:"hypothesisId"`
}
func Log(hypothesisID, location, message string, data map[string]any) {
logPath := os.Getenv("PROXYPILOT_AGENT_DEBUG_LOG_PATH")
if logPath == "" {
if runtime.GOOS != "windows" {
// Debug session is Windows-scoped; avoid hard-failing on other OS.
return
}
logPath = defaultWindowsLogPath
}
runID := os.Getenv("PROXYPILOT_AGENT_DEBUG_RUN_ID")
if runID == "" {
runID = "pre-fix"
}
now := time.Now()
id := atomic.AddUint64(&seq, 1)
b, err := json.Marshal(entry{
ID: "log_" + now.Format("20060102T150405.000") + "_" + fmtUint(id),
Timestamp: now.UnixMilli(),
Location: location,
Message: message,
Data: data,
SessionID: "debug-session",
RunID: runID,
HypothesisID: hypothesisID,
})
if err != nil {
return
}
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
return
}
_, _ = f.Write(append(b, '\n'))
_ = f.Close()
}
func fmtUint(v uint64) string {
// tiny, allocation-light formatting; no need for strconv import in hot paths.
const digits = "0123456789"
if v == 0 {
return "0"
}
var buf [20]byte
i := len(buf)
for v > 0 {
i--
buf[i] = digits[v%10]
v /= 10
}
return string(buf[i:])
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,93 @@
package management
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/registry"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
type authResetCooldownRequest struct {
AuthID string `json:"auth_id"`
Provider string `json:"provider"`
Model string `json:"model"`
}
// ResetAuthCooldown clears quota/cooldown flags so the next request can probe availability again.
// This is useful when an upstream 429 is suspected to be transient or misattributed.
func (h *Handler) ResetAuthCooldown(c *gin.Context) {
var req authResetCooldownRequest
_ = c.ShouldBindJSON(&req)
req.AuthID = strings.TrimSpace(req.AuthID)
req.Provider = strings.ToLower(strings.TrimSpace(req.Provider))
req.Model = strings.TrimSpace(req.Model)
if h.authManager == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth manager unavailable"})
return
}
updated := 0
now := time.Now()
resetAuth := func(a *coreauth.Auth) {
if a == nil {
return
}
a.Unavailable = false
a.NextRetryAfter = time.Time{}
a.Quota = coreauth.QuotaState{}
a.LastError = nil
a.StatusMessage = ""
a.UpdatedAt = now
if len(a.ModelStates) == 0 {
return
}
for modelID, st := range a.ModelStates {
if req.Model != "" && modelID != req.Model {
continue
}
if st == nil {
continue
}
st.Unavailable = false
st.NextRetryAfter = time.Time{}
st.Quota = coreauth.QuotaState{}
st.LastError = nil
st.StatusMessage = ""
st.Status = coreauth.StatusActive
st.UpdatedAt = now
registry.GetGlobalRegistry().ClearModelQuotaExceeded(a.ID, modelID)
registry.GetGlobalRegistry().ResumeClientModel(a.ID, modelID)
}
}
if req.AuthID != "" {
if a, ok := h.authManager.GetByID(req.AuthID); ok && a != nil {
resetAuth(a)
_, _ = h.authManager.Update(c.Request.Context(), a)
updated = 1
}
c.JSON(http.StatusOK, gin.H{"updated": updated})
return
}
for _, a := range h.authManager.List() {
if a == nil {
continue
}
if req.Provider != "" && strings.ToLower(strings.TrimSpace(a.Provider)) != req.Provider {
continue
}
resetAuth(a)
_, _ = h.authManager.Update(c.Request.Context(), a)
updated++
}
c.JSON(http.StatusOK, gin.H{"updated": updated})
}
+210 -32
View File
@@ -1,51 +1,194 @@
package management
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/routingdebug"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
"gopkg.in/yaml.v3"
)
const (
latestReleaseURL = "https://api.github.com/repos/router-for-me/CLIProxyAPIPlus/releases/latest"
latestReleaseUserAgent = "CLIProxyAPIPlus"
)
func (h *Handler) GetConfig(c *gin.Context) {
c.JSON(200, h.cfg)
if h == nil || h.cfg == nil {
c.JSON(200, gin.H{})
return
}
cfgCopy := *h.cfg
c.JSON(200, &cfgCopy)
}
func (h *Handler) GetConfigYAML(c *gin.Context) {
data, err := os.ReadFile(h.configFilePath)
// GetRoutingPreview returns a JSON description of how a given model would be normalised and routed.
//
// Query parameters:
// - model: required model identifier (may be alias, auto, or provider://model)
func (h *Handler) GetRoutingPreview(c *gin.Context) {
if h == nil || h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "unavailable", "message": "configuration not loaded"})
return
}
model := strings.TrimSpace(c.Query("model"))
if model == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing_model", "message": "provide model via ?model="})
return
}
preview, err := h.computeRoutingPreview(model)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "read_failed", "message": err.Error()})
c.JSON(http.StatusBadRequest, gin.H{"error": "routing_error", "message": err.Error()})
return
}
var node yaml.Node
if err := yaml.Unmarshal(data, &node); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "parse_failed", "message": err.Error()})
c.JSON(http.StatusOK, preview)
}
// GetRoutingRecent returns a small ring buffer of recently routed requests using the runtime selection trace.
func (h *Handler) GetRoutingRecent(c *gin.Context) {
// Even if h or cfg are nil, routingdebug.Snapshot() is safe; this endpoint is purely diagnostic.
entries := routingdebug.Snapshot()
if len(entries) == 0 {
c.JSON(http.StatusOK, gin.H{"entries": []routingdebug.Entry{}})
return
}
c.Header("Content-Type", "application/yaml; charset=utf-8")
c.Header("Vary", "format, Accept")
enc := yaml.NewEncoder(c.Writer)
enc.SetIndent(2)
_ = enc.Encode(&node)
_ = enc.Close()
c.JSON(http.StatusOK, gin.H{"entries": entries})
}
// PostRoutingPreview accepts a full request JSON (OpenAI/OpenAIResponses-compatible) and
// extracts the model name for routing preview.
func (h *Handler) PostRoutingPreview(c *gin.Context) {
if h == nil || h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "unavailable", "message": "configuration not loaded"})
return
}
body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20)) // 1 MiB safety cap
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_body", "message": "cannot read request body"})
return
}
if !gjson.ValidBytes(body) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_json", "message": "body is not valid JSON"})
return
}
// Try a few common shapes to extract the model name.
paths := []string{
"model", // standard OpenAI
"request.model", // some wrapper shapes
"response.model", // responses-style wrappers
}
var model string
for _, path := range paths {
v := gjson.GetBytes(body, path)
if v.Exists() && strings.TrimSpace(v.String()) != "" {
model = strings.TrimSpace(v.String())
break
}
}
if model == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing_model", "message": "could not find model field in JSON body"})
return
}
preview, err := h.computeRoutingPreview(model)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "routing_error", "message": err.Error(), "model": model})
return
}
c.JSON(http.StatusOK, gin.H{
"model": model,
"preview": preview,
})
}
type releaseInfo struct {
TagName string `json:"tag_name"`
Name string `json:"name"`
}
// GetLatestVersion returns the latest release version from GitHub without downloading assets.
func (h *Handler) GetLatestVersion(c *gin.Context) {
client := &http.Client{Timeout: 10 * time.Second}
proxyURL := ""
if h != nil && h.cfg != nil {
proxyURL = strings.TrimSpace(h.cfg.ProxyURL)
}
if proxyURL != "" {
sdkCfg := &sdkconfig.SDKConfig{ProxyURL: proxyURL}
util.SetProxy(sdkCfg, client)
}
req, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, latestReleaseURL, nil)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "request_create_failed", "message": err.Error()})
return
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("User-Agent", latestReleaseUserAgent)
resp, err := client.Do(req)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": "request_failed", "message": err.Error()})
return
}
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
log.WithError(errClose).Debug("failed to close latest version response body")
}
}()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
c.JSON(http.StatusBadGateway, gin.H{"error": "unexpected_status", "message": fmt.Sprintf("status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))})
return
}
var info releaseInfo
if errDecode := json.NewDecoder(resp.Body).Decode(&info); errDecode != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": "decode_failed", "message": errDecode.Error()})
return
}
version := strings.TrimSpace(info.TagName)
if version == "" {
version = strings.TrimSpace(info.Name)
}
if version == "" {
c.JSON(http.StatusBadGateway, gin.H{"error": "invalid_response", "message": "missing release version"})
return
}
c.JSON(http.StatusOK, gin.H{"latest-version": version})
}
func WriteConfig(path string, data []byte) error {
data = config.NormalizeCommentIndentation(data)
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
f.Close()
return err
if _, errWrite := f.Write(data); errWrite != nil {
_ = f.Close()
return errWrite
}
if err := f.Sync(); err != nil {
f.Close()
return err
if errSync := f.Sync(); errSync != nil {
_ = f.Close()
return errSync
}
return f.Close()
}
@@ -57,7 +200,7 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
return
}
var cfg config.Config
if err := yaml.Unmarshal(body, &cfg); err != nil {
if err = yaml.Unmarshal(body, &cfg); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_yaml", "message": err.Error()})
return
}
@@ -69,23 +212,38 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
return
}
tempFile := tmpFile.Name()
if _, err := tmpFile.Write(body); err != nil {
tmpFile.Close()
os.Remove(tempFile)
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": err.Error()})
if _, errWrite := tmpFile.Write(body); errWrite != nil {
_ = tmpFile.Close()
_ = os.Remove(tempFile)
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errWrite.Error()})
return
}
if err := tmpFile.Close(); err != nil {
os.Remove(tempFile)
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": err.Error()})
if errClose := tmpFile.Close(); errClose != nil {
_ = os.Remove(tempFile)
c.JSON(http.StatusInternalServerError, gin.H{"error": "write_failed", "message": errClose.Error()})
return
}
defer os.Remove(tempFile)
_, err = config.LoadConfigOptional(tempFile, false)
defer func() {
_ = os.Remove(tempFile)
}()
validatedCfg, err := config.LoadConfigOptional(tempFile, false)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": err.Error()})
return
}
if validatedCfg == nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": "configuration is empty"})
return
}
if warnings, errValidate := config.ValidateConfig(validatedCfg); errValidate != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "invalid_config", "message": errValidate.Error()})
return
} else if len(warnings) > 0 {
// Surface warnings in logs; the response body will include them after successful persist.
for _, w := range warnings {
log.Warnf("config warning (management update): %s", w)
}
}
h.mu.Lock()
defer h.mu.Unlock()
if WriteConfig(h.configFilePath, body) != nil {
@@ -99,12 +257,16 @@ func (h *Handler) PutConfigYAML(c *gin.Context) {
return
}
h.cfg = newCfg
c.JSON(http.StatusOK, gin.H{"ok": true, "changed": []string{"config"}})
resp := gin.H{"ok": true, "changed": []string{"config"}}
if warnings, errValidate := config.ValidateConfig(newCfg); errValidate == nil && len(warnings) > 0 {
resp["warnings"] = warnings
}
c.JSON(http.StatusOK, resp)
}
// GetConfigFile returns the raw config.yaml file bytes without re-encoding.
// GetConfigYAML returns the raw config.yaml file bytes without re-encoding.
// It preserves comments and original formatting/styles.
func (h *Handler) GetConfigFile(c *gin.Context) {
func (h *Handler) GetConfigYAML(c *gin.Context) {
data, err := os.ReadFile(h.configFilePath)
if err != nil {
if os.IsNotExist(err) {
@@ -147,6 +309,14 @@ func (h *Handler) PutRequestLog(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.RequestLog = v })
}
// Websocket auth
func (h *Handler) GetWebsocketAuth(c *gin.Context) {
c.JSON(200, gin.H{"ws-auth": h.cfg.WebsocketAuth})
}
func (h *Handler) PutWebsocketAuth(c *gin.Context) {
h.updateBoolField(c, func(v bool) { h.cfg.WebsocketAuth = v })
}
// Request retry
func (h *Handler) GetRequestRetry(c *gin.Context) {
c.JSON(200, gin.H{"request-retry": h.cfg.RequestRetry})
@@ -155,6 +325,14 @@ func (h *Handler) PutRequestRetry(c *gin.Context) {
h.updateIntField(c, func(v int) { h.cfg.RequestRetry = v })
}
// Max retry interval
func (h *Handler) GetMaxRetryInterval(c *gin.Context) {
c.JSON(200, gin.H{"max-retry-interval": h.cfg.MaxRetryInterval})
}
func (h *Handler) PutMaxRetryInterval(c *gin.Context) {
h.updateIntField(c, func(v int) { h.cfg.MaxRetryInterval = v })
}
// Proxy URL
func (h *Handler) GetProxyURL(c *gin.Context) { c.JSON(200, gin.H{"proxy-url": h.cfg.ProxyURL}) }
func (h *Handler) PutProxyURL(c *gin.Context) {
+383 -121
View File
@@ -87,10 +87,10 @@ func (h *Handler) deleteFromStringList(c *gin.Context, target *[]string, after f
return
}
}
if val := c.Query("value"); val != "" {
if val := strings.TrimSpace(c.Query("value")); val != "" {
out := make([]string, 0, len(*target))
for _, v := range *target {
if v != val {
if strings.TrimSpace(v) != val {
out = append(out, v)
}
}
@@ -119,15 +119,128 @@ func (h *Handler) DeleteAPIKeys(c *gin.Context) {
h.deleteFromStringList(c, &h.cfg.APIKeys, func() { h.cfg.Access.Providers = nil })
}
// generative-language-api-key
func (h *Handler) GetGlKeys(c *gin.Context) {
c.JSON(200, gin.H{"generative-language-api-key": h.cfg.GlAPIKey})
// gemini-api-key: []GeminiKey
func (h *Handler) GetGeminiKeys(c *gin.Context) {
c.JSON(200, gin.H{"gemini-api-key": h.cfg.GeminiKey})
}
func (h *Handler) PutGlKeys(c *gin.Context) {
h.putStringList(c, func(v []string) { h.cfg.GlAPIKey = v }, nil)
func (h *Handler) PutGeminiKeys(c *gin.Context) {
data, err := c.GetRawData()
if err != nil {
c.JSON(400, gin.H{"error": "failed to read body"})
return
}
var arr []config.GeminiKey
if err = json.Unmarshal(data, &arr); err != nil {
var obj struct {
Items []config.GeminiKey `json:"items"`
}
if err2 := json.Unmarshal(data, &obj); err2 != nil || len(obj.Items) == 0 {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
arr = obj.Items
}
h.cfg.GeminiKey = append([]config.GeminiKey(nil), arr...)
h.cfg.SanitizeGeminiKeys()
h.persist(c)
}
func (h *Handler) PatchGeminiKey(c *gin.Context) {
type geminiKeyPatch struct {
APIKey *string `json:"api-key"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
ProxyURL *string `json:"proxy-url"`
Headers *map[string]string `json:"headers"`
ExcludedModels *[]string `json:"excluded-models"`
}
var body struct {
Index *int `json:"index"`
Match *string `json:"match"`
Value *geminiKeyPatch `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
targetIndex := -1
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.GeminiKey) {
targetIndex = *body.Index
}
if targetIndex == -1 && body.Match != nil {
match := strings.TrimSpace(*body.Match)
if match != "" {
for i := range h.cfg.GeminiKey {
if h.cfg.GeminiKey[i].APIKey == match {
targetIndex = i
break
}
}
}
}
if targetIndex == -1 {
c.JSON(404, gin.H{"error": "item not found"})
return
}
entry := h.cfg.GeminiKey[targetIndex]
if body.Value.APIKey != nil {
trimmed := strings.TrimSpace(*body.Value.APIKey)
if trimmed == "" {
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:targetIndex], h.cfg.GeminiKey[targetIndex+1:]...)
h.cfg.SanitizeGeminiKeys()
h.persist(c)
return
}
entry.APIKey = trimmed
}
if body.Value.Prefix != nil {
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
}
if body.Value.BaseURL != nil {
entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL)
}
if body.Value.ProxyURL != nil {
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
}
if body.Value.Headers != nil {
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
}
if body.Value.ExcludedModels != nil {
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
}
h.cfg.GeminiKey[targetIndex] = entry
h.cfg.SanitizeGeminiKeys()
h.persist(c)
}
func (h *Handler) DeleteGeminiKey(c *gin.Context) {
if val := strings.TrimSpace(c.Query("api-key")); val != "" {
out := make([]config.GeminiKey, 0, len(h.cfg.GeminiKey))
for _, v := range h.cfg.GeminiKey {
if v.APIKey != val {
out = append(out, v)
}
}
if len(out) != len(h.cfg.GeminiKey) {
h.cfg.GeminiKey = out
h.cfg.SanitizeGeminiKeys()
h.persist(c)
} else {
c.JSON(404, gin.H{"error": "item not found"})
}
return
}
if idxStr := c.Query("index"); idxStr != "" {
var idx int
if _, err := fmt.Sscanf(idxStr, "%d", &idx); err == nil && idx >= 0 && idx < len(h.cfg.GeminiKey) {
h.cfg.GeminiKey = append(h.cfg.GeminiKey[:idx], h.cfg.GeminiKey[idx+1:]...)
h.cfg.SanitizeGeminiKeys()
h.persist(c)
return
}
}
c.JSON(400, gin.H{"error": "missing api-key or index"})
}
func (h *Handler) PatchGlKeys(c *gin.Context) { h.patchStringList(c, &h.cfg.GlAPIKey, nil) }
func (h *Handler) DeleteGlKeys(c *gin.Context) { h.deleteFromStringList(c, &h.cfg.GlAPIKey, nil) }
// claude-api-key: []ClaudeKey
func (h *Handler) GetClaudeKeys(c *gin.Context) {
@@ -154,35 +267,74 @@ func (h *Handler) PutClaudeKeys(c *gin.Context) {
normalizeClaudeKey(&arr[i])
}
h.cfg.ClaudeKey = arr
h.cfg.SanitizeClaudeKeys()
h.persist(c)
}
func (h *Handler) PatchClaudeKey(c *gin.Context) {
type claudeKeyPatch struct {
APIKey *string `json:"api-key"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
ProxyURL *string `json:"proxy-url"`
Models *[]config.ClaudeModel `json:"models"`
Headers *map[string]string `json:"headers"`
ExcludedModels *[]string `json:"excluded-models"`
}
var body struct {
Index *int `json:"index"`
Match *string `json:"match"`
Value *config.ClaudeKey `json:"value"`
Index *int `json:"index"`
Match *string `json:"match"`
Value *claudeKeyPatch `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
normalizeClaudeKey(body.Value)
targetIndex := -1
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.ClaudeKey) {
h.cfg.ClaudeKey[*body.Index] = *body.Value
h.persist(c)
return
targetIndex = *body.Index
}
if body.Match != nil {
if targetIndex == -1 && body.Match != nil {
match := strings.TrimSpace(*body.Match)
for i := range h.cfg.ClaudeKey {
if h.cfg.ClaudeKey[i].APIKey == *body.Match {
h.cfg.ClaudeKey[i] = *body.Value
h.persist(c)
return
if h.cfg.ClaudeKey[i].APIKey == match {
targetIndex = i
break
}
}
}
c.JSON(404, gin.H{"error": "item not found"})
if targetIndex == -1 {
c.JSON(404, gin.H{"error": "item not found"})
return
}
entry := h.cfg.ClaudeKey[targetIndex]
if body.Value.APIKey != nil {
entry.APIKey = strings.TrimSpace(*body.Value.APIKey)
}
if body.Value.Prefix != nil {
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
}
if body.Value.BaseURL != nil {
entry.BaseURL = strings.TrimSpace(*body.Value.BaseURL)
}
if body.Value.ProxyURL != nil {
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
}
if body.Value.Models != nil {
entry.Models = append([]config.ClaudeModel(nil), (*body.Value.Models)...)
}
if body.Value.Headers != nil {
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
}
if body.Value.ExcludedModels != nil {
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
}
normalizeClaudeKey(&entry)
h.cfg.ClaudeKey[targetIndex] = entry
h.cfg.SanitizeClaudeKeys()
h.persist(c)
}
func (h *Handler) DeleteClaudeKey(c *gin.Context) {
if val := c.Query("api-key"); val != "" {
out := make([]config.ClaudeKey, 0, len(h.cfg.ClaudeKey))
@@ -192,6 +344,7 @@ func (h *Handler) DeleteClaudeKey(c *gin.Context) {
}
}
h.cfg.ClaudeKey = out
h.cfg.SanitizeClaudeKeys()
h.persist(c)
return
}
@@ -200,6 +353,7 @@ func (h *Handler) DeleteClaudeKey(c *gin.Context) {
_, err := fmt.Sscanf(idxStr, "%d", &idx)
if err == nil && idx >= 0 && idx < len(h.cfg.ClaudeKey) {
h.cfg.ClaudeKey = append(h.cfg.ClaudeKey[:idx], h.cfg.ClaudeKey[idx+1:]...)
h.cfg.SanitizeClaudeKeys()
h.persist(c)
return
}
@@ -228,72 +382,85 @@ func (h *Handler) PutOpenAICompat(c *gin.Context) {
}
arr = obj.Items
}
for i := range arr {
normalizeOpenAICompatibilityEntry(&arr[i])
}
// Filter out providers with empty base-url -> remove provider entirely
filtered := make([]config.OpenAICompatibility, 0, len(arr))
for i := range arr {
normalizeOpenAICompatibilityEntry(&arr[i])
if strings.TrimSpace(arr[i].BaseURL) != "" {
filtered = append(filtered, arr[i])
}
}
h.cfg.OpenAICompatibility = filtered
h.cfg.SanitizeOpenAICompatibility()
h.persist(c)
}
func (h *Handler) PatchOpenAICompat(c *gin.Context) {
type openAICompatPatch struct {
Name *string `json:"name"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
APIKeyEntries *[]config.OpenAICompatibilityAPIKey `json:"api-key-entries"`
Models *[]config.OpenAICompatibilityModel `json:"models"`
Headers *map[string]string `json:"headers"`
}
var body struct {
Name *string `json:"name"`
Index *int `json:"index"`
Value *config.OpenAICompatibility `json:"value"`
Name *string `json:"name"`
Index *int `json:"index"`
Value *openAICompatPatch `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
normalizeOpenAICompatibilityEntry(body.Value)
// If base-url becomes empty, delete the provider instead of updating
if strings.TrimSpace(body.Value.BaseURL) == "" {
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) {
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:*body.Index], h.cfg.OpenAICompatibility[*body.Index+1:]...)
h.persist(c)
return
}
if body.Name != nil {
out := make([]config.OpenAICompatibility, 0, len(h.cfg.OpenAICompatibility))
removed := false
for i := range h.cfg.OpenAICompatibility {
if !removed && h.cfg.OpenAICompatibility[i].Name == *body.Name {
removed = true
continue
}
out = append(out, h.cfg.OpenAICompatibility[i])
}
if removed {
h.cfg.OpenAICompatibility = out
h.persist(c)
return
targetIndex := -1
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) {
targetIndex = *body.Index
}
if targetIndex == -1 && body.Name != nil {
match := strings.TrimSpace(*body.Name)
for i := range h.cfg.OpenAICompatibility {
if h.cfg.OpenAICompatibility[i].Name == match {
targetIndex = i
break
}
}
}
if targetIndex == -1 {
c.JSON(404, gin.H{"error": "item not found"})
return
}
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.OpenAICompatibility) {
h.cfg.OpenAICompatibility[*body.Index] = *body.Value
h.persist(c)
return
entry := h.cfg.OpenAICompatibility[targetIndex]
if body.Value.Name != nil {
entry.Name = strings.TrimSpace(*body.Value.Name)
}
if body.Name != nil {
for i := range h.cfg.OpenAICompatibility {
if h.cfg.OpenAICompatibility[i].Name == *body.Name {
h.cfg.OpenAICompatibility[i] = *body.Value
h.persist(c)
return
}
if body.Value.Prefix != nil {
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
}
if body.Value.BaseURL != nil {
trimmed := strings.TrimSpace(*body.Value.BaseURL)
if trimmed == "" {
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:targetIndex], h.cfg.OpenAICompatibility[targetIndex+1:]...)
h.cfg.SanitizeOpenAICompatibility()
h.persist(c)
return
}
entry.BaseURL = trimmed
}
c.JSON(404, gin.H{"error": "item not found"})
if body.Value.APIKeyEntries != nil {
entry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), (*body.Value.APIKeyEntries)...)
}
if body.Value.Models != nil {
entry.Models = append([]config.OpenAICompatibilityModel(nil), (*body.Value.Models)...)
}
if body.Value.Headers != nil {
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
}
normalizeOpenAICompatibilityEntry(&entry)
h.cfg.OpenAICompatibility[targetIndex] = entry
h.cfg.SanitizeOpenAICompatibility()
h.persist(c)
}
func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
if name := c.Query("name"); name != "" {
out := make([]config.OpenAICompatibility, 0, len(h.cfg.OpenAICompatibility))
@@ -303,6 +470,7 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
}
}
h.cfg.OpenAICompatibility = out
h.cfg.SanitizeOpenAICompatibility()
h.persist(c)
return
}
@@ -311,6 +479,7 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
_, err := fmt.Sscanf(idxStr, "%d", &idx)
if err == nil && idx >= 0 && idx < len(h.cfg.OpenAICompatibility) {
h.cfg.OpenAICompatibility = append(h.cfg.OpenAICompatibility[:idx], h.cfg.OpenAICompatibility[idx+1:]...)
h.cfg.SanitizeOpenAICompatibility()
h.persist(c)
return
}
@@ -318,6 +487,91 @@ func (h *Handler) DeleteOpenAICompat(c *gin.Context) {
c.JSON(400, gin.H{"error": "missing name or index"})
}
// oauth-excluded-models: map[string][]string
func (h *Handler) GetOAuthExcludedModels(c *gin.Context) {
c.JSON(200, gin.H{"oauth-excluded-models": config.NormalizeOAuthExcludedModels(h.cfg.OAuthExcludedModels)})
}
func (h *Handler) PutOAuthExcludedModels(c *gin.Context) {
data, err := c.GetRawData()
if err != nil {
c.JSON(400, gin.H{"error": "failed to read body"})
return
}
var entries map[string][]string
if err = json.Unmarshal(data, &entries); err != nil {
var wrapper struct {
Items map[string][]string `json:"items"`
}
if err2 := json.Unmarshal(data, &wrapper); err2 != nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
entries = wrapper.Items
}
h.cfg.OAuthExcludedModels = config.NormalizeOAuthExcludedModels(entries)
h.persist(c)
}
func (h *Handler) PatchOAuthExcludedModels(c *gin.Context) {
var body struct {
Provider *string `json:"provider"`
Models []string `json:"models"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Provider == nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
provider := strings.ToLower(strings.TrimSpace(*body.Provider))
if provider == "" {
c.JSON(400, gin.H{"error": "invalid provider"})
return
}
normalized := config.NormalizeExcludedModels(body.Models)
if len(normalized) == 0 {
if h.cfg.OAuthExcludedModels == nil {
c.JSON(404, gin.H{"error": "provider not found"})
return
}
if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok {
c.JSON(404, gin.H{"error": "provider not found"})
return
}
delete(h.cfg.OAuthExcludedModels, provider)
if len(h.cfg.OAuthExcludedModels) == 0 {
h.cfg.OAuthExcludedModels = nil
}
h.persist(c)
return
}
if h.cfg.OAuthExcludedModels == nil {
h.cfg.OAuthExcludedModels = make(map[string][]string)
}
h.cfg.OAuthExcludedModels[provider] = normalized
h.persist(c)
}
func (h *Handler) DeleteOAuthExcludedModels(c *gin.Context) {
provider := strings.ToLower(strings.TrimSpace(c.Query("provider")))
if provider == "" {
c.JSON(400, gin.H{"error": "missing provider"})
return
}
if h.cfg.OAuthExcludedModels == nil {
c.JSON(404, gin.H{"error": "provider not found"})
return
}
if _, ok := h.cfg.OAuthExcludedModels[provider]; !ok {
c.JSON(404, gin.H{"error": "provider not found"})
return
}
delete(h.cfg.OAuthExcludedModels, provider)
if len(h.cfg.OAuthExcludedModels) == 0 {
h.cfg.OAuthExcludedModels = nil
}
h.persist(c)
}
// codex-api-key: []CodexKey
func (h *Handler) GetCodexKeys(c *gin.Context) {
c.JSON(200, gin.H{"codex-api-key": h.cfg.CodexKey})
@@ -343,66 +597,87 @@ func (h *Handler) PutCodexKeys(c *gin.Context) {
filtered := make([]config.CodexKey, 0, len(arr))
for i := range arr {
entry := arr[i]
entry.APIKey = strings.TrimSpace(entry.APIKey)
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
entry.Headers = config.NormalizeHeaders(entry.Headers)
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
if entry.BaseURL == "" {
continue
}
filtered = append(filtered, entry)
}
h.cfg.CodexKey = filtered
h.cfg.SanitizeCodexKeys()
h.persist(c)
}
func (h *Handler) PatchCodexKey(c *gin.Context) {
type codexKeyPatch struct {
APIKey *string `json:"api-key"`
Prefix *string `json:"prefix"`
BaseURL *string `json:"base-url"`
ProxyURL *string `json:"proxy-url"`
Headers *map[string]string `json:"headers"`
ExcludedModels *[]string `json:"excluded-models"`
}
var body struct {
Index *int `json:"index"`
Match *string `json:"match"`
Value *config.CodexKey `json:"value"`
Index *int `json:"index"`
Match *string `json:"match"`
Value *codexKeyPatch `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
c.JSON(400, gin.H{"error": "invalid body"})
return
}
// If base-url becomes empty, delete instead of update
if strings.TrimSpace(body.Value.BaseURL) == "" {
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) {
h.cfg.CodexKey = append(h.cfg.CodexKey[:*body.Index], h.cfg.CodexKey[*body.Index+1:]...)
h.persist(c)
return
}
if body.Match != nil {
out := make([]config.CodexKey, 0, len(h.cfg.CodexKey))
removed := false
for i := range h.cfg.CodexKey {
if !removed && h.cfg.CodexKey[i].APIKey == *body.Match {
removed = true
continue
}
out = append(out, h.cfg.CodexKey[i])
}
if removed {
h.cfg.CodexKey = out
h.persist(c)
return
}
}
} else {
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) {
h.cfg.CodexKey[*body.Index] = *body.Value
h.persist(c)
return
}
if body.Match != nil {
for i := range h.cfg.CodexKey {
if h.cfg.CodexKey[i].APIKey == *body.Match {
h.cfg.CodexKey[i] = *body.Value
h.persist(c)
return
}
targetIndex := -1
if body.Index != nil && *body.Index >= 0 && *body.Index < len(h.cfg.CodexKey) {
targetIndex = *body.Index
}
if targetIndex == -1 && body.Match != nil {
match := strings.TrimSpace(*body.Match)
for i := range h.cfg.CodexKey {
if h.cfg.CodexKey[i].APIKey == match {
targetIndex = i
break
}
}
}
c.JSON(404, gin.H{"error": "item not found"})
if targetIndex == -1 {
c.JSON(404, gin.H{"error": "item not found"})
return
}
entry := h.cfg.CodexKey[targetIndex]
if body.Value.APIKey != nil {
entry.APIKey = strings.TrimSpace(*body.Value.APIKey)
}
if body.Value.Prefix != nil {
entry.Prefix = strings.TrimSpace(*body.Value.Prefix)
}
if body.Value.BaseURL != nil {
trimmed := strings.TrimSpace(*body.Value.BaseURL)
if trimmed == "" {
h.cfg.CodexKey = append(h.cfg.CodexKey[:targetIndex], h.cfg.CodexKey[targetIndex+1:]...)
h.cfg.SanitizeCodexKeys()
h.persist(c)
return
}
entry.BaseURL = trimmed
}
if body.Value.ProxyURL != nil {
entry.ProxyURL = strings.TrimSpace(*body.Value.ProxyURL)
}
if body.Value.Headers != nil {
entry.Headers = config.NormalizeHeaders(*body.Value.Headers)
}
if body.Value.ExcludedModels != nil {
entry.ExcludedModels = config.NormalizeExcludedModels(*body.Value.ExcludedModels)
}
h.cfg.CodexKey[targetIndex] = entry
h.cfg.SanitizeCodexKeys()
h.persist(c)
}
func (h *Handler) DeleteCodexKey(c *gin.Context) {
if val := c.Query("api-key"); val != "" {
out := make([]config.CodexKey, 0, len(h.cfg.CodexKey))
@@ -412,6 +687,7 @@ func (h *Handler) DeleteCodexKey(c *gin.Context) {
}
}
h.cfg.CodexKey = out
h.cfg.SanitizeCodexKeys()
h.persist(c)
return
}
@@ -420,6 +696,7 @@ func (h *Handler) DeleteCodexKey(c *gin.Context) {
_, err := fmt.Sscanf(idxStr, "%d", &idx)
if err == nil && idx >= 0 && idx < len(h.cfg.CodexKey) {
h.cfg.CodexKey = append(h.cfg.CodexKey[:idx], h.cfg.CodexKey[idx+1:]...)
h.cfg.SanitizeCodexKeys()
h.persist(c)
return
}
@@ -433,6 +710,7 @@ func normalizeOpenAICompatibilityEntry(entry *config.OpenAICompatibility) {
}
// Trim base-url; empty base-url indicates provider should be removed by sanitization
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
entry.Headers = config.NormalizeHeaders(entry.Headers)
existing := make(map[string]struct{}, len(entry.APIKeyEntries))
for i := range entry.APIKeyEntries {
trimmed := strings.TrimSpace(entry.APIKeyEntries[i].APIKey)
@@ -441,21 +719,6 @@ func normalizeOpenAICompatibilityEntry(entry *config.OpenAICompatibility) {
existing[trimmed] = struct{}{}
}
}
if len(entry.APIKeys) == 0 {
return
}
for _, legacyKey := range entry.APIKeys {
trimmed := strings.TrimSpace(legacyKey)
if trimmed == "" {
continue
}
if _, ok := existing[trimmed]; ok {
continue
}
entry.APIKeyEntries = append(entry.APIKeyEntries, config.OpenAICompatibilityAPIKey{APIKey: trimmed})
existing[trimmed] = struct{}{}
}
entry.APIKeys = nil
}
func normalizedOpenAICompatibilityEntries(entries []config.OpenAICompatibility) []config.OpenAICompatibility {
@@ -468,9 +731,6 @@ func normalizedOpenAICompatibilityEntries(entries []config.OpenAICompatibility)
if len(copyEntry.APIKeyEntries) > 0 {
copyEntry.APIKeyEntries = append([]config.OpenAICompatibilityAPIKey(nil), copyEntry.APIKeyEntries...)
}
if len(copyEntry.APIKeys) > 0 {
copyEntry.APIKeys = append([]string(nil), copyEntry.APIKeys...)
}
normalizeOpenAICompatibilityEntry(&copyEntry)
out[i] = copyEntry
}
@@ -484,6 +744,8 @@ func normalizeClaudeKey(entry *config.ClaudeKey) {
entry.APIKey = strings.TrimSpace(entry.APIKey)
entry.BaseURL = strings.TrimSpace(entry.BaseURL)
entry.ProxyURL = strings.TrimSpace(entry.ProxyURL)
entry.Headers = config.NormalizeHeaders(entry.Headers)
entry.ExcludedModels = config.NormalizeExcludedModels(entry.ExcludedModels)
if len(entry.Models) == 0 {
return
}
@@ -0,0 +1,170 @@
package management
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
// ImportCredential handles uploading a text file with credentials for a specific provider.
// Each credential is processed and saved as a separate auth record.
func (h *Handler) ImportCredential(c *gin.Context) {
provider := c.Param("provider")
if provider == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "provider required"})
return
}
if h == nil || h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "config unavailable"})
return
}
if h.cfg.AuthDir == "" {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth directory not configured"})
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
defer file.Close()
ctx := c.Request.Context()
if ctx == nil {
ctx = context.Background()
}
lines, err := parseLines(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to parse file", "details": err.Error()})
return
}
if len(lines) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "no valid credentials found in file"})
return
}
var results []importResult
successCount := 0
for i, raw := range lines {
lineNum := i + 1
var result importResult
switch provider {
case "iflow":
authSvc := iflowauth.NewIFlowAuth(h.cfg)
result = h.processIFlowCookie(ctx, authSvc, raw, lineNum)
case "openai", "claude", "gemini":
// Generic API Key import
result = h.processAPIKey(ctx, provider, raw, lineNum)
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported provider for bulk import"})
return
}
if result.Success {
successCount++
}
results = append(results, result)
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"provider": provider,
"total": len(lines),
"success_count": successCount,
"failed_count": len(lines) - successCount,
"results": results,
})
}
// Re-using importResult from iflow_import.go if it's exported, otherwise redefined here for clarity in new file.
// Ideally, we'd refactor iflow_import.go to share types, but for now assuming it stays as is or we modify it.
// Since we are creating a new file, let's assume we might replace iflow_import with this generic one eventually.
// For this step, I will assume we are ADDING this handler alongside existing ones.
// GenericTokenStorage is a simple map wrapper to satisfy TokenStorage interface
type GenericTokenStorage map[string]string
func (s GenericTokenStorage) SaveTokenToFile(path string) error {
return nil
}
// processAPIKey handles generic API key import
func (h *Handler) processAPIKey(ctx context.Context, provider, key string, lineNum int) importResult {
key = strings.TrimSpace(key)
if key == "" {
return importResult{Line: lineNum, Success: false, Error: "empty key"}
}
// Basic duplicate check could be added here if needed
timestamp := time.Now().Unix()
// Use a shortened key hash or prefix for filename to avoid leaking credentials in filenames
safeName := fmt.Sprintf("%s-%s", provider, key[:min(8, len(key))])
fileName := fmt.Sprintf("%s-%d.json", safeName, timestamp)
record := &coreauth.Auth{
ID: fileName,
Provider: provider,
FileName: fileName,
Storage: GenericTokenStorage{
"api_key": key,
},
Metadata: map[string]any{
"imported_at": timestamp,
"source": "bulk_import",
},
Attributes: map[string]string{
"api_key": key,
},
}
savedPath, err := h.saveTokenRecord(ctx, record)
if err != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to save credential"}
}
return importResult{Line: lineNum, Success: true, SavedPath: savedPath}
}
func parseLines(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return lines, nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+154 -11
View File
@@ -13,8 +13,11 @@ import (
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/integrations"
"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"
"golang.org/x/crypto/bcrypt"
@@ -39,6 +42,23 @@ type Handler struct {
allowRemoteOverride bool
envSecret string
logDir string
integrationManager *integrations.Manager
}
// openAICompatProviderNames returns the configured OpenAI-compat provider names from the current config.
func (h *Handler) openAICompatProviderNames() []string {
cfg := h.cfg
if cfg == nil {
return nil
}
out := make([]string, 0, len(cfg.OpenAICompatibility))
for _, c := range cfg.OpenAICompatibility {
name := strings.TrimSpace(c.Name)
if name != "" {
out = append(out, name)
}
}
return out
}
// NewHandler creates a new management handler instance.
@@ -46,7 +66,7 @@ func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Man
envSecret, _ := os.LookupEnv("MANAGEMENT_PASSWORD")
envSecret = strings.TrimSpace(envSecret)
return &Handler{
h := &Handler{
cfg: cfg,
configFilePath: configFilePath,
failedAttempts: make(map[string]*attemptInfo),
@@ -56,6 +76,30 @@ func NewHandler(cfg *config.Config, configFilePath string, manager *coreauth.Man
allowRemoteOverride: envSecret != "",
envSecret: envSecret,
}
// Initialize Integration Manager
// We need the proxy URL. If not in config, assume localhost default.
proxyURL := cfg.ProxyURL
if proxyURL == "" {
host := cfg.Host
if host == "" {
host = "http://127.0.0.1"
} else {
if !strings.HasPrefix(host, "http") {
host = "http://" + host
}
}
proxyURL = fmt.Sprintf("%s:%d", host, cfg.Port)
}
h.integrationManager = integrations.NewManager(proxyURL)
h.integrationManager.Register(&integrations.CodexIntegration{})
h.integrationManager.Register(&integrations.ContinueIntegration{})
h.integrationManager.Register(&integrations.ClaudeIntegration{})
h.integrationManager.Register(&integrations.DroidIntegration{})
h.integrationManager.Register(&integrations.GeminiIntegration{})
return h
}
// SetConfig updates the in-memory config reference when the server hot-reloads.
@@ -64,6 +108,111 @@ func (h *Handler) SetConfig(cfg *config.Config) { h.cfg = cfg }
// SetAuthManager updates the auth manager reference used by management endpoints.
func (h *Handler) SetAuthManager(manager *coreauth.Manager) { h.authManager = manager }
// routingPreview describes how a model would be normalised and routed according to current config.
type routingPreview struct {
RequestedModel string `json:"requested_model"`
ResolvedModel string `json:"resolved_model"`
NormalizedModel string `json:"normalized_model"`
ProviderCandidates []string `json:"provider_candidates"`
PreferredProvider string `json:"preferred_provider"`
Dynamic map[string]any `json:"dynamic"`
Metadata map[string]any `json:"metadata"`
}
// computeRoutingPreview replicates BaseAPIHandler.getRequestDetails for management/debug purposes.
func (h *Handler) computeRoutingPreview(modelName string) (*routingPreview, error) {
if strings.TrimSpace(modelName) == "" {
return nil, fmt.Errorf("model name is empty")
}
requested := strings.TrimSpace(modelName)
// Droid CLI sometimes sends a "custom:*" model id; normalize it before routing.
modelName = util.NormalizeDroidCustomModel(modelName)
// Resolve "auto" model to an actual available model first
resolvedModelName := util.ResolveAutoModel(modelName)
providerName, extractedModelName, isDynamic := parseDynamicModelWithConfig(resolvedModelName, h.openAICompatProviderNames())
targetModelName := resolvedModelName
if isDynamic {
targetModelName = extractedModelName
}
// Normalize the model name to handle dynamic thinking suffixes before determining the provider.
normalizedModel, metadata := util.NormalizeThinkingModel(targetModelName)
var providers []string
if isDynamic {
providers = []string{providerName}
} else {
// For non-dynamic models, use the normalizedModel to get the provider name.
providers = util.GetProviderName(normalizedModel)
if len(providers) == 0 && metadata != nil {
if originalRaw, ok := metadata[util.ThinkingOriginalModelMetadataKey]; ok {
if originalModel, okStr := originalRaw.(string); okStr {
originalModel = strings.TrimSpace(originalModel)
if originalModel != "" && !strings.EqualFold(originalModel, normalizedModel) {
if altProviders := util.GetProviderName(originalModel); len(altProviders) > 0 {
providers = altProviders
normalizedModel = originalModel
}
}
}
}
}
}
if len(providers) == 0 {
return nil, fmt.Errorf("unknown provider for model %s", requested)
}
preferred := ""
if len(providers) > 0 {
preferred = providers[0]
}
preview := &routingPreview{
RequestedModel: requested,
ResolvedModel: resolvedModelName,
NormalizedModel: normalizedModel,
ProviderCandidates: providers,
PreferredProvider: preferred,
Dynamic: map[string]any{
"is_dynamic": isDynamic,
"dynamic_provider": providerName,
"dynamic_model": extractedModelName,
},
Metadata: metadata,
}
return preview, nil
}
// parseDynamicModelWithConfig mirrors BaseAPIHandler.parseDynamicModel but uses the config provider list.
func parseDynamicModelWithConfig(modelName string, openAICompatProviders []string) (providerName, model string, isDynamic bool) {
var providerPart, modelPart string
for _, sep := range []string{"://"} {
if parts := strings.SplitN(modelName, sep, 2); len(parts) == 2 {
providerPart = parts[0]
modelPart = parts[1]
break
}
}
if providerPart == "" {
return "", modelName, false
}
for _, pName := range openAICompatProviders {
if pName == providerPart {
return providerPart, modelPart, true
}
}
return "", modelName, false
}
// SetUsageStatistics allows replacing the usage statistics reference.
func (h *Handler) SetUsageStatistics(stats *usage.RequestStatistics) { h.usageStats = stats }
@@ -91,6 +240,10 @@ func (h *Handler) Middleware() gin.HandlerFunc {
const banDuration = 30 * time.Minute
return func(c *gin.Context) {
c.Header("X-CPA-VERSION", buildinfo.Version)
c.Header("X-CPA-COMMIT", buildinfo.Commit)
c.Header("X-CPA-BUILD-DATE", buildinfo.BuildDate)
clientIP := c.ClientIP()
localClient := clientIP == "127.0.0.1" || clientIP == "::1"
cfg := h.cfg
@@ -235,16 +388,6 @@ func (h *Handler) updateBoolField(c *gin.Context, set func(bool)) {
Value *bool `json:"value"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Value == nil {
var m map[string]any
if err2 := c.ShouldBindJSON(&m); err2 == nil {
for _, v := range m {
if b, ok := v.(bool); ok {
set(b)
h.persist(c)
return
}
}
}
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
@@ -0,0 +1,172 @@
package management
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
iflowauth "github.com/router-for-me/CLIProxyAPI/v6/internal/auth/iflow"
"github.com/router-for-me/CLIProxyAPI/v6/internal/errors"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
// ImportIFlowCredential handles uploading a text file with iFlow cookies (one per line).
// Each cookie is authenticated and saved as a separate auth record.
func (h *Handler) ImportIFlowCredential(c *gin.Context) {
if h == nil || h.cfg == nil {
e := errors.New(http.StatusServiceUnavailable, "service_unavailable", "config unavailable", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
if h.cfg.AuthDir == "" {
e := errors.New(http.StatusServiceUnavailable, "config_error", "auth directory not configured", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
e := errors.New(http.StatusBadRequest, "invalid_request", "file required", err)
c.JSON(e.HTTPStatusCode, e)
return
}
file, err := fileHeader.Open()
if err != nil {
e := errors.New(http.StatusBadRequest, "file_error", fmt.Sprintf("failed to read file: %v", err), err)
c.JSON(e.HTTPStatusCode, e)
return
}
defer file.Close()
ctx := context.Background()
if reqCtx := c.Request.Context(); reqCtx != nil {
ctx = reqCtx
}
cookies, err := parseCookieLines(file)
if err != nil {
e := errors.New(http.StatusBadRequest, "parse_error", "failed to parse file", err)
c.JSON(e.HTTPStatusCode, e)
return
}
if len(cookies) == 0 {
e := errors.New(http.StatusBadRequest, "invalid_file", "no valid cookies found in file", nil)
c.JSON(e.HTTPStatusCode, e)
return
}
authSvc := iflowauth.NewIFlowAuth(h.cfg)
var results []importResult
successCount := 0
for i, raw := range cookies {
lineNum := i + 1
result := h.processIFlowCookie(ctx, authSvc, raw, lineNum)
if result.Success {
successCount++
}
results = append(results, result)
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"total": len(cookies),
"success_count": successCount,
"failed_count": len(cookies) - successCount,
"results": results,
})
}
type importResult struct {
Line int `json:"line"`
Success bool `json:"success"`
Email string `json:"email,omitempty"`
SavedPath string `json:"saved_path,omitempty"`
Error string `json:"error,omitempty"`
}
func parseCookieLines(r io.Reader) ([]string, error) {
var cookies []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
cookies = append(cookies, line)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return cookies, nil
}
func (h *Handler) processIFlowCookie(ctx context.Context, authSvc *iflowauth.IFlowAuth, raw string, lineNum int) importResult {
cookieValue, errNormalize := iflowauth.NormalizeCookie(raw)
if errNormalize != nil {
return importResult{Line: lineNum, Success: false, Error: errNormalize.Error()}
}
// Check for duplicate BXAuth before authentication
bxAuth := iflowauth.ExtractBXAuth(cookieValue)
if existingFile, err := iflowauth.CheckDuplicateBXAuth(h.cfg.AuthDir, bxAuth); err != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to check duplicate"}
} else if existingFile != "" {
existingFileName := filepath.Base(existingFile)
return importResult{Line: lineNum, Success: false, Error: fmt.Sprintf("duplicate BXAuth found: %s", existingFileName)}
}
tokenData, errAuth := authSvc.AuthenticateWithCookie(ctx, cookieValue)
if errAuth != nil {
return importResult{Line: lineNum, Success: false, Error: errAuth.Error()}
}
tokenData.Cookie = cookieValue
tokenStorage := authSvc.CreateCookieTokenStorage(tokenData)
email := strings.TrimSpace(tokenStorage.Email)
if email == "" {
return importResult{Line: lineNum, Success: false, Error: "failed to extract email from token"}
}
fileName := iflowauth.SanitizeIFlowFileName(email)
if fileName == "" {
fileName = fmt.Sprintf("iflow-%d", time.Now().UnixMilli())
}
tokenStorage.Email = email
timestamp := time.Now().Unix()
record := &coreauth.Auth{
ID: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Provider: "iflow",
FileName: fmt.Sprintf("iflow-%s-%d.json", fileName, timestamp),
Storage: tokenStorage,
Metadata: map[string]any{
"email": email,
"api_key": tokenStorage.APIKey,
"expired": tokenStorage.Expire,
"cookie": tokenStorage.Cookie,
"type": tokenStorage.Type,
"last_refresh": tokenStorage.LastRefresh,
},
Attributes: map[string]string{
"api_key": tokenStorage.APIKey,
},
}
savedPath, errSave := h.saveTokenRecord(ctx, record)
if errSave != nil {
return importResult{Line: lineNum, Success: false, Error: "failed to save authentication tokens"}
}
return importResult{Line: lineNum, Success: true, Email: email, SavedPath: savedPath}
}
@@ -0,0 +1,93 @@
package management
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/stretchr/testify/assert"
)
func TestImportIFlowCredential_NoConfig(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: nil}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "config unavailable")
}
func TestImportIFlowCredential_NoAuthDir(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusServiceUnavailable, w.Code)
assert.Contains(t, w.Body.String(), "auth directory not configured")
}
func TestImportIFlowCredential_NoFile(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{AuthDir: "/tmp"}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req, _ := http.NewRequest("POST", "/import", nil)
c.Request = req
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "file required")
}
func TestImportIFlowCredential_EmptyFile(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &Handler{cfg: &config.Config{AuthDir: "/tmp"}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "test.txt")
part.Write([]byte(""))
writer.Close()
req, _ := http.NewRequest("POST", "/import", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
c.Request = req
h.ImportIFlowCredential(c)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "no valid cookies found")
}
func TestParseCookieLines(t *testing.T) {
content := `
# Comment
cookie1
cookie2
`
reader := bytes.NewReader([]byte(content))
cookies, err := parseCookieLines(reader)
assert.NoError(t, err)
assert.Len(t, cookies, 2)
assert.Equal(t, "cookie1", cookies[0])
assert.Equal(t, "cookie2", cookies[1])
}
@@ -0,0 +1,37 @@
package management
import (
"net/http"
"github.com/gin-gonic/gin"
)
// GetIntegrationsStatus returns the list of detected tools and their configuration status.
func (h *Handler) GetIntegrationsStatus(c *gin.Context) {
if h.integrationManager == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "integration manager not initialized"})
return
}
statuses := h.integrationManager.ListStatus()
c.JSON(http.StatusOK, gin.H{"integrations": statuses})
}
// PostIntegrationConfigure triggers the configuration logic for a specific tool.
func (h *Handler) PostIntegrationConfigure(c *gin.Context) {
if h.integrationManager == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "integration manager not initialized"})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing integration id"})
return
}
if err := h.integrationManager.Configure(id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "configured", "id": id})
}
+250 -6
View File
@@ -58,8 +58,14 @@ func (h *Handler) GetLogs(c *gin.Context) {
return
}
limit, errLimit := parseLimit(c.Query("limit"))
if errLimit != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("invalid limit: %v", errLimit)})
return
}
cutoff := parseCutoff(c.Query("after"))
acc := newLogAccumulator(cutoff)
acc := newLogAccumulator(cutoff, limit)
for i := range files {
if errProcess := acc.consumeFile(files[i]); errProcess != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file %s: %v", files[i], errProcess)})
@@ -139,6 +145,214 @@ func (h *Handler) DeleteLogs(c *gin.Context) {
})
}
// GetRequestErrorLogs lists error request log files when RequestLog is disabled.
// It returns an empty list when RequestLog is enabled.
func (h *Handler) GetRequestErrorLogs(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
if h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
return
}
if h.cfg.RequestLog {
c.JSON(http.StatusOK, gin.H{"files": []any{}})
return
}
dir := h.logDirectory()
if strings.TrimSpace(dir) == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
return
}
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusOK, gin.H{"files": []any{}})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list request error logs: %v", err)})
return
}
type errorLog struct {
Name string `json:"name"`
Size int64 `json:"size"`
Modified int64 `json:"modified"`
}
files := make([]errorLog, 0, len(entries))
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") {
continue
}
info, errInfo := entry.Info()
if errInfo != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log info for %s: %v", name, errInfo)})
return
}
files = append(files, errorLog{
Name: name,
Size: info.Size(),
Modified: info.ModTime().Unix(),
})
}
sort.Slice(files, func(i, j int) bool { return files[i].Modified > files[j].Modified })
c.JSON(http.StatusOK, gin.H{"files": files})
}
// GetRequestLogByID finds and downloads a request log file by its request ID.
// The ID is matched against the suffix of log file names (format: *-{requestID}.log).
func (h *Handler) GetRequestLogByID(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
if h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
return
}
dir := h.logDirectory()
if strings.TrimSpace(dir) == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
return
}
requestID := strings.TrimSpace(c.Param("id"))
if requestID == "" {
requestID = strings.TrimSpace(c.Query("id"))
}
if requestID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing request ID"})
return
}
if strings.ContainsAny(requestID, "/\\") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request ID"})
return
}
entries, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "log directory not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to list log directory: %v", err)})
return
}
suffix := "-" + requestID + ".log"
var matchedFile string
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
if strings.HasSuffix(name, suffix) {
matchedFile = name
break
}
}
if matchedFile == "" {
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found for the given request ID"})
return
}
dirAbs, errAbs := filepath.Abs(dir)
if errAbs != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)})
return
}
fullPath := filepath.Clean(filepath.Join(dirAbs, matchedFile))
prefix := dirAbs + string(os.PathSeparator)
if !strings.HasPrefix(fullPath, prefix) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"})
return
}
info, errStat := os.Stat(fullPath)
if errStat != nil {
if os.IsNotExist(errStat) {
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"})
return
}
c.FileAttachment(fullPath, matchedFile)
}
// DownloadRequestErrorLog downloads a specific error request log file by name.
func (h *Handler) DownloadRequestErrorLog(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
if h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "configuration unavailable"})
return
}
dir := h.logDirectory()
if strings.TrimSpace(dir) == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "log directory not configured"})
return
}
name := strings.TrimSpace(c.Param("name"))
if name == "" || strings.Contains(name, "/") || strings.Contains(name, "\\") {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file name"})
return
}
if !strings.HasPrefix(name, "error-") || !strings.HasSuffix(name, ".log") {
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
return
}
dirAbs, errAbs := filepath.Abs(dir)
if errAbs != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to resolve log directory: %v", errAbs)})
return
}
fullPath := filepath.Clean(filepath.Join(dirAbs, name))
prefix := dirAbs + string(os.PathSeparator)
if !strings.HasPrefix(fullPath, prefix) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file path"})
return
}
info, errStat := os.Stat(fullPath)
if errStat != nil {
if os.IsNotExist(errStat) {
c.JSON(http.StatusNotFound, gin.H{"error": "log file not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log file: %v", errStat)})
return
}
if info.IsDir() {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid log file"})
return
}
c.FileAttachment(fullPath, name)
}
func (h *Handler) logDirectory() string {
if h == nil {
return ""
@@ -194,16 +408,22 @@ func (h *Handler) collectLogFiles(dir string) ([]string, error) {
type logAccumulator struct {
cutoff int64
limit int
lines []string
total int
latest int64
include bool
}
func newLogAccumulator(cutoff int64) *logAccumulator {
func newLogAccumulator(cutoff int64, limit int) *logAccumulator {
capacity := 256
if limit > 0 && limit < capacity {
capacity = limit
}
return &logAccumulator{
cutoff: cutoff,
lines: make([]string, 0, 256),
limit: limit,
lines: make([]string, 0, capacity),
}
}
@@ -215,7 +435,9 @@ func (acc *logAccumulator) consumeFile(path string) error {
}
return err
}
defer file.Close()
defer func() {
_ = file.Close()
}()
scanner := bufio.NewScanner(file)
buf := make([]byte, 0, logScannerInitialBuffer)
@@ -239,12 +461,19 @@ func (acc *logAccumulator) addLine(raw string) {
if ts > 0 {
acc.include = acc.cutoff == 0 || ts > acc.cutoff
if acc.cutoff == 0 || acc.include {
acc.lines = append(acc.lines, line)
acc.append(line)
}
return
}
if acc.cutoff == 0 || acc.include {
acc.lines = append(acc.lines, line)
acc.append(line)
}
}
func (acc *logAccumulator) append(line string) {
acc.lines = append(acc.lines, line)
if acc.limit > 0 && len(acc.lines) > acc.limit {
acc.lines = acc.lines[len(acc.lines)-acc.limit:]
}
}
@@ -267,6 +496,21 @@ func parseCutoff(raw string) int64 {
return ts
}
func parseLimit(raw string) (int, error) {
value := strings.TrimSpace(raw)
if value == "" {
return 0, nil
}
limit, err := strconv.Atoi(value)
if err != nil {
return 0, fmt.Errorf("must be a positive integer")
}
if limit <= 0 {
return 0, fmt.Errorf("must be greater than zero")
}
return limit, nil
}
func parseTimestamp(line string) int64 {
if strings.HasPrefix(line, "[") {
line = line[1:]
+462
View File
@@ -0,0 +1,462 @@
package management
import (
"archive/zip"
"bytes"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
)
func (h *Handler) ListMemorySessions(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"sessions": []any{}})
return
}
limit := 50
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
sessions, err := store.ListSessions(limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(sessions))
for _, s := range sessions {
out = append(out, gin.H{
"key": s.Key,
"updated_at": formatTime(s.UpdatedAt),
"size_bytes": s.SizeBytes,
"events_bytes": s.EventsBytes,
"has_summary": s.HasSummary,
"has_todo": s.HasTodo,
"has_pinned": s.HasPinned,
"has_anchor_pending": s.HasAnchorPending,
"semantic_disabled": s.SemanticDisabled,
})
}
c.JSON(http.StatusOK, gin.H{"sessions": out})
}
func (h *Handler) GetMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"session": gin.H{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
store := memory.NewFileStore(base)
info, err := store.GetSessionInfo(session)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := gin.H{
"key": info.Key,
"updated_at": formatTime(info.UpdatedAt),
"size_bytes": info.SizeBytes,
"events_bytes": info.EventsBytes,
"has_summary": info.HasSummary,
"has_todo": info.HasTodo,
"has_pinned": info.HasPinned,
"has_anchor_pending": info.HasAnchorPending,
"semantic_disabled": info.SemanticDisabled,
}
out["summary"] = store.ReadSummary(session, 14_000)
out["todo"] = store.ReadTodo(session, 8_000)
out["pinned"] = store.ReadPinned(session, 8_000)
out["anchor_pending"] = store.ReadPendingAnchor(session, 6_000)
c.JSON(http.StatusOK, gin.H{"session": out})
}
func (h *Handler) GetMemoryEvents(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"events": []any{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
limit := 100
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
events, err := store.ReadEventTail(session, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(events))
for _, e := range events {
out = append(out, gin.H{
"ts": formatTime(e.TS),
"kind": e.Kind,
"role": e.Role,
"type": e.Type,
"text": e.Text,
})
}
c.JSON(http.StatusOK, gin.H{"events": out})
}
func (h *Handler) GetMemoryAnchors(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"anchors": []any{}})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
limit := 20
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
limit = n
}
}
store := memory.NewFileStore(base)
anchors, err := store.ReadAnchorTail(session, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(anchors))
for _, a := range anchors {
out = append(out, gin.H{
"ts": formatTime(a.TS),
"summary": a.Summary,
})
}
c.JSON(http.StatusOK, gin.H{"anchors": out})
}
type memoryUpdateRequest struct {
Session string `json:"session"`
Value string `json:"value"`
}
func (h *Handler) PutMemoryTodo(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
return store.WriteTodo(session, value, 8000)
})
}
func (h *Handler) PutMemoryPinned(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
return store.WritePinned(session, value, 8000)
})
}
func (h *Handler) PutMemorySummary(c *gin.Context) {
h.updateMemoryField(c, func(store *memory.FileStore, session string, value string) error {
if anchorAppendOnlyEnabled() {
return store.SetAnchorSummary(session, value, 14_000)
}
return store.WriteSummary(session, value, 14_000)
})
}
type memoryToggleRequest struct {
Session string `json:"session"`
Enabled *bool `json:"enabled"`
}
func (h *Handler) PutMemorySemanticToggle(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req memoryToggleRequest
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Session) == "" || req.Enabled == nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
if err := store.SetSemanticDisabled(req.Session, !*req.Enabled); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) DeleteMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
path := filepath.Join(base, "sessions", session)
if err := os.RemoveAll(path); err != nil && !os.IsNotExist(err) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
type memoryPruneRequest struct {
MaxAgeDays *int `json:"max_age_days"`
MaxSessions *int `json:"max_sessions"`
MaxBytesPerSession *int64 `json:"max_bytes_per_session"`
MaxNamespaces *int `json:"max_namespaces"`
MaxBytesPerNamespace *int64 `json:"max_bytes_per_namespace"`
}
func (h *Handler) PruneMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
var req memoryPruneRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
maxAge := 0
maxSessions := 0
maxBytesSession := int64(0)
maxNamespaces := 0
maxBytesNamespace := int64(0)
if req.MaxAgeDays != nil {
maxAge = *req.MaxAgeDays
}
if req.MaxSessions != nil {
maxSessions = *req.MaxSessions
}
if req.MaxBytesPerSession != nil {
maxBytesSession = *req.MaxBytesPerSession
}
if req.MaxNamespaces != nil {
maxNamespaces = *req.MaxNamespaces
}
if req.MaxBytesPerNamespace != nil {
maxBytesNamespace = *req.MaxBytesPerNamespace
}
sres, err := store.PruneSessions(maxAge, maxSessions, maxBytesSession)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
semres, err := store.PruneSemantic(maxAge, maxNamespaces, maxBytesNamespace)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := memory.PruneResult{
SessionsRemoved: sres.SessionsRemoved,
SessionsTrimmed: sres.SessionsTrimmed,
SemanticNamespacesRemoved: semres.SemanticNamespacesRemoved,
SemanticNamespacesTrimmed: semres.SemanticNamespacesTrimmed,
BytesFreed: sres.BytesFreed + semres.BytesFreed,
}
c.JSON(http.StatusOK, gin.H{"status": "ok", "result": out})
}
func (h *Handler) ExportMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
dir := filepath.Join(base, "sessions", session)
if _, err := os.Stat(dir); err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return
}
data, err := memory.ExportSessionZip(dir)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if max := memoryExportMaxBytes(); max > 0 && int64(len(data)) > max {
c.JSON(http.StatusInternalServerError, gin.H{"error": "export exceeds size limit"})
return
}
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\"proxypilot-session-"+session+".zip\"")
c.Data(http.StatusOK, "application/zip", data)
}
func (h *Handler) ExportAllMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
data, err := memory.ExportAllZip(base, memoryExportMaxBytes())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Header("Content-Type", "application/zip")
c.Header("Content-Disposition", "attachment; filename=\"proxypilot-memory-all.zip\"")
c.Data(http.StatusOK, "application/zip", data)
}
func (h *Handler) DeleteAllMemory(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
return
}
confirm := strings.TrimSpace(c.Query("confirm"))
if !strings.EqualFold(confirm, "true") && !strings.EqualFold(confirm, "yes") {
c.JSON(http.StatusBadRequest, gin.H{"error": "confirm=true required"})
return
}
if err := os.RemoveAll(base); err != nil && !os.IsNotExist(err) {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) ImportMemorySession(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
if ct := strings.TrimSpace(c.ContentType()); ct != "" && !strings.HasPrefix(strings.ToLower(ct), "multipart/") {
c.JSON(http.StatusBadRequest, gin.H{"error": "multipart form required"})
return
}
session := strings.TrimSpace(c.Query("session"))
if session == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing session"})
return
}
replace := strings.EqualFold(strings.TrimSpace(c.Query("replace")), "true")
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
return
}
if fileHeader.Size > 50*1024*1024 {
c.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, 50*1024*1024))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file", "details": err.Error()})
return
}
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid zip"})
return
}
dest := filepath.Join(base, "sessions", session)
if replace {
_ = os.RemoveAll(dest)
}
if err := os.MkdirAll(dest, 0o755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
}
name := filepath.ToSlash(f.Name)
name = strings.TrimPrefix(name, "/")
if strings.Contains(name, "..") {
continue
}
target := filepath.Join(dest, filepath.FromSlash(name))
if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(dest)) {
continue
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
continue
}
rc, err := f.Open()
if err != nil {
continue
}
b, err := io.ReadAll(io.LimitReader(rc, 10*1024*1024))
_ = rc.Close()
if err != nil {
continue
}
_ = os.WriteFile(target, b, 0o644)
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func (h *Handler) updateMemoryField(c *gin.Context, fn func(store *memory.FileStore, session string, value string) error) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "memory not configured"})
return
}
var req memoryUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil || strings.TrimSpace(req.Session) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid body"})
return
}
store := memory.NewFileStore(base)
if err := fn(store, req.Session, req.Value); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
func formatTime(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
func anchorAppendOnlyEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_ANCHOR_APPEND_ONLY")); v != "" {
if strings.EqualFold(v, "0") || strings.EqualFold(v, "false") || strings.EqualFold(v, "off") || strings.EqualFold(v, "no") {
return false
}
}
return true
}
@@ -0,0 +1,29 @@
package management
import (
"os"
"path/filepath"
"strconv"
"strings"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
)
func memoryBaseDir() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_MEMORY_DIR")); v != "" {
return v
}
if w := util.WritablePath(); w != "" {
return filepath.Join(w, ".proxypilot", "memory")
}
return filepath.Join(".proxypilot", "memory")
}
func memoryExportMaxBytes() int64 {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_MEMORY_EXPORT_MAX_BYTES")); v != "" {
if n, err := strconv.ParseInt(v, 10, 64); err == nil {
return n
}
}
return 250 * 1024 * 1024
}
@@ -0,0 +1,100 @@
package management
import (
"errors"
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
)
type oauthCallbackRequest struct {
Provider string `json:"provider"`
RedirectURL string `json:"redirect_url"`
Code string `json:"code"`
State string `json:"state"`
Error string `json:"error"`
}
func (h *Handler) PostOAuthCallback(c *gin.Context) {
if h == nil || h.cfg == nil {
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "handler not initialized"})
return
}
var req oauthCallbackRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid body"})
return
}
canonicalProvider, err := NormalizeOAuthProvider(req.Provider)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "unsupported provider"})
return
}
state := strings.TrimSpace(req.State)
code := strings.TrimSpace(req.Code)
errMsg := strings.TrimSpace(req.Error)
if rawRedirect := strings.TrimSpace(req.RedirectURL); rawRedirect != "" {
u, errParse := url.Parse(rawRedirect)
if errParse != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid redirect_url"})
return
}
q := u.Query()
if state == "" {
state = strings.TrimSpace(q.Get("state"))
}
if code == "" {
code = strings.TrimSpace(q.Get("code"))
}
if errMsg == "" {
errMsg = strings.TrimSpace(q.Get("error"))
if errMsg == "" {
errMsg = strings.TrimSpace(q.Get("error_description"))
}
}
}
if state == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "state is required"})
return
}
if err := ValidateOAuthState(state); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "invalid state"})
return
}
if code == "" && errMsg == "" {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "code or error is required"})
return
}
sessionProvider, sessionStatus, ok := GetOAuthSession(state)
if !ok {
c.JSON(http.StatusNotFound, gin.H{"status": "error", "error": "unknown or expired state"})
return
}
if sessionStatus != "" {
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is not pending"})
return
}
if !strings.EqualFold(sessionProvider, canonicalProvider) {
c.JSON(http.StatusBadRequest, gin.H{"status": "error", "error": "provider does not match state"})
return
}
if _, errWrite := WriteOAuthCallbackFileForPendingSession(h.cfg.AuthDir, canonicalProvider, state, code, errMsg); errWrite != nil {
if errors.Is(errWrite, errOAuthSessionNotPending) {
c.JSON(http.StatusConflict, gin.H{"status": "error", "error": "oauth flow is not pending"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "error": "failed to persist oauth callback"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}
@@ -0,0 +1,290 @@
package management
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
const (
oauthSessionTTL = 10 * time.Minute
maxOAuthStateLength = 128
)
var (
errInvalidOAuthState = errors.New("invalid oauth state")
errUnsupportedOAuthFlow = errors.New("unsupported oauth provider")
errOAuthSessionNotPending = errors.New("oauth session is not pending")
)
type oauthSession struct {
Provider string
Status string
CreatedAt time.Time
ExpiresAt time.Time
}
type oauthSessionStore struct {
mu sync.RWMutex
ttl time.Duration
sessions map[string]oauthSession
}
func newOAuthSessionStore(ttl time.Duration) *oauthSessionStore {
if ttl <= 0 {
ttl = oauthSessionTTL
}
return &oauthSessionStore{
ttl: ttl,
sessions: make(map[string]oauthSession),
}
}
func (s *oauthSessionStore) purgeExpiredLocked(now time.Time) {
for state, session := range s.sessions {
if !session.ExpiresAt.IsZero() && now.After(session.ExpiresAt) {
delete(s.sessions, state)
}
}
}
func (s *oauthSessionStore) Register(state, provider string) {
state = strings.TrimSpace(state)
provider = strings.ToLower(strings.TrimSpace(provider))
if state == "" || provider == "" {
return
}
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
s.sessions[state] = oauthSession{
Provider: provider,
Status: "",
CreatedAt: now,
ExpiresAt: now.Add(s.ttl),
}
}
func (s *oauthSessionStore) SetError(state, message string) {
state = strings.TrimSpace(state)
message = strings.TrimSpace(message)
if state == "" {
return
}
if message == "" {
message = "Authentication failed"
}
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
session, ok := s.sessions[state]
if !ok {
return
}
session.Status = message
session.ExpiresAt = now.Add(s.ttl)
s.sessions[state] = session
}
func (s *oauthSessionStore) Complete(state string) {
state = strings.TrimSpace(state)
if state == "" {
return
}
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
delete(s.sessions, state)
}
func (s *oauthSessionStore) CompleteProvider(provider string) int {
provider = strings.ToLower(strings.TrimSpace(provider))
if provider == "" {
return 0
}
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
removed := 0
for state, session := range s.sessions {
if strings.EqualFold(session.Provider, provider) {
delete(s.sessions, state)
removed++
}
}
return removed
}
func (s *oauthSessionStore) Get(state string) (oauthSession, bool) {
state = strings.TrimSpace(state)
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
session, ok := s.sessions[state]
return session, ok
}
func (s *oauthSessionStore) IsPending(state, provider string) bool {
state = strings.TrimSpace(state)
provider = strings.ToLower(strings.TrimSpace(provider))
now := time.Now()
s.mu.Lock()
defer s.mu.Unlock()
s.purgeExpiredLocked(now)
session, ok := s.sessions[state]
if !ok {
return false
}
if session.Status != "" {
if !strings.EqualFold(session.Provider, "kiro") {
return false
}
if !strings.HasPrefix(session.Status, "device_code|") && !strings.HasPrefix(session.Status, "auth_url|") {
return false
}
}
if provider == "" {
return true
}
return strings.EqualFold(session.Provider, provider)
}
var oauthSessions = newOAuthSessionStore(oauthSessionTTL)
func RegisterOAuthSession(state, provider string) { oauthSessions.Register(state, provider) }
func SetOAuthSessionError(state, message string) { oauthSessions.SetError(state, message) }
func CompleteOAuthSession(state string) { oauthSessions.Complete(state) }
func CompleteOAuthSessionsByProvider(provider string) int {
return oauthSessions.CompleteProvider(provider)
}
func GetOAuthSession(state string) (provider string, status string, ok bool) {
session, ok := oauthSessions.Get(state)
if !ok {
return "", "", false
}
return session.Provider, session.Status, true
}
func IsOAuthSessionPending(state, provider string) bool {
return oauthSessions.IsPending(state, provider)
}
func ValidateOAuthState(state string) error {
trimmed := strings.TrimSpace(state)
if trimmed == "" {
return fmt.Errorf("%w: empty", errInvalidOAuthState)
}
if len(trimmed) > maxOAuthStateLength {
return fmt.Errorf("%w: too long", errInvalidOAuthState)
}
if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") {
return fmt.Errorf("%w: contains path separator", errInvalidOAuthState)
}
if strings.Contains(trimmed, "..") {
return fmt.Errorf("%w: contains '..'", errInvalidOAuthState)
}
for _, r := range trimmed {
switch {
case r >= 'a' && r <= 'z':
case r >= 'A' && r <= 'Z':
case r >= '0' && r <= '9':
case r == '-' || r == '_' || r == '.':
default:
return fmt.Errorf("%w: invalid character", errInvalidOAuthState)
}
}
return nil
}
func NormalizeOAuthProvider(provider string) (string, error) {
switch strings.ToLower(strings.TrimSpace(provider)) {
case "anthropic", "claude":
return "anthropic", nil
case "codex", "openai":
return "codex", nil
case "gemini", "google":
return "gemini", nil
case "iflow", "i-flow":
return "iflow", nil
case "antigravity", "anti-gravity":
return "antigravity", nil
case "qwen":
return "qwen", nil
case "kiro":
return "kiro", nil
default:
return "", errUnsupportedOAuthFlow
}
}
type oauthCallbackFilePayload struct {
Code string `json:"code"`
State string `json:"state"`
Error string `json:"error"`
}
func WriteOAuthCallbackFile(authDir, provider, state, code, errorMessage string) (string, error) {
if strings.TrimSpace(authDir) == "" {
return "", fmt.Errorf("auth dir is empty")
}
canonicalProvider, err := NormalizeOAuthProvider(provider)
if err != nil {
return "", err
}
if err := ValidateOAuthState(state); err != nil {
return "", err
}
fileName := fmt.Sprintf(".oauth-%s-%s.oauth", canonicalProvider, state)
filePath := filepath.Join(authDir, fileName)
payload := oauthCallbackFilePayload{
Code: strings.TrimSpace(code),
State: strings.TrimSpace(state),
Error: strings.TrimSpace(errorMessage),
}
data, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("marshal oauth callback payload: %w", err)
}
if err := os.WriteFile(filePath, data, 0o600); err != nil {
return "", fmt.Errorf("write oauth callback file: %w", err)
}
return filePath, nil
}
func WriteOAuthCallbackFileForPendingSession(authDir, provider, state, code, errorMessage string) (string, error) {
canonicalProvider, err := NormalizeOAuthProvider(provider)
if err != nil {
return "", err
}
if !IsOAuthSessionPending(state, canonicalProvider) {
return "", errOAuthSessionNotPending
}
return WriteOAuthCallbackFile(authDir, canonicalProvider, state, code, errorMessage)
}
@@ -0,0 +1,176 @@
package management
import (
"bytes"
"fmt"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/buildinfo"
)
// GetProxyPilotLogTail returns tail lines for the launcher-managed stdout/stderr logs.
// These files are written by ProxyPilot when it spawns the server binary.
func (h *Handler) GetProxyPilotLogTail(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
kind := strings.ToLower(strings.TrimSpace(c.Query("file")))
lines := 200
if v := strings.TrimSpace(c.Query("lines")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 2000 {
lines = n
}
}
var name string
switch kind {
case "stdout", "out":
name = "proxypilot-engine.out.log"
case "stderr", "err":
name = "proxypilot-engine.err.log"
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid file (use stdout|stderr)"})
return
}
dir := h.logDirectory()
full := filepath.Join(dir, name)
content, truncated, err := tailTextFile(full, lines, 512*1024)
if err != nil {
if os.IsNotExist(err) {
c.JSON(http.StatusOK, gin.H{"lines": []string{}, "truncated": false})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("failed to read log: %v", err)})
return
}
outLines := splitLines(content)
if len(outLines) > lines {
outLines = outLines[len(outLines)-lines:]
truncated = true
}
c.JSON(http.StatusOK, gin.H{"lines": outLines, "truncated": truncated})
}
// GetProxyPilotDiagnostics returns a single text blob suitable for copy/paste.
func (h *Handler) GetProxyPilotDiagnostics(c *gin.Context) {
if h == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "handler unavailable"})
return
}
lines := 120
if v := strings.TrimSpace(c.Query("lines")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 1000 {
lines = n
}
}
var b strings.Builder
b.WriteString("ProxyPilot Diagnostics\n")
b.WriteString("\n")
b.WriteString(fmt.Sprintf("Built: version=%s commit=%s date=%s\n", buildinfo.Version, buildinfo.Commit, buildinfo.BuildDate))
if h.cfg != nil {
b.WriteString(fmt.Sprintf("Port: %d\n", h.cfg.Port))
b.WriteString(fmt.Sprintf("AuthDir: %s\n", strings.TrimSpace(h.cfg.AuthDir)))
b.WriteString(fmt.Sprintf("RequestLog: %v\n", h.cfg.RequestLog))
b.WriteString(fmt.Sprintf("Debug: %v\n", h.cfg.Debug))
}
if strings.TrimSpace(h.configFilePath) != "" {
b.WriteString(fmt.Sprintf("ConfigPath: %s\n", h.configFilePath))
}
logDir := h.logDirectory()
b.WriteString(fmt.Sprintf("LogDir: %s\n", logDir))
b.WriteString(fmt.Sprintf("CapturedAt: %s\n", time.Now().Format(time.RFC3339)))
b.WriteString("\n")
addTail := func(label, fileName string) {
full := filepath.Join(logDir, fileName)
content, _, err := tailTextFile(full, lines, 512*1024)
b.WriteString("=== " + label + " (" + fileName + ") ===\n")
if err != nil {
if os.IsNotExist(err) {
b.WriteString("(file not found)\n\n")
return
}
b.WriteString("(error reading log: " + err.Error() + ")\n\n")
return
}
b.WriteString(content)
if !strings.HasSuffix(content, "\n") {
b.WriteString("\n")
}
b.WriteString("\n")
}
addTail("Launcher Stdout", "proxypilot-engine.out.log")
addTail("Launcher Stderr", "proxypilot-engine.err.log")
c.JSON(http.StatusOK, gin.H{"text": b.String()})
}
func splitLines(s string) []string {
s = strings.ReplaceAll(s, "\r\n", "\n")
s = strings.TrimSuffix(s, "\n")
if strings.TrimSpace(s) == "" {
return []string{}
}
return strings.Split(s, "\n")
}
func tailTextFile(path string, wantLines int, maxBytes int64) (string, bool, error) {
f, err := os.Open(path)
if err != nil {
return "", false, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return "", false, err
}
size := info.Size()
if size <= 0 {
return "", false, nil
}
readBytes := maxBytes
if readBytes <= 0 {
readBytes = 256 * 1024
}
if readBytes > size {
readBytes = size
}
start := size - readBytes
if _, err := f.Seek(start, 0); err != nil {
return "", false, err
}
buf := make([]byte, readBytes)
n, err := f.Read(buf)
if err != nil && n == 0 {
return "", false, err
}
buf = buf[:n]
// Drop partial first line when we started mid-file.
if start > 0 {
if i := bytes.IndexByte(buf, '\n'); i >= 0 && i+1 < len(buf) {
buf = buf[i+1:]
}
}
text := string(buf)
// Best-effort: return enough lines; caller will truncate if needed.
truncated := start > 0
if wantLines <= 0 {
return text, truncated, nil
}
return text, truncated, nil
}
@@ -0,0 +1,182 @@
package management
import (
"bytes"
"encoding/json"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/memory"
)
func (h *Handler) GetSemanticHealth(c *gin.Context) {
enabled := semanticEnabled()
baseURL := semanticBaseURL()
model := semanticModel()
status := "disabled"
version := ""
errMsg := ""
modelPresent := false
latencyMs := int64(0)
if enabled {
status = "unreachable"
client := &http.Client{Timeout: 4 * time.Second}
req, _ := http.NewRequest(http.MethodGet, strings.TrimRight(baseURL, "/")+"/api/tags", nil)
resp, err := client.Do(req)
if err != nil {
errMsg = err.Error()
} else {
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
var out struct {
Models []struct {
Name string `json:"name"`
} `json:"models"`
}
if err := json.NewDecoder(resp.Body).Decode(&out); err == nil {
for _, m := range out.Models {
if strings.EqualFold(strings.TrimSpace(m.Name), strings.TrimSpace(model)) {
modelPresent = true
break
}
}
}
version = resp.Status
} else {
errMsg = resp.Status
}
}
if modelPresent {
start := time.Now()
payload := map[string]any{"model": model, "prompt": "ping"}
body, _ := json.Marshal(payload)
embedReq, _ := http.NewRequest(http.MethodPost, strings.TrimRight(baseURL, "/")+"/api/embeddings", bytes.NewReader(body))
embedReq.Header.Set("Content-Type", "application/json")
embedResp, err := client.Do(embedReq)
if err != nil {
errMsg = err.Error()
} else {
defer embedResp.Body.Close()
if embedResp.StatusCode >= 200 && embedResp.StatusCode < 300 {
status = "ok"
latencyMs = time.Since(start).Milliseconds()
} else {
errMsg = embedResp.Status
}
}
} else if errMsg == "" {
status = "model_missing"
}
}
queueStats := memory.GetSemanticQueueStats()
c.JSON(http.StatusOK, gin.H{
"enabled": enabled,
"baseURL": baseURL,
"model": model,
"status": status,
"version": version,
"model_present": modelPresent,
"latency_ms": latencyMs,
"error": errMsg,
"queue": queueStats,
})
}
func (h *Handler) ListSemanticNamespaces(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"namespaces": []any{}})
return
}
limit := 200
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 500 {
limit = n
}
}
store := memory.NewFileStore(base)
namespaces, err := store.ListSemanticNamespaces(limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(namespaces))
for _, ns := range namespaces {
out = append(out, gin.H{
"key": ns.Key,
"label": ns.Namespace,
"updated_at": ns.UpdatedAt.Format(time.RFC3339),
"size_bytes": ns.SizeBytes,
"items_bytes": ns.ItemsBytes,
})
}
c.JSON(http.StatusOK, gin.H{"namespaces": out})
}
func (h *Handler) GetSemanticItems(c *gin.Context) {
base := memoryBaseDir()
if base == "" {
c.JSON(http.StatusOK, gin.H{"items": []any{}})
return
}
key := strings.TrimSpace(c.Query("namespace"))
if key == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing namespace"})
return
}
limit := 50
if v := strings.TrimSpace(c.Query("limit")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
limit = n
}
}
store := memory.NewFileStore(base)
items, err := store.ReadSemanticTail(key, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
out := make([]gin.H, 0, len(items))
for _, it := range items {
out = append(out, gin.H{
"ts": it.TS.Format(time.RFC3339),
"role": it.Role,
"text": it.Text,
"source": it.Source,
"session": it.Session,
"repo": it.Repo,
})
}
c.JSON(http.StatusOK, gin.H{"items": out})
}
func semanticEnabled() bool {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_ENABLED")); v != "" {
if strings.EqualFold(v, "0") || strings.EqualFold(v, "false") || strings.EqualFold(v, "off") || strings.EqualFold(v, "no") {
return false
}
}
return true
}
func semanticModel() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_MODEL")); v != "" {
return v
}
return "embeddinggemma"
}
func semanticBaseURL() string {
if v := strings.TrimSpace(os.Getenv("CLIPROXY_SEMANTIC_BASE_URL")); v != "" {
return v
}
return "http://127.0.0.1:11434"
}
@@ -0,0 +1,156 @@
package management
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/vertex"
coreauth "github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
)
// ImportVertexCredential handles uploading a Vertex service account JSON and saving it as an auth record.
func (h *Handler) ImportVertexCredential(c *gin.Context) {
if h == nil || h.cfg == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "config unavailable"})
return
}
if h.cfg.AuthDir == "" {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "auth directory not configured"})
return
}
fileHeader, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "file required"})
return
}
file, err := fileHeader.Open()
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)})
return
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("failed to read file: %v", err)})
return
}
var serviceAccount map[string]any
if err := json.Unmarshal(data, &serviceAccount); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json", "message": err.Error()})
return
}
normalizedSA, err := vertex.NormalizeServiceAccountMap(serviceAccount)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid service account", "message": err.Error()})
return
}
serviceAccount = normalizedSA
projectID := strings.TrimSpace(valueAsString(serviceAccount["project_id"]))
if projectID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "project_id missing"})
return
}
email := strings.TrimSpace(valueAsString(serviceAccount["client_email"]))
location := strings.TrimSpace(c.PostForm("location"))
if location == "" {
location = strings.TrimSpace(c.Query("location"))
}
if location == "" {
location = "us-central1"
}
fileName := fmt.Sprintf("vertex-%s.json", sanitizeVertexFilePart(projectID))
label := labelForVertex(projectID, email)
storage := &vertex.VertexCredentialStorage{
ServiceAccount: serviceAccount,
ProjectID: projectID,
Email: email,
Location: location,
Type: "vertex",
}
metadata := map[string]any{
"service_account": serviceAccount,
"project_id": projectID,
"email": email,
"location": location,
"type": "vertex",
"label": label,
}
record := &coreauth.Auth{
ID: fileName,
Provider: "vertex",
FileName: fileName,
Storage: storage,
Label: label,
Metadata: metadata,
}
ctx := context.Background()
if reqCtx := c.Request.Context(); reqCtx != nil {
ctx = reqCtx
}
savedPath, err := h.saveTokenRecord(ctx, record)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "save_failed", "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"auth-file": savedPath,
"project_id": projectID,
"email": email,
"location": location,
})
}
func valueAsString(v any) string {
if v == nil {
return ""
}
switch t := v.(type) {
case string:
return t
default:
return fmt.Sprint(t)
}
}
func sanitizeVertexFilePart(s string) string {
out := strings.TrimSpace(s)
replacers := []string{"/", "_", "\\", "_", ":", "_", " ", "-"}
for i := 0; i < len(replacers); i += 2 {
out = strings.ReplaceAll(out, replacers[i], replacers[i+1])
}
if out == "" {
return "vertex"
}
return out
}
func labelForVertex(projectID, email string) string {
p := strings.TrimSpace(projectID)
e := strings.TrimSpace(email)
if p != "" && e != "" {
return fmt.Sprintf("%s (%s)", p, e)
}
if p != "" {
return p
}
if e != "" {
return e
}
return "vertex"
}
+402
View File
@@ -0,0 +1,402 @@
package middleware
import (
"bytes"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
const (
// Initializer prompt: forces the agent to set up the environment.
harnessInitializerPrompt = `
<harness_mode>INITIALIZER</harness_mode>
You are the **Initializer Agent** in a Long-Running Agent Harness.
Your ONLY goal is to set up the project environment for future Coding Agents.
**CRITICAL INSTRUCTIONS**:
1. **Analyze the User's Request**: Understand what feature or app needs to be built.
2. **Create 'feature_list.json'**:
- Write a JSON file listing ALL features/requirements as separate items.
- Mark them all as "passes": false.
- Format:
Request: "Build a todo app"
File Content:
[
{ "category": "core", "description": "User can add a todo", "steps": ["Open app", "Enter text", "Press enter", "See new item"], "passes": false },
{ "category": "core", "description": "User can delete a todo", "steps": ["Open app", "Click delete", "Item removed"], "passes": false }
]
3. **Create 'claude-progress.txt'**:
- Create this file with a header "## Progress Log".
- Add an initial entry: "- [Initializer] Environment setup started."
4. **Create 'init.sh' (Optional)**:
- If a dev server is needed, create a script to start it (e.g., 'npm run dev').
5. **Initial Commit**:
- Initialize git if not present.
- Commit these foundational files.
**DO NOT** start implementing features yourself. Your job is ONLY to scaffold the harness.
`
// Coding prompt: forces the agent to work incrementally.
harnessCodingPrompt = `
<harness_mode>CODING</harness_mode>
You are a **Coding Agent** in a Long-Running Agent Harness.
Your goal is to make **incremental progress** on the project.
**WORKFLOW**:
1. **Read Context**:
- Read 'claude-progress.txt' to see what was done last.
- Read 'feature_list.json' to see what is missing.
- Read recent git log to understand recent changes.
- If 'init.sh' exists, run it to start the dev server.
- Run a basic end-to-end sanity check before new work.
2. **Pick ONE Task**:
- Choose the highest-priority failing feature from 'feature_list.json'.
- Announce your plan.
3. **Implement & Verify**:
- Write code for that ONE feature.
- Verify it works end-to-end (tests or browser check).
4. **Update State**:
- Update 'feature_list.json': set "passes": true for the completed feature.
- Append to 'claude-progress.txt': "- [Coding] Implemented <feature>."
5. **Commit**:
- Git commit your changes.
**RESTRICTIONS**:
- Do NOT try to finish the whole project in one turn.
- Do NOT leave the code in a broken state.
- Always update the harness files ('feature_list.json', 'claude-progress.txt') before stopping.
- Do NOT edit 'feature_list.json' except toggling a feature's "passes" field after verified testing.
`
)
// AgenticHarnessMiddleware injects system prompts to guide long-running agents.
func AgenticHarnessMiddleware() gin.HandlerFunc {
return AgenticHarnessMiddlewareWithRootDir("")
}
// AgenticHarnessMiddlewareWithRootDir injects system prompts and checks harness files under rootDir.
// If rootDir is empty, the current working directory is used.
func AgenticHarnessMiddlewareWithRootDir(rootDir string) gin.HandlerFunc {
return func(c *gin.Context) {
req := c.Request
if req == nil || req.Method != http.MethodPost {
c.Next()
return
}
// 1. Check eligibility
ua := strings.ToLower(req.Header.Get("User-Agent"))
isAgenticCLI := strings.Contains(ua, "claude-cli") ||
strings.Contains(ua, "codex") ||
strings.Contains(ua, "droid") ||
req.Header.Get("X-ProxyPilot-Harness") == "true"
if !isAgenticCLI {
c.Next()
return
}
// 2. Read Body
body, err := io.ReadAll(req.Body)
if err != nil {
c.Next()
return
}
// restore body for next handler if we bail
req.Body = io.NopCloser(bytes.NewReader(body))
// 3. Detect State
// We look for evidence that the harness is already active (features/progress files).
// We also check conversation length.
state := detectHarnessState(body, rootDir)
// 4. Inject Prompt
var promptToInject string
switch state {
case "INITIALIZER":
promptToInject = harnessInitializerPrompt
case "CODING":
promptToInject = harnessCodingPrompt
default:
// "PASSIVE" - do nothing, let the user drive.
c.Next()
return
}
newBody := injectSystemPrompt(body, promptToInject)
// 5. Update Request
if !bytes.Equal(newBody, body) {
req.Body = io.NopCloser(bytes.NewReader(newBody))
req.ContentLength = int64(len(newBody))
req.Header.Set("Content-Length", strconv.Itoa(len(newBody)))
c.Header("X-ProxyPilot-Harness-Mode", state)
}
c.Next()
}
}
func detectHarnessState(body []byte, rootDir string) string {
// Simple heuristic:
// If the conversation contains references to "claude-progress.txt" or "feature_list.json",
// it's likely already in the harness flow -> CODING.
// If it's very short (just the user prompt) and lacks those, -> INITIALIZER.
raw := string(body)
if strings.Contains(raw, "claude-progress.txt") || strings.Contains(raw, "feature_list.json") {
return "CODING"
}
// Prefer filesystem truth when available.
if fileExists(rootDir, "claude-progress.txt") || fileExists(rootDir, "feature_list.json") {
return "CODING"
}
// Check conversation depth
// For OAI/Claude, we look at "messages" array length.
msgs := gjson.GetBytes(body, "messages")
if msgs.Exists() && msgs.IsArray() {
count := len(msgs.Array())
// Usually: System + User = 2 messages for a fresh start.
// If it's small, and we haven't seen progress files, assume we want to initialize.
// We use < 5 to be safe (System, User, maybe a tool use in between).
if count < 5 {
return "INITIALIZER"
}
}
// Responses API: check "input" array length if present.
input := gjson.GetBytes(body, "input")
if input.Exists() && input.IsArray() {
if len(input.Array()) < 5 {
return "INITIALIZER"
}
}
if input.Exists() && input.Type == gjson.String {
return "INITIALIZER"
}
// If it's a long conversation but no harness files mentioned,
// maybe the user didn't want the harness, or it's a legacy chat.
// We'll default to PASSIVE to avoid annoying the user.
return "PASSIVE"
}
func injectSystemPrompt(body []byte, prompt string) []byte {
// We prepend this prompt to the existing system prompt or messages.
// This logic handles OAI /v1/chat/completions, Claude /v1/messages, and OAI /v1/responses.
// 1. Try "messages" (Chat/Claude)
msgs := gjson.GetBytes(body, "messages")
if msgs.Exists() && msgs.IsArray() {
arr := msgs.Array()
// Look for existing system message to append to
for i, m := range arr {
if strings.EqualFold(m.Get("role").String(), "system") {
content := m.Get("content")
if content.Type == gjson.String {
old := content.String()
newText := old + "\n\n" + prompt
out, _ := sjson.SetBytes(body, "messages."+strconv.Itoa(i)+".content", newText)
return out
}
// If array content (Claude), append text block?
// Simpler to just Insert a new system message if complex.
}
}
// If no system message found, prepend one.
// Construct new message object
// Note: For Claude /v1/messages, "system" is arguably a top-level field,
// but `claude-cli` often speaks OAI dialect or we map it.
// Let's check for top-level system field first for pure Claude Messages API.
}
// 2. Claude Messages API top-level "system"
if sys := gjson.GetBytes(body, "system"); sys.Exists() {
if sys.Type == gjson.String {
old := sys.String()
newText := old + "\n\n" + prompt
out, _ := sjson.SetBytes(body, "system", newText)
return out
}
}
// 2b. Responses API top-level "instructions" or "input"
if inst := gjson.GetBytes(body, "instructions"); inst.Exists() && inst.Type == gjson.String {
old := inst.String()
newText := old + "\n\n" + prompt
out, _ := sjson.SetBytes(body, "instructions", newText)
return out
}
if input := gjson.GetBytes(body, "input"); input.Exists() {
if input.Type == gjson.String {
old := input.String()
newText := prompt + "\n\n" + old
out, _ := sjson.SetBytes(body, "input", newText)
return out
}
if input.IsArray() {
return prependHarnessToResponsesInput(body, prompt)
}
}
// 3. Fallback: Prepend a system message to "messages" array
// Valid for OAI. For Claude, if top-level system is missing, we might use this
// but strictly Claude Messages API wants top-level.
// Let's assume standard OAI-like messages array is the target for now.
// newMsg map removed as it was unused and causing lint errors
// We proceed to check for Claude or use prependHarnessToLastUserText.
// sjson doesn't easily "prepend" to array without reading it all.
// But we can use sjson.Set to insert at index 0?
// sjson path "messages.-1" appends. "messages.0" overwrites.
// We might need to unmarshal/marshal if sjson is too tricky for insert.
// Actually, creating a new body string is safer/easier than strict JSON manipulation for insertion.
// But let's try sjson properly:
// If we must insert at the front, sjson isn't great.
// Strategy: If existing systems exist, we updated them above.
// If NOT, we need to add one.
// Let's try to set "system" top level again if it's empty (Anthropic specific)
// If the request body HAS "max_tokens" (Claude) but NO "messages" (Completion), handle that?
// Assuming Chat/Messages API.
// If it's Claude-style body without system:
if gjson.GetBytes(body, "messages").Exists() {
// If checking for Claude-specifics:
if gjson.GetBytes(body, "anthropic_version").Exists() {
// It is Claude Messages API. Set top-level system.
out, _ := sjson.SetBytes(body, "system", prompt)
return out
}
// Otherwise assume OAI Chat. Prepend to messages.
// "messages.0" -> insert? No, sjson overwrites.
// We'll read the whole array, prepend in Go, write back.
// This is expensive but safe.
// Wait, we can cheat: Just append the prompt to the *last user message*.
// This is what `codex_prompt_budget.go` does (`prependToLastUserText`).
// It's robust and works for all models (context is context).
// AND it avoids "multiple system messages" issues some models hate.
return prependHarnessToLastUserText(body, prompt)
}
return body
}
// Reuse logic similar to codex_prompt_budget but simplified for just prepending to USER message.
// This ensures the model "hears" it as part of the latest command.
func prependHarnessToLastUserText(body []byte, prefix string) []byte {
prefix = "\n\n[SYSTEM NOTE: " + strings.TrimSpace(prefix) + "]\n\n"
msgs := gjson.GetBytes(body, "messages")
if !msgs.Exists() || !msgs.IsArray() {
return body
}
arr := msgs.Array()
// Find last user message
for i := len(arr) - 1; i >= 0; i-- {
if strings.EqualFold(arr[i].Get("role").String(), "user") {
content := arr[i].Get("content")
// String content
if content.Type == gjson.String {
old := content.String()
newText := prefix + old
out, err := sjson.SetBytes(body, "messages."+strconv.Itoa(i)+".content", newText)
if err == nil {
return out
}
}
// Array content (multimodal)
if content.IsArray() {
parts := content.Array()
for j := 0; j < len(parts); j++ {
// Find text part
if parts[j].Get("type").String() == "text" || parts[j].Get("text").Exists() {
old := parts[j].Get("text").String()
newText := prefix + old
out, err := sjson.SetBytes(body, "messages."+strconv.Itoa(i)+".content."+strconv.Itoa(j)+".text", newText)
if err == nil {
return out
}
}
}
}
return body // Found user but failed to inject?
}
}
return body
}
func prependHarnessToResponsesInput(body []byte, prefix string) []byte {
prefix = "\n\n[SYSTEM NOTE: " + strings.TrimSpace(prefix) + "]\n\n"
input := gjson.GetBytes(body, "input")
if !input.Exists() || !input.IsArray() {
return body
}
arr := input.Array()
for i := len(arr) - 1; i >= 0; i-- {
role := arr[i].Get("role").String()
if !strings.EqualFold(role, "user") {
continue
}
// String content
content := arr[i].Get("content")
if content.Type == gjson.String {
old := content.String()
newText := prefix + old
out, err := sjson.SetBytes(body, "input."+strconv.Itoa(i)+".content", newText)
if err == nil {
return out
}
}
// Array content (multimodal)
if content.IsArray() {
parts := content.Array()
for j := 0; j < len(parts); j++ {
if parts[j].Get("type").String() == "text" || parts[j].Get("text").Exists() {
old := parts[j].Get("text").String()
newText := prefix + old
out, err := sjson.SetBytes(body, "input."+strconv.Itoa(i)+".content."+strconv.Itoa(j)+".text", newText)
if err == nil {
return out
}
}
}
}
return body
}
return body
}
func fileExists(rootDir, path string) bool {
target := path
if rootDir != "" && !filepath.IsAbs(path) {
target = filepath.Join(rootDir, path)
}
info, err := os.Stat(target)
return err == nil && !info.IsDir()
}
@@ -0,0 +1,184 @@
package middleware
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestAgenticHarnessMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
rootDir := t.TempDir()
tests := []struct {
name string
userAgent string
body string
expectMode string // "INITIALIZER", "CODING", or "" (passive)
expectInjected bool
}{
{
name: "Non-Agentic Client",
userAgent: "curl/7.64.1",
body: `{"messages": [{"role": "user", "content": "hi"}]}`,
expectMode: "",
expectInjected: false,
},
{
name: "Agentic Client - Fresh Conversation (Initializer)",
userAgent: "claude-cli/0.0.1",
body: `{"messages": [{"role": "system", "content": "sys"}, {"role": "user", "content": "create todo app"}]}`,
expectMode: "INITIALIZER", // Only 2 messages
expectInjected: true,
},
{
name: "Agentic Client - Short Conversation but Manual Override (Initializer)",
userAgent: "codex-cli",
body: `{"messages": [{"role": "user", "content": "setup environment"}]}`,
expectMode: "INITIALIZER",
expectInjected: true,
},
{
name: "Agentic Client - With Progress File (Coding)",
userAgent: "droid-cli",
body: `{"messages": [{"role": "user", "content": "I checked claude-progress.txt and..."}]}`,
expectMode: "CODING",
expectInjected: true,
},
{
name: "Agentic Client - With Feature List (Coding)",
userAgent: "claude-cli",
body: `{"messages": [{"role": "user", "content": "feature_list.json shows 2 features"}]}`,
expectMode: "CODING",
expectInjected: true,
},
{
name: "Agentic Client - Long Conversation/Passive",
userAgent: "claude-cli",
body: `{"messages": [{"role":"u","content":"1"},{"role":"a","content":"2"},{"role":"u","content":"3"},{"role":"a","content":"4"},{"role":"u","content":"5"}]}`, // 5 messages
expectMode: "", // Default passive because length >= 5 and no files mentioned
expectInjected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewBufferString(tt.body))
req.Header.Set("User-Agent", tt.userAgent)
req.Header.Set("Content-Type", "application/json")
c.Request = req
// Chain: Harness -> Verification Handler
handler := AgenticHarnessMiddlewareWithRootDir(rootDir)
// Execute middleware
handler(c)
// Check Header
actualMode := c.Writer.Header().Get("X-ProxyPilot-Harness-Mode")
assert.Equal(t, tt.expectMode, actualMode)
// Check Body Injection
// Since handler replaces request body, we read it back.
newBodyBytes, _ := io.ReadAll(c.Request.Body)
newBody := string(newBodyBytes)
if tt.expectInjected {
if tt.expectMode == "INITIALIZER" {
assert.Contains(t, newBody, "Initializer Agent")
assert.Contains(t, newBody, "feature_list.json")
}
if tt.expectMode == "CODING" {
assert.Contains(t, newBody, "Coding Agent")
assert.Contains(t, newBody, "incremental progress")
}
} else {
assert.NotContains(t, newBody, "Initializer Agent")
assert.NotContains(t, newBody, "Coding Agent")
}
})
}
}
func TestAgenticHarnessMiddleware_FilePresenceForcesCoding(t *testing.T) {
gin.SetMode(gin.TestMode)
rootDir := t.TempDir()
if err := os.WriteFile(filepath.Join(rootDir, "feature_list.json"), []byte(`[]`), 0o644); err != nil {
t.Fatalf("write feature_list.json: %v", err)
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
body := `{"messages": [{"role": "user", "content": "setup environment"}]}`
req, _ := http.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewBufferString(body))
req.Header.Set("User-Agent", "claude-cli")
req.Header.Set("Content-Type", "application/json")
c.Request = req
handler := AgenticHarnessMiddlewareWithRootDir(rootDir)
handler(c)
assert.Equal(t, "CODING", c.Writer.Header().Get("X-ProxyPilot-Harness-Mode"))
newBodyBytes, _ := io.ReadAll(c.Request.Body)
assert.Contains(t, string(newBodyBytes), "Coding Agent")
}
func TestAgenticHarnessMiddleware_ResponsesAPI(t *testing.T) {
gin.SetMode(gin.TestMode)
rootDir := t.TempDir()
tests := []struct {
name string
body string
expectContains string
}{
{
name: "Inject into instructions",
body: `{"instructions":"Follow the user","input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`,
expectContains: "instructions",
},
{
name: "Inject into input string",
body: `{"input":"hello world"}`,
expectContains: "hello world",
},
{
name: "Inject into input array",
body: `{"input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`,
expectContains: "SYSTEM NOTE",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req, _ := http.NewRequest(http.MethodPost, "/v1/responses", bytes.NewBufferString(tt.body))
req.Header.Set("User-Agent", "codex_cli_rs/0.75.0")
req.Header.Set("Content-Type", "application/json")
c.Request = req
handler := AgenticHarnessMiddlewareWithRootDir(rootDir)
handler(c)
assert.Equal(t, "INITIALIZER", c.Writer.Header().Get("X-ProxyPilot-Harness-Mode"))
newBodyBytes, _ := io.ReadAll(c.Request.Body)
newBody := string(newBodyBytes)
assert.Contains(t, newBody, "Initializer Agent")
assert.Contains(t, newBody, tt.expectContains)
})
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
package middleware
import (
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestAppendScaffoldStateChat(t *testing.T) {
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
out := appendScaffoldState("chat", body, "<proxypilot_state>ok</proxypilot_state>", 10000)
msgs := gjson.GetBytes(out, "messages").Array()
require.Len(t, msgs, 2)
require.Equal(t, "system", msgs[1].Get("role").String())
require.Contains(t, msgs[1].Get("content").String(), "proxypilot_state")
}
func TestAppendScaffoldStateResponses(t *testing.T) {
body := []byte(`{"input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`)
out := appendScaffoldState("responses", body, "<proxypilot_state>ok</proxypilot_state>", 10000)
input := gjson.GetBytes(out, "input").Array()
require.Len(t, input, 2)
require.Equal(t, "system", input[1].Get("role").String())
require.Contains(t, input[1].Get("content.0.text").String(), "proxypilot_state")
}
func TestSpecModeHeader(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/v1/responses", nil)
req.Header.Set("X-CLIProxyAPI-Spec-Mode", "true")
require.True(t, agenticSpecModeEnabled(req, []byte(`{}`)))
}
func TestAppendSystemBlockChat(t *testing.T) {
body := []byte(`{"messages":[{"role":"user","content":"hi"}]}`)
out, ok := appendSystemBlock("chat", body, "<proxypilot_anchor>ok</proxypilot_anchor>", 10000)
require.True(t, ok)
msgs := gjson.GetBytes(out, "messages").Array()
require.Len(t, msgs, 2)
require.Equal(t, "system", msgs[1].Get("role").String())
require.Contains(t, msgs[1].Get("content").String(), "proxypilot_anchor")
}
@@ -0,0 +1,68 @@
package middleware
import (
"bytes"
"compress/gzip"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// RequestDecompressionMiddleware transparently decompresses gzipped request bodies.
//
// Some clients (notably Factory Droid / OpenAI Node SDK) send requests with
// Content-Encoding: gzip. net/http does not automatically decode request bodies,
// so handlers that expect JSON will otherwise see compressed bytes and fail with
// confusing 400/no-body errors.
func RequestDecompressionMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
enc := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Encoding")))
if enc == "" || !strings.Contains(enc, "gzip") {
c.Next()
return
}
// Defensive cap against gzip bombs. Real-world CLI requests are far below this.
const maxDecompressedBytes = 128 << 20 // 128MiB
gzr, err := gzip.NewReader(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"error": gin.H{
"message": "invalid gzip request body",
"type": "invalid_request_error",
},
})
return
}
defer gzr.Close()
decoded, err := io.ReadAll(io.LimitReader(gzr, maxDecompressedBytes+1))
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"error": gin.H{
"message": "failed to decompress gzip request body",
"type": "invalid_request_error",
},
})
return
}
if int64(len(decoded)) > maxDecompressedBytes {
c.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{
"error": gin.H{
"message": "decompressed request body too large",
"type": "invalid_request_error",
},
})
return
}
c.Request.Body = io.NopCloser(bytes.NewReader(decoded))
c.Request.ContentLength = int64(len(decoded))
c.Request.Header.Del("Content-Encoding")
c.Next()
}
}
+34 -15
View File
@@ -6,6 +6,7 @@ package middleware
import (
"bytes"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -15,23 +16,22 @@ import (
// RequestLoggingMiddleware creates a Gin middleware that logs HTTP requests and responses.
// It captures detailed information about the request and response, including headers and body,
// and uses the provided RequestLogger to record this data. If logging is disabled in the
// logger, the middleware has minimal overhead.
// and uses the provided RequestLogger to record this data. When logging is disabled in the
// logger, it still captures data so that upstream errors can be persisted.
func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
shouldLog := false
if strings.HasPrefix(path, "/v1") {
shouldLog = true
}
if !shouldLog {
if logger == nil {
c.Next()
return
}
// Early return if logging is disabled (zero overhead)
if !logger.IsEnabled() {
if c.Request.Method == http.MethodGet {
c.Next()
return
}
path := c.Request.URL.Path
if !shouldLogRequest(path) {
c.Next()
return
}
@@ -47,6 +47,9 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc {
// Create response writer wrapper
wrapper := NewResponseWriterWrapper(c.Writer, logger, requestInfo)
if !logger.IsEnabled() {
wrapper.logOnErrorOnly = true
}
c.Writer = wrapper
// Process the request
@@ -95,9 +98,25 @@ func captureRequestInfo(c *gin.Context) (*RequestInfo, error) {
}
return &RequestInfo{
URL: url,
Method: method,
Headers: headers,
Body: body,
URL: url,
Method: method,
Headers: headers,
Body: body,
RequestID: logging.GetGinRequestID(c),
}, nil
}
// shouldLogRequest determines whether the request should be logged.
// It skips management endpoints to avoid leaking secrets but allows
// all other routes, including module-provided ones, to honor request-log.
func shouldLogRequest(path string) bool {
if strings.HasPrefix(path, "/v0/management") || strings.HasPrefix(path, "/management") {
return false
}
if strings.HasPrefix(path, "/api") {
return strings.HasPrefix(path, "/api/provider")
}
return true
}
+183 -110
View File
@@ -5,6 +5,7 @@ package middleware
import (
"bytes"
"net/http"
"strings"
"github.com/gin-gonic/gin"
@@ -14,25 +15,27 @@ import (
// RequestInfo holds essential details of an incoming HTTP request for logging purposes.
type RequestInfo struct {
URL string // URL is the request URL.
Method string // Method is the HTTP method (e.g., GET, POST).
Headers map[string][]string // Headers contains the request headers.
Body []byte // Body is the raw request body.
URL string // URL is the request URL.
Method string // Method is the HTTP method (e.g., GET, POST).
Headers map[string][]string // Headers contains the request headers.
Body []byte // Body is the raw request body.
RequestID string // RequestID is the unique identifier for the request.
}
// ResponseWriterWrapper wraps the standard gin.ResponseWriter to intercept and log response data.
// It is designed to handle both standard and streaming responses, ensuring that logging operations do not block the client response.
type ResponseWriterWrapper struct {
gin.ResponseWriter
body *bytes.Buffer // body is a buffer to store the response body for non-streaming responses.
isStreaming bool // isStreaming indicates whether the response is a streaming type (e.g., text/event-stream).
streamWriter logging.StreamingLogWriter // streamWriter is a writer for handling streaming log entries.
chunkChannel chan []byte // chunkChannel is a channel for asynchronously passing response chunks to the logger.
streamDone chan struct{} // streamDone signals when the streaming goroutine completes.
logger logging.RequestLogger // logger is the instance of the request logger service.
requestInfo *RequestInfo // requestInfo holds the details of the original request.
statusCode int // statusCode stores the HTTP status code of the response.
headers map[string][]string // headers stores the response headers.
body *bytes.Buffer // body is a buffer to store the response body for non-streaming responses.
isStreaming bool // isStreaming indicates whether the response is a streaming type (e.g., text/event-stream).
streamWriter logging.StreamingLogWriter // streamWriter is a writer for handling streaming log entries.
chunkChannel chan []byte // chunkChannel is a channel for asynchronously passing response chunks to the logger.
streamDone chan struct{} // streamDone signals when the streaming goroutine completes.
logger logging.RequestLogger // logger is the instance of the request logger service.
requestInfo *RequestInfo // requestInfo holds the details of the original request.
statusCode int // statusCode stores the HTTP status code of the response.
headers map[string][]string // headers stores the response headers.
logOnErrorOnly bool // logOnErrorOnly enables logging only when an error response is detected.
}
// NewResponseWriterWrapper creates and initializes a new ResponseWriterWrapper.
@@ -69,22 +72,64 @@ func (w *ResponseWriterWrapper) Write(data []byte) (int, error) {
n, err := w.ResponseWriter.Write(data)
// THEN: Handle logging based on response type
if w.isStreaming {
if w.isStreaming && w.chunkChannel != nil {
// For streaming responses: Send to async logging channel (non-blocking)
if w.chunkChannel != nil {
select {
case w.chunkChannel <- append([]byte(nil), data...): // Non-blocking send with copy
default: // Channel full, skip logging to avoid blocking
}
select {
case w.chunkChannel <- append([]byte(nil), data...): // Non-blocking send with copy
default: // Channel full, skip logging to avoid blocking
}
} else {
// For non-streaming responses: Buffer complete response
return n, err
}
if w.shouldBufferResponseBody() {
w.body.Write(data)
}
return n, err
}
func (w *ResponseWriterWrapper) shouldBufferResponseBody() bool {
if w.logger != nil && w.logger.IsEnabled() {
return true
}
if !w.logOnErrorOnly {
return false
}
status := w.statusCode
if status == 0 {
if statusWriter, ok := w.ResponseWriter.(interface{ Status() int }); ok && statusWriter != nil {
status = statusWriter.Status()
} else {
status = http.StatusOK
}
}
return status >= http.StatusBadRequest
}
// WriteString wraps the underlying ResponseWriter's WriteString method to capture response data.
// Some handlers (and fmt/io helpers) write via io.StringWriter; without this override, those writes
// bypass Write() and would be missing from request logs.
func (w *ResponseWriterWrapper) WriteString(data string) (int, error) {
w.ensureHeadersCaptured()
// CRITICAL: Write to client first (zero latency)
n, err := w.ResponseWriter.WriteString(data)
// THEN: Capture for logging
if w.isStreaming && w.chunkChannel != nil {
select {
case w.chunkChannel <- []byte(data):
default:
}
return n, err
}
if w.shouldBufferResponseBody() {
w.body.WriteString(data)
}
return n, err
}
// WriteHeader wraps the underlying ResponseWriter's WriteHeader method.
// It captures the status code, detects if the response is streaming based on the Content-Type header,
// and initializes the appropriate logging mechanism (standard or streaming).
@@ -105,6 +150,7 @@ func (w *ResponseWriterWrapper) WriteHeader(statusCode int) {
w.requestInfo.Method,
w.requestInfo.Headers,
w.requestInfo.Body,
w.requestInfo.RequestID,
)
if err == nil {
w.streamWriter = streamWriter
@@ -158,12 +204,16 @@ func (w *ResponseWriterWrapper) detectStreaming(contentType string) bool {
return true
}
// Check request body for streaming indicators
if w.requestInfo.Body != nil {
// If a concrete Content-Type is already set (e.g., application/json for error responses),
// treat it as non-streaming instead of inferring from the request payload.
if strings.TrimSpace(contentType) != "" {
return false
}
// Only fall back to request payload hints when Content-Type is not set yet.
if w.requestInfo != nil && len(w.requestInfo.Body) > 0 {
bodyStr := string(w.requestInfo.Body)
if strings.Contains(bodyStr, `"stream": true`) || strings.Contains(bodyStr, `"stream":true`) {
return true
}
return strings.Contains(bodyStr, `"stream": true`) || strings.Contains(bodyStr, `"stream":true`)
}
return false
@@ -192,12 +242,34 @@ func (w *ResponseWriterWrapper) processStreamingChunks(done chan struct{}) {
// For non-streaming responses, it logs the complete request and response details,
// including any API-specific request/response data stored in the Gin context.
func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
if !w.logger.IsEnabled() {
if w.logger == nil {
return nil
}
if w.isStreaming {
// Close streaming channel and writer
finalStatusCode := w.statusCode
if finalStatusCode == 0 {
if statusWriter, ok := w.ResponseWriter.(interface{ Status() int }); ok {
finalStatusCode = statusWriter.Status()
} else {
finalStatusCode = 200
}
}
var slicesAPIResponseError []*interfaces.ErrorMessage
apiResponseError, isExist := c.Get("API_RESPONSE_ERROR")
if isExist {
if apiErrors, ok := apiResponseError.([]*interfaces.ErrorMessage); ok {
slicesAPIResponseError = apiErrors
}
}
hasAPIError := len(slicesAPIResponseError) > 0 || finalStatusCode >= http.StatusBadRequest
forceLog := w.logOnErrorOnly && hasAPIError && !w.logger.IsEnabled()
if !w.logger.IsEnabled() && !forceLog {
return nil
}
if w.isStreaming && w.streamWriter != nil {
if w.chunkChannel != nil {
close(w.chunkChannel)
w.chunkChannel = nil
@@ -208,102 +280,103 @@ func (w *ResponseWriterWrapper) Finalize(c *gin.Context) error {
w.streamDone = nil
}
if w.streamWriter != nil {
err := w.streamWriter.Close()
// Write API Request and Response to the streaming log before closing
apiRequest := w.extractAPIRequest(c)
if len(apiRequest) > 0 {
_ = w.streamWriter.WriteAPIRequest(apiRequest)
}
apiResponse := w.extractAPIResponse(c)
if len(apiResponse) > 0 {
_ = w.streamWriter.WriteAPIResponse(apiResponse)
}
if err := w.streamWriter.Close(); err != nil {
w.streamWriter = nil
return err
}
} else {
// Capture final status code and headers if not already captured
finalStatusCode := w.statusCode
if finalStatusCode == 0 {
// Get status from underlying ResponseWriter if available
if statusWriter, ok := w.ResponseWriter.(interface{ Status() int }); ok {
finalStatusCode = statusWriter.Status()
} else {
finalStatusCode = 200 // Default
}
}
w.streamWriter = nil
return nil
}
// Ensure we have the latest headers before finalizing
w.ensureHeadersCaptured()
return w.logRequest(finalStatusCode, w.cloneHeaders(), w.body.Bytes(), w.extractAPIRequest(c), w.extractAPIResponse(c), slicesAPIResponseError, forceLog)
}
// Use the captured headers as the final headers
finalHeaders := make(map[string][]string)
for key, values := range w.headers {
// Make a copy of the values slice to avoid reference issues
headerValues := make([]string, len(values))
copy(headerValues, values)
finalHeaders[key] = headerValues
}
func (w *ResponseWriterWrapper) cloneHeaders() map[string][]string {
w.ensureHeadersCaptured()
var apiRequestBody []byte
apiRequest, isExist := c.Get("API_REQUEST")
if isExist {
var ok bool
apiRequestBody, ok = apiRequest.([]byte)
if !ok {
apiRequestBody = nil
}
}
finalHeaders := make(map[string][]string, len(w.headers))
for key, values := range w.headers {
headerValues := make([]string, len(values))
copy(headerValues, values)
finalHeaders[key] = headerValues
}
var apiResponseBody []byte
apiResponse, isExist := c.Get("API_RESPONSE")
if isExist {
var ok bool
apiResponseBody, ok = apiResponse.([]byte)
if !ok {
apiResponseBody = nil
}
}
return finalHeaders
}
var slicesAPIResponseError []*interfaces.ErrorMessage
apiResponseError, isExist := c.Get("API_RESPONSE_ERROR")
if isExist {
var ok bool
slicesAPIResponseError, ok = apiResponseError.([]*interfaces.ErrorMessage)
if !ok {
slicesAPIResponseError = nil
}
}
func (w *ResponseWriterWrapper) extractAPIRequest(c *gin.Context) []byte {
apiRequest, isExist := c.Get("API_REQUEST")
if !isExist {
return nil
}
data, ok := apiRequest.([]byte)
if !ok || len(data) == 0 {
return nil
}
return data
}
// Log complete non-streaming response
return w.logger.LogRequest(
func (w *ResponseWriterWrapper) extractAPIResponse(c *gin.Context) []byte {
apiResponse, isExist := c.Get("API_RESPONSE")
if !isExist {
return nil
}
data, ok := apiResponse.([]byte)
if !ok || len(data) == 0 {
return nil
}
return data
}
func (w *ResponseWriterWrapper) logRequest(statusCode int, headers map[string][]string, body []byte, apiRequestBody, apiResponseBody []byte, apiResponseErrors []*interfaces.ErrorMessage, forceLog bool) error {
if w.requestInfo == nil {
return nil
}
var requestBody []byte
if len(w.requestInfo.Body) > 0 {
requestBody = w.requestInfo.Body
}
if loggerWithOptions, ok := w.logger.(interface {
LogRequestWithOptions(string, string, map[string][]string, []byte, int, map[string][]string, []byte, []byte, []byte, []*interfaces.ErrorMessage, bool, string) error
}); ok {
return loggerWithOptions.LogRequestWithOptions(
w.requestInfo.URL,
w.requestInfo.Method,
w.requestInfo.Headers,
w.requestInfo.Body,
finalStatusCode,
finalHeaders,
w.body.Bytes(),
requestBody,
statusCode,
headers,
body,
apiRequestBody,
apiResponseBody,
slicesAPIResponseError,
apiResponseErrors,
forceLog,
w.requestInfo.RequestID,
)
}
return nil
}
// Status returns the HTTP response status code captured by the wrapper.
// It defaults to 200 if WriteHeader has not been called.
func (w *ResponseWriterWrapper) Status() int {
if w.statusCode == 0 {
return 200 // Default status code
}
return w.statusCode
}
// Size returns the size of the response body in bytes for non-streaming responses.
// For streaming responses, it returns -1, as the total size is unknown.
func (w *ResponseWriterWrapper) Size() int {
if w.isStreaming {
return -1 // Unknown size for streaming responses
}
return w.body.Len()
}
// Written returns true if the response header has been written (i.e., a status code has been set).
func (w *ResponseWriterWrapper) Written() bool {
return w.statusCode != 0
return w.logger.LogRequest(
w.requestInfo.URL,
w.requestInfo.Method,
w.requestInfo.Headers,
requestBody,
statusCode,
headers,
body,
apiRequestBody,
apiResponseBody,
apiResponseErrors,
w.requestInfo.RequestID,
)
}
+114
View File
@@ -0,0 +1,114 @@
package api
import (
"io"
"net/http"
"os"
"path"
"strings"
"github.com/gin-gonic/gin"
ppassets "github.com/router-for-me/CLIProxyAPI/v6/cmd/proxypilotui/assets"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
)
func (s *Server) registerProxyPilotDashboardRoutes() {
if s == nil || s.engine == nil {
return
}
s.engine.GET("/proxypilot", func(c *gin.Context) {
c.Redirect(http.StatusTemporaryRedirect, "/proxypilot.html")
})
s.engine.GET("/proxypilot.html", s.serveProxyPilotDashboard)
s.engine.GET("/assets/*filepath", s.serveProxyPilotAsset)
s.engine.GET("/vite.svg", s.serveProxyPilotViteIcon)
}
func (s *Server) serveProxyPilotDashboard(c *gin.Context) {
if !isLocalClient(c) {
c.AbortWithStatus(http.StatusForbidden)
return
}
index, err := fsReadFile("index.html")
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
html := string(index)
key := strings.TrimSpace(getManagementKey())
if key != "" && s.managementRoutesEnabled.Load() {
meta := `<meta name="pp-mgmt-key" content="` + escapeAttr(key) + `">`
html = strings.Replace(html, "</head>", meta+"</head>", 1)
}
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, html)
}
func (s *Server) serveProxyPilotAsset(c *gin.Context) {
if !isLocalClient(c) {
c.AbortWithStatus(http.StatusForbidden)
return
}
fp := strings.TrimPrefix(c.Param("filepath"), "/")
if fp == "" {
c.AbortWithStatus(http.StatusNotFound)
return
}
name := path.Clean("assets/" + fp)
data, err := fsReadFile(name)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
writeAssetResponse(c, name, data)
}
func (s *Server) serveProxyPilotViteIcon(c *gin.Context) {
if !isLocalClient(c) {
c.AbortWithStatus(http.StatusForbidden)
return
}
data, err := fsReadFile("vite.svg")
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
writeAssetResponse(c, "vite.svg", data)
}
func writeAssetResponse(c *gin.Context, name string, data []byte) {
ext := strings.TrimPrefix(path.Ext(name), ".")
if mt := misc.MimeTypes[strings.ToLower(ext)]; mt != "" {
c.Header("Content-Type", mt)
} else {
c.Header("Content-Type", "application/octet-stream")
}
c.Header("Cache-Control", "public, max-age=600")
c.Writer.WriteHeader(http.StatusOK)
_, _ = c.Writer.Write(data)
}
func fsReadFile(name string) ([]byte, error) {
f, err := ppassets.FS.Open(name)
if err != nil {
return nil, err
}
defer func() { _ = f.Close() }()
return io.ReadAll(f)
}
func isLocalClient(c *gin.Context) bool {
clientIP := c.ClientIP()
return clientIP == "127.0.0.1" || clientIP == "::1"
}
func getManagementKey() string {
return strings.TrimSpace(os.Getenv("MANAGEMENT_PASSWORD"))
}
func escapeAttr(s string) string {
return strings.ReplaceAll(strings.TrimSpace(s), `"`, "")
}
+1010 -916
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
package api
import (
"os"
"path/filepath"
"testing"
gin "github.com/gin-gonic/gin"
proxyconfig "github.com/router-for-me/CLIProxyAPI/v6/internal/config"
sdkaccess "github.com/router-for-me/CLIProxyAPI/v6/sdk/access"
"github.com/router-for-me/CLIProxyAPI/v6/sdk/cliproxy/auth"
sdkconfig "github.com/router-for-me/CLIProxyAPI/v6/sdk/config"
)
func newTestServer(t *testing.T) *Server {
t.Helper()
gin.SetMode(gin.TestMode)
tmpDir := t.TempDir()
authDir := filepath.Join(tmpDir, "auth")
if err := os.MkdirAll(authDir, 0o700); err != nil {
t.Fatalf("failed to create auth dir: %v", err)
}
cfg := &proxyconfig.Config{
SDKConfig: sdkconfig.SDKConfig{
APIKeys: []string{"test-key"},
},
Port: 0,
AuthDir: authDir,
Debug: true,
LoggingToFile: false,
UsageStatisticsEnabled: false,
}
authManager := auth.NewManager(nil, nil, nil)
accessManager := sdkaccess.NewManager()
configPath := filepath.Join(tmpDir, "config.yaml")
return NewServer(cfg, authManager, accessManager, configPath)
}
+11
View File
@@ -242,6 +242,11 @@ func (s *OAuthServer) handleSuccess(w http.ResponseWriter, r *http.Request) {
platformURL = "https://console.anthropic.com/"
}
// Validate platformURL to prevent XSS - only allow http/https URLs
if !isValidURL(platformURL) {
platformURL = "https://console.anthropic.com/"
}
// Generate success page HTML with dynamic content
successHTML := s.generateSuccessHTML(setupRequired, platformURL)
@@ -251,6 +256,12 @@ func (s *OAuthServer) handleSuccess(w http.ResponseWriter, r *http.Request) {
}
}
// isValidURL checks if the URL is a valid http/https URL to prevent XSS
func isValidURL(urlStr string) bool {
urlStr = strings.TrimSpace(urlStr)
return strings.HasPrefix(urlStr, "https://") || strings.HasPrefix(urlStr, "http://")
}
// generateSuccessHTML creates the HTML content for the success page.
// It customizes the page based on whether additional setup is required
// and includes a link to the platform.
+11
View File
@@ -239,6 +239,11 @@ func (s *OAuthServer) handleSuccess(w http.ResponseWriter, r *http.Request) {
platformURL = "https://platform.openai.com"
}
// Validate platformURL to prevent XSS - only allow http/https URLs
if !isValidURL(platformURL) {
platformURL = "https://platform.openai.com"
}
// Generate success page HTML with dynamic content
successHTML := s.generateSuccessHTML(setupRequired, platformURL)
@@ -248,6 +253,12 @@ func (s *OAuthServer) handleSuccess(w http.ResponseWriter, r *http.Request) {
}
}
// isValidURL checks if the URL is a valid http/https URL to prevent XSS
func isValidURL(urlStr string) bool {
urlStr = strings.TrimSpace(urlStr)
return strings.HasPrefix(urlStr, "https://") || strings.HasPrefix(urlStr, "http://")
}
// generateSuccessHTML creates the HTML content for the success page.
// It customizes the page based on whether additional setup is required
// and includes a link to the platform.
-26
View File
@@ -1,26 +0,0 @@
// Package empty provides a no-operation token storage implementation.
// This package is used when authentication tokens are not required or when
// using API key-based authentication instead of OAuth tokens for any provider.
package empty
// EmptyStorage is a no-operation implementation of the TokenStorage interface.
// It provides empty implementations for scenarios where token storage is not needed,
// such as when using API keys instead of OAuth tokens for authentication.
type EmptyStorage struct {
// Type indicates the authentication provider type, always "empty" for this implementation.
Type string `json:"type"`
}
// SaveTokenToFile is a no-operation implementation that always succeeds.
// This method satisfies the TokenStorage interface but performs no actual file operations
// since empty storage doesn't require persistent token data.
//
// Parameters:
// - _: The file path parameter is ignored in this implementation
//
// Returns:
// - error: Always returns nil (no error)
func (ts *EmptyStorage) SaveTokenToFile(_ string) error {
ts.Type = "empty"
return nil
}
+93 -20
View File
@@ -18,6 +18,7 @@ import (
"github.com/router-for-me/CLIProxyAPI/v6/internal/auth/codex"
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
"github.com/tidwall/gjson"
@@ -46,6 +47,12 @@ var (
type GeminiAuth struct {
}
// WebLoginOptions customizes the interactive OAuth flow.
type WebLoginOptions struct {
NoBrowser bool
Prompt func(string) (string, error)
}
// NewGeminiAuth creates a new instance of GeminiAuth.
func NewGeminiAuth() *GeminiAuth {
return &GeminiAuth{}
@@ -59,12 +66,12 @@ func NewGeminiAuth() *GeminiAuth {
// - ctx: The context for the HTTP client
// - ts: The Gemini token storage containing authentication tokens
// - cfg: The configuration containing proxy settings
// - noBrowser: Optional parameter to disable browser opening
// - opts: Optional parameters to customize browser and prompt behavior
//
// Returns:
// - *http.Client: An HTTP client configured with authentication
// - error: An error if the client configuration fails, nil otherwise
func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiTokenStorage, cfg *config.Config, noBrowser ...bool) (*http.Client, error) {
func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiTokenStorage, cfg *config.Config, opts *WebLoginOptions) (*http.Client, error) {
// Configure proxy settings for the HTTP client if a proxy URL is provided.
proxyURL, err := url.Parse(cfg.ProxyURL)
if err == nil {
@@ -76,7 +83,8 @@ func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiToken
auth := &proxy.Auth{User: username, Password: password}
dialer, errSOCKS5 := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct)
if errSOCKS5 != nil {
log.Fatalf("create SOCKS5 dialer failed: %v", errSOCKS5)
log.Errorf("create SOCKS5 dialer failed: %v", errSOCKS5)
return nil, fmt.Errorf("create SOCKS5 dialer failed: %w", errSOCKS5)
}
transport = &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
@@ -108,7 +116,7 @@ func (g *GeminiAuth) GetAuthenticatedClient(ctx context.Context, ts *GeminiToken
// If no token is found in storage, initiate the web-based OAuth flow.
if ts.Token == nil {
fmt.Printf("Could not load token from file, starting OAuth flow.\n")
token, err = g.getTokenFromWeb(ctx, conf, noBrowser...)
token, err = g.getTokenFromWeb(ctx, conf, opts)
if err != nil {
return nil, fmt.Errorf("failed to get token from web: %w", err)
}
@@ -204,15 +212,15 @@ func (g *GeminiAuth) createTokenStorage(ctx context.Context, config *oauth2.Conf
// Parameters:
// - ctx: The context for the HTTP client
// - config: The OAuth2 configuration
// - noBrowser: Optional parameter to disable browser opening
// - opts: Optional parameters to customize browser and prompt behavior
//
// Returns:
// - *oauth2.Token: The OAuth2 token obtained from the authorization flow
// - error: An error if the token acquisition fails, nil otherwise
func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config, noBrowser ...bool) (*oauth2.Token, error) {
func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config, opts *WebLoginOptions) (*oauth2.Token, error) {
// Use a channel to pass the authorization code from the HTTP handler to the main function.
codeChan := make(chan string)
errChan := make(chan error)
codeChan := make(chan string, 1)
errChan := make(chan error, 1)
// Create a new HTTP server with its own multiplexer.
mux := http.NewServeMux()
@@ -222,30 +230,48 @@ func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config,
mux.HandleFunc("/oauth2callback", func(w http.ResponseWriter, r *http.Request) {
if err := r.URL.Query().Get("error"); err != "" {
_, _ = fmt.Fprintf(w, "Authentication failed: %s", err)
errChan <- fmt.Errorf("authentication failed via callback: %s", err)
select {
case errChan <- fmt.Errorf("authentication failed via callback: %s", err):
default:
}
return
}
code := r.URL.Query().Get("code")
if code == "" {
_, _ = fmt.Fprint(w, "Authentication failed: code not found.")
errChan <- fmt.Errorf("code not found in callback")
select {
case errChan <- fmt.Errorf("code not found in callback"):
default:
}
return
}
_, _ = fmt.Fprint(w, "<html><body><h1>Authentication successful!</h1><p>You can close this window.</p></body></html>")
codeChan <- code
select {
case codeChan <- code:
default:
}
})
// Start the server in a goroutine.
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("ListenAndServe(): %v", err)
log.Errorf("ListenAndServe(): %v", err)
select {
case errChan <- err:
default:
}
}
}()
// Open the authorization URL in the user's browser.
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"))
if len(noBrowser) == 1 && !noBrowser[0] {
noBrowser := false
if opts != nil {
noBrowser = opts.NoBrowser
}
if !noBrowser {
fmt.Println("Opening browser for authentication...")
// Check if browser is available
@@ -276,13 +302,60 @@ func (g *GeminiAuth) getTokenFromWeb(ctx context.Context, config *oauth2.Config,
// Wait for the authorization code or an error.
var authCode string
select {
case code := <-codeChan:
authCode = code
case err := <-errChan:
return nil, err
case <-time.After(5 * time.Minute): // Timeout
return nil, fmt.Errorf("oauth flow timed out")
timeoutTimer := time.NewTimer(5 * time.Minute)
defer timeoutTimer.Stop()
var manualPromptTimer *time.Timer
var manualPromptC <-chan time.Time
if opts != nil && opts.Prompt != nil {
manualPromptTimer = time.NewTimer(15 * time.Second)
manualPromptC = manualPromptTimer.C
defer manualPromptTimer.Stop()
}
waitForCallback:
for {
select {
case code := <-codeChan:
authCode = code
break waitForCallback
case err := <-errChan:
return nil, err
case <-manualPromptC:
manualPromptC = nil
if manualPromptTimer != nil {
manualPromptTimer.Stop()
}
select {
case code := <-codeChan:
authCode = code
break waitForCallback
case err := <-errChan:
return nil, err
default:
}
input, err := opts.Prompt("Paste the Gemini callback URL (or press Enter to keep waiting): ")
if err != nil {
return nil, err
}
parsed, err := misc.ParseOAuthCallback(input)
if err != nil {
return nil, err
}
if parsed == nil {
continue
}
if parsed.Error != "" {
return nil, fmt.Errorf("authentication failed via callback: %s", parsed.Error)
}
if parsed.Code == "" {
return nil, fmt.Errorf("code not found in callback")
}
authCode = parsed.Code
break waitForCallback
case <-timeoutTimer.C:
return nil, fmt.Errorf("oauth flow timed out")
}
}
// Shutdown the server.
+18
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
log "github.com/sirupsen/logrus"
@@ -67,3 +68,20 @@ func (ts *GeminiTokenStorage) SaveTokenToFile(authFilePath string) error {
}
return nil
}
// CredentialFileName returns the filename used to persist Gemini CLI credentials.
// When projectID represents multiple projects (comma-separated or literal ALL),
// the suffix is normalized to "all" and a "gemini-" prefix is enforced to keep
// web and CLI generated files consistent.
func CredentialFileName(email, projectID string, includeProviderPrefix bool) string {
email = strings.TrimSpace(email)
project := strings.TrimSpace(projectID)
if strings.EqualFold(project, "all") || strings.Contains(project, ",") {
return fmt.Sprintf("gemini-%s-all.json", email)
}
prefix := ""
if includeProviderPrefix {
prefix = "gemini-"
}
return fmt.Sprintf("%s%s-%s.json", prefix, email, project)
}
+99
View File
@@ -0,0 +1,99 @@
package iflow
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// NormalizeCookie normalizes raw cookie strings for iFlow authentication flows.
func NormalizeCookie(raw string) (string, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return "", fmt.Errorf("cookie cannot be empty")
}
combined := strings.Join(strings.Fields(trimmed), " ")
if !strings.HasSuffix(combined, ";") {
combined += ";"
}
if !strings.Contains(combined, "BXAuth=") {
return "", fmt.Errorf("cookie missing BXAuth field")
}
return combined, nil
}
// SanitizeIFlowFileName normalizes user identifiers for safe filename usage.
func SanitizeIFlowFileName(raw string) string {
if raw == "" {
return ""
}
cleanEmail := strings.ReplaceAll(raw, "*", "x")
var result strings.Builder
for _, r := range cleanEmail {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '@' || r == '.' || r == '-' {
result.WriteRune(r)
}
}
return strings.TrimSpace(result.String())
}
// ExtractBXAuth extracts the BXAuth value from a cookie string.
func ExtractBXAuth(cookie string) string {
parts := strings.Split(cookie, ";")
for _, part := range parts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "BXAuth=") {
return strings.TrimPrefix(part, "BXAuth=")
}
}
return ""
}
// CheckDuplicateBXAuth checks if the given BXAuth value already exists in any iflow auth file.
// Returns the path of the existing file if found, empty string otherwise.
func CheckDuplicateBXAuth(authDir, bxAuth string) (string, error) {
if bxAuth == "" {
return "", nil
}
entries, err := os.ReadDir(authDir)
if err != nil {
if os.IsNotExist(err) {
return "", nil
}
return "", fmt.Errorf("read auth dir failed: %w", err)
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
if !strings.HasPrefix(name, "iflow-") || !strings.HasSuffix(name, ".json") {
continue
}
filePath := filepath.Join(authDir, name)
data, err := os.ReadFile(filePath)
if err != nil {
continue
}
var tokenData struct {
Cookie string `json:"cookie"`
}
if err := json.Unmarshal(data, &tokenData); err != nil {
continue
}
existingBXAuth := ExtractBXAuth(tokenData.Cookie)
if existingBXAuth != "" && existingBXAuth == bxAuth {
return filePath, nil
}
}
return "", nil
}
+264 -5
View File
@@ -1,6 +1,7 @@
package iflow
import (
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
@@ -8,6 +9,7 @@ import (
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
@@ -23,11 +25,25 @@ const (
iFlowUserInfoEndpoint = "https://iflow.cn/api/oauth/getUserInfo"
iFlowSuccessRedirectURL = "https://iflow.cn/oauth/success"
// Cookie authentication endpoints
iFlowAPIKeyEndpoint = "https://platform.iflow.cn/api/openapi/apikey"
// Client credentials provided by iFlow for the Code Assist integration.
iFlowOAuthClientID = "10009311001"
iFlowOAuthClientSecret = "4Z3YjXycVsQvyGF1etiNlIBB4RsqSDtW"
iFlowOAuthClientID = "10009311001"
// Default client secret (can be overridden via IFLOW_CLIENT_SECRET env var)
defaultIFlowClientSecret = "4Z3YjXycVsQvyGF1etiNlIBB4RsqSDtW"
)
// getIFlowClientSecret returns the iFlow OAuth client secret.
// It first checks the IFLOW_CLIENT_SECRET environment variable,
// falling back to the default value if not set.
func getIFlowClientSecret() string {
if secret := os.Getenv("IFLOW_CLIENT_SECRET"); secret != "" {
return secret
}
return defaultIFlowClientSecret
}
// DefaultAPIBaseURL is the canonical chat completions endpoint.
const DefaultAPIBaseURL = "https://apis.iflow.cn/v1"
@@ -68,7 +84,7 @@ func (ia *IFlowAuth) ExchangeCodeForTokens(ctx context.Context, code, redirectUR
form.Set("code", code)
form.Set("redirect_uri", redirectURI)
form.Set("client_id", iFlowOAuthClientID)
form.Set("client_secret", iFlowOAuthClientSecret)
form.Set("client_secret", getIFlowClientSecret())
req, err := ia.newTokenRequest(ctx, form)
if err != nil {
@@ -84,7 +100,7 @@ func (ia *IFlowAuth) RefreshTokens(ctx context.Context, refreshToken string) (*I
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
form.Set("client_id", iFlowOAuthClientID)
form.Set("client_secret", iFlowOAuthClientSecret)
form.Set("client_secret", getIFlowClientSecret())
req, err := ia.newTokenRequest(ctx, form)
if err != nil {
@@ -100,7 +116,7 @@ func (ia *IFlowAuth) newTokenRequest(ctx context.Context, form url.Values) (*htt
return nil, fmt.Errorf("iflow token: create request failed: %w", err)
}
basic := base64.StdEncoding.EncodeToString([]byte(iFlowOAuthClientID + ":" + iFlowOAuthClientSecret))
basic := base64.StdEncoding.EncodeToString([]byte(iFlowOAuthClientID + ":" + getIFlowClientSecret()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Basic "+basic)
@@ -261,6 +277,7 @@ type IFlowTokenData struct {
Expire string
APIKey string
Email string
Cookie string
}
// userInfoResponse represents the structure returned by the user info endpoint.
@@ -274,3 +291,245 @@ type userInfoData struct {
Email string `json:"email"`
Phone string `json:"phone"`
}
// iFlowAPIKeyResponse represents the response from the API key endpoint
type iFlowAPIKeyResponse struct {
Success bool `json:"success"`
Code string `json:"code"`
Message string `json:"message"`
Data iFlowKeyData `json:"data"`
Extra interface{} `json:"extra"`
}
// iFlowKeyData contains the API key information
type iFlowKeyData struct {
HasExpired bool `json:"hasExpired"`
ExpireTime string `json:"expireTime"`
Name string `json:"name"`
APIKey string `json:"apiKey"`
APIKeyMask string `json:"apiKeyMask"`
}
// iFlowRefreshRequest represents the request body for refreshing API key
type iFlowRefreshRequest struct {
Name string `json:"name"`
}
// AuthenticateWithCookie performs authentication using browser cookies
func (ia *IFlowAuth) AuthenticateWithCookie(ctx context.Context, cookie string) (*IFlowTokenData, error) {
if strings.TrimSpace(cookie) == "" {
return nil, fmt.Errorf("iflow cookie authentication: cookie is empty")
}
// First, get initial API key information using GET request to obtain the name
keyInfo, err := ia.fetchAPIKeyInfo(ctx, cookie)
if err != nil {
return nil, fmt.Errorf("iflow cookie authentication: fetch initial API key info failed: %w", err)
}
// Refresh the API key using POST request
refreshedKeyInfo, err := ia.RefreshAPIKey(ctx, cookie, keyInfo.Name)
if err != nil {
return nil, fmt.Errorf("iflow cookie authentication: refresh API key failed: %w", err)
}
// Convert to token data format using refreshed key
data := &IFlowTokenData{
APIKey: refreshedKeyInfo.APIKey,
Expire: refreshedKeyInfo.ExpireTime,
Email: refreshedKeyInfo.Name,
Cookie: cookie,
}
return data, nil
}
// fetchAPIKeyInfo retrieves API key information using GET request with cookie
func (ia *IFlowAuth) fetchAPIKeyInfo(ctx context.Context, cookie string) (*iFlowKeyData, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, iFlowAPIKeyEndpoint, nil)
if err != nil {
return nil, fmt.Errorf("iflow cookie: create GET request failed: %w", err)
}
// Set cookie and other headers to mimic browser
req.Header.Set("Cookie", cookie)
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Sec-Fetch-Dest", "empty")
req.Header.Set("Sec-Fetch-Mode", "cors")
req.Header.Set("Sec-Fetch-Site", "same-origin")
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow cookie: GET request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Handle gzip compression
var reader io.Reader = resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow cookie: create gzip reader failed: %w", err)
}
defer func() { _ = gzipReader.Close() }()
reader = gzipReader
}
body, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("iflow cookie: read GET response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow cookie GET request failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow cookie: GET request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var keyResp iFlowAPIKeyResponse
if err = json.Unmarshal(body, &keyResp); err != nil {
return nil, fmt.Errorf("iflow cookie: decode GET response failed: %w", err)
}
if !keyResp.Success {
return nil, fmt.Errorf("iflow cookie: GET request not successful: %s", keyResp.Message)
}
// Handle initial response where apiKey field might be apiKeyMask
if keyResp.Data.APIKey == "" && keyResp.Data.APIKeyMask != "" {
keyResp.Data.APIKey = keyResp.Data.APIKeyMask
}
return &keyResp.Data, nil
}
// RefreshAPIKey refreshes the API key using POST request
func (ia *IFlowAuth) RefreshAPIKey(ctx context.Context, cookie, name string) (*iFlowKeyData, error) {
if strings.TrimSpace(cookie) == "" {
return nil, fmt.Errorf("iflow cookie refresh: cookie is empty")
}
if strings.TrimSpace(name) == "" {
return nil, fmt.Errorf("iflow cookie refresh: name is empty")
}
// Prepare request body
refreshReq := iFlowRefreshRequest{
Name: name,
}
bodyBytes, err := json.Marshal(refreshReq)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: marshal request failed: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, iFlowAPIKeyEndpoint, strings.NewReader(string(bodyBytes)))
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: create POST request failed: %w", err)
}
// Set cookie and other headers to mimic browser
req.Header.Set("Cookie", cookie)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/plain, */*")
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Origin", "https://platform.iflow.cn")
req.Header.Set("Referer", "https://platform.iflow.cn/")
resp, err := ia.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: POST request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Handle gzip compression
var reader io.Reader = resp.Body
if resp.Header.Get("Content-Encoding") == "gzip" {
gzipReader, err := gzip.NewReader(resp.Body)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: create gzip reader failed: %w", err)
}
defer func() { _ = gzipReader.Close() }()
reader = gzipReader
}
body, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("iflow cookie refresh: read POST response failed: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("iflow cookie POST request failed: status=%d body=%s", resp.StatusCode, string(body))
return nil, fmt.Errorf("iflow cookie refresh: POST request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
var keyResp iFlowAPIKeyResponse
if err = json.Unmarshal(body, &keyResp); err != nil {
return nil, fmt.Errorf("iflow cookie refresh: decode POST response failed: %w", err)
}
if !keyResp.Success {
return nil, fmt.Errorf("iflow cookie refresh: POST request not successful: %s", keyResp.Message)
}
return &keyResp.Data, nil
}
// ShouldRefreshAPIKey checks if the API key needs to be refreshed (within 2 days of expiry)
func ShouldRefreshAPIKey(expireTime string) (bool, time.Duration, error) {
if strings.TrimSpace(expireTime) == "" {
return false, 0, fmt.Errorf("iflow cookie: expire time is empty")
}
expire, err := time.Parse("2006-01-02 15:04", expireTime)
if err != nil {
return false, 0, fmt.Errorf("iflow cookie: parse expire time failed: %w", err)
}
now := time.Now()
twoDaysFromNow := now.Add(48 * time.Hour)
needsRefresh := expire.Before(twoDaysFromNow)
timeUntilExpiry := expire.Sub(now)
return needsRefresh, timeUntilExpiry, nil
}
// CreateCookieTokenStorage converts cookie-based token data into persistence storage
func (ia *IFlowAuth) CreateCookieTokenStorage(data *IFlowTokenData) *IFlowTokenStorage {
if data == nil {
return nil
}
// Only save the BXAuth field from the cookie
bxAuth := ExtractBXAuth(data.Cookie)
cookieToSave := ""
if bxAuth != "" {
cookieToSave = "BXAuth=" + bxAuth + ";"
}
return &IFlowTokenStorage{
APIKey: data.APIKey,
Email: data.Email,
Expire: data.Expire,
Cookie: cookieToSave,
LastRefresh: time.Now().Format(time.RFC3339),
Type: "iflow",
}
}
// UpdateCookieTokenStorage updates the persisted token storage with refreshed API key data
func (ia *IFlowAuth) UpdateCookieTokenStorage(storage *IFlowTokenStorage, keyData *iFlowKeyData) {
if storage == nil || keyData == nil {
return
}
storage.APIKey = keyData.APIKey
storage.Expire = keyData.ExpireTime
storage.LastRefresh = time.Now().Format(time.RFC3339)
}
+1
View File
@@ -19,6 +19,7 @@ type IFlowTokenStorage struct {
Email string `json:"email"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Cookie string `json:"cookie"`
Type string `json:"type"`
}
+305
View File
@@ -0,0 +1,305 @@
// Package kiro provides authentication functionality for AWS CodeWhisperer (Kiro) API.
// It includes interfaces and implementations for token storage and authentication methods.
package kiro
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
)
// PKCECodes holds PKCE verification codes for OAuth2 PKCE flow
type PKCECodes struct {
// CodeVerifier is the cryptographically random string used to correlate
// the authorization request to the token request
CodeVerifier string `json:"code_verifier"`
// CodeChallenge is the SHA256 hash of the code verifier, base64url-encoded
CodeChallenge string `json:"code_challenge"`
}
// KiroTokenData holds OAuth token information from AWS CodeWhisperer (Kiro)
type KiroTokenData struct {
// AccessToken is the OAuth2 access token for API access
AccessToken string `json:"accessToken"`
// RefreshToken is used to obtain new access tokens
RefreshToken string `json:"refreshToken"`
// ProfileArn is the AWS CodeWhisperer profile ARN
ProfileArn string `json:"profileArn"`
// ExpiresAt is the timestamp when the token expires
ExpiresAt string `json:"expiresAt"`
// AuthMethod indicates the authentication method used (e.g., "builder-id", "social")
AuthMethod string `json:"authMethod"`
// Provider indicates the OAuth provider (e.g., "AWS", "Google")
Provider string `json:"provider"`
// ClientID is the OIDC client ID (needed for token refresh)
ClientID string `json:"clientId,omitempty"`
// ClientSecret is the OIDC client secret (needed for token refresh)
ClientSecret string `json:"clientSecret,omitempty"`
// Email is the user's email address (used for file naming)
Email string `json:"email,omitempty"`
// StartURL is the IDC/Identity Center start URL (only for IDC auth method)
StartURL string `json:"startUrl,omitempty"`
// Region is the AWS region for IDC authentication (only for IDC auth method)
Region string `json:"region,omitempty"`
}
// KiroAuthBundle aggregates authentication data after OAuth flow completion
type KiroAuthBundle struct {
// TokenData contains the OAuth tokens from the authentication flow
TokenData KiroTokenData `json:"token_data"`
// LastRefresh is the timestamp of the last token refresh
LastRefresh string `json:"last_refresh"`
}
// KiroUsageInfo represents usage information from CodeWhisperer API
type KiroUsageInfo struct {
// SubscriptionTitle is the subscription plan name (e.g., "KIRO FREE")
SubscriptionTitle string `json:"subscription_title"`
// CurrentUsage is the current credit usage
CurrentUsage float64 `json:"current_usage"`
// UsageLimit is the maximum credit limit
UsageLimit float64 `json:"usage_limit"`
// NextReset is the timestamp of the next usage reset
NextReset string `json:"next_reset"`
}
// KiroModel represents a model available through the CodeWhisperer API
type KiroModel struct {
// ModelID is the unique identifier for the model
ModelID string `json:"modelId"`
// ModelName is the human-readable name
ModelName string `json:"modelName"`
// Description is the model description
Description string `json:"description"`
// RateMultiplier is the credit multiplier for this model
RateMultiplier float64 `json:"rateMultiplier"`
// RateUnit is the unit for rate calculation (e.g., "credit")
RateUnit string `json:"rateUnit"`
// MaxInputTokens is the maximum input token limit
MaxInputTokens int `json:"maxInputTokens,omitempty"`
}
// KiroIDETokenFile is the default path to Kiro IDE's token file
const KiroIDETokenFile = ".aws/sso/cache/kiro-auth-token.json"
// LoadKiroIDEToken loads token data from Kiro IDE's token file.
func LoadKiroIDEToken() (*KiroTokenData, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
tokenPath := filepath.Join(homeDir, KiroIDETokenFile)
data, err := os.ReadFile(tokenPath)
if err != nil {
return nil, fmt.Errorf("failed to read Kiro IDE token file (%s): %w", tokenPath, err)
}
var token KiroTokenData
if err := json.Unmarshal(data, &token); err != nil {
return nil, fmt.Errorf("failed to parse Kiro IDE token: %w", err)
}
if token.AccessToken == "" {
return nil, fmt.Errorf("access token is empty in Kiro IDE token file")
}
return &token, nil
}
// LoadKiroTokenFromPath loads token data from a custom path.
// This supports multiple accounts by allowing different token files.
func LoadKiroTokenFromPath(tokenPath string) (*KiroTokenData, error) {
// Expand ~ to home directory
if len(tokenPath) > 0 && tokenPath[0] == '~' {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
tokenPath = filepath.Join(homeDir, tokenPath[1:])
}
data, err := os.ReadFile(tokenPath)
if err != nil {
return nil, fmt.Errorf("failed to read token file (%s): %w", tokenPath, err)
}
var token KiroTokenData
if err := json.Unmarshal(data, &token); err != nil {
return nil, fmt.Errorf("failed to parse token file: %w", err)
}
if token.AccessToken == "" {
return nil, fmt.Errorf("access token is empty in token file")
}
return &token, nil
}
// ListKiroTokenFiles lists all Kiro token files in the cache directory.
// This supports multiple accounts by finding all token files.
func ListKiroTokenFiles() ([]string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
cacheDir := filepath.Join(homeDir, ".aws", "sso", "cache")
// Check if directory exists
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
return nil, nil // No token files
}
entries, err := os.ReadDir(cacheDir)
if err != nil {
return nil, fmt.Errorf("failed to read cache directory: %w", err)
}
var tokenFiles []string
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
// Look for kiro token files only (avoid matching unrelated AWS SSO cache files)
if strings.HasSuffix(name, ".json") && strings.HasPrefix(name, "kiro") {
tokenFiles = append(tokenFiles, filepath.Join(cacheDir, name))
}
}
return tokenFiles, nil
}
// LoadAllKiroTokens loads all Kiro tokens from the cache directory.
// This supports multiple accounts.
func LoadAllKiroTokens() ([]*KiroTokenData, error) {
files, err := ListKiroTokenFiles()
if err != nil {
return nil, err
}
var tokens []*KiroTokenData
for _, file := range files {
token, err := LoadKiroTokenFromPath(file)
if err != nil {
// Skip invalid token files
continue
}
tokens = append(tokens, token)
}
return tokens, nil
}
// JWTClaims represents the claims we care about from a JWT token.
// JWT tokens from Kiro/AWS contain user information in the payload.
type JWTClaims struct {
Email string `json:"email,omitempty"`
Sub string `json:"sub,omitempty"`
PreferredUser string `json:"preferred_username,omitempty"`
Name string `json:"name,omitempty"`
Iss string `json:"iss,omitempty"`
}
// ExtractEmailFromJWT extracts the user's email from a JWT access token.
// JWT tokens typically have format: header.payload.signature
// The payload is base64url-encoded JSON containing user claims.
func ExtractEmailFromJWT(accessToken string) string {
if accessToken == "" {
return ""
}
// JWT format: header.payload.signature
parts := strings.Split(accessToken, ".")
if len(parts) != 3 {
return ""
}
// Decode the payload (second part)
payload := parts[1]
// Add padding if needed (base64url requires padding)
switch len(payload) % 4 {
case 2:
payload += "=="
case 3:
payload += "="
}
decoded, err := base64.URLEncoding.DecodeString(payload)
if err != nil {
// Try RawURLEncoding (no padding)
decoded, err = base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return ""
}
}
var claims JWTClaims
if err := json.Unmarshal(decoded, &claims); err != nil {
return ""
}
// Return email if available
if claims.Email != "" {
return claims.Email
}
// Fallback to preferred_username (some providers use this)
if claims.PreferredUser != "" && strings.Contains(claims.PreferredUser, "@") {
return claims.PreferredUser
}
// Fallback to sub if it looks like an email
if claims.Sub != "" && strings.Contains(claims.Sub, "@") {
return claims.Sub
}
return ""
}
// SanitizeEmailForFilename sanitizes an email address for use in a filename.
// Replaces special characters with underscores and prevents path traversal attacks.
// Also handles URL-encoded characters to prevent encoded path traversal attempts.
func SanitizeEmailForFilename(email string) string {
if email == "" {
return ""
}
result := email
// First, handle URL-encoded path traversal attempts (%2F, %2E, %5C, etc.)
// This prevents encoded characters from bypassing the sanitization.
// Note: We replace % last to catch any remaining encodings including double-encoding (%252F)
result = strings.ReplaceAll(result, "%2F", "_") // /
result = strings.ReplaceAll(result, "%2f", "_")
result = strings.ReplaceAll(result, "%5C", "_") // \
result = strings.ReplaceAll(result, "%5c", "_")
result = strings.ReplaceAll(result, "%2E", "_") // .
result = strings.ReplaceAll(result, "%2e", "_")
result = strings.ReplaceAll(result, "%00", "_") // null byte
result = strings.ReplaceAll(result, "%", "_") // Catch remaining % to prevent double-encoding attacks
// Replace characters that are problematic in filenames
// Keep @ and . in middle but replace other special characters
for _, char := range []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|", " ", "\x00"} {
result = strings.ReplaceAll(result, char, "_")
}
// Prevent path traversal: replace leading dots in each path component
// This handles cases like "../../../etc/passwd" → "_.._.._.._etc_passwd"
parts := strings.Split(result, "_")
for i, part := range parts {
for strings.HasPrefix(part, ".") {
part = "_" + part[1:]
}
parts[i] = part
}
result = strings.Join(parts, "_")
return result
}
+314
View File
@@ -0,0 +1,314 @@
// Package kiro provides OAuth2 authentication functionality for AWS CodeWhisperer (Kiro) API.
// This package implements token loading, refresh, and API communication with CodeWhisperer.
package kiro
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
)
const (
// awsKiroEndpoint is used for CodeWhisperer management APIs (GetUsageLimits, ListProfiles, etc.)
// Note: This is different from the Amazon Q streaming endpoint (q.us-east-1.amazonaws.com)
// used in kiro_executor.go for GenerateAssistantResponse. Both endpoints are correct
// for their respective API operations.
awsKiroEndpoint = "https://codewhisperer.us-east-1.amazonaws.com"
defaultTokenFile = "~/.aws/sso/cache/kiro-auth-token.json"
targetGetUsage = "AmazonCodeWhispererService.GetUsageLimits"
targetListModels = "AmazonCodeWhispererService.ListAvailableModels"
targetGenerateChat = "AmazonCodeWhispererStreamingService.GenerateAssistantResponse"
)
// KiroAuth handles AWS CodeWhisperer authentication and API communication.
// It provides methods for loading tokens, refreshing expired tokens,
// and communicating with the CodeWhisperer API.
type KiroAuth struct {
httpClient *http.Client
endpoint string
}
// NewKiroAuth creates a new Kiro authentication service.
// It initializes the HTTP client with proxy settings from the configuration.
//
// Parameters:
// - cfg: The application configuration containing proxy settings
//
// Returns:
// - *KiroAuth: A new Kiro authentication service instance
func NewKiroAuth(cfg *config.Config) *KiroAuth {
return &KiroAuth{
httpClient: util.SetProxy(&cfg.SDKConfig, &http.Client{Timeout: 120 * time.Second}),
endpoint: awsKiroEndpoint,
}
}
// LoadTokenFromFile loads token data from a file path.
// This method reads and parses the token file, expanding ~ to the home directory.
//
// Parameters:
// - tokenFile: Path to the token file (supports ~ expansion)
//
// Returns:
// - *KiroTokenData: The parsed token data
// - error: An error if file reading or parsing fails
func (k *KiroAuth) LoadTokenFromFile(tokenFile string) (*KiroTokenData, error) {
// Expand ~ to home directory
if strings.HasPrefix(tokenFile, "~") {
home, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
tokenFile = filepath.Join(home, tokenFile[1:])
}
data, err := os.ReadFile(tokenFile)
if err != nil {
return nil, fmt.Errorf("failed to read token file: %w", err)
}
var tokenData KiroTokenData
if err := json.Unmarshal(data, &tokenData); err != nil {
return nil, fmt.Errorf("failed to parse token file: %w", err)
}
return &tokenData, nil
}
// IsTokenExpired checks if the token has expired.
// This method parses the expiration timestamp and compares it with the current time.
//
// Parameters:
// - tokenData: The token data to check
//
// Returns:
// - bool: True if the token has expired, false otherwise
func (k *KiroAuth) IsTokenExpired(tokenData *KiroTokenData) bool {
if tokenData.ExpiresAt == "" {
return true
}
expiresAt, err := time.Parse(time.RFC3339, tokenData.ExpiresAt)
if err != nil {
// Try alternate format
expiresAt, err = time.Parse("2006-01-02T15:04:05.000Z", tokenData.ExpiresAt)
if err != nil {
return true
}
}
return time.Now().After(expiresAt)
}
// makeRequest sends a request to the CodeWhisperer API.
// This is an internal method for making authenticated API calls.
//
// Parameters:
// - ctx: The context for the request
// - target: The API target (e.g., "AmazonCodeWhispererService.GetUsageLimits")
// - accessToken: The OAuth access token
// - payload: The request payload
//
// Returns:
// - []byte: The response body
// - error: An error if the request fails
func (k *KiroAuth) makeRequest(ctx context.Context, target string, accessToken string, payload interface{}) ([]byte, error) {
jsonBody, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, k.endpoint, strings.NewReader(string(jsonBody)))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-amz-json-1.0")
req.Header.Set("x-amz-target", target)
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := k.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer func() {
if errClose := resp.Body.Close(); errClose != nil {
log.Errorf("failed to close response body: %v", errClose)
}
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(body))
}
return body, nil
}
// GetUsageLimits retrieves usage information from the CodeWhisperer API.
// This method fetches the current usage statistics and subscription information.
//
// Parameters:
// - ctx: The context for the request
// - tokenData: The token data containing access token and profile ARN
//
// Returns:
// - *KiroUsageInfo: The usage information
// - error: An error if the request fails
func (k *KiroAuth) GetUsageLimits(ctx context.Context, tokenData *KiroTokenData) (*KiroUsageInfo, error) {
payload := map[string]interface{}{
"origin": "AI_EDITOR",
"profileArn": tokenData.ProfileArn,
"resourceType": "AGENTIC_REQUEST",
}
body, err := k.makeRequest(ctx, targetGetUsage, tokenData.AccessToken, payload)
if err != nil {
return nil, err
}
var result struct {
SubscriptionInfo struct {
SubscriptionTitle string `json:"subscriptionTitle"`
} `json:"subscriptionInfo"`
UsageBreakdownList []struct {
CurrentUsageWithPrecision float64 `json:"currentUsageWithPrecision"`
UsageLimitWithPrecision float64 `json:"usageLimitWithPrecision"`
} `json:"usageBreakdownList"`
NextDateReset float64 `json:"nextDateReset"`
}
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse usage response: %w", err)
}
usage := &KiroUsageInfo{
SubscriptionTitle: result.SubscriptionInfo.SubscriptionTitle,
NextReset: fmt.Sprintf("%v", result.NextDateReset),
}
if len(result.UsageBreakdownList) > 0 {
usage.CurrentUsage = result.UsageBreakdownList[0].CurrentUsageWithPrecision
usage.UsageLimit = result.UsageBreakdownList[0].UsageLimitWithPrecision
}
return usage, nil
}
// ListAvailableModels retrieves available models from the CodeWhisperer API.
// This method fetches the list of AI models available for the authenticated user.
//
// Parameters:
// - ctx: The context for the request
// - tokenData: The token data containing access token and profile ARN
//
// Returns:
// - []*KiroModel: The list of available models
// - error: An error if the request fails
func (k *KiroAuth) ListAvailableModels(ctx context.Context, tokenData *KiroTokenData) ([]*KiroModel, error) {
payload := map[string]interface{}{
"origin": "AI_EDITOR",
"profileArn": tokenData.ProfileArn,
}
body, err := k.makeRequest(ctx, targetListModels, tokenData.AccessToken, payload)
if err != nil {
return nil, err
}
var result struct {
Models []struct {
ModelID string `json:"modelId"`
ModelName string `json:"modelName"`
Description string `json:"description"`
RateMultiplier float64 `json:"rateMultiplier"`
RateUnit string `json:"rateUnit"`
TokenLimits struct {
MaxInputTokens int `json:"maxInputTokens"`
} `json:"tokenLimits"`
} `json:"models"`
}
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse models response: %w", err)
}
models := make([]*KiroModel, 0, len(result.Models))
for _, m := range result.Models {
models = append(models, &KiroModel{
ModelID: m.ModelID,
ModelName: m.ModelName,
Description: m.Description,
RateMultiplier: m.RateMultiplier,
RateUnit: m.RateUnit,
MaxInputTokens: m.TokenLimits.MaxInputTokens,
})
}
return models, nil
}
// CreateTokenStorage creates a new KiroTokenStorage from token data.
// This method converts the token data into a storage structure suitable for persistence.
//
// Parameters:
// - tokenData: The token data to convert
//
// Returns:
// - *KiroTokenStorage: A new token storage instance
func (k *KiroAuth) CreateTokenStorage(tokenData *KiroTokenData) *KiroTokenStorage {
return &KiroTokenStorage{
AccessToken: tokenData.AccessToken,
RefreshToken: tokenData.RefreshToken,
ProfileArn: tokenData.ProfileArn,
ExpiresAt: tokenData.ExpiresAt,
AuthMethod: tokenData.AuthMethod,
Provider: tokenData.Provider,
LastRefresh: time.Now().Format(time.RFC3339),
}
}
// ValidateToken checks if the token is valid by making a test API call.
// This method verifies the token by attempting to fetch usage limits.
//
// Parameters:
// - ctx: The context for the request
// - tokenData: The token data to validate
//
// Returns:
// - error: An error if the token is invalid
func (k *KiroAuth) ValidateToken(ctx context.Context, tokenData *KiroTokenData) error {
_, err := k.GetUsageLimits(ctx, tokenData)
return err
}
// UpdateTokenStorage updates an existing token storage with new token data.
// This method refreshes the token storage with newly obtained access and refresh tokens.
//
// Parameters:
// - storage: The existing token storage to update
// - tokenData: The new token data to apply
func (k *KiroAuth) UpdateTokenStorage(storage *KiroTokenStorage, tokenData *KiroTokenData) {
storage.AccessToken = tokenData.AccessToken
storage.RefreshToken = tokenData.RefreshToken
storage.ProfileArn = tokenData.ProfileArn
storage.ExpiresAt = tokenData.ExpiresAt
storage.AuthMethod = tokenData.AuthMethod
storage.Provider = tokenData.Provider
storage.LastRefresh = time.Now().Format(time.RFC3339)
}
+161
View File
@@ -0,0 +1,161 @@
package kiro
import (
"encoding/base64"
"encoding/json"
"testing"
)
func TestExtractEmailFromJWT(t *testing.T) {
tests := []struct {
name string
token string
expected string
}{
{
name: "Empty token",
token: "",
expected: "",
},
{
name: "Invalid token format",
token: "not.a.valid.jwt",
expected: "",
},
{
name: "Invalid token - not base64",
token: "xxx.yyy.zzz",
expected: "",
},
{
name: "Valid JWT with email",
token: createTestJWT(map[string]any{"email": "test@example.com", "sub": "user123"}),
expected: "test@example.com",
},
{
name: "JWT without email but with preferred_username",
token: createTestJWT(map[string]any{"preferred_username": "user@domain.com", "sub": "user123"}),
expected: "user@domain.com",
},
{
name: "JWT with email-like sub",
token: createTestJWT(map[string]any{"sub": "another@test.com"}),
expected: "another@test.com",
},
{
name: "JWT without any email fields",
token: createTestJWT(map[string]any{"sub": "user123", "name": "Test User"}),
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := ExtractEmailFromJWT(tt.token)
if result != tt.expected {
t.Errorf("ExtractEmailFromJWT() = %q, want %q", result, tt.expected)
}
})
}
}
func TestSanitizeEmailForFilename(t *testing.T) {
tests := []struct {
name string
email string
expected string
}{
{
name: "Empty email",
email: "",
expected: "",
},
{
name: "Simple email",
email: "user@example.com",
expected: "user@example.com",
},
{
name: "Email with space",
email: "user name@example.com",
expected: "user_name@example.com",
},
{
name: "Email with special chars",
email: "user:name@example.com",
expected: "user_name@example.com",
},
{
name: "Email with multiple special chars",
email: "user/name:test@example.com",
expected: "user_name_test@example.com",
},
{
name: "Path traversal attempt",
email: "../../../etc/passwd",
expected: "_.__.__._etc_passwd",
},
{
name: "Path traversal with backslash",
email: `..\..\..\..\windows\system32`,
expected: "_.__.__.__._windows_system32",
},
{
name: "Null byte injection attempt",
email: "user\x00@evil.com",
expected: "user_@evil.com",
},
// URL-encoded path traversal tests
{
name: "URL-encoded slash",
email: "user%2Fpath@example.com",
expected: "user_path@example.com",
},
{
name: "URL-encoded backslash",
email: "user%5Cpath@example.com",
expected: "user_path@example.com",
},
{
name: "URL-encoded dot",
email: "%2E%2E%2Fetc%2Fpasswd",
expected: "___etc_passwd",
},
{
name: "URL-encoded null",
email: "user%00@evil.com",
expected: "user_@evil.com",
},
{
name: "Double URL-encoding attack",
email: "%252F%252E%252E",
expected: "_252F_252E_252E", // % replaced with _, remaining chars preserved (safe)
},
{
name: "Mixed case URL-encoding",
email: "%2f%2F%5c%5C",
expected: "____",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := SanitizeEmailForFilename(tt.email)
if result != tt.expected {
t.Errorf("SanitizeEmailForFilename() = %q, want %q", result, tt.expected)
}
})
}
}
// createTestJWT creates a test JWT token with the given claims
func createTestJWT(claims map[string]any) string {
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`))
payloadBytes, _ := json.Marshal(claims)
payload := base64.RawURLEncoding.EncodeToString(payloadBytes)
signature := base64.RawURLEncoding.EncodeToString([]byte("fake-signature"))
return header + "." + payload + "." + signature
}
+166
View File
@@ -0,0 +1,166 @@
// Package kiro provides CodeWhisperer API client for fetching user info.
package kiro
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/google/uuid"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
)
const (
codeWhispererAPI = "https://codewhisperer.us-east-1.amazonaws.com"
kiroVersion = "0.6.18"
)
// CodeWhispererClient handles CodeWhisperer API calls.
type CodeWhispererClient struct {
httpClient *http.Client
machineID string
}
// UsageLimitsResponse represents the getUsageLimits API response.
type UsageLimitsResponse struct {
DaysUntilReset *int `json:"daysUntilReset,omitempty"`
NextDateReset *float64 `json:"nextDateReset,omitempty"`
UserInfo *UserInfo `json:"userInfo,omitempty"`
SubscriptionInfo *SubscriptionInfo `json:"subscriptionInfo,omitempty"`
UsageBreakdownList []UsageBreakdown `json:"usageBreakdownList,omitempty"`
}
// UserInfo contains user information from the API.
type UserInfo struct {
Email string `json:"email,omitempty"`
UserID string `json:"userId,omitempty"`
}
// SubscriptionInfo contains subscription details.
type SubscriptionInfo struct {
SubscriptionTitle string `json:"subscriptionTitle,omitempty"`
Type string `json:"type,omitempty"`
}
// UsageBreakdown contains usage details.
type UsageBreakdown struct {
UsageLimit *int `json:"usageLimit,omitempty"`
CurrentUsage *int `json:"currentUsage,omitempty"`
UsageLimitWithPrecision *float64 `json:"usageLimitWithPrecision,omitempty"`
CurrentUsageWithPrecision *float64 `json:"currentUsageWithPrecision,omitempty"`
NextDateReset *float64 `json:"nextDateReset,omitempty"`
DisplayName string `json:"displayName,omitempty"`
ResourceType string `json:"resourceType,omitempty"`
}
// NewCodeWhispererClient creates a new CodeWhisperer client.
func NewCodeWhispererClient(cfg *config.Config, machineID string) *CodeWhispererClient {
client := &http.Client{Timeout: 30 * time.Second}
if cfg != nil {
client = util.SetProxy(&cfg.SDKConfig, client)
}
if machineID == "" {
machineID = uuid.New().String()
}
return &CodeWhispererClient{
httpClient: client,
machineID: machineID,
}
}
// generateInvocationID generates a unique invocation ID.
func generateInvocationID() string {
return uuid.New().String()
}
// GetUsageLimits fetches usage limits and user info from CodeWhisperer API.
// This is the recommended way to get user email after login.
func (c *CodeWhispererClient) GetUsageLimits(ctx context.Context, accessToken string) (*UsageLimitsResponse, error) {
url := fmt.Sprintf("%s/getUsageLimits?isEmailRequired=true&origin=AI_EDITOR&resourceType=AGENTIC_REQUEST", codeWhispererAPI)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Set headers to match Kiro IDE
xAmzUserAgent := fmt.Sprintf("aws-sdk-js/1.0.0 KiroIDE-%s-%s", kiroVersion, c.machineID)
userAgent := fmt.Sprintf("aws-sdk-js/1.0.0 ua/2.1 os/windows lang/js md/nodejs#20.16.0 api/codewhispererruntime#1.0.0 m/E KiroIDE-%s-%s", kiroVersion, c.machineID)
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("x-amz-user-agent", xAmzUserAgent)
req.Header.Set("User-Agent", userAgent)
req.Header.Set("amz-sdk-invocation-id", generateInvocationID())
req.Header.Set("amz-sdk-request", "attempt=1; max=1")
req.Header.Set("Connection", "close")
log.Debugf("codewhisperer: GET %s", url)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
log.Debugf("codewhisperer: status=%d, body=%s", resp.StatusCode, string(body))
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API returned status %d: %s", resp.StatusCode, string(body))
}
var result UsageLimitsResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
return &result, nil
}
// FetchUserEmailFromAPI fetches user email using CodeWhisperer getUsageLimits API.
// This is more reliable than JWT parsing as it uses the official API.
func (c *CodeWhispererClient) FetchUserEmailFromAPI(ctx context.Context, accessToken string) string {
resp, err := c.GetUsageLimits(ctx, accessToken)
if err != nil {
log.Debugf("codewhisperer: failed to get usage limits: %v", err)
return ""
}
if resp.UserInfo != nil && resp.UserInfo.Email != "" {
log.Debugf("codewhisperer: got email from API: %s", resp.UserInfo.Email)
return resp.UserInfo.Email
}
log.Debugf("codewhisperer: no email in response")
return ""
}
// FetchUserEmailWithFallback fetches user email with multiple fallback methods.
// Priority: 1. CodeWhisperer API 2. userinfo endpoint 3. JWT parsing
func FetchUserEmailWithFallback(ctx context.Context, cfg *config.Config, accessToken string) string {
// Method 1: Try CodeWhisperer API (most reliable)
cwClient := NewCodeWhispererClient(cfg, "")
email := cwClient.FetchUserEmailFromAPI(ctx, accessToken)
if email != "" {
return email
}
// Method 2: Try SSO OIDC userinfo endpoint
ssoClient := NewSSOOIDCClient(cfg)
email = ssoClient.FetchUserEmail(ctx, accessToken)
if email != "" {
return email
}
// Method 3: Fallback to JWT parsing
return ExtractEmailFromJWT(accessToken)
}
+192
View File
@@ -0,0 +1,192 @@
package kiro
import (
"errors"
"fmt"
"net/http"
)
// OAuthError represents an OAuth-specific error.
type OAuthError struct {
// Code is the OAuth error code.
Code string `json:"error"`
// Description is a human-readable description of the error.
Description string `json:"error_description,omitempty"`
// URI is a URI identifying a human-readable web page with information about the error.
URI string `json:"error_uri,omitempty"`
// StatusCode is the HTTP status code associated with the error.
StatusCode int `json:"-"`
}
// Error returns a string representation of the OAuth error.
func (e *OAuthError) Error() string {
if e.Description != "" {
return fmt.Sprintf("OAuth error %s: %s", e.Code, e.Description)
}
return fmt.Sprintf("OAuth error: %s", e.Code)
}
// NewOAuthError creates a new OAuth error with the specified code, description, and status code.
func NewOAuthError(code, description string, statusCode int) *OAuthError {
return &OAuthError{
Code: code,
Description: description,
StatusCode: statusCode,
}
}
// AuthenticationError represents authentication-related errors.
type AuthenticationError struct {
// Type is the type of authentication error.
Type string `json:"type"`
// Message is a human-readable message describing the error.
Message string `json:"message"`
// Code is the HTTP status code associated with the error.
Code int `json:"code"`
// Cause is the underlying error that caused this authentication error.
Cause error `json:"-"`
}
// Error returns a string representation of the authentication error.
func (e *AuthenticationError) Error() string {
if e.Cause != nil {
return fmt.Sprintf("%s: %s (caused by: %v)", e.Type, e.Message, e.Cause)
}
return fmt.Sprintf("%s: %s", e.Type, e.Message)
}
// Common authentication error types.
var (
// ErrInvalidState represents an error for invalid OAuth state parameter.
ErrInvalidState = &AuthenticationError{
Type: "invalid_state",
Message: "OAuth state parameter is invalid",
Code: http.StatusBadRequest,
}
// ErrCodeExchangeFailed represents an error when exchanging authorization code for tokens fails.
ErrCodeExchangeFailed = &AuthenticationError{
Type: "code_exchange_failed",
Message: "Failed to exchange authorization code for tokens",
Code: http.StatusBadRequest,
}
// ErrServerStartFailed represents an error when starting the OAuth callback server fails.
ErrServerStartFailed = &AuthenticationError{
Type: "server_start_failed",
Message: "Failed to start OAuth callback server",
Code: http.StatusInternalServerError,
}
// ErrPortInUse represents an error when the OAuth callback port is already in use.
ErrPortInUse = &AuthenticationError{
Type: "port_in_use",
Message: "OAuth callback port is already in use",
Code: 13, // Special exit code for port-in-use
}
// ErrCallbackTimeout represents an error when waiting for OAuth callback times out.
ErrCallbackTimeout = &AuthenticationError{
Type: "callback_timeout",
Message: "Timeout waiting for OAuth callback",
Code: http.StatusRequestTimeout,
}
// ErrBrowserOpenFailed represents an error when opening the browser for authentication fails.
ErrBrowserOpenFailed = &AuthenticationError{
Type: "browser_open_failed",
Message: "Failed to open browser for authentication",
Code: http.StatusInternalServerError,
}
// ErrAuthorizationPending indicates the user hasn't completed device authorization yet
ErrAuthorizationPending = &AuthenticationError{
Type: "authorization_pending",
Message: "User has not completed device authorization",
Code: http.StatusAccepted,
}
// ErrSlowDown indicates the client is polling too frequently
ErrSlowDown = &AuthenticationError{
Type: "slow_down",
Message: "Polling too frequently, slow down",
Code: http.StatusTooManyRequests,
}
// ErrExpiredToken indicates the device code has expired
ErrExpiredToken = &AuthenticationError{
Type: "expired_token",
Message: "Device code has expired",
Code: http.StatusBadRequest,
}
)
// NewAuthenticationError creates a new authentication error with a cause based on a base error.
func NewAuthenticationError(baseErr *AuthenticationError, cause error) *AuthenticationError {
return &AuthenticationError{
Type: baseErr.Type,
Message: baseErr.Message,
Code: baseErr.Code,
Cause: cause,
}
}
// IsAuthenticationError checks if an error is an authentication error.
func IsAuthenticationError(err error) bool {
var authenticationError *AuthenticationError
ok := errors.As(err, &authenticationError)
return ok
}
// IsOAuthError checks if an error is an OAuth error.
func IsOAuthError(err error) bool {
var oAuthError *OAuthError
ok := errors.As(err, &oAuthError)
return ok
}
// GetUserFriendlyMessage returns a user-friendly error message based on the error type.
func GetUserFriendlyMessage(err error) string {
switch {
case IsAuthenticationError(err):
var authErr *AuthenticationError
errors.As(err, &authErr)
switch authErr.Type {
case "token_expired":
return "Your authentication has expired. Please log in again."
case "token_invalid":
return "Your authentication is invalid. Please log in again."
case "authentication_required":
return "Please log in to continue."
case "port_in_use":
return "The required port is already in use. Please close any applications using the port and try again."
case "callback_timeout":
return "Authentication timed out. Please try again."
case "browser_open_failed":
return "Could not open your browser automatically. Please copy and paste the URL manually."
case "authorization_pending":
return "Waiting for you to complete authentication in your browser..."
case "slow_down":
return "Polling too frequently. Slowing down..."
case "expired_token":
return "The device code has expired. Please restart the login process."
default:
return "Authentication failed. Please try again."
}
case IsOAuthError(err):
var oauthErr *OAuthError
errors.As(err, &oauthErr)
switch oauthErr.Code {
case "access_denied":
return "Authentication was cancelled or denied."
case "invalid_request":
return "Invalid authentication request. Please try again."
case "server_error":
return "Authentication server error. Please try again later."
default:
return fmt.Sprintf("Authentication failed: %s", oauthErr.Description)
}
default:
return "An unexpected error occurred. Please try again."
}
}
+303
View File
@@ -0,0 +1,303 @@
// Package kiro provides OAuth2 authentication for Kiro using native Google login.
package kiro
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"html"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
)
const (
// Kiro auth endpoint
kiroAuthEndpoint = "https://prod.us-east-1.auth.desktop.kiro.dev"
// Default callback port
defaultCallbackPort = 9876
// Auth timeout
authTimeout = 10 * time.Minute
)
// KiroTokenResponse represents the response from Kiro token endpoint.
type KiroTokenResponse struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ProfileArn string `json:"profileArn"`
ExpiresIn int `json:"expiresIn"`
}
// KiroOAuth handles the OAuth flow for Kiro authentication.
type KiroOAuth struct {
httpClient *http.Client
cfg *config.Config
}
// NewKiroOAuth creates a new Kiro OAuth handler.
func NewKiroOAuth(cfg *config.Config) *KiroOAuth {
client := &http.Client{Timeout: 30 * time.Second}
if cfg != nil {
client = util.SetProxy(&cfg.SDKConfig, client)
}
return &KiroOAuth{
httpClient: client,
cfg: cfg,
}
}
// generateCodeVerifier generates a random code verifier for PKCE.
func generateCodeVerifier() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// generateCodeChallenge generates the code challenge from verifier.
func generateCodeChallenge(verifier string) string {
h := sha256.Sum256([]byte(verifier))
return base64.RawURLEncoding.EncodeToString(h[:])
}
// generateState generates a random state parameter.
func generateState() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// AuthResult contains the authorization code and state from callback.
type AuthResult struct {
Code string
State string
Error string
}
// startCallbackServer starts a local HTTP server to receive the OAuth callback.
func (o *KiroOAuth) startCallbackServer(ctx context.Context, expectedState string) (string, <-chan AuthResult, error) {
// Try to find an available port - use localhost like Kiro does
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", defaultCallbackPort))
if err != nil {
// Try with dynamic port (RFC 8252 allows dynamic ports for native apps)
log.Warnf("kiro oauth: default port %d is busy, falling back to dynamic port", defaultCallbackPort)
listener, err = net.Listen("tcp", "localhost:0")
if err != nil {
return "", nil, fmt.Errorf("failed to start callback server: %w", err)
}
}
port := listener.Addr().(*net.TCPAddr).Port
// Use http scheme for local callback server
redirectURI := fmt.Sprintf("http://localhost:%d/oauth/callback", port)
resultChan := make(chan AuthResult, 1)
server := &http.Server{
ReadHeaderTimeout: 10 * time.Second,
}
mux := http.NewServeMux()
mux.HandleFunc("/oauth/callback", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
errParam := r.URL.Query().Get("error")
if errParam != "" {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `<html><body><h1>Login Failed</h1><p>%s</p><p>You can close this window.</p></body></html>`, html.EscapeString(errParam))
resultChan <- AuthResult{Error: errParam}
return
}
if state != expectedState {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, `<html><body><h1>Login Failed</h1><p>Invalid state parameter</p><p>You can close this window.</p></body></html>`)
resultChan <- AuthResult{Error: "state mismatch"}
return
}
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<html><body><h1>Login Successful!</h1><p>You can close this window and return to the terminal.</p></body></html>`)
resultChan <- AuthResult{Code: code, State: state}
})
server.Handler = mux
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Debugf("callback server error: %v", err)
}
}()
go func() {
select {
case <-ctx.Done():
case <-time.After(authTimeout):
case <-resultChan:
}
_ = server.Shutdown(context.Background())
}()
return redirectURI, resultChan, nil
}
// LoginWithBuilderID performs OAuth login with AWS Builder ID using device code flow.
func (o *KiroOAuth) LoginWithBuilderID(ctx context.Context) (*KiroTokenData, error) {
ssoClient := NewSSOOIDCClient(o.cfg)
return ssoClient.LoginWithBuilderID(ctx)
}
// LoginWithBuilderIDAuthCode performs OAuth login with AWS Builder ID using authorization code flow.
// This provides a better UX than device code flow as it uses automatic browser callback.
func (o *KiroOAuth) LoginWithBuilderIDAuthCode(ctx context.Context) (*KiroTokenData, error) {
ssoClient := NewSSOOIDCClient(o.cfg)
return ssoClient.LoginWithBuilderIDAuthCode(ctx)
}
// exchangeCodeForToken exchanges the authorization code for tokens.
func (o *KiroOAuth) exchangeCodeForToken(ctx context.Context, code, codeVerifier, redirectURI string) (*KiroTokenData, error) {
payload := map[string]string{
"code": code,
"code_verifier": codeVerifier,
"redirect_uri": redirectURI,
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
tokenURL := kiroAuthEndpoint + "/oauth/token"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(string(body)))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "cli-proxy-api/1.0.0")
resp, err := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("token exchange failed (status %d): %s", resp.StatusCode, string(respBody))
return nil, fmt.Errorf("token exchange failed (status %d)", resp.StatusCode)
}
var tokenResp KiroTokenResponse
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
// Validate ExpiresIn - use default 1 hour if invalid
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
expiresIn = 3600
}
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
return &KiroTokenData{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
ProfileArn: tokenResp.ProfileArn,
ExpiresAt: expiresAt.Format(time.RFC3339),
AuthMethod: "social",
Provider: "", // Caller should preserve original provider
}, nil
}
// RefreshToken refreshes an expired access token.
func (o *KiroOAuth) RefreshToken(ctx context.Context, refreshToken string) (*KiroTokenData, error) {
payload := map[string]string{
"refreshToken": refreshToken,
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
refreshURL := kiroAuthEndpoint + "/refreshToken"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, refreshURL, strings.NewReader(string(body)))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "cli-proxy-api/1.0.0")
resp, err := o.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("refresh request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("token refresh failed (status %d): %s", resp.StatusCode, string(respBody))
return nil, fmt.Errorf("token refresh failed (status %d)", resp.StatusCode)
}
var tokenResp KiroTokenResponse
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
// Validate ExpiresIn - use default 1 hour if invalid
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
expiresIn = 3600
}
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
return &KiroTokenData{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
ProfileArn: tokenResp.ProfileArn,
ExpiresAt: expiresAt.Format(time.RFC3339),
AuthMethod: "social",
Provider: "", // Caller should preserve original provider
}, nil
}
// LoginWithGoogle performs OAuth login with Google using Kiro's social auth.
// This uses a custom protocol handler (kiro://) to receive the callback.
func (o *KiroOAuth) LoginWithGoogle(ctx context.Context) (*KiroTokenData, error) {
socialClient := NewSocialAuthClient(o.cfg)
return socialClient.LoginWithGoogle(ctx)
}
// LoginWithGitHub performs OAuth login with GitHub using Kiro's social auth.
// This uses a custom protocol handler (kiro://) to receive the callback.
func (o *KiroOAuth) LoginWithGitHub(ctx context.Context) (*KiroTokenData, error) {
socialClient := NewSocialAuthClient(o.cfg)
return socialClient.LoginWithGitHub(ctx)
}
+725
View File
@@ -0,0 +1,725 @@
// Package kiro provides custom protocol handler registration for Kiro OAuth.
// This enables the CLI to intercept kiro:// URIs for social authentication (Google/GitHub).
package kiro
import (
"context"
"fmt"
"html"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
const (
// KiroProtocol is the custom URI scheme used by Kiro
KiroProtocol = "kiro"
// KiroAuthority is the URI authority for authentication callbacks
KiroAuthority = "kiro.kiroAgent"
// KiroAuthPath is the path for successful authentication
KiroAuthPath = "/authenticate-success"
// KiroRedirectURI is the full redirect URI for social auth
KiroRedirectURI = "kiro://kiro.kiroAgent/authenticate-success"
// DefaultHandlerPort is the default port for the local callback server
DefaultHandlerPort = 19876
// HandlerTimeout is how long to wait for the OAuth callback
HandlerTimeout = 10 * time.Minute
)
// ProtocolHandler manages the custom kiro:// protocol handler for OAuth callbacks.
type ProtocolHandler struct {
port int
server *http.Server
listener net.Listener
resultChan chan *AuthCallback
stopChan chan struct{}
mu sync.Mutex
running bool
}
// AuthCallback contains the OAuth callback parameters.
type AuthCallback struct {
Code string
State string
Error string
}
// NewProtocolHandler creates a new protocol handler.
func NewProtocolHandler() *ProtocolHandler {
return &ProtocolHandler{
port: DefaultHandlerPort,
resultChan: make(chan *AuthCallback, 1),
stopChan: make(chan struct{}),
}
}
// Start starts the local callback server that receives redirects from the protocol handler.
func (h *ProtocolHandler) Start(ctx context.Context) (int, error) {
h.mu.Lock()
defer h.mu.Unlock()
if h.running {
return h.port, nil
}
// Drain any stale results from previous runs
select {
case <-h.resultChan:
default:
}
// Reset stopChan for reuse - close old channel first to unblock any waiting goroutines
if h.stopChan != nil {
select {
case <-h.stopChan:
// Already closed
default:
close(h.stopChan)
}
}
h.stopChan = make(chan struct{})
// Try ports in known range (must match handler script port range)
var listener net.Listener
var err error
portRange := []int{DefaultHandlerPort, DefaultHandlerPort + 1, DefaultHandlerPort + 2, DefaultHandlerPort + 3, DefaultHandlerPort + 4}
for _, port := range portRange {
listener, err = net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err == nil {
break
}
log.Debugf("kiro protocol handler: port %d busy, trying next", port)
}
if listener == nil {
return 0, fmt.Errorf("failed to start callback server: all ports %d-%d are busy", DefaultHandlerPort, DefaultHandlerPort+4)
}
h.listener = listener
h.port = listener.Addr().(*net.TCPAddr).Port
mux := http.NewServeMux()
mux.HandleFunc("/oauth/callback", h.handleCallback)
h.server = &http.Server{
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
go func() {
if err := h.server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Debugf("kiro protocol handler server error: %v", err)
}
}()
h.running = true
log.Debugf("kiro protocol handler started on port %d", h.port)
// Auto-shutdown after context done, timeout, or explicit stop
// Capture references to prevent race with new Start() calls
currentStopChan := h.stopChan
currentServer := h.server
currentListener := h.listener
go func() {
select {
case <-ctx.Done():
case <-time.After(HandlerTimeout):
case <-currentStopChan:
return // Already stopped, exit goroutine
}
// Only stop if this is still the current server/listener instance
h.mu.Lock()
if h.server == currentServer && h.listener == currentListener {
h.mu.Unlock()
h.Stop()
} else {
h.mu.Unlock()
}
}()
return h.port, nil
}
// Stop stops the callback server.
func (h *ProtocolHandler) Stop() {
h.mu.Lock()
defer h.mu.Unlock()
if !h.running {
return
}
// Signal the auto-shutdown goroutine to exit.
// This select pattern is safe because stopChan is only modified while holding h.mu,
// and we hold the lock here. The select prevents panic from double-close.
select {
case <-h.stopChan:
// Already closed
default:
close(h.stopChan)
}
if h.server != nil {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = h.server.Shutdown(ctx)
}
h.running = false
log.Debug("kiro protocol handler stopped")
}
// WaitForCallback waits for the OAuth callback and returns the result.
func (h *ProtocolHandler) WaitForCallback(ctx context.Context) (*AuthCallback, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(HandlerTimeout):
return nil, fmt.Errorf("timeout waiting for OAuth callback")
case result := <-h.resultChan:
return result, nil
}
}
// GetPort returns the port the handler is listening on.
func (h *ProtocolHandler) GetPort() int {
return h.port
}
// handleCallback processes the OAuth callback from the protocol handler script.
func (h *ProtocolHandler) handleCallback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
errParam := r.URL.Query().Get("error")
result := &AuthCallback{
Code: code,
State: state,
Error: errParam,
}
// Send result
select {
case h.resultChan <- result:
default:
// Channel full, ignore duplicate callbacks
}
// Send success response
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if errParam != "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `<!DOCTYPE html>
<html>
<head><title>Login Failed</title></head>
<body>
<h1>Login Failed</h1>
<p>Error: %s</p>
<p>You can close this window.</p>
</body>
</html>`, html.EscapeString(errParam))
} else {
fmt.Fprint(w, `<!DOCTYPE html>
<html>
<head><title>Login Successful</title></head>
<body>
<h1>Login Successful!</h1>
<p>You can close this window and return to the terminal.</p>
<script>window.close();</script>
</body>
</html>`)
}
}
// IsProtocolHandlerInstalled checks if the kiro:// protocol handler is installed.
func IsProtocolHandlerInstalled() bool {
switch runtime.GOOS {
case "linux":
return isLinuxHandlerInstalled()
case "windows":
return isWindowsHandlerInstalled()
case "darwin":
return isDarwinHandlerInstalled()
default:
return false
}
}
// InstallProtocolHandler installs the kiro:// protocol handler for the current platform.
func InstallProtocolHandler(handlerPort int) error {
switch runtime.GOOS {
case "linux":
return installLinuxHandler(handlerPort)
case "windows":
return installWindowsHandler(handlerPort)
case "darwin":
return installDarwinHandler(handlerPort)
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
}
// UninstallProtocolHandler removes the kiro:// protocol handler.
func UninstallProtocolHandler() error {
switch runtime.GOOS {
case "linux":
return uninstallLinuxHandler()
case "windows":
return uninstallWindowsHandler()
case "darwin":
return uninstallDarwinHandler()
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
}
// --- Linux Implementation ---
func getLinuxDesktopPath() string {
homeDir, _ := os.UserHomeDir()
return filepath.Join(homeDir, ".local", "share", "applications", "kiro-oauth-handler.desktop")
}
func getLinuxHandlerScriptPath() string {
homeDir, _ := os.UserHomeDir()
return filepath.Join(homeDir, ".local", "bin", "kiro-oauth-handler")
}
func isLinuxHandlerInstalled() bool {
desktopPath := getLinuxDesktopPath()
_, err := os.Stat(desktopPath)
return err == nil
}
func installLinuxHandler(handlerPort int) error {
// Create directories
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
binDir := filepath.Join(homeDir, ".local", "bin")
appDir := filepath.Join(homeDir, ".local", "share", "applications")
if err := os.MkdirAll(binDir, 0755); err != nil {
return fmt.Errorf("failed to create bin directory: %w", err)
}
if err := os.MkdirAll(appDir, 0755); err != nil {
return fmt.Errorf("failed to create applications directory: %w", err)
}
// Create handler script - tries multiple ports to handle dynamic port allocation
scriptPath := getLinuxHandlerScriptPath()
scriptContent := fmt.Sprintf(`#!/bin/bash
# Kiro OAuth Protocol Handler
# Handles kiro:// URIs - tries CLI first, then forwards to Kiro IDE
URL="$1"
# Check curl availability
if ! command -v curl &> /dev/null; then
echo "Error: curl is required for Kiro OAuth handler" >&2
exit 1
fi
# Extract code and state from URL
[[ "$URL" =~ code=([^&]+) ]] && CODE="${BASH_REMATCH[1]}"
[[ "$URL" =~ state=([^&]+) ]] && STATE="${BASH_REMATCH[1]}"
[[ "$URL" =~ error=([^&]+) ]] && ERROR="${BASH_REMATCH[1]}"
# Try CLI proxy on multiple possible ports (default + dynamic range)
CLI_OK=0
for PORT in %d %d %d %d %d; do
if [ -n "$ERROR" ]; then
curl -sf --connect-timeout 1 "http://127.0.0.1:$PORT/oauth/callback?error=$ERROR" && CLI_OK=1 && break
elif [ -n "$CODE" ] && [ -n "$STATE" ]; then
curl -sf --connect-timeout 1 "http://127.0.0.1:$PORT/oauth/callback?code=$CODE&state=$STATE" && CLI_OK=1 && break
fi
done
# If CLI not available, forward to Kiro IDE
if [ $CLI_OK -eq 0 ] && [ -x "/usr/share/kiro/kiro" ]; then
/usr/share/kiro/kiro --open-url "$URL" &
fi
`, handlerPort, handlerPort+1, handlerPort+2, handlerPort+3, handlerPort+4)
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil {
return fmt.Errorf("failed to write handler script: %w", err)
}
// Create .desktop file
desktopPath := getLinuxDesktopPath()
desktopContent := fmt.Sprintf(`[Desktop Entry]
Name=Kiro OAuth Handler
Comment=Handle kiro:// protocol for CLI Proxy API authentication
Exec=%s %%u
Type=Application
Terminal=false
NoDisplay=true
MimeType=x-scheme-handler/kiro;
Categories=Utility;
`, scriptPath)
if err := os.WriteFile(desktopPath, []byte(desktopContent), 0644); err != nil {
return fmt.Errorf("failed to write desktop file: %w", err)
}
// Register handler with xdg-mime
cmd := exec.Command("xdg-mime", "default", "kiro-oauth-handler.desktop", "x-scheme-handler/kiro")
if err := cmd.Run(); err != nil {
log.Warnf("xdg-mime registration failed (may need manual setup): %v", err)
}
// Update desktop database
cmd = exec.Command("update-desktop-database", appDir)
_ = cmd.Run() // Ignore errors, not critical
log.Info("Kiro protocol handler installed for Linux")
return nil
}
func uninstallLinuxHandler() error {
desktopPath := getLinuxDesktopPath()
scriptPath := getLinuxHandlerScriptPath()
if err := os.Remove(desktopPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove desktop file: %w", err)
}
if err := os.Remove(scriptPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove handler script: %w", err)
}
log.Info("Kiro protocol handler uninstalled")
return nil
}
// --- Windows Implementation ---
func isWindowsHandlerInstalled() bool {
// Check registry key existence
cmd := exec.Command("reg", "query", `HKCU\Software\Classes\kiro`, "/ve")
return cmd.Run() == nil
}
func installWindowsHandler(handlerPort int) error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}
// Create handler script (PowerShell)
scriptDir := filepath.Join(homeDir, ".cliproxyapi")
if err := os.MkdirAll(scriptDir, 0755); err != nil {
return fmt.Errorf("failed to create script directory: %w", err)
}
scriptPath := filepath.Join(scriptDir, "kiro-oauth-handler.ps1")
scriptContent := fmt.Sprintf(`# Kiro OAuth Protocol Handler for Windows
param([string]$url)
# Load required assembly for HttpUtility
Add-Type -AssemblyName System.Web
# Parse URL parameters
$uri = [System.Uri]$url
$query = [System.Web.HttpUtility]::ParseQueryString($uri.Query)
$code = $query["code"]
$state = $query["state"]
$errorParam = $query["error"]
# Try multiple ports (default + dynamic range)
$ports = @(%d, %d, %d, %d, %d)
$success = $false
foreach ($port in $ports) {
if ($success) { break }
$callbackUrl = "http://127.0.0.1:$port/oauth/callback"
try {
if ($errorParam) {
$fullUrl = $callbackUrl + "?error=" + $errorParam
Invoke-WebRequest -Uri $fullUrl -UseBasicParsing -TimeoutSec 1 -ErrorAction Stop | Out-Null
$success = $true
} elseif ($code -and $state) {
$fullUrl = $callbackUrl + "?code=" + $code + "&state=" + $state
Invoke-WebRequest -Uri $fullUrl -UseBasicParsing -TimeoutSec 1 -ErrorAction Stop | Out-Null
$success = $true
}
} catch {
# Try next port
}
}
`, handlerPort, handlerPort+1, handlerPort+2, handlerPort+3, handlerPort+4)
if err := os.WriteFile(scriptPath, []byte(scriptContent), 0644); err != nil {
return fmt.Errorf("failed to write handler script: %w", err)
}
// Create batch wrapper
batchPath := filepath.Join(scriptDir, "kiro-oauth-handler.bat")
batchContent := fmt.Sprintf("@echo off\npowershell -ExecutionPolicy Bypass -File \"%s\" %%1\n", scriptPath)
if err := os.WriteFile(batchPath, []byte(batchContent), 0644); err != nil {
return fmt.Errorf("failed to write batch wrapper: %w", err)
}
// Register in Windows registry
commands := [][]string{
{"reg", "add", `HKCU\Software\Classes\kiro`, "/ve", "/d", "URL:Kiro Protocol", "/f"},
{"reg", "add", `HKCU\Software\Classes\kiro`, "/v", "URL Protocol", "/d", "", "/f"},
{"reg", "add", `HKCU\Software\Classes\kiro\shell`, "/f"},
{"reg", "add", `HKCU\Software\Classes\kiro\shell\open`, "/f"},
{"reg", "add", `HKCU\Software\Classes\kiro\shell\open\command`, "/ve", "/d", fmt.Sprintf("\"%s\" \"%%1\"", batchPath), "/f"},
}
for _, args := range commands {
cmd := exec.Command(args[0], args[1:]...)
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to run registry command: %w", err)
}
}
log.Info("Kiro protocol handler installed for Windows")
return nil
}
func uninstallWindowsHandler() error {
// Remove registry keys
cmd := exec.Command("reg", "delete", `HKCU\Software\Classes\kiro`, "/f")
if err := cmd.Run(); err != nil {
log.Warnf("failed to remove registry key: %v", err)
}
// Remove scripts
homeDir, _ := os.UserHomeDir()
scriptDir := filepath.Join(homeDir, ".cliproxyapi")
_ = os.Remove(filepath.Join(scriptDir, "kiro-oauth-handler.ps1"))
_ = os.Remove(filepath.Join(scriptDir, "kiro-oauth-handler.bat"))
log.Info("Kiro protocol handler uninstalled")
return nil
}
// --- macOS Implementation ---
func getDarwinAppPath() string {
homeDir, _ := os.UserHomeDir()
return filepath.Join(homeDir, "Applications", "KiroOAuthHandler.app")
}
func isDarwinHandlerInstalled() bool {
appPath := getDarwinAppPath()
_, err := os.Stat(appPath)
return err == nil
}
func installDarwinHandler(handlerPort int) error {
// Create app bundle structure
appPath := getDarwinAppPath()
contentsPath := filepath.Join(appPath, "Contents")
macOSPath := filepath.Join(contentsPath, "MacOS")
if err := os.MkdirAll(macOSPath, 0755); err != nil {
return fmt.Errorf("failed to create app bundle: %w", err)
}
// Create Info.plist
plistPath := filepath.Join(contentsPath, "Info.plist")
plistContent := `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>com.cliproxyapi.kiro-oauth-handler</string>
<key>CFBundleName</key>
<string>KiroOAuthHandler</string>
<key>CFBundleExecutable</key>
<string>kiro-oauth-handler</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>Kiro Protocol</string>
<key>CFBundleURLSchemes</key>
<array>
<string>kiro</string>
</array>
</dict>
</array>
<key>LSBackgroundOnly</key>
<true/>
</dict>
</plist>`
if err := os.WriteFile(plistPath, []byte(plistContent), 0644); err != nil {
return fmt.Errorf("failed to write Info.plist: %w", err)
}
// Create executable script - tries multiple ports to handle dynamic port allocation
execPath := filepath.Join(macOSPath, "kiro-oauth-handler")
execContent := fmt.Sprintf(`#!/bin/bash
# Kiro OAuth Protocol Handler for macOS
URL="$1"
# Check curl availability (should always exist on macOS)
if [ ! -x /usr/bin/curl ]; then
echo "Error: curl is required for Kiro OAuth handler" >&2
exit 1
fi
# Extract code and state from URL
[[ "$URL" =~ code=([^&]+) ]] && CODE="${BASH_REMATCH[1]}"
[[ "$URL" =~ state=([^&]+) ]] && STATE="${BASH_REMATCH[1]}"
[[ "$URL" =~ error=([^&]+) ]] && ERROR="${BASH_REMATCH[1]}"
# Try multiple ports (default + dynamic range)
for PORT in %d %d %d %d %d; do
if [ -n "$ERROR" ]; then
/usr/bin/curl -sf --connect-timeout 1 "http://127.0.0.1:$PORT/oauth/callback?error=$ERROR" && exit 0
elif [ -n "$CODE" ] && [ -n "$STATE" ]; then
/usr/bin/curl -sf --connect-timeout 1 "http://127.0.0.1:$PORT/oauth/callback?code=$CODE&state=$STATE" && exit 0
fi
done
`, handlerPort, handlerPort+1, handlerPort+2, handlerPort+3, handlerPort+4)
if err := os.WriteFile(execPath, []byte(execContent), 0755); err != nil {
return fmt.Errorf("failed to write executable: %w", err)
}
// Register the app with Launch Services
cmd := exec.Command("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
"-f", appPath)
if err := cmd.Run(); err != nil {
log.Warnf("lsregister failed (handler may still work): %v", err)
}
log.Info("Kiro protocol handler installed for macOS")
return nil
}
func uninstallDarwinHandler() error {
appPath := getDarwinAppPath()
// Unregister from Launch Services
cmd := exec.Command("/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
"-u", appPath)
_ = cmd.Run()
// Remove app bundle
if err := os.RemoveAll(appPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("failed to remove app bundle: %w", err)
}
log.Info("Kiro protocol handler uninstalled")
return nil
}
// ParseKiroURI parses a kiro:// URI and extracts the callback parameters.
func ParseKiroURI(rawURI string) (*AuthCallback, error) {
u, err := url.Parse(rawURI)
if err != nil {
return nil, fmt.Errorf("invalid URI: %w", err)
}
if u.Scheme != KiroProtocol {
return nil, fmt.Errorf("invalid scheme: expected %s, got %s", KiroProtocol, u.Scheme)
}
if u.Host != KiroAuthority {
return nil, fmt.Errorf("invalid authority: expected %s, got %s", KiroAuthority, u.Host)
}
query := u.Query()
return &AuthCallback{
Code: query.Get("code"),
State: query.Get("state"),
Error: query.Get("error"),
}, nil
}
// GetHandlerInstructions returns platform-specific instructions for manual handler setup.
func GetHandlerInstructions() string {
switch runtime.GOOS {
case "linux":
return `To manually set up the Kiro protocol handler on Linux:
1. Create ~/.local/share/applications/kiro-oauth-handler.desktop:
[Desktop Entry]
Name=Kiro OAuth Handler
Exec=~/.local/bin/kiro-oauth-handler %u
Type=Application
Terminal=false
MimeType=x-scheme-handler/kiro;
2. Create ~/.local/bin/kiro-oauth-handler (make it executable):
#!/bin/bash
URL="$1"
# ... (see generated script for full content)
3. Run: xdg-mime default kiro-oauth-handler.desktop x-scheme-handler/kiro`
case "windows":
return `To manually set up the Kiro protocol handler on Windows:
1. Open Registry Editor (regedit.exe)
2. Create key: HKEY_CURRENT_USER\Software\Classes\kiro
3. Set default value to: URL:Kiro Protocol
4. Create string value "URL Protocol" with empty data
5. Create subkey: shell\open\command
6. Set default value to: "C:\path\to\handler.bat" "%1"`
case "darwin":
return `To manually set up the Kiro protocol handler on macOS:
1. Create ~/Applications/KiroOAuthHandler.app bundle
2. Add Info.plist with CFBundleURLTypes containing "kiro" scheme
3. Create executable in Contents/MacOS/
4. Run: /System/Library/.../lsregister -f ~/Applications/KiroOAuthHandler.app`
default:
return "Protocol handler setup is not supported on this platform."
}
}
// SetupProtocolHandlerIfNeeded checks and installs the protocol handler if needed.
func SetupProtocolHandlerIfNeeded(handlerPort int) error {
if IsProtocolHandlerInstalled() {
log.Debug("Kiro protocol handler already installed")
return nil
}
fmt.Println("\n╔══════════════════════════════════════════════════════════╗")
fmt.Println("║ Kiro Protocol Handler Setup Required ║")
fmt.Println("╚══════════════════════════════════════════════════════════╝")
fmt.Println("\nTo enable Google/GitHub login, we need to install a protocol handler.")
fmt.Println("This allows your browser to redirect back to the CLI after authentication.")
fmt.Println("\nInstalling protocol handler...")
if err := InstallProtocolHandler(handlerPort); err != nil {
fmt.Printf("\n⚠ Automatic installation failed: %v\n", err)
fmt.Println("\nManual setup instructions:")
fmt.Println(strings.Repeat("-", 60))
fmt.Println(GetHandlerInstructions())
return err
}
fmt.Println("\n✓ Protocol handler installed successfully!")
return nil
}
+403
View File
@@ -0,0 +1,403 @@
// Package kiro provides social authentication (Google/GitHub) for Kiro via AuthServiceClient.
package kiro
import (
"bufio"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/router-for-me/CLIProxyAPI/v6/internal/browser"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
"github.com/router-for-me/CLIProxyAPI/v6/internal/util"
log "github.com/sirupsen/logrus"
"golang.org/x/term"
)
const (
// Kiro AuthService endpoint
kiroAuthServiceEndpoint = "https://prod.us-east-1.auth.desktop.kiro.dev"
// OAuth timeout
socialAuthTimeout = 10 * time.Minute
)
// SocialProvider represents the social login provider.
type SocialProvider string
const (
// ProviderGoogle is Google OAuth provider
ProviderGoogle SocialProvider = "Google"
// ProviderGitHub is GitHub OAuth provider
ProviderGitHub SocialProvider = "Github"
// Note: AWS Builder ID is NOT supported by Kiro's auth service.
// It only supports: Google, Github, Cognito
// AWS Builder ID must use device code flow via SSO OIDC.
)
// CreateTokenRequest is sent to Kiro's /oauth/token endpoint.
type CreateTokenRequest struct {
Code string `json:"code"`
CodeVerifier string `json:"code_verifier"`
RedirectURI string `json:"redirect_uri"`
InvitationCode string `json:"invitation_code,omitempty"`
}
// SocialTokenResponse from Kiro's /oauth/token endpoint for social auth.
type SocialTokenResponse struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ProfileArn string `json:"profileArn"`
ExpiresIn int `json:"expiresIn"`
}
// RefreshTokenRequest is sent to Kiro's /refreshToken endpoint.
type RefreshTokenRequest struct {
RefreshToken string `json:"refreshToken"`
}
// SocialAuthClient handles social authentication with Kiro.
type SocialAuthClient struct {
httpClient *http.Client
cfg *config.Config
protocolHandler *ProtocolHandler
}
// NewSocialAuthClient creates a new social auth client.
func NewSocialAuthClient(cfg *config.Config) *SocialAuthClient {
client := &http.Client{Timeout: 30 * time.Second}
if cfg != nil {
client = util.SetProxy(&cfg.SDKConfig, client)
}
return &SocialAuthClient{
httpClient: client,
cfg: cfg,
protocolHandler: NewProtocolHandler(),
}
}
// generatePKCE generates PKCE code verifier and challenge.
func generatePKCE() (verifier, challenge string, err error) {
// Generate 32 bytes of random data for verifier
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", "", fmt.Errorf("failed to generate random bytes: %w", err)
}
verifier = base64.RawURLEncoding.EncodeToString(b)
// Generate SHA256 hash of verifier for challenge
h := sha256.Sum256([]byte(verifier))
challenge = base64.RawURLEncoding.EncodeToString(h[:])
return verifier, challenge, nil
}
// generateState generates a random state parameter.
func generateStateParam() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// buildLoginURL constructs the Kiro OAuth login URL.
// The login endpoint expects a GET request with query parameters.
// Format: /login?idp=Google&redirect_uri=...&code_challenge=...&code_challenge_method=S256&state=...&prompt=select_account
// The prompt=select_account parameter forces the account selection screen even if already logged in.
func (c *SocialAuthClient) buildLoginURL(provider, redirectURI, codeChallenge, state string) string {
return fmt.Sprintf("%s/login?idp=%s&redirect_uri=%s&code_challenge=%s&code_challenge_method=S256&state=%s&prompt=select_account",
kiroAuthServiceEndpoint,
provider,
url.QueryEscape(redirectURI),
codeChallenge,
state,
)
}
// CreateToken exchanges the authorization code for tokens.
func (c *SocialAuthClient) CreateToken(ctx context.Context, req *CreateTokenRequest) (*SocialTokenResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to marshal token request: %w", err)
}
tokenURL := kiroAuthServiceEndpoint + "/oauth/token"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(string(body)))
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("User-Agent", "cli-proxy-api/1.0.0")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("token request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("token exchange failed (status %d): %s", resp.StatusCode, string(respBody))
return nil, fmt.Errorf("token exchange failed (status %d)", resp.StatusCode)
}
var tokenResp SocialTokenResponse
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResp, nil
}
// RefreshSocialToken refreshes an expired social auth token.
func (c *SocialAuthClient) RefreshSocialToken(ctx context.Context, refreshToken string) (*KiroTokenData, error) {
body, err := json.Marshal(&RefreshTokenRequest{RefreshToken: refreshToken})
if err != nil {
return nil, fmt.Errorf("failed to marshal refresh request: %w", err)
}
refreshURL := kiroAuthServiceEndpoint + "/refreshToken"
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, refreshURL, strings.NewReader(string(body)))
if err != nil {
return nil, fmt.Errorf("failed to create refresh request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("User-Agent", "cli-proxy-api/1.0.0")
resp, err := c.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("refresh request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read refresh response: %w", err)
}
if resp.StatusCode != http.StatusOK {
log.Debugf("token refresh failed (status %d): %s", resp.StatusCode, string(respBody))
return nil, fmt.Errorf("token refresh failed (status %d)", resp.StatusCode)
}
var tokenResp SocialTokenResponse
if err := json.Unmarshal(respBody, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse refresh response: %w", err)
}
// Validate ExpiresIn - use default 1 hour if invalid
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
expiresIn = 3600 // Default 1 hour
}
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
return &KiroTokenData{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
ProfileArn: tokenResp.ProfileArn,
ExpiresAt: expiresAt.Format(time.RFC3339),
AuthMethod: "social",
Provider: "", // Caller should preserve original provider
}, nil
}
// LoginWithSocial performs OAuth login with Google.
func (c *SocialAuthClient) LoginWithSocial(ctx context.Context, provider SocialProvider) (*KiroTokenData, error) {
providerName := string(provider)
fmt.Println("\n╔══════════════════════════════════════════════════════════╗")
fmt.Printf("║ Kiro Authentication (%s) ║\n", providerName)
fmt.Println("╚══════════════════════════════════════════════════════════╝")
// Step 1: Setup protocol handler
fmt.Println("\nSetting up authentication...")
// Start the local callback server
handlerPort, err := c.protocolHandler.Start(ctx)
if err != nil {
return nil, fmt.Errorf("failed to start callback server: %w", err)
}
defer c.protocolHandler.Stop()
// Ensure protocol handler is installed and set as default
if err := SetupProtocolHandlerIfNeeded(handlerPort); err != nil {
fmt.Println("\n⚠ Protocol handler setup failed. Trying alternative method...")
fmt.Println(" If you see a browser 'Open with' dialog, select your default browser.")
fmt.Println(" For manual setup instructions, run: cliproxy kiro --help-protocol")
log.Debugf("kiro: protocol handler setup error: %v", err)
// Continue anyway - user might have set it up manually or select browser manually
} else {
// Force set our handler as default (prevents "Open with" dialog)
forceDefaultProtocolHandler()
}
// Step 2: Generate PKCE codes
codeVerifier, codeChallenge, err := generatePKCE()
if err != nil {
return nil, fmt.Errorf("failed to generate PKCE: %w", err)
}
// Step 3: Generate state
state, err := generateStateParam()
if err != nil {
return nil, fmt.Errorf("failed to generate state: %w", err)
}
// Step 4: Build the login URL (Kiro uses GET request with query params)
authURL := c.buildLoginURL(providerName, KiroRedirectURI, codeChallenge, state)
// Set incognito mode based on config (defaults to true for Kiro, can be overridden with --no-incognito)
// Incognito mode enables multi-account support by bypassing cached sessions
if c.cfg != nil {
browser.SetIncognitoMode(c.cfg.IncognitoBrowser)
if !c.cfg.IncognitoBrowser {
log.Info("kiro: using normal browser mode (--no-incognito). Note: You may not be able to select a different account.")
} else {
log.Debug("kiro: using incognito mode for multi-account support")
}
} else {
browser.SetIncognitoMode(true) // Default to incognito if no config
log.Debug("kiro: using incognito mode for multi-account support (default)")
}
// Step 5: Open browser for user authentication
fmt.Println("\n════════════════════════════════════════════════════════════")
fmt.Printf(" Opening browser for %s authentication...\n", providerName)
fmt.Println("════════════════════════════════════════════════════════════")
fmt.Printf("\n URL: %s\n\n", authURL)
if err := browser.OpenURL(authURL); err != nil {
log.Warnf("Could not open browser automatically: %v", err)
fmt.Println(" ⚠ Could not open browser automatically.")
fmt.Println(" Please open the URL above in your browser manually.")
} else {
fmt.Println(" (Browser opened automatically)")
}
fmt.Println("\n Waiting for authentication callback...")
// Step 6: Wait for callback
callback, err := c.protocolHandler.WaitForCallback(ctx)
if err != nil {
return nil, fmt.Errorf("failed to receive callback: %w", err)
}
if callback.Error != "" {
return nil, fmt.Errorf("authentication error: %s", callback.Error)
}
if callback.State != state {
// Log state values for debugging, but don't expose in user-facing error
log.Debugf("kiro: OAuth state mismatch - expected %s, got %s", state, callback.State)
return nil, fmt.Errorf("OAuth state validation failed - please try again")
}
if callback.Code == "" {
return nil, fmt.Errorf("no authorization code received")
}
fmt.Println("\n✓ Authorization received!")
// Step 7: Exchange code for tokens
fmt.Println("Exchanging code for tokens...")
tokenReq := &CreateTokenRequest{
Code: callback.Code,
CodeVerifier: codeVerifier,
RedirectURI: KiroRedirectURI,
}
tokenResp, err := c.CreateToken(ctx, tokenReq)
if err != nil {
return nil, fmt.Errorf("failed to exchange code for tokens: %w", err)
}
fmt.Println("\n✓ Authentication successful!")
// Close the browser window
if err := browser.CloseBrowser(); err != nil {
log.Debugf("Failed to close browser: %v", err)
}
// Validate ExpiresIn - use default 1 hour if invalid
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
expiresIn = 3600
}
expiresAt := time.Now().Add(time.Duration(expiresIn) * time.Second)
// Try to extract email from JWT access token first
email := ExtractEmailFromJWT(tokenResp.AccessToken)
// If no email in JWT, ask user for account label (only in interactive mode)
if email == "" && isInteractiveTerminal() {
fmt.Print("\n Enter account label for file naming (optional, press Enter to skip): ")
reader := bufio.NewReader(os.Stdin)
var err error
email, err = reader.ReadString('\n')
if err != nil {
log.Debugf("Failed to read account label: %v", err)
}
email = strings.TrimSpace(email)
}
return &KiroTokenData{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
ProfileArn: tokenResp.ProfileArn,
ExpiresAt: expiresAt.Format(time.RFC3339),
AuthMethod: "social",
Provider: providerName,
Email: email, // JWT email or user-provided label
}, nil
}
// LoginWithGoogle performs OAuth login with Google.
func (c *SocialAuthClient) LoginWithGoogle(ctx context.Context) (*KiroTokenData, error) {
return c.LoginWithSocial(ctx, ProviderGoogle)
}
// LoginWithGitHub performs OAuth login with GitHub.
func (c *SocialAuthClient) LoginWithGitHub(ctx context.Context) (*KiroTokenData, error) {
return c.LoginWithSocial(ctx, ProviderGitHub)
}
// forceDefaultProtocolHandler sets our protocol handler as the default for kiro:// URLs.
// This prevents the "Open with" dialog from appearing on Linux.
// On non-Linux platforms, this is a no-op as they use different mechanisms.
func forceDefaultProtocolHandler() {
if runtime.GOOS != "linux" {
return // Non-Linux platforms use different handler mechanisms
}
// Set our handler as default using xdg-mime
cmd := exec.Command("xdg-mime", "default", "kiro-oauth-handler.desktop", "x-scheme-handler/kiro")
if err := cmd.Run(); err != nil {
log.Warnf("Failed to set default protocol handler: %v. You may see a handler selection dialog.", err)
}
}
// isInteractiveTerminal checks if stdin is connected to an interactive terminal.
// Returns false in CI/automated environments or when stdin is piped.
func isInteractiveTerminal() bool {
return term.IsTerminal(int(os.Stdin.Fd()))
}
File diff suppressed because it is too large Load Diff
+72
View File
@@ -0,0 +1,72 @@
package kiro
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
// KiroTokenStorage holds the persistent token data for Kiro authentication.
type KiroTokenStorage struct {
// AccessToken is the OAuth2 access token for API access
AccessToken string `json:"access_token"`
// RefreshToken is used to obtain new access tokens
RefreshToken string `json:"refresh_token"`
// ProfileArn is the AWS CodeWhisperer profile ARN
ProfileArn string `json:"profile_arn"`
// ExpiresAt is the timestamp when the token expires
ExpiresAt string `json:"expires_at"`
// AuthMethod indicates the authentication method used
AuthMethod string `json:"auth_method"`
// Provider indicates the OAuth provider
Provider string `json:"provider"`
// LastRefresh is the timestamp of the last token refresh
LastRefresh string `json:"last_refresh"`
}
// SaveTokenToFile persists the token storage to the specified file path.
func (s *KiroTokenStorage) SaveTokenToFile(authFilePath string) error {
dir := filepath.Dir(authFilePath)
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal token storage: %w", err)
}
if err := os.WriteFile(authFilePath, data, 0600); err != nil {
return fmt.Errorf("failed to write token file: %w", err)
}
return nil
}
// LoadFromFile loads token storage from the specified file path.
func LoadFromFile(authFilePath string) (*KiroTokenStorage, error) {
data, err := os.ReadFile(authFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read token file: %w", err)
}
var storage KiroTokenStorage
if err := json.Unmarshal(data, &storage); err != nil {
return nil, fmt.Errorf("failed to parse token file: %w", err)
}
return &storage, nil
}
// ToTokenData converts storage to KiroTokenData for API use.
func (s *KiroTokenStorage) ToTokenData() *KiroTokenData {
return &KiroTokenData{
AccessToken: s.AccessToken,
RefreshToken: s.RefreshToken,
ProfileArn: s.ProfileArn,
ExpiresAt: s.ExpiresAt,
AuthMethod: s.AuthMethod,
Provider: s.Provider,
}
}
+208
View File
@@ -0,0 +1,208 @@
package vertex
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"strings"
)
// NormalizeServiceAccountJSON normalizes the given JSON-encoded service account payload.
// It returns the normalized JSON (with sanitized private_key) or, if normalization fails,
// the original bytes and the encountered error.
func NormalizeServiceAccountJSON(raw []byte) ([]byte, error) {
if len(raw) == 0 {
return raw, nil
}
var payload map[string]any
if err := json.Unmarshal(raw, &payload); err != nil {
return raw, err
}
normalized, err := NormalizeServiceAccountMap(payload)
if err != nil {
return raw, err
}
out, err := json.Marshal(normalized)
if err != nil {
return raw, err
}
return out, nil
}
// NormalizeServiceAccountMap returns a copy of the given service account map with
// a sanitized private_key field that is guaranteed to contain a valid RSA PRIVATE KEY PEM block.
func NormalizeServiceAccountMap(sa map[string]any) (map[string]any, error) {
if sa == nil {
return nil, fmt.Errorf("service account payload is empty")
}
pk, _ := sa["private_key"].(string)
if strings.TrimSpace(pk) == "" {
return nil, fmt.Errorf("service account missing private_key")
}
normalized, err := sanitizePrivateKey(pk)
if err != nil {
return nil, err
}
clone := make(map[string]any, len(sa))
for k, v := range sa {
clone[k] = v
}
clone["private_key"] = normalized
return clone, nil
}
func sanitizePrivateKey(raw string) (string, error) {
pk := strings.ReplaceAll(raw, "\r\n", "\n")
pk = strings.ReplaceAll(pk, "\r", "\n")
pk = stripANSIEscape(pk)
pk = strings.ToValidUTF8(pk, "")
pk = strings.TrimSpace(pk)
normalized := pk
if block, _ := pem.Decode([]byte(pk)); block == nil {
// Attempt to reconstruct from the textual payload.
if reconstructed, err := rebuildPEM(pk); err == nil {
normalized = reconstructed
} else {
return "", fmt.Errorf("private_key is not valid pem: %w", err)
}
}
block, _ := pem.Decode([]byte(normalized))
if block == nil {
return "", fmt.Errorf("private_key pem decode failed")
}
rsaBlock, err := ensureRSAPrivateKey(block)
if err != nil {
return "", err
}
return string(pem.EncodeToMemory(rsaBlock)), nil
}
func ensureRSAPrivateKey(block *pem.Block) (*pem.Block, error) {
if block == nil {
return nil, fmt.Errorf("pem block is nil")
}
if block.Type == "RSA PRIVATE KEY" {
if _, err := x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
return nil, fmt.Errorf("private_key invalid rsa: %w", err)
}
return block, nil
}
if block.Type == "PRIVATE KEY" {
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("private_key invalid pkcs8: %w", err)
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("private_key is not an RSA key")
}
der := x509.MarshalPKCS1PrivateKey(rsaKey)
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: der}, nil
}
// Attempt auto-detection: try PKCS#1 first, then PKCS#8.
if rsaKey, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil {
der := x509.MarshalPKCS1PrivateKey(rsaKey)
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: der}, nil
}
if key, err := x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
if rsaKey, ok := key.(*rsa.PrivateKey); ok {
der := x509.MarshalPKCS1PrivateKey(rsaKey)
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: der}, nil
}
}
return nil, fmt.Errorf("private_key uses unsupported format")
}
func rebuildPEM(raw string) (string, error) {
kind := "PRIVATE KEY"
if strings.Contains(raw, "RSA PRIVATE KEY") {
kind = "RSA PRIVATE KEY"
}
header := "-----BEGIN " + kind + "-----"
footer := "-----END " + kind + "-----"
start := strings.Index(raw, header)
end := strings.Index(raw, footer)
if start < 0 || end <= start {
return "", fmt.Errorf("missing pem markers")
}
body := raw[start+len(header) : end]
payload := filterBase64(body)
if payload == "" {
return "", fmt.Errorf("private_key base64 payload empty")
}
der, err := base64.StdEncoding.DecodeString(payload)
if err != nil {
return "", fmt.Errorf("private_key base64 decode failed: %w", err)
}
block := &pem.Block{Type: kind, Bytes: der}
return string(pem.EncodeToMemory(block)), nil
}
func filterBase64(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r >= 'A' && r <= 'Z':
b.WriteRune(r)
case r >= 'a' && r <= 'z':
b.WriteRune(r)
case r >= '0' && r <= '9':
b.WriteRune(r)
case r == '+' || r == '/' || r == '=':
b.WriteRune(r)
default:
// skip
}
}
return b.String()
}
func stripANSIEscape(s string) string {
in := []rune(s)
var out []rune
for i := 0; i < len(in); i++ {
r := in[i]
if r != 0x1b {
out = append(out, r)
continue
}
if i+1 >= len(in) {
continue
}
next := in[i+1]
switch next {
case ']':
i += 2
for i < len(in) {
if in[i] == 0x07 {
break
}
if in[i] == 0x1b && i+1 < len(in) && in[i+1] == '\\' {
i++
break
}
i++
}
case '[':
i += 2
for i < len(in) {
if (in[i] >= 'A' && in[i] <= 'Z') || (in[i] >= 'a' && in[i] <= 'z') {
break
}
i++
}
default:
// skip single ESC
}
}
return string(out)
}
@@ -0,0 +1,66 @@
// Package vertex provides token storage for Google Vertex AI Gemini via service account credentials.
// It serialises service account JSON into an auth file that is consumed by the runtime executor.
package vertex
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/router-for-me/CLIProxyAPI/v6/internal/misc"
log "github.com/sirupsen/logrus"
)
// VertexCredentialStorage stores the service account JSON for Vertex AI access.
// The content is persisted verbatim under the "service_account" key, together with
// helper fields for project, location and email to improve logging and discovery.
type VertexCredentialStorage struct {
// ServiceAccount holds the parsed service account JSON content.
ServiceAccount map[string]any `json:"service_account"`
// ProjectID is derived from the service account JSON (project_id).
ProjectID string `json:"project_id"`
// Email is the client_email from the service account JSON.
Email string `json:"email"`
// Location optionally sets a default region (e.g., us-central1) for Vertex endpoints.
Location string `json:"location,omitempty"`
// Type is the provider identifier stored alongside credentials. Always "vertex".
Type string `json:"type"`
}
// SaveTokenToFile writes the credential payload to the given file path in JSON format.
// It ensures the parent directory exists and logs the operation for transparency.
func (s *VertexCredentialStorage) SaveTokenToFile(authFilePath string) error {
misc.LogSavingCredentials(authFilePath)
if s == nil {
return fmt.Errorf("vertex credential: storage is nil")
}
if s.ServiceAccount == nil {
return fmt.Errorf("vertex credential: service account content is empty")
}
// Ensure we tag the file with the provider type.
s.Type = "vertex"
if err := os.MkdirAll(filepath.Dir(authFilePath), 0o700); err != nil {
return fmt.Errorf("vertex credential: create directory failed: %w", err)
}
f, err := os.Create(authFilePath)
if err != nil {
return fmt.Errorf("vertex credential: create file failed: %w", err)
}
defer func() {
if errClose := f.Close(); errClose != nil {
log.Errorf("vertex credential: failed to close file: %v", errClose)
}
}()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
if err = enc.Encode(s); err != nil {
return fmt.Errorf("vertex credential: encode failed: %w", err)
}
return nil
}
+416 -14
View File
@@ -6,14 +6,49 @@ import (
"fmt"
"os/exec"
"runtime"
"strings"
"sync"
pkgbrowser "github.com/pkg/browser"
log "github.com/sirupsen/logrus"
"github.com/skratchdot/open-golang/open"
)
// incognitoMode controls whether to open URLs in incognito/private mode.
// This is useful for OAuth flows where you want to use a different account.
var incognitoMode bool
// lastBrowserProcess stores the last opened browser process for cleanup
var lastBrowserProcess *exec.Cmd
var browserMutex sync.Mutex
// SetIncognitoMode enables or disables incognito/private browsing mode.
func SetIncognitoMode(enabled bool) {
incognitoMode = enabled
}
// IsIncognitoMode returns whether incognito mode is enabled.
func IsIncognitoMode() bool {
return incognitoMode
}
// CloseBrowser closes the last opened browser process.
func CloseBrowser() error {
browserMutex.Lock()
defer browserMutex.Unlock()
if lastBrowserProcess == nil || lastBrowserProcess.Process == nil {
return nil
}
err := lastBrowserProcess.Process.Kill()
lastBrowserProcess = nil
return err
}
// OpenURL opens the specified URL in the default web browser.
// It first attempts to use a platform-agnostic library and falls back to
// platform-specific commands if that fails.
// It uses the pkg/browser library which provides robust cross-platform support
// for Windows, macOS, and Linux.
// If incognito mode is enabled, it will open in a private/incognito window.
//
// Parameters:
// - url: The URL to open.
@@ -21,16 +56,22 @@ import (
// Returns:
// - An error if the URL cannot be opened, otherwise nil.
func OpenURL(url string) error {
fmt.Printf("Attempting to open URL in browser: %s\n", url)
log.Debugf("Opening URL in browser: %s (incognito=%v)", url, incognitoMode)
// Try using the open-golang library first
err := open.Run(url)
// If incognito mode is enabled, use platform-specific incognito commands
if incognitoMode {
log.Debug("Using incognito mode")
return openURLIncognito(url)
}
// Use pkg/browser for cross-platform support
err := pkgbrowser.OpenURL(url)
if err == nil {
log.Debug("Successfully opened URL using open-golang library")
log.Debug("Successfully opened URL using pkg/browser library")
return nil
}
log.Debugf("open-golang failed: %v, trying platform-specific commands", err)
log.Debugf("pkg/browser failed: %v, trying platform-specific commands", err)
// Fallback to platform-specific commands
return openURLPlatformSpecific(url)
@@ -78,18 +119,379 @@ func openURLPlatformSpecific(url string) error {
return nil
}
// openURLIncognito opens a URL in incognito/private browsing mode.
// It first tries to detect the default browser and use its incognito flag.
// Falls back to a chain of known browsers if detection fails.
//
// Parameters:
// - url: The URL to open.
//
// Returns:
// - An error if the URL cannot be opened, otherwise nil.
func openURLIncognito(url string) error {
// First, try to detect and use the default browser
if cmd := tryDefaultBrowserIncognito(url); cmd != nil {
log.Debugf("Using detected default browser: %s %v", cmd.Path, cmd.Args[1:])
if err := cmd.Start(); err == nil {
storeBrowserProcess(cmd)
log.Debug("Successfully opened URL in default browser's incognito mode")
return nil
}
log.Debugf("Failed to start default browser, trying fallback chain")
}
// Fallback to known browser chain
cmd := tryFallbackBrowsersIncognito(url)
if cmd == nil {
log.Warn("No browser with incognito support found, falling back to normal mode")
return openURLPlatformSpecific(url)
}
log.Debugf("Running incognito command: %s %v", cmd.Path, cmd.Args[1:])
err := cmd.Start()
if err != nil {
log.Warnf("Failed to open incognito browser: %v, falling back to normal mode", err)
return openURLPlatformSpecific(url)
}
storeBrowserProcess(cmd)
log.Debug("Successfully opened URL in incognito/private mode")
return nil
}
// storeBrowserProcess safely stores the browser process for later cleanup.
func storeBrowserProcess(cmd *exec.Cmd) {
browserMutex.Lock()
lastBrowserProcess = cmd
browserMutex.Unlock()
}
// tryDefaultBrowserIncognito attempts to detect the default browser and return
// an exec.Cmd configured with the appropriate incognito flag.
func tryDefaultBrowserIncognito(url string) *exec.Cmd {
switch runtime.GOOS {
case "darwin":
return tryDefaultBrowserMacOS(url)
case "windows":
return tryDefaultBrowserWindows(url)
case "linux":
return tryDefaultBrowserLinux(url)
}
return nil
}
// tryDefaultBrowserMacOS detects the default browser on macOS.
func tryDefaultBrowserMacOS(url string) *exec.Cmd {
// Try to get default browser from Launch Services
out, err := exec.Command("defaults", "read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers").Output()
if err != nil {
return nil
}
output := string(out)
var browserName string
// Parse the output to find the http/https handler
if containsBrowserID(output, "com.google.chrome") {
browserName = "chrome"
} else if containsBrowserID(output, "org.mozilla.firefox") {
browserName = "firefox"
} else if containsBrowserID(output, "com.apple.safari") {
browserName = "safari"
} else if containsBrowserID(output, "com.brave.browser") {
browserName = "brave"
} else if containsBrowserID(output, "com.microsoft.edgemac") {
browserName = "edge"
}
return createMacOSIncognitoCmd(browserName, url)
}
// containsBrowserID checks if the LaunchServices output contains a browser ID.
func containsBrowserID(output, bundleID string) bool {
return strings.Contains(output, bundleID)
}
// createMacOSIncognitoCmd creates the appropriate incognito command for macOS browsers.
func createMacOSIncognitoCmd(browserName, url string) *exec.Cmd {
switch browserName {
case "chrome":
// Try direct path first
chromePath := "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
if _, err := exec.LookPath(chromePath); err == nil {
return exec.Command(chromePath, "--incognito", url)
}
return exec.Command("open", "-na", "Google Chrome", "--args", "--incognito", url)
case "firefox":
return exec.Command("open", "-na", "Firefox", "--args", "--private-window", url)
case "safari":
// Safari doesn't have CLI incognito, try AppleScript
return tryAppleScriptSafariPrivate(url)
case "brave":
return exec.Command("open", "-na", "Brave Browser", "--args", "--incognito", url)
case "edge":
return exec.Command("open", "-na", "Microsoft Edge", "--args", "--inprivate", url)
}
return nil
}
// tryAppleScriptSafariPrivate attempts to open Safari in private browsing mode using AppleScript.
func tryAppleScriptSafariPrivate(url string) *exec.Cmd {
// AppleScript to open a new private window in Safari
script := fmt.Sprintf(`
tell application "Safari"
activate
tell application "System Events"
keystroke "n" using {command down, shift down}
delay 0.5
end tell
set URL of document 1 to "%s"
end tell
`, url)
cmd := exec.Command("osascript", "-e", script)
// Test if this approach works by checking if Safari is available
if _, err := exec.LookPath("/Applications/Safari.app/Contents/MacOS/Safari"); err != nil {
log.Debug("Safari not found, AppleScript private window not available")
return nil
}
log.Debug("Attempting Safari private window via AppleScript")
return cmd
}
// tryDefaultBrowserWindows detects the default browser on Windows via registry.
func tryDefaultBrowserWindows(url string) *exec.Cmd {
// Query registry for default browser
out, err := exec.Command("reg", "query",
`HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice`,
"/v", "ProgId").Output()
if err != nil {
return nil
}
output := string(out)
var browserName string
// Map ProgId to browser name
if strings.Contains(output, "ChromeHTML") {
browserName = "chrome"
} else if strings.Contains(output, "FirefoxURL") {
browserName = "firefox"
} else if strings.Contains(output, "MSEdgeHTM") {
browserName = "edge"
} else if strings.Contains(output, "BraveHTML") {
browserName = "brave"
}
return createWindowsIncognitoCmd(browserName, url)
}
// createWindowsIncognitoCmd creates the appropriate incognito command for Windows browsers.
func createWindowsIncognitoCmd(browserName, url string) *exec.Cmd {
switch browserName {
case "chrome":
paths := []string{
"chrome",
`C:\Program Files\Google\Chrome\Application\chrome.exe`,
`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
}
for _, p := range paths {
if _, err := exec.LookPath(p); err == nil {
return exec.Command(p, "--incognito", url)
}
}
case "firefox":
if path, err := exec.LookPath("firefox"); err == nil {
return exec.Command(path, "--private-window", url)
}
case "edge":
paths := []string{
"msedge",
`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
}
for _, p := range paths {
if _, err := exec.LookPath(p); err == nil {
return exec.Command(p, "--inprivate", url)
}
}
case "brave":
paths := []string{
`C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe`,
`C:\Program Files (x86)\BraveSoftware\Brave-Browser\Application\brave.exe`,
}
for _, p := range paths {
if _, err := exec.LookPath(p); err == nil {
return exec.Command(p, "--incognito", url)
}
}
}
return nil
}
// tryDefaultBrowserLinux detects the default browser on Linux using xdg-settings.
func tryDefaultBrowserLinux(url string) *exec.Cmd {
out, err := exec.Command("xdg-settings", "get", "default-web-browser").Output()
if err != nil {
return nil
}
desktop := string(out)
var browserName string
// Map .desktop file to browser name
if strings.Contains(desktop, "google-chrome") || strings.Contains(desktop, "chrome") {
browserName = "chrome"
} else if strings.Contains(desktop, "firefox") {
browserName = "firefox"
} else if strings.Contains(desktop, "chromium") {
browserName = "chromium"
} else if strings.Contains(desktop, "brave") {
browserName = "brave"
} else if strings.Contains(desktop, "microsoft-edge") || strings.Contains(desktop, "msedge") {
browserName = "edge"
}
return createLinuxIncognitoCmd(browserName, url)
}
// createLinuxIncognitoCmd creates the appropriate incognito command for Linux browsers.
func createLinuxIncognitoCmd(browserName, url string) *exec.Cmd {
switch browserName {
case "chrome":
paths := []string{"google-chrome", "google-chrome-stable"}
for _, p := range paths {
if path, err := exec.LookPath(p); err == nil {
return exec.Command(path, "--incognito", url)
}
}
case "firefox":
paths := []string{"firefox", "firefox-esr"}
for _, p := range paths {
if path, err := exec.LookPath(p); err == nil {
return exec.Command(path, "--private-window", url)
}
}
case "chromium":
paths := []string{"chromium", "chromium-browser"}
for _, p := range paths {
if path, err := exec.LookPath(p); err == nil {
return exec.Command(path, "--incognito", url)
}
}
case "brave":
if path, err := exec.LookPath("brave-browser"); err == nil {
return exec.Command(path, "--incognito", url)
}
case "edge":
if path, err := exec.LookPath("microsoft-edge"); err == nil {
return exec.Command(path, "--inprivate", url)
}
}
return nil
}
// tryFallbackBrowsersIncognito tries a chain of known browsers as fallback.
func tryFallbackBrowsersIncognito(url string) *exec.Cmd {
switch runtime.GOOS {
case "darwin":
return tryFallbackBrowsersMacOS(url)
case "windows":
return tryFallbackBrowsersWindows(url)
case "linux":
return tryFallbackBrowsersLinuxChain(url)
}
return nil
}
// tryFallbackBrowsersMacOS tries known browsers on macOS.
func tryFallbackBrowsersMacOS(url string) *exec.Cmd {
// Try Chrome
chromePath := "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
if _, err := exec.LookPath(chromePath); err == nil {
return exec.Command(chromePath, "--incognito", url)
}
// Try Firefox
if _, err := exec.LookPath("/Applications/Firefox.app/Contents/MacOS/firefox"); err == nil {
return exec.Command("open", "-na", "Firefox", "--args", "--private-window", url)
}
// Try Brave
if _, err := exec.LookPath("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"); err == nil {
return exec.Command("open", "-na", "Brave Browser", "--args", "--incognito", url)
}
// Try Edge
if _, err := exec.LookPath("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"); err == nil {
return exec.Command("open", "-na", "Microsoft Edge", "--args", "--inprivate", url)
}
// Last resort: try Safari with AppleScript
if cmd := tryAppleScriptSafariPrivate(url); cmd != nil {
log.Info("Using Safari with AppleScript for private browsing (may require accessibility permissions)")
return cmd
}
return nil
}
// tryFallbackBrowsersWindows tries known browsers on Windows.
func tryFallbackBrowsersWindows(url string) *exec.Cmd {
// Chrome
chromePaths := []string{
"chrome",
`C:\Program Files\Google\Chrome\Application\chrome.exe`,
`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
}
for _, p := range chromePaths {
if _, err := exec.LookPath(p); err == nil {
return exec.Command(p, "--incognito", url)
}
}
// Firefox
if path, err := exec.LookPath("firefox"); err == nil {
return exec.Command(path, "--private-window", url)
}
// Edge (usually available on Windows 10+)
edgePaths := []string{
"msedge",
`C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`,
`C:\Program Files\Microsoft\Edge\Application\msedge.exe`,
}
for _, p := range edgePaths {
if _, err := exec.LookPath(p); err == nil {
return exec.Command(p, "--inprivate", url)
}
}
return nil
}
// tryFallbackBrowsersLinuxChain tries known browsers on Linux.
func tryFallbackBrowsersLinuxChain(url string) *exec.Cmd {
type browserConfig struct {
name string
flag string
}
browsers := []browserConfig{
{"google-chrome", "--incognito"},
{"google-chrome-stable", "--incognito"},
{"chromium", "--incognito"},
{"chromium-browser", "--incognito"},
{"firefox", "--private-window"},
{"firefox-esr", "--private-window"},
{"brave-browser", "--incognito"},
{"microsoft-edge", "--inprivate"},
}
for _, b := range browsers {
if path, err := exec.LookPath(b.name); err == nil {
return exec.Command(path, b.flag, url)
}
}
return nil
}
// IsAvailable checks if the system has a command available to open a web browser.
// It verifies the presence of necessary commands for the current operating system.
//
// Returns:
// - true if a browser can be opened, false otherwise.
func IsAvailable() bool {
// First check if open-golang can work
testErr := open.Run("about:blank")
if testErr == nil {
return true
}
// Check platform-specific commands
switch runtime.GOOS {
case "darwin":
+15
View File
@@ -0,0 +1,15 @@
// Package buildinfo exposes compile-time metadata shared across the server.
package buildinfo
// The following variables are overridden via ldflags during release builds.
// Defaults cover local development builds.
var (
// Version is the semantic version or git describe output of the binary.
Version = "dev"
// Commit is the git commit SHA baked into the binary.
Commit = "none"
// BuildDate records when the binary was built in UTC.
BuildDate = "unknown"
)
+164
View File
@@ -0,0 +1,164 @@
package cache
import (
"crypto/sha256"
"encoding/hex"
"sort"
"sync"
"time"
)
// SignatureEntry holds a cached thinking signature with timestamp
type SignatureEntry struct {
Signature string
Timestamp time.Time
}
const (
// SignatureCacheTTL is how long signatures are valid
SignatureCacheTTL = 1 * time.Hour
// MaxEntriesPerSession limits memory usage per session
MaxEntriesPerSession = 100
// SignatureTextHashLen is the length of the hash key (16 hex chars = 64-bit key space)
SignatureTextHashLen = 16
// MinValidSignatureLen is the minimum length for a signature to be considered valid
MinValidSignatureLen = 50
)
// signatureCache stores signatures by sessionId -> textHash -> SignatureEntry
var signatureCache sync.Map
// sessionCache is the inner map type
type sessionCache struct {
mu sync.RWMutex
entries map[string]SignatureEntry
}
// hashText creates a stable, Unicode-safe key from text content
func hashText(text string) string {
h := sha256.Sum256([]byte(text))
return hex.EncodeToString(h[:])[:SignatureTextHashLen]
}
// getOrCreateSession gets or creates a session cache
func getOrCreateSession(sessionID string) *sessionCache {
if val, ok := signatureCache.Load(sessionID); ok {
return val.(*sessionCache)
}
sc := &sessionCache{entries: make(map[string]SignatureEntry)}
actual, _ := signatureCache.LoadOrStore(sessionID, sc)
return actual.(*sessionCache)
}
// CacheSignature stores a thinking signature for a given session and text.
// Used for Claude models that require signed thinking blocks in multi-turn conversations.
func CacheSignature(sessionID, text, signature string) {
if sessionID == "" || text == "" || signature == "" {
return
}
if len(signature) < MinValidSignatureLen {
return
}
sc := getOrCreateSession(sessionID)
textHash := hashText(text)
sc.mu.Lock()
defer sc.mu.Unlock()
// Evict expired entries if at capacity
if len(sc.entries) >= MaxEntriesPerSession {
now := time.Now()
for key, entry := range sc.entries {
if now.Sub(entry.Timestamp) > SignatureCacheTTL {
delete(sc.entries, key)
}
}
// If still at capacity, remove oldest entries
if len(sc.entries) >= MaxEntriesPerSession {
// Find and remove oldest quarter
oldest := make([]struct {
key string
ts time.Time
}, 0, len(sc.entries))
for key, entry := range sc.entries {
oldest = append(oldest, struct {
key string
ts time.Time
}{key, entry.Timestamp})
}
// Sort by timestamp (oldest first) using sort.Slice
sort.Slice(oldest, func(i, j int) bool {
return oldest[i].ts.Before(oldest[j].ts)
})
toRemove := len(oldest) / 4
if toRemove < 1 {
toRemove = 1
}
for i := 0; i < toRemove; i++ {
delete(sc.entries, oldest[i].key)
}
}
}
sc.entries[textHash] = SignatureEntry{
Signature: signature,
Timestamp: time.Now(),
}
}
// GetCachedSignature retrieves a cached signature for a given session and text.
// Returns empty string if not found or expired.
func GetCachedSignature(sessionID, text string) string {
if sessionID == "" || text == "" {
return ""
}
val, ok := signatureCache.Load(sessionID)
if !ok {
return ""
}
sc := val.(*sessionCache)
textHash := hashText(text)
sc.mu.RLock()
entry, exists := sc.entries[textHash]
sc.mu.RUnlock()
if !exists {
return ""
}
// Check if expired
if time.Since(entry.Timestamp) > SignatureCacheTTL {
sc.mu.Lock()
delete(sc.entries, textHash)
sc.mu.Unlock()
return ""
}
return entry.Signature
}
// ClearSignatureCache clears signature cache for a specific session or all sessions.
func ClearSignatureCache(sessionID string) {
if sessionID != "" {
signatureCache.Delete(sessionID)
} else {
signatureCache.Range(func(key, _ any) bool {
signatureCache.Delete(key)
return true
})
}
}
// HasValidSignature checks if a signature is valid (non-empty and long enough)
func HasValidSignature(signature string) bool {
return signature != "" && len(signature) >= MinValidSignatureLen
}
+216
View File
@@ -0,0 +1,216 @@
package cache
import (
"testing"
"time"
)
func TestCacheSignature_BasicStorageAndRetrieval(t *testing.T) {
ClearSignatureCache("")
sessionID := "test-session-1"
text := "This is some thinking text content"
signature := "abc123validSignature1234567890123456789012345678901234567890"
// Store signature
CacheSignature(sessionID, text, signature)
// Retrieve signature
retrieved := GetCachedSignature(sessionID, text)
if retrieved != signature {
t.Errorf("Expected signature '%s', got '%s'", signature, retrieved)
}
}
func TestCacheSignature_DifferentSessions(t *testing.T) {
ClearSignatureCache("")
text := "Same text in different sessions"
sig1 := "signature1_1234567890123456789012345678901234567890123456"
sig2 := "signature2_1234567890123456789012345678901234567890123456"
CacheSignature("session-a", text, sig1)
CacheSignature("session-b", text, sig2)
if GetCachedSignature("session-a", text) != sig1 {
t.Error("Session-a signature mismatch")
}
if GetCachedSignature("session-b", text) != sig2 {
t.Error("Session-b signature mismatch")
}
}
func TestCacheSignature_NotFound(t *testing.T) {
ClearSignatureCache("")
// Non-existent session
if got := GetCachedSignature("nonexistent", "some text"); got != "" {
t.Errorf("Expected empty string for nonexistent session, got '%s'", got)
}
// Existing session but different text
CacheSignature("session-x", "text-a", "sigA12345678901234567890123456789012345678901234567890")
if got := GetCachedSignature("session-x", "text-b"); got != "" {
t.Errorf("Expected empty string for different text, got '%s'", got)
}
}
func TestCacheSignature_EmptyInputs(t *testing.T) {
ClearSignatureCache("")
// All empty/invalid inputs should be no-ops
CacheSignature("", "text", "sig12345678901234567890123456789012345678901234567890")
CacheSignature("session", "", "sig12345678901234567890123456789012345678901234567890")
CacheSignature("session", "text", "")
CacheSignature("session", "text", "short") // Too short
if got := GetCachedSignature("session", "text"); got != "" {
t.Errorf("Expected empty after invalid cache attempts, got '%s'", got)
}
}
func TestCacheSignature_ShortSignatureRejected(t *testing.T) {
ClearSignatureCache("")
sessionID := "test-short-sig"
text := "Some text"
shortSig := "abc123" // Less than 50 chars
CacheSignature(sessionID, text, shortSig)
if got := GetCachedSignature(sessionID, text); got != "" {
t.Errorf("Short signature should be rejected, got '%s'", got)
}
}
func TestClearSignatureCache_SpecificSession(t *testing.T) {
ClearSignatureCache("")
sig := "validSig1234567890123456789012345678901234567890123456"
CacheSignature("session-1", "text", sig)
CacheSignature("session-2", "text", sig)
ClearSignatureCache("session-1")
if got := GetCachedSignature("session-1", "text"); got != "" {
t.Error("session-1 should be cleared")
}
if got := GetCachedSignature("session-2", "text"); got != sig {
t.Error("session-2 should still exist")
}
}
func TestClearSignatureCache_AllSessions(t *testing.T) {
ClearSignatureCache("")
sig := "validSig1234567890123456789012345678901234567890123456"
CacheSignature("session-1", "text", sig)
CacheSignature("session-2", "text", sig)
ClearSignatureCache("")
if got := GetCachedSignature("session-1", "text"); got != "" {
t.Error("session-1 should be cleared")
}
if got := GetCachedSignature("session-2", "text"); got != "" {
t.Error("session-2 should be cleared")
}
}
func TestHasValidSignature(t *testing.T) {
tests := []struct {
name string
signature string
expected bool
}{
{"valid long signature", "abc123validSignature1234567890123456789012345678901234567890", true},
{"exactly 50 chars", "12345678901234567890123456789012345678901234567890", true},
{"49 chars - invalid", "1234567890123456789012345678901234567890123456789", false},
{"empty string", "", false},
{"short signature", "abc", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := HasValidSignature(tt.signature)
if result != tt.expected {
t.Errorf("HasValidSignature(%q) = %v, expected %v", tt.signature, result, tt.expected)
}
})
}
}
func TestCacheSignature_TextHashCollisionResistance(t *testing.T) {
ClearSignatureCache("")
sessionID := "hash-test-session"
// Different texts should produce different hashes
text1 := "First thinking text"
text2 := "Second thinking text"
sig1 := "signature1_1234567890123456789012345678901234567890123456"
sig2 := "signature2_1234567890123456789012345678901234567890123456"
CacheSignature(sessionID, text1, sig1)
CacheSignature(sessionID, text2, sig2)
if GetCachedSignature(sessionID, text1) != sig1 {
t.Error("text1 signature mismatch")
}
if GetCachedSignature(sessionID, text2) != sig2 {
t.Error("text2 signature mismatch")
}
}
func TestCacheSignature_UnicodeText(t *testing.T) {
ClearSignatureCache("")
sessionID := "unicode-session"
text := "한글 텍스트와 이모지 🎉 그리고 特殊文字"
sig := "unicodeSig123456789012345678901234567890123456789012345"
CacheSignature(sessionID, text, sig)
if got := GetCachedSignature(sessionID, text); got != sig {
t.Errorf("Unicode text signature retrieval failed, got '%s'", got)
}
}
func TestCacheSignature_Overwrite(t *testing.T) {
ClearSignatureCache("")
sessionID := "overwrite-session"
text := "Same text"
sig1 := "firstSignature12345678901234567890123456789012345678901"
sig2 := "secondSignature1234567890123456789012345678901234567890"
CacheSignature(sessionID, text, sig1)
CacheSignature(sessionID, text, sig2) // Overwrite
if got := GetCachedSignature(sessionID, text); got != sig2 {
t.Errorf("Expected overwritten signature '%s', got '%s'", sig2, got)
}
}
// Note: TTL expiration test is tricky to test without mocking time
// We test the logic path exists but actual expiration would require time manipulation
func TestCacheSignature_ExpirationLogic(t *testing.T) {
ClearSignatureCache("")
// This test verifies the expiration check exists
// In a real scenario, we'd mock time.Now()
sessionID := "expiration-test"
text := "text"
sig := "validSig1234567890123456789012345678901234567890123456"
CacheSignature(sessionID, text, sig)
// Fresh entry should be retrievable
if got := GetCachedSignature(sessionID, text); got != sig {
t.Errorf("Fresh entry should be retrievable, got '%s'", got)
}
// We can't easily test actual expiration without time mocking
// but the logic is verified by the implementation
_ = time.Now() // Acknowledge we're not testing time passage
}
+6 -1
View File
@@ -24,12 +24,17 @@ func DoClaudeLogin(cfg *config.Config, options *LoginOptions) {
options = &LoginOptions{}
}
promptFn := options.Prompt
if promptFn == nil {
promptFn = defaultProjectPrompt()
}
manager := newAuthManager()
authOpts := &sdkAuth.LoginOptions{
NoBrowser: options.NoBrowser,
Metadata: map[string]string{},
Prompt: options.Prompt,
Prompt: promptFn,
}
_, savedPath, err := manager.Login(context.Background(), "claude", cfg, authOpts)
+43
View File
@@ -0,0 +1,43 @@
package cmd
import (
"context"
"fmt"
"github.com/router-for-me/CLIProxyAPI/v6/internal/config"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
log "github.com/sirupsen/logrus"
)
// DoAntigravityLogin triggers the OAuth flow for the antigravity provider and saves tokens.
func DoAntigravityLogin(cfg *config.Config, options *LoginOptions) {
if options == nil {
options = &LoginOptions{}
}
promptFn := options.Prompt
if promptFn == nil {
promptFn = defaultProjectPrompt()
}
manager := newAuthManager()
authOpts := &sdkAuth.LoginOptions{
NoBrowser: options.NoBrowser,
Metadata: map[string]string{},
Prompt: promptFn,
}
record, savedPath, err := manager.Login(context.Background(), "antigravity", cfg, authOpts)
if err != nil {
log.Errorf("Antigravity authentication failed: %v", err)
return
}
if savedPath != "" {
fmt.Printf("Authentication saved to %s\n", savedPath)
}
if record != nil && record.Label != "" {
fmt.Printf("Authenticated as %s\n", record.Label)
}
fmt.Println("Antigravity authentication successful!")
}
+25 -23
View File
@@ -1,23 +1,25 @@
package cmd
import (
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
)
// newAuthManager creates a new authentication manager instance with all supported
// authenticators and a file-based token store. It initializes authenticators for
// Gemini, Codex, Claude, and Qwen providers.
//
// Returns:
// - *sdkAuth.Manager: A configured authentication manager instance
func newAuthManager() *sdkAuth.Manager {
store := sdkAuth.GetTokenStore()
manager := sdkAuth.NewManager(store,
sdkAuth.NewGeminiAuthenticator(),
sdkAuth.NewCodexAuthenticator(),
sdkAuth.NewClaudeAuthenticator(),
sdkAuth.NewQwenAuthenticator(),
sdkAuth.NewIFlowAuthenticator(),
)
return manager
}
package cmd
import (
sdkAuth "github.com/router-for-me/CLIProxyAPI/v6/sdk/auth"
)
// newAuthManager creates a new authentication manager instance with all supported
// authenticators and a file-based token store. It initializes authenticators for
// Gemini, Codex, Claude, Qwen, IFlow, Antigravity, and Kiro providers.
//
// Returns:
// - *sdkAuth.Manager: A configured authentication manager instance
func newAuthManager() *sdkAuth.Manager {
store := sdkAuth.GetTokenStore()
manager := sdkAuth.NewManager(store,
sdkAuth.NewGeminiAuthenticator(),
sdkAuth.NewCodexAuthenticator(),
sdkAuth.NewClaudeAuthenticator(),
sdkAuth.NewQwenAuthenticator(),
sdkAuth.NewIFlowAuthenticator(),
sdkAuth.NewAntigravityAuthenticator(),
sdkAuth.NewKiroAuthenticator(),
)
return manager
}

Some files were not shown because too many files have changed in this diff Show More