mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-25 21:54:58 +08:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e01ef2f51a | |||
| 3434dcb87c | |||
| dc8a70b14e | |||
| 4ee45d2bc3 | |||
| be246f8596 | |||
| 6046c166cc | |||
| fe4a968eef | |||
| 55301abc00 | |||
| 1c6689a0bc | |||
| 9404341f14 | |||
| 53dd0a90f3 | |||
| 779fefd86d | |||
| 096c1d57c4 | |||
| adb868d0cf | |||
| a6ad896db0 | |||
| d6cf4390ac | |||
| 0ef670325b | |||
| 07fc6b175e | |||
| 79d3ecc1b8 | |||
| 9c249d9486 | |||
| 15f60e8ce2 | |||
| 3d733a3b80 | |||
| cfb113ac8d | |||
| 62a4ab2ad3 | |||
| aa0f191420 | |||
| b8305f281b | |||
| b3af191fab |
@@ -9,6 +9,55 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
---
|
||||
|
||||
## [3.10.2] - 2026-01-24
|
||||
|
||||
### Patch Release
|
||||
|
||||
This maintenance release adds skill sync options and includes important bug fixes.
|
||||
|
||||
### Added
|
||||
|
||||
- **Skills**: Add skill sync method setting with symlink/copy options
|
||||
- **Partners**: Add RightCode as official partner
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Prompts**: Clear prompt file when all prompts are disabled
|
||||
- **OpenCode**: Preserve extra model fields during serialization
|
||||
- **Provider Form**: Backfill model fields when editing Claude provider
|
||||
|
||||
---
|
||||
|
||||
## [3.10.1] - 2026-01-23
|
||||
|
||||
### Patch Release
|
||||
|
||||
This maintenance release includes important bug fixes for Windows platform, UI improvements, and code quality enhancements.
|
||||
|
||||
### Added
|
||||
|
||||
- **Provider Icons**: Updated RightCode provider icon with improved visual design
|
||||
|
||||
### Changed
|
||||
|
||||
- **Proxy Rectifier**: Changed rectifier default state to disabled for better stability
|
||||
- **Window Settings**: Reordered window settings and updated default values for improved UX
|
||||
- **UI Layout**: Increased app icon collapse threshold from 3 to 4 icons
|
||||
- **Code Quality**: Simplified `RectifierConfig` implementation using `#[derive(Default)]`
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Windows Platform**:
|
||||
- Fixed terminal window closing immediately after execution on Windows
|
||||
- Corrected OpenCode config path resolution on Windows
|
||||
- **UI Improvements**:
|
||||
- Fixed ProviderIcon color validation to prevent black icons from appearing
|
||||
- Unified layout padding across all panels for consistent spacing
|
||||
- Fixed panel content alignment with header constraints
|
||||
- **Code Quality**: Resolved Rust Clippy warnings and applied consistent formatting
|
||||
|
||||
---
|
||||
|
||||
## [3.10.0] - 2026-01-21
|
||||
|
||||
### Feature Release
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# All-in-One Assistant for Claude Code, Codex & Gemini CLI
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@ This project is sponsored by Z.ai, supporting us with their GLM CODING PLAN.GLM
|
||||
|
||||
## Features
|
||||
|
||||
### Current Version: v3.10.0 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.9.0-en.md)
|
||||
### Current Version: v3.10.2 | [Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-note-v3.9.0-en.md)
|
||||
|
||||
**v3.8.0 Major Update (2025-11-28)**
|
||||
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI オールインワン・アシスタント
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
## 特長
|
||||
|
||||
### 現在のバージョン:v3.10.0 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.9.0-ja.md)
|
||||
### 現在のバージョン:v3.10.2 | [完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-note-v3.9.0-ja.md)
|
||||
|
||||
**v3.8.0 メジャーアップデート (2025-11-28)**
|
||||
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
# Claude Code / Codex / Gemini CLI 全方位辅助工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://tauri.app/)
|
||||
[](https://github.com/farion1231/cc-switch/releases/latest)
|
||||
@@ -52,7 +52,7 @@
|
||||
|
||||
## 功能特性
|
||||
|
||||
### 当前版本:v3.10.0 | [完整更新日志](CHANGELOG.md) | [发布说明](docs/release-note-v3.9.0-zh.md)
|
||||
### 当前版本:v3.10.2 | [完整更新日志](CHANGELOG.md) | [发布说明](docs/release-note-v3.9.0-zh.md)
|
||||
|
||||
**v3.8.0 重大更新(2025-11-28)**
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode Support, Global Proxy, Claude Rectifier & Multi-App Experience Enhancements
|
||||
|
||||
**[中文版 →](release-note-v3.10.0-zh.md) | [日本語版 →](release-note-v3.10.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.10.0 introduces OpenCode support, becoming the fourth managed CLI application.
|
||||
This release also brings global proxy settings, Claude Rectifier (thinking signature fixer), enhanced health checks, per-provider configuration, and many other important features, along with comprehensive improvements to multi-app workflows and terminal experience.
|
||||
|
||||
**Release Date**: 2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- OpenCode Support: Full management of providers, MCP servers, and Skills with auto-import on first launch
|
||||
- Global Proxy: Configure a unified proxy for all outbound network requests
|
||||
- Claude Rectifier: Thinking signature fixer for better compatibility with third-party APIs
|
||||
- Enhanced Health Checks: Configurable prompts and CLI-compatible request format
|
||||
- Per-Provider Config: Persistent provider-specific configuration support
|
||||
- App Visibility Control: Freely show/hide apps with synchronized tray menu updates
|
||||
- Terminal Improvements: Provider-specific terminal buttons, fnm path support, cross-platform safe launch
|
||||
- WSL Tool Detection: Detect tool versions in WSL environment with security hardening
|
||||
|
||||
---
|
||||
|
||||
## Main Features
|
||||
|
||||
### OpenCode Support (New Fourth App)
|
||||
|
||||
- Complete OpenCode provider management: add, edit, switch, delete
|
||||
- MCP server management: unified architecture with Claude/Codex/Gemini
|
||||
- Skills support: OpenCode can also use Skills functionality
|
||||
- Auto-import on first launch: automatically imports existing OpenCode configuration when detected
|
||||
- Full internationalization: Chinese/English/Japanese support (#695)
|
||||
|
||||
### Global Proxy
|
||||
|
||||
- Configure a unified proxy for all outbound network requests (#596, thanks @yovinchen)
|
||||
- Supports HTTP/HTTPS proxy protocols
|
||||
- Suitable for network environments requiring proxy access to external APIs
|
||||
|
||||
### Claude Rectifier (Thinking Signature Fixer)
|
||||
|
||||
- Automatically fixes Claude API thinking signatures (#595, thanks @yovinchen)
|
||||
- Resolves incompatible thinking block formats returned by some third-party API gateways
|
||||
- Can be enabled/disabled in Advanced Settings
|
||||
|
||||
### Enhanced Health Checks
|
||||
|
||||
- Configurable custom prompts for streaming health checks (#623, thanks @yovinchen)
|
||||
- Supports CLI-compatible request format for better simulation of real usage scenarios
|
||||
- Improves fault detection accuracy
|
||||
|
||||
### Per-Provider Config
|
||||
|
||||
- Support for saving configuration separately for each provider (#663, thanks @yovinchen)
|
||||
- Persistent configuration: provider-specific settings retained after restart
|
||||
- Suitable for scenarios where different providers require different configurations
|
||||
|
||||
### App Visibility Control
|
||||
|
||||
- Freely show/hide any app (Gemini hidden by default)
|
||||
- Tray menu automatically syncs visibility settings
|
||||
- Hidden apps won't appear in the main interface or tray menu
|
||||
|
||||
### Takeover Compact Mode
|
||||
|
||||
- Automatically uses compact layout when 3 or more visible apps are displayed
|
||||
- Optimizes space utilization in multi-app scenarios
|
||||
|
||||
### Terminal Improvements
|
||||
|
||||
- Provider-specific terminal button: one-click to use current provider in terminal (#564, thanks @kkkman22)
|
||||
- `fnm` path support: automatically recognizes Node.js paths managed by fnm
|
||||
- Cross-platform safe launch: improved terminal launch logic for Windows/macOS/Linux
|
||||
|
||||
### WSL Tool Detection
|
||||
|
||||
- Detect tool versions in WSL environment (#627, thanks @yovinchen)
|
||||
- Added security hardening to prevent command injection risks
|
||||
|
||||
### Skills Preset Enhancements
|
||||
|
||||
- Added `baoyu-skills` preset repository
|
||||
- Automatically supplements missing default repositories for out-of-the-box experience
|
||||
|
||||
---
|
||||
|
||||
## Experience Improvements
|
||||
|
||||
- Keyboard shortcuts: Press `ESC` to quickly return/close panels (#670, thanks @xxk8)
|
||||
- Simplified proxy logs: cleaner and more readable output (#585, thanks @yovinchen)
|
||||
- Pricing editor UX: unified `FullScreenPanel` style
|
||||
- Advanced settings layout: Rectifier section moved below Failover for better logical flow
|
||||
- OpenRouter compatibility mode: disabled by default, UI toggle hidden (reduces clutter)
|
||||
|
||||
---
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
### Proxy & Failover
|
||||
|
||||
- Immediately switch to P1 when auto-failover is enabled (instead of waiting for next request)
|
||||
|
||||
### Provider Management
|
||||
|
||||
- Fixed stale data when reopening provider edit dialog after save (#654, thanks @YangYongAn)
|
||||
- Fixed baseUrl and apiKey state not resetting when switching presets
|
||||
- Fixed endpoint auto-selection state not persisting (#611, thanks @yovinchen)
|
||||
- Automatically apply default color when icon color is not set
|
||||
|
||||
### Deep Links
|
||||
|
||||
- Support multi-endpoint import (#597, thanks @yovinchen)
|
||||
- Prefer `GOOGLE_GEMINI_BASE_URL` over `GEMINI_BASE_URL`
|
||||
|
||||
### MCP
|
||||
|
||||
- Skip `cmd /c` wrapper for WSL target paths (#592, thanks @cxyfer)
|
||||
|
||||
### Usage Templates
|
||||
|
||||
- Added variable hints, fixed validation issues (#628, thanks @YangYongAn)
|
||||
- Prevent configuration leakage between providers
|
||||
- Usage block offset automatically adapts to action button width (#613, thanks @yovinchen)
|
||||
|
||||
### Gemini
|
||||
|
||||
- Convert timeout parameters to Gemini CLI format (#580, thanks @cxyfer)
|
||||
|
||||
### UI
|
||||
|
||||
- Fixed Select dropdown rendering issues in `FullScreenPanel`
|
||||
|
||||
---
|
||||
|
||||
## Notes & Considerations
|
||||
|
||||
- **OpenCode is a newly supported app**: OpenCode CLI must be installed first to use related features.
|
||||
- **Global proxy affects all outbound requests**: including usage queries, health checks, and other network operations.
|
||||
- **Rectifier is experimental**: can be disabled in Advanced Settings if issues occur.
|
||||
|
||||
---
|
||||
|
||||
## Special Thanks
|
||||
|
||||
Thanks to @yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 for their contributions to this release!
|
||||
Thanks to @libukai for designing the elegant failover-related UI!
|
||||
|
||||
---
|
||||
|
||||
## Download & Installation
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 or later | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) or later | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | Portable version, extract and run, no registry write |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ------------------------------------------------------------------ |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **Recommended** - Extract and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | For Homebrew installation and auto-update |
|
||||
|
||||
> **Note**: Since the author doesn't have an Apple Developer account, you may see an "unidentified developer" warning on first launch. Please close it, then go to "System Settings" → "Privacy & Security" → click "Open Anyway", and it will open normally afterwards.
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Update:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| Distribution | Recommended Format | Installation Method |
|
||||
| --------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run directly, or use AUR |
|
||||
| Other distributions / Unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode サポート、グローバルプロキシ、Claude Rectifier とマルチアプリ体験の強化
|
||||
|
||||
**[中文版 →](release-note-v3.10.0-zh.md) | [English →](release-note-v3.10.0-en.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.10.0 では OpenCode サポートが追加され、4番目の管理対象 CLI アプリケーションとなりました。
|
||||
また、グローバルプロキシ設定、Claude Rectifier(thinking 署名修正機能)、ヘルスチェックの強化、プロバイダー別設定など、多くの重要な機能が追加され、マルチアプリワークフローとターミナル体験が全面的に改善されました。
|
||||
|
||||
**リリース日**: 2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- OpenCode サポート:プロバイダー、MCP サーバー、Skills の完全管理、初回起動時の自動インポート
|
||||
- グローバルプロキシ:すべての送信ネットワークリクエストに統一プロキシを設定
|
||||
- Claude Rectifier:thinking 署名修正機能、サードパーティ API との互換性向上
|
||||
- ヘルスチェック強化:カスタムプロンプト設定、CLI 互換リクエスト形式
|
||||
- プロバイダー別設定:プロバイダー固有の設定の永続化をサポート
|
||||
- アプリ表示制御:アプリの表示/非表示を自由に設定、トレイメニューと同期
|
||||
- ターミナル改善:プロバイダー専用ターミナルボタン、fnm パスサポート、クロスプラットフォーム安全起動
|
||||
- WSL ツール検出:WSL 環境でのツールバージョン検出とセキュリティ強化
|
||||
|
||||
---
|
||||
|
||||
## 主な機能
|
||||
|
||||
### OpenCode サポート(新しい4番目のアプリ)
|
||||
|
||||
- 完全な OpenCode プロバイダー管理:追加、編集、切り替え、削除
|
||||
- MCP サーバー管理:Claude/Codex/Gemini と統一されたアーキテクチャ
|
||||
- Skills サポート:OpenCode でも Skills 機能を使用可能
|
||||
- 初回起動時の自動インポート:既存の OpenCode 設定を検出すると自動的にインポート
|
||||
- 完全な国際化:中国語/英語/日本語サポート (#695)
|
||||
|
||||
### グローバルプロキシ
|
||||
|
||||
- すべての送信ネットワークリクエストに統一プロキシを設定 (#596、@yovinchen に感謝)
|
||||
- HTTP/HTTPS プロキシプロトコルをサポート
|
||||
- 外部 API へのプロキシアクセスが必要なネットワーク環境に適用
|
||||
|
||||
### Claude Rectifier(Thinking 署名修正機能)
|
||||
|
||||
- Claude API の thinking 署名を自動修正 (#595、@yovinchen に感謝)
|
||||
- 一部のサードパーティ API ゲートウェイが返す互換性のない thinking ブロック形式を解決
|
||||
- 詳細設定で有効/無効を切り替え可能
|
||||
|
||||
### ヘルスチェック強化
|
||||
|
||||
- ストリーミングヘルスチェック用のカスタムプロンプトを設定可能 (#623、@yovinchen に感謝)
|
||||
- CLI 互換リクエスト形式をサポートし、実際の使用シナリオをより良くシミュレート
|
||||
- 障害検出の精度を向上
|
||||
|
||||
### プロバイダー別設定
|
||||
|
||||
- 各プロバイダーごとに設定を個別に保存可能 (#663、@yovinchen に感謝)
|
||||
- 設定の永続化:再起動後もプロバイダー固有の設定を保持
|
||||
- 異なるプロバイダーに異なる設定が必要なシナリオに適用
|
||||
|
||||
### アプリ表示制御
|
||||
|
||||
- 任意のアプリを自由に表示/非表示(Gemini はデフォルトで非表示)
|
||||
- トレイメニューは表示設定と自動的に同期
|
||||
- 非表示のアプリはメインインターフェースとトレイメニューに表示されない
|
||||
|
||||
### Takeover コンパクトモード
|
||||
|
||||
- 3つ以上の表示アプリがある場合、自動的にコンパクトレイアウトを使用
|
||||
- マルチアプリシナリオでのスペース利用を最適化
|
||||
|
||||
### ターミナル改善
|
||||
|
||||
- プロバイダー専用ターミナルボタン:ワンクリックでターミナルで現在のプロバイダーを使用 (#564、@kkkman22 に感謝)
|
||||
- `fnm` パスサポート:fnm で管理された Node.js パスを自動認識
|
||||
- クロスプラットフォーム安全起動:Windows/macOS/Linux のターミナル起動ロジックを改善
|
||||
|
||||
### WSL ツール検出
|
||||
|
||||
- WSL 環境でツールバージョンを検出 (#627、@yovinchen に感謝)
|
||||
- コマンドインジェクションリスクを防ぐためのセキュリティ強化を追加
|
||||
|
||||
### Skills プリセット強化
|
||||
|
||||
- `baoyu-skills` プリセットリポジトリを追加
|
||||
- 不足しているデフォルトリポジトリを自動補完し、すぐに使える状態を確保
|
||||
|
||||
---
|
||||
|
||||
## 体験の改善
|
||||
|
||||
- キーボードショートカット:`ESC` を押してパネルをすばやく戻る/閉じる (#670、@xxk8 に感謝)
|
||||
- プロキシログの簡素化:より明確で読みやすい出力 (#585、@yovinchen に感謝)
|
||||
- 価格エディター UX:統一された `FullScreenPanel` スタイル
|
||||
- 詳細設定レイアウト:Rectifier セクションを Failover の下に移動し、論理的な流れを改善
|
||||
- OpenRouter 互換モード:デフォルトで無効、UI トグルを非表示(煩雑さを軽減)
|
||||
|
||||
---
|
||||
|
||||
## バグ修正
|
||||
|
||||
### プロキシとフェイルオーバー
|
||||
|
||||
- 自動フェイルオーバーが有効な場合、すぐに P1 に切り替え(次のリクエストを待たずに)
|
||||
|
||||
### プロバイダー管理
|
||||
|
||||
- 保存後にプロバイダー編集ダイアログを再度開いたときにデータが古い問題を修正 (#654、@YangYongAn に感謝)
|
||||
- プリセット切り替え時に baseUrl と apiKey の状態がリセットされない問題を修正
|
||||
- エンドポイント自動選択状態が永続化されない問題を修正 (#611、@yovinchen に感謝)
|
||||
- アイコンカラーが設定されていない場合、デフォルトカラーを自動適用
|
||||
|
||||
### ディープリンク
|
||||
|
||||
- マルチエンドポイントインポートをサポート (#597、@yovinchen に感謝)
|
||||
- `GEMINI_BASE_URL` より `GOOGLE_GEMINI_BASE_URL` を優先
|
||||
|
||||
### MCP
|
||||
|
||||
- WSL ターゲットパスの `cmd /c` ラッパーをスキップ (#592、@cxyfer に感謝)
|
||||
|
||||
### 使用量テンプレート
|
||||
|
||||
- 変数ヒントを追加、検証の問題を修正 (#628、@YangYongAn に感謝)
|
||||
- プロバイダー間での設定漏洩を防止
|
||||
- 使用量ブロックのオフセットがアクションボタンの幅に自動適応 (#613、@yovinchen に感謝)
|
||||
|
||||
### Gemini
|
||||
|
||||
- タイムアウトパラメータを Gemini CLI 形式に変換 (#580、@cxyfer に感謝)
|
||||
|
||||
### UI
|
||||
|
||||
- `FullScreenPanel` での Select ドロップダウンのレンダリング問題を修正
|
||||
|
||||
---
|
||||
|
||||
## 注意事項
|
||||
|
||||
- **OpenCode は新しくサポートされたアプリです**:関連機能を使用するには、まず OpenCode CLI をインストールする必要があります。
|
||||
- **グローバルプロキシはすべての送信リクエストに影響します**:使用量クエリ、ヘルスチェックなどのネットワーク操作を含みます。
|
||||
- **Rectifier は実験的機能です**:問題が発生した場合は、詳細設定で無効にできます。
|
||||
|
||||
---
|
||||
|
||||
## 特別な感謝
|
||||
|
||||
@yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 の皆様、このリリースへの貢献に感謝します!
|
||||
@libukai 様、エレガントなフェイルオーバー関連 UI のデザインに感謝します!
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から適切なバージョンをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最小バージョン | アーキテクチャ |
|
||||
| -------- | -------------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表参照 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | ---------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ書き込みなし |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ----------------------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **推奨** - 解凍して Applications にドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
> **注意**:作者が Apple Developer アカウントを持っていないため、初回起動時に「開発元を確認できません」という警告が表示される場合があります。一度閉じてから、「システム設定」→「プライバシーとセキュリティ」→「このまま開く」をクリックすると、その後は正常に開けます。
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 実行権限を追加して直接実行、または AUR を使用 |
|
||||
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,206 @@
|
||||
# CC Switch v3.10.0
|
||||
|
||||
> OpenCode 支持、全局代理、Claude Rectifier 与多应用体验增强
|
||||
|
||||
**[English →](release-note-v3.10.0-en.md) | [日本語版 →](release-note-v3.10.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.10.0 新增 OpenCode 支持,成为第四个受管理的 CLI 应用。
|
||||
同时带来全局代理设置、Claude Rectifier(thinking 签名修正器)、健康检查增强、按供应商配置等多项重要功能,并对多应用工作流与终端体验做了全面改进。
|
||||
|
||||
**发布日期**:2026-01-21
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- OpenCode 支持:供应商、MCP 服务器、Skills 全面管理,首次启动自动导入
|
||||
- 全局代理:为出站网络请求统一配置代理
|
||||
- Claude Rectifier:thinking 签名修正器,兼容更多第三方 API
|
||||
- 健康检查增强:可配置提示词、CLI 兼容请求
|
||||
- 按供应商配置:支持供应商特定配置的持久化
|
||||
- 应用可见性控制:自由显示/隐藏应用,托盘菜单同步更新
|
||||
- 终端改进:供应商专属终端按钮、fnm 路径支持、跨平台安全启动
|
||||
- WSL 工具检测:在 WSL 环境检测工具版本,并增加安全加固
|
||||
|
||||
---
|
||||
|
||||
## 主要功能
|
||||
|
||||
### OpenCode 支持(新增第四应用)
|
||||
|
||||
- 完整的 OpenCode 供应商管理:新增、编辑、切换、删除
|
||||
- MCP 服务器管理:与 Claude/Codex/Gemini 统一架构
|
||||
- Skills 支持:OpenCode 也可使用 Skills 功能
|
||||
- 首次启动自动导入:检测到已有 OpenCode 配置时自动导入
|
||||
- 完整国际化:中/英/日三语支持(#695)
|
||||
|
||||
### 全局代理(Global Proxy)
|
||||
|
||||
- 为所有出站网络请求配置统一代理(#596,感谢 @yovinchen)
|
||||
- 支持 HTTP/HTTPS 代理协议
|
||||
- 适用于需要代理访问外部 API 的网络环境
|
||||
|
||||
### Claude Rectifier(Thinking 签名修正器)
|
||||
|
||||
- 自动修正 Claude API 的 thinking 签名(#595,感谢 @yovinchen)
|
||||
- 解决部分第三方 API 网关返回的 thinking 块格式不兼容问题
|
||||
- 在高级设置中可开启/关闭
|
||||
|
||||
### 健康检查增强
|
||||
|
||||
- 可配置自定义提示词(prompt)用于流式健康检查(#623,感谢 @yovinchen)
|
||||
- 支持 CLI 兼容请求格式,更好地模拟真实使用场景
|
||||
- 提升故障检测的准确性
|
||||
|
||||
### 按供应商配置(Per-Provider Config)
|
||||
|
||||
- 支持为每个供应商单独保存配置(#663,感谢 @yovinchen)
|
||||
- 配置持久化:重启后保留供应商专属设置
|
||||
- 适用于不同供应商需要不同配置的场景
|
||||
|
||||
### 应用可见性控制
|
||||
|
||||
- 自由显示/隐藏任意应用(Gemini 默认隐藏)
|
||||
- 托盘菜单自动同步可见性设置
|
||||
- 隐藏的应用不会出现在主界面和托盘菜单中
|
||||
|
||||
### Takeover Compact Mode
|
||||
|
||||
- 当显示 3 个及以上可见应用时,自动使用紧凑布局
|
||||
- 优化多应用场景下的空间利用
|
||||
|
||||
### 终端改进
|
||||
|
||||
- 供应商专属终端按钮:一键在终端中使用当前供应商(#564,感谢 @kkkman22)
|
||||
- `fnm` 路径支持:自动识别 fnm 管理的 Node.js 路径
|
||||
- 跨平台安全启动:改进 Windows/macOS/Linux 的终端启动逻辑
|
||||
|
||||
### WSL 工具检测
|
||||
|
||||
- 在 WSL 环境中检测工具版本(#627,感谢 @yovinchen)
|
||||
- 增加安全加固,防止命令注入风险
|
||||
|
||||
### Skills 预设增强
|
||||
|
||||
- 新增 `baoyu-skills` 预设仓库
|
||||
- 自动补充缺失的默认仓库,确保开箱即用
|
||||
|
||||
---
|
||||
|
||||
## 体验优化
|
||||
|
||||
- 键盘快捷键:按 `ESC` 快速返回/关闭面板(#670,感谢 @xxk8)
|
||||
- 代理日志简化:输出更清晰易读(#585,感谢 @yovinchen)
|
||||
- 定价编辑器 UX:统一使用 `FullScreenPanel` 风格
|
||||
- 高级设置布局:Rectifier 区块移至 Failover 下方,逻辑更顺畅
|
||||
- OpenRouter 兼容模式:默认禁用,UI 开关隐藏(减少干扰)
|
||||
|
||||
---
|
||||
|
||||
## Bug 修复
|
||||
|
||||
### 代理与故障切换
|
||||
|
||||
- 启用自动故障切换时立即切换到 P1(而非等待下次请求)
|
||||
|
||||
### 供应商管理
|
||||
|
||||
- 修复供应商编辑对话框保存后重新打开时数据过时的问题(#654,感谢 @YangYongAn)
|
||||
- 修复切换预设时 baseUrl 和 apiKey 状态未重置的问题
|
||||
- 修复端点自动选择状态未持久化的问题(#611,感谢 @yovinchen)
|
||||
- 未设置图标颜色时自动应用默认颜色
|
||||
|
||||
### 深链接
|
||||
|
||||
- 支持多端点导入(#597,感谢 @yovinchen)
|
||||
- 优先使用 `GOOGLE_GEMINI_BASE_URL` 而非 `GEMINI_BASE_URL`
|
||||
|
||||
### MCP
|
||||
|
||||
- WSL 目标路径跳过 `cmd /c` 包裹(#592,感谢 @cxyfer)
|
||||
|
||||
### 用量模板
|
||||
|
||||
- 新增变量提示,修复验证问题(#628,感谢 @YangYongAn)
|
||||
- 防止配置在供应商之间泄漏
|
||||
- 用量区块偏移量根据操作按钮宽度自动适应(#613,感谢 @yovinchen)
|
||||
|
||||
### Gemini
|
||||
|
||||
- 超时参数转换为 Gemini CLI 格式(#580,感谢 @cxyfer)
|
||||
|
||||
### UI
|
||||
|
||||
- 修复 `FullScreenPanel` 中 Select 下拉框渲染问题
|
||||
|
||||
---
|
||||
|
||||
## 说明与注意事项
|
||||
|
||||
- **OpenCode 为新支持的应用**:需要先安装 OpenCode CLI 才能使用相关功能。
|
||||
- **全局代理会影响所有出站请求**:包括用量查询、健康检查等网络操作。
|
||||
- **Rectifier 功能为实验性**:如遇问题可在高级设置中关闭。
|
||||
|
||||
---
|
||||
|
||||
## 特别感谢
|
||||
|
||||
感谢 @yovinchen @YangYongAn @cxyfer @xxk8 @kkkman22 @Shuimo03 为本版本做出的贡献!
|
||||
感谢 @libukai 设计的故障转移相关 UI,非常优雅!
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | ----------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 10.15 (Catalina) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.10.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.10.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------------------- |
|
||||
| `CC-Switch-v3.10.0-macOS.zip` | **推荐** - 解压后拖入 Applications 即可,Universal Binary |
|
||||
| `CC-Switch-v3.10.0-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
> **注意**:由于作者没有苹果开发者账号,首次打开可能出现"未知开发者"警告,请先关闭,然后前往"系统设置" → "隐私与安全性" → 点击"仍要打开",之后便可以正常打开
|
||||
|
||||
### Homebrew(macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.10.0",
|
||||
"version": "3.10.2",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
Generated
+1
-1
@@ -701,7 +701,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.10.0"
|
||||
version = "3.10.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-stream",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.10.0"
|
||||
version = "3.10.2"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -729,19 +729,16 @@ echo {}
|
||||
claude --settings \"{}\"
|
||||
del \"{}\" >nul 2>&1
|
||||
del \"%~f0\" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo Press any key to close...
|
||||
pause >nul
|
||||
)",
|
||||
",
|
||||
config_path_for_batch, config_path_for_batch, config_path_for_batch
|
||||
);
|
||||
|
||||
std::fs::write(&bat_file, content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
|
||||
|
||||
// Use output() to capture errors from the start command
|
||||
// Use /K instead of /C to keep the window open after execution
|
||||
let output = Command::new("cmd")
|
||||
.args(["/C", "start", "cmd", "/C", &bat_file.to_string_lossy()])
|
||||
.args(["/C", "start", "cmd", "/K", &bat_file.to_string_lossy()])
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
.map_err(|e| format!("执行 cmd 失败: {e}"))?;
|
||||
|
||||
@@ -42,21 +42,10 @@ pub fn get_opencode_dir() -> PathBuf {
|
||||
return override_dir;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Windows: %APPDATA%\opencode
|
||||
dirs::data_dir()
|
||||
.map(|d| d.join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
// Unix: ~/.config/opencode
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".config").join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
// 所有平台统一使用 ~/.config/opencode
|
||||
dirs::home_dir()
|
||||
.map(|h| h.join(".config").join("opencode"))
|
||||
.unwrap_or_else(|| PathBuf::from(".config").join("opencode"))
|
||||
}
|
||||
|
||||
/// 获取 OpenCode 配置文件路径
|
||||
|
||||
@@ -191,6 +191,23 @@ pub struct ProviderProxyConfig {
|
||||
pub proxy_password: Option<String>,
|
||||
}
|
||||
|
||||
/// 格式转换配置(用于 OpenRouter 等需要 API 格式转换的供应商)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct FormatTransformConfig {
|
||||
/// 是否启用格式转换
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 源格式:anthropic, openai, gemini
|
||||
#[serde(rename = "sourceFormat", skip_serializing_if = "Option::is_none")]
|
||||
pub source_format: Option<String>,
|
||||
/// 目标格式:anthropic, openai, gemini
|
||||
#[serde(rename = "targetFormat", skip_serializing_if = "Option::is_none")]
|
||||
pub target_format: Option<String>,
|
||||
/// 是否转换流式响应(默认 true)
|
||||
#[serde(rename = "transformStreaming", skip_serializing_if = "Option::is_none")]
|
||||
pub transform_streaming: Option<bool>,
|
||||
}
|
||||
|
||||
/// 供应商元数据
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderMeta {
|
||||
@@ -227,6 +244,9 @@ pub struct ProviderMeta {
|
||||
/// 供应商单独的代理配置
|
||||
#[serde(rename = "proxyConfig", skip_serializing_if = "Option::is_none")]
|
||||
pub proxy_config: Option<ProviderProxyConfig>,
|
||||
/// 格式转换配置(用于 OpenRouter 等需要 API 格式转换的供应商)
|
||||
#[serde(rename = "formatTransform", skip_serializing_if = "Option::is_none")]
|
||||
pub format_transform: Option<FormatTransformConfig>,
|
||||
}
|
||||
|
||||
impl ProviderManager {
|
||||
@@ -596,6 +616,11 @@ pub struct OpenCodeModel {
|
||||
/// 模型额外选项(provider 路由等)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub options: Option<HashMap<String, Value>>,
|
||||
|
||||
/// 额外字段(cost、modalities、thinking、variants 等)
|
||||
/// 使用 flatten 捕获所有未明确定义的字段
|
||||
#[serde(flatten, default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub extra: HashMap<String, Value>,
|
||||
}
|
||||
|
||||
/// OpenCode 模型限制
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::{
|
||||
provider_router::ProviderRouter,
|
||||
providers::{get_adapter, ProviderAdapter, ProviderType},
|
||||
thinking_rectifier::{rectify_anthropic_request, should_rectify_thinking_signature},
|
||||
transform::{get_transformer, TransformConfig},
|
||||
types::{ProxyStatus, RectifierConfig},
|
||||
ProxyError,
|
||||
};
|
||||
@@ -558,26 +559,63 @@ impl RequestForwarder {
|
||||
// 使用适配器提取 base_url
|
||||
let base_url = adapter.extract_base_url(provider)?;
|
||||
|
||||
// 检查是否需要格式转换
|
||||
let needs_transform = adapter.needs_transform(provider);
|
||||
// 获取格式转换配置
|
||||
let transform_config = TransformConfig::from_provider(provider);
|
||||
let needs_transform = transform_config.needs_transform();
|
||||
|
||||
let effective_endpoint =
|
||||
if needs_transform && adapter.name() == "Claude" && endpoint == "/v1/messages" {
|
||||
"/v1/chat/completions"
|
||||
} else {
|
||||
endpoint
|
||||
};
|
||||
// 如果需要转换但找不到转换器,直接返回错误(避免静默透传后在响应阶段失败)
|
||||
let transformer = if needs_transform {
|
||||
let t = get_transformer(
|
||||
transform_config.source_format,
|
||||
transform_config.target_format,
|
||||
);
|
||||
if t.is_none() {
|
||||
log::error!(
|
||||
"[Forwarder] 格式转换已启用但找不到转换器: {:?} → {:?}",
|
||||
transform_config.source_format,
|
||||
transform_config.target_format
|
||||
);
|
||||
return Err(ProxyError::TransformError(format!(
|
||||
"No transformer registered for {:?} → {:?}. Please disable format transform or use supported formats (Anthropic ↔ OpenAI).",
|
||||
transform_config.source_format,
|
||||
transform_config.target_format
|
||||
)));
|
||||
}
|
||||
t
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 确定有效端点
|
||||
let effective_endpoint = if let Some(ref t) = transformer {
|
||||
t.transform_endpoint(endpoint)
|
||||
} else {
|
||||
endpoint.to_string()
|
||||
};
|
||||
|
||||
// 使用适配器构建 URL
|
||||
let url = adapter.build_url(&base_url, effective_endpoint);
|
||||
let url = adapter.build_url(&base_url, &effective_endpoint);
|
||||
|
||||
// 应用模型映射(独立于格式转换)
|
||||
let (mapped_body, _original_model, _mapped_model) =
|
||||
let (mut mapped_body, _original_model, _mapped_model) =
|
||||
super::model_mapper::apply_model_mapping(body.clone(), provider);
|
||||
|
||||
// 如果启用格式转换但禁用流式转换,强制将 stream 设为 false
|
||||
// 避免上游返回 SSE 流但我们无法转换的情况
|
||||
if needs_transform && !transform_config.transform_streaming {
|
||||
if let Some(stream_val) = mapped_body.get("stream") {
|
||||
if stream_val.as_bool() == Some(true) {
|
||||
log::info!("[Forwarder] transform_streaming=false,强制将 stream 设为 false");
|
||||
if let Some(obj) = mapped_body.as_object_mut() {
|
||||
obj.insert("stream".to_string(), serde_json::Value::Bool(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 转换请求体(如果需要)
|
||||
let request_body = if needs_transform {
|
||||
adapter.transform_request(mapped_body, provider)?
|
||||
let request_body = if let Some(ref t) = transformer {
|
||||
t.transform_request(mapped_body)?
|
||||
} else {
|
||||
mapped_body
|
||||
};
|
||||
|
||||
@@ -13,9 +13,9 @@ use super::{
|
||||
CLAUDE_PARSER_CONFIG, CODEX_PARSER_CONFIG, GEMINI_PARSER_CONFIG, OPENAI_PARSER_CONFIG,
|
||||
},
|
||||
handler_context::RequestContext,
|
||||
providers::{get_adapter, streaming::create_anthropic_sse_stream, transform},
|
||||
response_processor::{create_logged_passthrough_stream, process_response, SseUsageCollector},
|
||||
server::ProxyState,
|
||||
transform::{get_transformer, TransformConfig},
|
||||
types::*,
|
||||
usage::parser::TokenUsage,
|
||||
ProxyError,
|
||||
@@ -94,13 +94,20 @@ pub async fn handle_messages(
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
// 检查是否需要格式转换(OpenRouter 等中转服务)
|
||||
let adapter = get_adapter(&AppType::Claude);
|
||||
let needs_transform = adapter.needs_transform(&ctx.provider);
|
||||
// 检查是否需要格式转换(通过 Provider 配置)
|
||||
let transform_config = TransformConfig::from_provider(&ctx.provider);
|
||||
|
||||
// Claude 特有:格式转换处理
|
||||
if needs_transform {
|
||||
return handle_claude_transform(response, &ctx, &state, &body, is_stream).await;
|
||||
if transform_config.needs_transform() {
|
||||
return handle_claude_transform(
|
||||
response,
|
||||
&ctx,
|
||||
&state,
|
||||
&body,
|
||||
is_stream,
|
||||
&transform_config,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// 通用响应处理(透传模式)
|
||||
@@ -116,13 +123,26 @@ async fn handle_claude_transform(
|
||||
state: &ProxyState,
|
||||
_original_body: &Value,
|
||||
is_stream: bool,
|
||||
transform_config: &TransformConfig,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = response.status();
|
||||
|
||||
if is_stream {
|
||||
// 获取响应转换器(OpenAI → Anthropic)
|
||||
let response_transformer = get_transformer(
|
||||
transform_config.target_format,
|
||||
transform_config.source_format,
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
ProxyError::TransformError(format!(
|
||||
"No transformer for {:?} → {:?}",
|
||||
transform_config.target_format, transform_config.source_format
|
||||
))
|
||||
})?;
|
||||
|
||||
if is_stream && transform_config.transform_streaming {
|
||||
// 流式响应转换 (OpenAI SSE → Anthropic SSE)
|
||||
let stream = response.bytes_stream();
|
||||
let sse_stream = create_anthropic_sse_stream(stream);
|
||||
let sse_stream = response_transformer.transform_stream(Box::pin(stream));
|
||||
|
||||
// 创建使用量收集器
|
||||
let usage_collector = {
|
||||
@@ -202,10 +222,12 @@ async fn handle_claude_transform(
|
||||
ProxyError::TransformError(format!("Failed to parse OpenAI response: {e}"))
|
||||
})?;
|
||||
|
||||
let anthropic_response = transform::openai_to_anthropic(openai_response).map_err(|e| {
|
||||
log::error!("[Claude] 转换响应失败: {e}");
|
||||
e
|
||||
})?;
|
||||
let anthropic_response = response_transformer
|
||||
.transform_response(openai_response)
|
||||
.map_err(|e| {
|
||||
log::error!("[Claude] 转换响应失败: {e}");
|
||||
e
|
||||
})?;
|
||||
|
||||
// 记录使用量
|
||||
if let Some(usage) = TokenUsage::from_claude_response(&anthropic_response) {
|
||||
|
||||
@@ -22,6 +22,7 @@ pub mod response_processor;
|
||||
pub(crate) mod server;
|
||||
pub mod session;
|
||||
pub mod thinking_rectifier;
|
||||
pub mod transform;
|
||||
pub(crate) mod types;
|
||||
pub mod usage;
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ use super::auth::AuthInfo;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use reqwest::RequestBuilder;
|
||||
use serde_json::Value;
|
||||
|
||||
/// 供应商适配器 Trait
|
||||
///
|
||||
@@ -83,49 +82,4 @@ pub trait ProviderAdapter: Send + Sync {
|
||||
/// # Returns
|
||||
/// 添加了认证头的 RequestBuilder
|
||||
fn add_auth_headers(&self, request: RequestBuilder, auth: &AuthInfo) -> RequestBuilder;
|
||||
|
||||
/// 是否需要格式转换
|
||||
///
|
||||
/// 默认返回 `false`(透传模式)。
|
||||
/// 仅当供应商需要格式转换时(如 Claude + OpenRouter 旧 OpenAI 兼容接口)才返回 `true`。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `provider` - Provider 配置
|
||||
fn needs_transform(&self, _provider: &Provider) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// 转换请求体
|
||||
///
|
||||
/// 将请求体从一种格式转换为另一种格式(如 Anthropic → OpenAI)。
|
||||
/// 默认实现直接返回原始请求体(透传)。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `body` - 原始请求体
|
||||
/// * `provider` - Provider 配置(用于获取模型映射等)
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Value)` - 转换后的请求体
|
||||
/// * `Err(ProxyError)` - 转换失败
|
||||
fn transform_request(&self, body: Value, _provider: &Provider) -> Result<Value, ProxyError> {
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// 转换响应体
|
||||
///
|
||||
/// 将响应体从一种格式转换为另一种格式(如 OpenAI → Anthropic)。
|
||||
/// 默认实现直接返回原始响应体(透传)。
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `body` - 原始响应体
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(Value)` - 转换后的响应体
|
||||
/// * `Err(ProxyError)` - 转换失败
|
||||
///
|
||||
/// Note: 响应转换将在 handler 层集成,目前预留接口
|
||||
#[allow(dead_code)]
|
||||
fn transform_response(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
Ok(body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,25 +48,6 @@ impl ClaudeAdapter {
|
||||
false
|
||||
}
|
||||
|
||||
/// 检测 OpenRouter 是否启用兼容模式
|
||||
fn is_openrouter_compat_enabled(&self, provider: &Provider) -> bool {
|
||||
if !self.is_openrouter(provider) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let raw = provider.settings_config.get("openrouter_compat_mode");
|
||||
match raw {
|
||||
Some(serde_json::Value::Bool(enabled)) => *enabled,
|
||||
Some(serde_json::Value::Number(num)) => num.as_i64().unwrap_or(0) != 0,
|
||||
Some(serde_json::Value::String(value)) => {
|
||||
let normalized = value.trim().to_lowercase();
|
||||
normalized == "true" || normalized == "1"
|
||||
}
|
||||
// OpenRouter now supports Claude Code compatible API, default to passthrough
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 检测是否为仅 Bearer 认证模式
|
||||
fn is_bearer_only_mode(&self, provider: &Provider) -> bool {
|
||||
// 检查 settings_config 中的 auth_mode
|
||||
@@ -252,27 +233,6 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
_ => request,
|
||||
}
|
||||
}
|
||||
|
||||
fn needs_transform(&self, _provider: &Provider) -> bool {
|
||||
// NOTE:
|
||||
// OpenRouter 已推出 Claude Code 兼容接口(可直接处理 `/v1/messages`),默认不再启用
|
||||
// Anthropic ↔ OpenAI 的格式转换。
|
||||
//
|
||||
// 如果未来需要回退到旧的 OpenAI Chat Completions 方案,可恢复下面这行:
|
||||
self.is_openrouter_compat_enabled(_provider)
|
||||
}
|
||||
|
||||
fn transform_request(
|
||||
&self,
|
||||
body: serde_json::Value,
|
||||
provider: &Provider,
|
||||
) -> Result<serde_json::Value, ProxyError> {
|
||||
super::transform::anthropic_to_openai(body, provider)
|
||||
}
|
||||
|
||||
fn transform_response(&self, body: serde_json::Value) -> Result<serde_json::Value, ProxyError> {
|
||||
super::transform::openai_to_anthropic(body)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -454,41 +414,4 @@ mod tests {
|
||||
let url = adapter.build_url("https://api.anthropic.com", "/v1/messages?foo=bar");
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages?foo=bar");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_needs_transform() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
|
||||
let anthropic_provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
|
||||
}
|
||||
}));
|
||||
assert!(!adapter.needs_transform(&anthropic_provider));
|
||||
|
||||
// OpenRouter provider without explicit setting now defaults to passthrough (no transform)
|
||||
let openrouter_provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api"
|
||||
}
|
||||
}));
|
||||
assert!(!adapter.needs_transform(&openrouter_provider));
|
||||
|
||||
// OpenRouter provider with explicit compat mode enabled should transform
|
||||
let openrouter_enabled = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api"
|
||||
},
|
||||
"openrouter_compat_mode": true
|
||||
}));
|
||||
assert!(adapter.needs_transform(&openrouter_enabled));
|
||||
|
||||
let openrouter_disabled = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api"
|
||||
},
|
||||
"openrouter_compat_mode": false
|
||||
}));
|
||||
assert!(!adapter.needs_transform(&openrouter_disabled));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +141,20 @@ impl ProviderAdapter for CodexAdapter {
|
||||
let base_trimmed = base_url.trim_end_matches('/');
|
||||
let endpoint_trimmed = endpoint.trim_start_matches('/');
|
||||
|
||||
// 检查 base_url 是否已包含 endpoint 的核心路径
|
||||
// 例如:base_url = "https://api.example.com/v1/chat/completions"
|
||||
// endpoint = "/v1/chat/completions"
|
||||
// 此时不应再拼接,直接返回 base_url
|
||||
let endpoint_core = endpoint_trimmed
|
||||
.trim_start_matches("v1/")
|
||||
.trim_start_matches("v1");
|
||||
let endpoint_core = endpoint_core.trim_start_matches('/');
|
||||
|
||||
// 如果 base_url 已经以 endpoint 核心路径结尾,直接返回 base_url
|
||||
if !endpoint_core.is_empty() && base_trimmed.ends_with(endpoint_core) {
|
||||
return base_trimmed.to_string();
|
||||
}
|
||||
|
||||
let mut url = format!("{base_trimmed}/{endpoint_trimmed}");
|
||||
|
||||
// 去除重复的 /v1/v1
|
||||
@@ -231,6 +245,33 @@ mod tests {
|
||||
assert_eq!(url, "https://www.packyapi.com/v1/responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_base_already_has_chat_completions() {
|
||||
let adapter = CodexAdapter::new();
|
||||
// base_url 已包含 chat/completions,不应再拼接
|
||||
let url = adapter.build_url(
|
||||
"https://api.example.com/v1/chat/completions",
|
||||
"/v1/chat/completions",
|
||||
);
|
||||
assert_eq!(url, "https://api.example.com/v1/chat/completions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_base_already_has_responses() {
|
||||
let adapter = CodexAdapter::new();
|
||||
// base_url 已包含 responses,不应再拼接
|
||||
let url = adapter.build_url("https://api.example.com/v1/responses", "/v1/responses");
|
||||
assert_eq!(url, "https://api.example.com/v1/responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_base_without_endpoint() {
|
||||
let adapter = CodexAdapter::new();
|
||||
// base_url 不包含 endpoint,应正常拼接
|
||||
let url = adapter.build_url("https://api.example.com/v1", "/v1/chat/completions");
|
||||
assert_eq!(url, "https://api.example.com/v1/chat/completions");
|
||||
}
|
||||
|
||||
// 官方客户端检测测试
|
||||
#[test]
|
||||
fn test_is_official_client_vscode() {
|
||||
|
||||
@@ -17,8 +17,6 @@ mod claude;
|
||||
mod codex;
|
||||
mod gemini;
|
||||
pub mod models;
|
||||
pub mod streaming;
|
||||
pub mod transform;
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::provider::Provider;
|
||||
|
||||
@@ -1,640 +0,0 @@
|
||||
//! 格式转换模块
|
||||
//!
|
||||
//! 实现 Anthropic ↔ OpenAI 格式转换,用于 OpenRouter 支持
|
||||
//! 参考: anthropic-proxy-rs
|
||||
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// 从 Provider 配置中获取模型映射
|
||||
fn get_model_from_provider(model: &str, provider: &Provider, body: &Value) -> String {
|
||||
let env = provider.settings_config.get("env");
|
||||
let model_lower = model.to_lowercase();
|
||||
|
||||
// 检测 thinking 参数
|
||||
let has_thinking = body
|
||||
.get("thinking")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|o| o.get("type"))
|
||||
.and_then(|t| t.as_str())
|
||||
== Some("enabled");
|
||||
|
||||
if let Some(env) = env {
|
||||
// 如果启用 thinking,优先使用推理模型
|
||||
if has_thinking {
|
||||
if let Some(m) = env
|
||||
.get("ANTHROPIC_REASONING_MODEL")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
log::debug!("[Transform] 使用推理模型: {m}");
|
||||
return m.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// 根据模型类型选择配置模型
|
||||
if model_lower.contains("haiku") {
|
||||
if let Some(m) = env
|
||||
.get("ANTHROPIC_DEFAULT_HAIKU_MODEL")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return m.to_string();
|
||||
}
|
||||
}
|
||||
if model_lower.contains("opus") {
|
||||
if let Some(m) = env
|
||||
.get("ANTHROPIC_DEFAULT_OPUS_MODEL")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return m.to_string();
|
||||
}
|
||||
}
|
||||
if model_lower.contains("sonnet") {
|
||||
if let Some(m) = env
|
||||
.get("ANTHROPIC_DEFAULT_SONNET_MODEL")
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return m.to_string();
|
||||
}
|
||||
}
|
||||
// 默认使用 ANTHROPIC_MODEL
|
||||
if let Some(m) = env.get("ANTHROPIC_MODEL").and_then(|v| v.as_str()) {
|
||||
return m.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
model.to_string()
|
||||
}
|
||||
|
||||
/// Anthropic 请求 → OpenAI 请求
|
||||
pub fn anthropic_to_openai(body: Value, provider: &Provider) -> Result<Value, ProxyError> {
|
||||
let mut result = json!({});
|
||||
|
||||
// 模型映射:使用 Provider 配置中的模型(支持 thinking 参数)
|
||||
if let Some(model) = body.get("model").and_then(|m| m.as_str()) {
|
||||
let mapped_model = get_model_from_provider(model, provider, &body);
|
||||
result["model"] = json!(mapped_model);
|
||||
}
|
||||
|
||||
let mut messages = Vec::new();
|
||||
|
||||
// 处理 system prompt
|
||||
if let Some(system) = body.get("system") {
|
||||
if let Some(text) = system.as_str() {
|
||||
// 单个字符串
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
} else if let Some(arr) = system.as_array() {
|
||||
// 多个 system message
|
||||
for msg in arr {
|
||||
if let Some(text) = msg.get("text").and_then(|t| t.as_str()) {
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 转换 messages
|
||||
if let Some(msgs) = body.get("messages").and_then(|m| m.as_array()) {
|
||||
for msg in msgs {
|
||||
let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("user");
|
||||
let content = msg.get("content");
|
||||
let converted = convert_message_to_openai(role, content)?;
|
||||
messages.extend(converted);
|
||||
}
|
||||
}
|
||||
|
||||
result["messages"] = json!(messages);
|
||||
|
||||
// 转换参数
|
||||
if let Some(v) = body.get("max_tokens") {
|
||||
result["max_tokens"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("temperature") {
|
||||
result["temperature"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("top_p") {
|
||||
result["top_p"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("stop_sequences") {
|
||||
result["stop"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("stream") {
|
||||
result["stream"] = v.clone();
|
||||
}
|
||||
|
||||
// 转换 tools (过滤 BatchTool)
|
||||
if let Some(tools) = body.get("tools").and_then(|t| t.as_array()) {
|
||||
let openai_tools: Vec<Value> = tools
|
||||
.iter()
|
||||
.filter(|t| t.get("type").and_then(|v| v.as_str()) != Some("BatchTool"))
|
||||
.map(|t| {
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name").and_then(|n| n.as_str()).unwrap_or(""),
|
||||
"description": t.get("description"),
|
||||
"parameters": clean_schema(t.get("input_schema").cloned().unwrap_or(json!({})))
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
if !openai_tools.is_empty() {
|
||||
result["tools"] = json!(openai_tools);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(v) = body.get("tool_choice") {
|
||||
result["tool_choice"] = v.clone();
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 转换单条消息到 OpenAI 格式(可能产生多条消息)
|
||||
fn convert_message_to_openai(
|
||||
role: &str,
|
||||
content: Option<&Value>,
|
||||
) -> Result<Vec<Value>, ProxyError> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
let content = match content {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
result.push(json!({"role": role, "content": null}));
|
||||
return Ok(result);
|
||||
}
|
||||
};
|
||||
|
||||
// 字符串内容
|
||||
if let Some(text) = content.as_str() {
|
||||
result.push(json!({"role": role, "content": text}));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// 数组内容(多模态/工具调用)
|
||||
if let Some(blocks) = content.as_array() {
|
||||
let mut content_parts = Vec::new();
|
||||
let mut tool_calls = Vec::new();
|
||||
|
||||
for block in blocks {
|
||||
let block_type = block.get("type").and_then(|t| t.as_str()).unwrap_or("");
|
||||
|
||||
match block_type {
|
||||
"text" => {
|
||||
if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
|
||||
content_parts.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
}
|
||||
"image" => {
|
||||
if let Some(source) = block.get("source") {
|
||||
let media_type = source
|
||||
.get("media_type")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("image/png");
|
||||
let data = source.get("data").and_then(|d| d.as_str()).unwrap_or("");
|
||||
content_parts.push(json!({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": format!("data:{};base64,{}", media_type, data)}
|
||||
}));
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
let id = block.get("id").and_then(|i| i.as_str()).unwrap_or("");
|
||||
let name = block.get("name").and_then(|n| n.as_str()).unwrap_or("");
|
||||
let input = block.get("input").cloned().unwrap_or(json!({}));
|
||||
tool_calls.push(json!({
|
||||
"id": id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"arguments": serde_json::to_string(&input).unwrap_or_default()
|
||||
}
|
||||
}));
|
||||
}
|
||||
"tool_result" => {
|
||||
// tool_result 变成单独的 tool role 消息
|
||||
let tool_use_id = block
|
||||
.get("tool_use_id")
|
||||
.and_then(|i| i.as_str())
|
||||
.unwrap_or("");
|
||||
let content_val = block.get("content");
|
||||
let content_str = match content_val {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(v) => serde_json::to_string(v).unwrap_or_default(),
|
||||
None => String::new(),
|
||||
};
|
||||
result.push(json!({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_use_id,
|
||||
"content": content_str
|
||||
}));
|
||||
}
|
||||
"thinking" => {
|
||||
// 跳过 thinking blocks
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加带内容和/或工具调用的消息
|
||||
if !content_parts.is_empty() || !tool_calls.is_empty() {
|
||||
let mut msg = json!({"role": role});
|
||||
|
||||
// 内容处理
|
||||
if content_parts.is_empty() {
|
||||
msg["content"] = Value::Null;
|
||||
} else if content_parts.len() == 1 {
|
||||
if let Some(text) = content_parts[0].get("text") {
|
||||
msg["content"] = text.clone();
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if !tool_calls.is_empty() {
|
||||
msg["tool_calls"] = json!(tool_calls);
|
||||
}
|
||||
|
||||
result.push(msg);
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// 其他情况直接透传
|
||||
result.push(json!({"role": role, "content": content}));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 清理 JSON schema(移除不支持的 format)
|
||||
fn clean_schema(mut schema: Value) -> Value {
|
||||
if let Some(obj) = schema.as_object_mut() {
|
||||
// 移除 "format": "uri"
|
||||
if obj.get("format").and_then(|v| v.as_str()) == Some("uri") {
|
||||
obj.remove("format");
|
||||
}
|
||||
|
||||
// 递归清理嵌套 schema
|
||||
if let Some(properties) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
|
||||
for (_, value) in properties.iter_mut() {
|
||||
*value = clean_schema(value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(items) = obj.get_mut("items") {
|
||||
*items = clean_schema(items.clone());
|
||||
}
|
||||
}
|
||||
schema
|
||||
}
|
||||
|
||||
/// OpenAI 响应 → Anthropic 响应
|
||||
pub fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
let choices = body
|
||||
.get("choices")
|
||||
.and_then(|c| c.as_array())
|
||||
.ok_or_else(|| ProxyError::TransformError("No choices in response".to_string()))?;
|
||||
|
||||
let choice = choices
|
||||
.first()
|
||||
.ok_or_else(|| ProxyError::TransformError("Empty choices array".to_string()))?;
|
||||
|
||||
let message = choice
|
||||
.get("message")
|
||||
.ok_or_else(|| ProxyError::TransformError("No message in choice".to_string()))?;
|
||||
|
||||
let mut content = Vec::new();
|
||||
|
||||
// 文本内容
|
||||
if let Some(text) = message.get("content").and_then(|c| c.as_str()) {
|
||||
if !text.is_empty() {
|
||||
content.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if let Some(tool_calls) = message.get("tool_calls").and_then(|t| t.as_array()) {
|
||||
for tc in tool_calls {
|
||||
let id = tc.get("id").and_then(|i| i.as_str()).unwrap_or("");
|
||||
let empty_obj = json!({});
|
||||
let func = tc.get("function").unwrap_or(&empty_obj);
|
||||
let name = func.get("name").and_then(|n| n.as_str()).unwrap_or("");
|
||||
let args_str = func
|
||||
.get("arguments")
|
||||
.and_then(|a| a.as_str())
|
||||
.unwrap_or("{}");
|
||||
let input: Value = serde_json::from_str(args_str).unwrap_or(json!({}));
|
||||
|
||||
content.push(json!({
|
||||
"type": "tool_use",
|
||||
"id": id,
|
||||
"name": name,
|
||||
"input": input
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// 映射 finish_reason → stop_reason
|
||||
let stop_reason = choice
|
||||
.get("finish_reason")
|
||||
.and_then(|r| r.as_str())
|
||||
.map(|r| match r {
|
||||
"stop" => "end_turn",
|
||||
"length" => "max_tokens",
|
||||
"tool_calls" => "tool_use",
|
||||
other => other,
|
||||
});
|
||||
|
||||
// usage
|
||||
let usage = body.get("usage").cloned().unwrap_or(json!({}));
|
||||
let input_tokens = usage
|
||||
.get("prompt_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
let output_tokens = usage
|
||||
.get("completion_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
|
||||
let result = json!({
|
||||
"id": body.get("id").and_then(|i| i.as_str()).unwrap_or(""),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
"model": body.get("model").and_then(|m| m.as_str()).unwrap_or(""),
|
||||
"stop_reason": stop_reason,
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens
|
||||
}
|
||||
});
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn create_provider(env_config: Value) -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test Provider".to_string(),
|
||||
settings_config: json!({"env": env_config}),
|
||||
website_url: None,
|
||||
category: None,
|
||||
created_at: None,
|
||||
sort_index: None,
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_openrouter_provider() -> Provider {
|
||||
create_provider(json!({
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api",
|
||||
"ANTHROPIC_MODEL": "anthropic/claude-sonnet-4.5",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "anthropic/claude-haiku-4.5",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL": "anthropic/claude-sonnet-4.5",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": "anthropic/claude-opus-4.5"
|
||||
}))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_simple() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
// opus 模型映射到配置的 ANTHROPIC_DEFAULT_OPUS_MODEL
|
||||
assert_eq!(result["model"], "anthropic/claude-opus-4.5");
|
||||
assert_eq!(result["max_tokens"], 1024);
|
||||
assert_eq!(result["messages"][0]["role"], "user");
|
||||
assert_eq!(result["messages"][0]["content"], "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_with_system() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-3-sonnet",
|
||||
"max_tokens": 1024,
|
||||
"system": "You are a helpful assistant.",
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
assert_eq!(result["messages"][0]["role"], "system");
|
||||
assert_eq!(
|
||||
result["messages"][0]["content"],
|
||||
"You are a helpful assistant."
|
||||
);
|
||||
assert_eq!(result["messages"][1]["role"], "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_with_tools() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "What's the weather?"}],
|
||||
"tools": [{
|
||||
"name": "get_weather",
|
||||
"description": "Get weather info",
|
||||
"input_schema": {"type": "object", "properties": {"location": {"type": "string"}}}
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
assert_eq!(result["tools"][0]["type"], "function");
|
||||
assert_eq!(result["tools"][0]["function"]["name"], "get_weather");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_tool_use() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{"type": "text", "text": "Let me check"},
|
||||
{"type": "tool_use", "id": "call_123", "name": "get_weather", "input": {"location": "Tokyo"}}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
let msg = &result["messages"][0];
|
||||
assert_eq!(msg["role"], "assistant");
|
||||
assert!(msg.get("tool_calls").is_some());
|
||||
assert_eq!(msg["tool_calls"][0]["id"], "call_123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_tool_result() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "call_123", "content": "Sunny, 25°C"}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
let msg = &result["messages"][0];
|
||||
assert_eq!(msg["role"], "tool");
|
||||
assert_eq!(msg["tool_call_id"], "call_123");
|
||||
assert_eq!(msg["content"], "Sunny, 25°C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_openai_to_anthropic_simple() {
|
||||
let input = json!({
|
||||
"id": "chatcmpl-123",
|
||||
"object": "chat.completion",
|
||||
"created": 1234567890,
|
||||
"model": "gpt-4",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "Hello!"},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
});
|
||||
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["id"], "chatcmpl-123");
|
||||
assert_eq!(result["type"], "message");
|
||||
assert_eq!(result["content"][0]["type"], "text");
|
||||
assert_eq!(result["content"][0]["text"], "Hello!");
|
||||
assert_eq!(result["stop_reason"], "end_turn");
|
||||
assert_eq!(result["usage"]["input_tokens"], 10);
|
||||
assert_eq!(result["usage"]["output_tokens"], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_openai_to_anthropic_with_tool_calls() {
|
||||
let input = json!({
|
||||
"id": "chatcmpl-123",
|
||||
"object": "chat.completion",
|
||||
"created": 1234567890,
|
||||
"model": "gpt-4",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [{
|
||||
"id": "call_123",
|
||||
"type": "function",
|
||||
"function": {"name": "get_weather", "arguments": "{\"location\": \"Tokyo\"}"}
|
||||
}]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
});
|
||||
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["content"][0]["type"], "tool_use");
|
||||
assert_eq!(result["content"][0]["id"], "call_123");
|
||||
assert_eq!(result["content"][0]["name"], "get_weather");
|
||||
assert_eq!(result["content"][0]["input"]["location"], "Tokyo");
|
||||
assert_eq!(result["stop_reason"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_model_mapping_from_provider() {
|
||||
let provider = create_openrouter_provider();
|
||||
let body = json!({"model": "test"});
|
||||
|
||||
// sonnet 模型
|
||||
assert_eq!(
|
||||
get_model_from_provider("claude-sonnet-4-5-20250929", &provider, &body),
|
||||
"anthropic/claude-sonnet-4.5"
|
||||
);
|
||||
|
||||
// haiku 模型
|
||||
assert_eq!(
|
||||
get_model_from_provider("claude-haiku-4-5-20250929", &provider, &body),
|
||||
"anthropic/claude-haiku-4.5"
|
||||
);
|
||||
|
||||
// opus 模型
|
||||
assert_eq!(
|
||||
get_model_from_provider("claude-opus-4-5", &provider, &body),
|
||||
"anthropic/claude-opus-4.5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_model_mapping() {
|
||||
let provider = create_openrouter_provider();
|
||||
let input = json!({
|
||||
"model": "claude-sonnet-4-5-20250929",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
assert_eq!(result["model"], "anthropic/claude-sonnet-4.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_parameter_detection() {
|
||||
let mut provider = create_openrouter_provider();
|
||||
// 添加推理模型配置
|
||||
if let Some(env) = provider.settings_config.get_mut("env") {
|
||||
env["ANTHROPIC_REASONING_MODEL"] = json!("anthropic/claude-sonnet-4.5:extended");
|
||||
}
|
||||
|
||||
let input = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "enabled"},
|
||||
"messages": [{"role": "user", "content": "Solve this problem"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
// 应该使用推理模型
|
||||
assert_eq!(result["model"], "anthropic/claude-sonnet-4.5:extended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_parameter_disabled() {
|
||||
let mut provider = create_openrouter_provider();
|
||||
if let Some(env) = provider.settings_config.get_mut("env") {
|
||||
env["ANTHROPIC_REASONING_MODEL"] = json!("anthropic/claude-sonnet-4.5:extended");
|
||||
}
|
||||
|
||||
let input = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"max_tokens": 1024,
|
||||
"thinking": {"type": "disabled"},
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input, &provider).unwrap();
|
||||
// 应该使用普通模型
|
||||
assert_eq!(result["model"], "anthropic/claude-sonnet-4.5");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//! Anthropic ↔ OpenAI 格式转换模块
|
||||
//!
|
||||
//! 提供 Anthropic Messages API 和 OpenAI Chat Completions API 之间的双向转换
|
||||
|
||||
mod request;
|
||||
mod response;
|
||||
pub mod streaming;
|
||||
|
||||
pub use request::AnthropicToOpenAITransformer;
|
||||
pub use response::OpenAIToAnthropicTransformer;
|
||||
@@ -0,0 +1,397 @@
|
||||
//! Anthropic → OpenAI 请求转换器
|
||||
//!
|
||||
//! 将 Anthropic Messages API 请求转换为 OpenAI Chat Completions API 格式
|
||||
|
||||
use crate::proxy::error::ProxyError;
|
||||
use crate::proxy::transform::{format::ApiFormat, traits::FormatTransformer};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::Stream;
|
||||
use serde_json::{json, Value};
|
||||
use std::pin::Pin;
|
||||
|
||||
/// Anthropic → OpenAI 请求转换器
|
||||
pub struct AnthropicToOpenAITransformer;
|
||||
|
||||
impl AnthropicToOpenAITransformer {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AnthropicToOpenAITransformer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FormatTransformer for AnthropicToOpenAITransformer {
|
||||
fn name(&self) -> &'static str {
|
||||
"Anthropic→OpenAI"
|
||||
}
|
||||
|
||||
fn source_format(&self) -> ApiFormat {
|
||||
ApiFormat::Anthropic
|
||||
}
|
||||
|
||||
fn target_format(&self) -> ApiFormat {
|
||||
ApiFormat::OpenAI
|
||||
}
|
||||
|
||||
fn transform_request(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
anthropic_to_openai(body)
|
||||
}
|
||||
|
||||
fn transform_response(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
// 请求转换器不处理响应,直接透传
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn transform_stream(
|
||||
&self,
|
||||
_stream: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
|
||||
) -> Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>> {
|
||||
// 请求转换器不处理流
|
||||
Box::pin(futures::stream::empty())
|
||||
}
|
||||
|
||||
fn transform_endpoint(&self, endpoint: &str) -> String {
|
||||
// /v1/messages → /v1/chat/completions
|
||||
if endpoint == "/v1/messages" {
|
||||
"/v1/chat/completions".to_string()
|
||||
} else {
|
||||
endpoint.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Anthropic 请求 → OpenAI 请求
|
||||
fn anthropic_to_openai(body: Value) -> Result<Value, ProxyError> {
|
||||
let mut result = json!({});
|
||||
|
||||
// 模型直接透传(模型映射由 model_mapper 模块独立处理)
|
||||
if let Some(model) = body.get("model") {
|
||||
result["model"] = model.clone();
|
||||
}
|
||||
|
||||
let mut messages = Vec::new();
|
||||
|
||||
// 处理 system prompt
|
||||
if let Some(system) = body.get("system") {
|
||||
if let Some(text) = system.as_str() {
|
||||
// 单个字符串
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
} else if let Some(arr) = system.as_array() {
|
||||
// 多个 system message
|
||||
for msg in arr {
|
||||
if let Some(text) = msg.get("text").and_then(|t| t.as_str()) {
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 转换 messages
|
||||
if let Some(msgs) = body.get("messages").and_then(|m| m.as_array()) {
|
||||
for msg in msgs {
|
||||
let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("user");
|
||||
let content = msg.get("content");
|
||||
let converted = convert_message_to_openai(role, content)?;
|
||||
messages.extend(converted);
|
||||
}
|
||||
}
|
||||
|
||||
result["messages"] = json!(messages);
|
||||
|
||||
// 转换参数
|
||||
if let Some(v) = body.get("max_tokens") {
|
||||
result["max_tokens"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("temperature") {
|
||||
result["temperature"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("top_p") {
|
||||
result["top_p"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("stop_sequences") {
|
||||
result["stop"] = v.clone();
|
||||
}
|
||||
if let Some(v) = body.get("stream") {
|
||||
result["stream"] = v.clone();
|
||||
}
|
||||
|
||||
// 转换 tools (过滤 BatchTool)
|
||||
if let Some(tools) = body.get("tools").and_then(|t| t.as_array()) {
|
||||
let openai_tools: Vec<Value> = tools
|
||||
.iter()
|
||||
.filter(|t| t.get("type").and_then(|v| v.as_str()) != Some("BatchTool"))
|
||||
.map(|t| {
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name").and_then(|n| n.as_str()).unwrap_or(""),
|
||||
"description": t.get("description"),
|
||||
"parameters": clean_schema(t.get("input_schema").cloned().unwrap_or(json!({})))
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
if !openai_tools.is_empty() {
|
||||
result["tools"] = json!(openai_tools);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(v) = body.get("tool_choice") {
|
||||
result["tool_choice"] = v.clone();
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 转换单条消息到 OpenAI 格式(可能产生多条消息)
|
||||
fn convert_message_to_openai(
|
||||
role: &str,
|
||||
content: Option<&Value>,
|
||||
) -> Result<Vec<Value>, ProxyError> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
let content = match content {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
result.push(json!({"role": role, "content": null}));
|
||||
return Ok(result);
|
||||
}
|
||||
};
|
||||
|
||||
// 字符串内容
|
||||
if let Some(text) = content.as_str() {
|
||||
result.push(json!({"role": role, "content": text}));
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// 数组内容(多模态/工具调用)
|
||||
if let Some(blocks) = content.as_array() {
|
||||
let mut content_parts = Vec::new();
|
||||
let mut tool_calls = Vec::new();
|
||||
|
||||
for block in blocks {
|
||||
let block_type = block.get("type").and_then(|t| t.as_str()).unwrap_or("");
|
||||
|
||||
match block_type {
|
||||
"text" => {
|
||||
if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
|
||||
content_parts.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
}
|
||||
"image" => {
|
||||
if let Some(source) = block.get("source") {
|
||||
let media_type = source
|
||||
.get("media_type")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("image/png");
|
||||
let data = source.get("data").and_then(|d| d.as_str()).unwrap_or("");
|
||||
content_parts.push(json!({
|
||||
"type": "image_url",
|
||||
"image_url": {"url": format!("data:{};base64,{}", media_type, data)}
|
||||
}));
|
||||
}
|
||||
}
|
||||
"tool_use" => {
|
||||
let id = block.get("id").and_then(|i| i.as_str()).unwrap_or("");
|
||||
let name = block.get("name").and_then(|n| n.as_str()).unwrap_or("");
|
||||
let input = block.get("input").cloned().unwrap_or(json!({}));
|
||||
tool_calls.push(json!({
|
||||
"id": id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"arguments": serde_json::to_string(&input).unwrap_or_default()
|
||||
}
|
||||
}));
|
||||
}
|
||||
"tool_result" => {
|
||||
// tool_result 变成单独的 tool role 消息
|
||||
let tool_use_id = block
|
||||
.get("tool_use_id")
|
||||
.and_then(|i| i.as_str())
|
||||
.unwrap_or("");
|
||||
let content_val = block.get("content");
|
||||
let content_str = match content_val {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(v) => serde_json::to_string(v).unwrap_or_default(),
|
||||
None => String::new(),
|
||||
};
|
||||
result.push(json!({
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_use_id,
|
||||
"content": content_str
|
||||
}));
|
||||
}
|
||||
"thinking" => {
|
||||
// 跳过 thinking blocks
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// 添加带内容和/或工具调用的消息
|
||||
if !content_parts.is_empty() || !tool_calls.is_empty() {
|
||||
let mut msg = json!({"role": role});
|
||||
|
||||
// 内容处理
|
||||
if content_parts.is_empty() {
|
||||
msg["content"] = Value::Null;
|
||||
} else if content_parts.len() == 1 {
|
||||
if let Some(text) = content_parts[0].get("text") {
|
||||
msg["content"] = text.clone();
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if !tool_calls.is_empty() {
|
||||
msg["tool_calls"] = json!(tool_calls);
|
||||
}
|
||||
|
||||
result.push(msg);
|
||||
}
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// 其他情况直接透传
|
||||
result.push(json!({"role": role, "content": content}));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 清理 JSON schema(移除不支持的 format)
|
||||
fn clean_schema(mut schema: Value) -> Value {
|
||||
if let Some(obj) = schema.as_object_mut() {
|
||||
// 移除 "format": "uri"
|
||||
if obj.get("format").and_then(|v| v.as_str()) == Some("uri") {
|
||||
obj.remove("format");
|
||||
}
|
||||
|
||||
// 递归清理嵌套 schema
|
||||
if let Some(properties) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
|
||||
for (_, value) in properties.iter_mut() {
|
||||
*value = clean_schema(value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(items) = obj.get_mut("items") {
|
||||
*items = clean_schema(items.clone());
|
||||
}
|
||||
}
|
||||
schema
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_simple() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
assert_eq!(result["model"], "claude-3-opus");
|
||||
assert_eq!(result["max_tokens"], 1024);
|
||||
assert_eq!(result["messages"][0]["role"], "user");
|
||||
assert_eq!(result["messages"][0]["content"], "Hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_with_system() {
|
||||
let input = json!({
|
||||
"model": "claude-3-sonnet",
|
||||
"max_tokens": 1024,
|
||||
"system": "You are a helpful assistant.",
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
assert_eq!(result["messages"][0]["role"], "system");
|
||||
assert_eq!(
|
||||
result["messages"][0]["content"],
|
||||
"You are a helpful assistant."
|
||||
);
|
||||
assert_eq!(result["messages"][1]["role"], "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_with_tools() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "What's the weather?"}],
|
||||
"tools": [{
|
||||
"name": "get_weather",
|
||||
"description": "Get weather info",
|
||||
"input_schema": {"type": "object", "properties": {"location": {"type": "string"}}}
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
assert_eq!(result["tools"][0]["type"], "function");
|
||||
assert_eq!(result["tools"][0]["function"]["name"], "get_weather");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_tool_use() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{"type": "text", "text": "Let me check"},
|
||||
{"type": "tool_use", "id": "call_123", "name": "get_weather", "input": {"location": "Tokyo"}}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
let msg = &result["messages"][0];
|
||||
assert_eq!(msg["role"], "assistant");
|
||||
assert!(msg.get("tool_calls").is_some());
|
||||
assert_eq!(msg["tool_calls"][0]["id"], "call_123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_tool_result() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "tool_result", "tool_use_id": "call_123", "content": "Sunny, 25°C"}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
let msg = &result["messages"][0];
|
||||
assert_eq!(msg["role"], "tool");
|
||||
assert_eq!(msg["tool_call_id"], "call_123");
|
||||
assert_eq!(msg["content"], "Sunny, 25°C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform_endpoint() {
|
||||
let transformer = AnthropicToOpenAITransformer::new();
|
||||
assert_eq!(
|
||||
transformer.transform_endpoint("/v1/messages"),
|
||||
"/v1/chat/completions"
|
||||
);
|
||||
assert_eq!(transformer.transform_endpoint("/v1/other"), "/v1/other");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! OpenAI → Anthropic 响应转换器
|
||||
//!
|
||||
//! 将 OpenAI Chat Completions API 响应转换为 Anthropic Messages API 格式
|
||||
|
||||
use crate::proxy::error::ProxyError;
|
||||
use crate::proxy::transform::{format::ApiFormat, traits::FormatTransformer};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::Stream;
|
||||
use serde_json::{json, Value};
|
||||
use std::pin::Pin;
|
||||
|
||||
use super::streaming::create_anthropic_sse_stream;
|
||||
|
||||
/// OpenAI → Anthropic 响应转换器
|
||||
pub struct OpenAIToAnthropicTransformer;
|
||||
|
||||
impl OpenAIToAnthropicTransformer {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for OpenAIToAnthropicTransformer {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl FormatTransformer for OpenAIToAnthropicTransformer {
|
||||
fn name(&self) -> &'static str {
|
||||
"OpenAI→Anthropic"
|
||||
}
|
||||
|
||||
fn source_format(&self) -> ApiFormat {
|
||||
ApiFormat::OpenAI
|
||||
}
|
||||
|
||||
fn target_format(&self) -> ApiFormat {
|
||||
ApiFormat::Anthropic
|
||||
}
|
||||
|
||||
fn transform_request(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
// 响应转换器不处理请求,直接透传
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn transform_response(&self, body: Value) -> Result<Value, ProxyError> {
|
||||
openai_to_anthropic(body)
|
||||
}
|
||||
|
||||
fn transform_stream(
|
||||
&self,
|
||||
stream: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
|
||||
) -> Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>> {
|
||||
Box::pin(create_anthropic_sse_stream(stream))
|
||||
}
|
||||
}
|
||||
|
||||
/// OpenAI 响应 → Anthropic 响应
|
||||
fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
let choices = body
|
||||
.get("choices")
|
||||
.and_then(|c| c.as_array())
|
||||
.ok_or_else(|| ProxyError::TransformError("No choices in response".to_string()))?;
|
||||
|
||||
let choice = choices
|
||||
.first()
|
||||
.ok_or_else(|| ProxyError::TransformError("Empty choices array".to_string()))?;
|
||||
|
||||
let message = choice
|
||||
.get("message")
|
||||
.ok_or_else(|| ProxyError::TransformError("No message in choice".to_string()))?;
|
||||
|
||||
let mut content = Vec::new();
|
||||
|
||||
// 文本内容
|
||||
if let Some(text) = message.get("content").and_then(|c| c.as_str()) {
|
||||
if !text.is_empty() {
|
||||
content.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
}
|
||||
|
||||
// 工具调用
|
||||
if let Some(tool_calls) = message.get("tool_calls").and_then(|t| t.as_array()) {
|
||||
for tc in tool_calls {
|
||||
let id = tc.get("id").and_then(|i| i.as_str()).unwrap_or("");
|
||||
let empty_obj = json!({});
|
||||
let func = tc.get("function").unwrap_or(&empty_obj);
|
||||
let name = func.get("name").and_then(|n| n.as_str()).unwrap_or("");
|
||||
let args_str = func
|
||||
.get("arguments")
|
||||
.and_then(|a| a.as_str())
|
||||
.unwrap_or("{}");
|
||||
|
||||
// 解析 arguments JSON,失败时返回错误而不是静默使用空对象
|
||||
let input: Value = serde_json::from_str(args_str).map_err(|e| {
|
||||
log::error!("[Transform] tool_calls.arguments 解析失败: {e}, 原始内容: {args_str}");
|
||||
ProxyError::TransformError(format!(
|
||||
"Failed to parse tool_calls.arguments: {e}, content: {args_str}"
|
||||
))
|
||||
})?;
|
||||
|
||||
content.push(json!({
|
||||
"type": "tool_use",
|
||||
"id": id,
|
||||
"name": name,
|
||||
"input": input
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// 映射 finish_reason → stop_reason
|
||||
let stop_reason = choice
|
||||
.get("finish_reason")
|
||||
.and_then(|r| r.as_str())
|
||||
.map(|r| match r {
|
||||
"stop" => "end_turn",
|
||||
"length" => "max_tokens",
|
||||
"tool_calls" => "tool_use",
|
||||
other => other,
|
||||
});
|
||||
|
||||
// usage
|
||||
let usage = body.get("usage").cloned().unwrap_or(json!({}));
|
||||
let input_tokens = usage
|
||||
.get("prompt_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
let output_tokens = usage
|
||||
.get("completion_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
|
||||
let result = json!({
|
||||
"id": body.get("id").and_then(|i| i.as_str()).unwrap_or(""),
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
"model": body.get("model").and_then(|m| m.as_str()).unwrap_or(""),
|
||||
"stop_reason": stop_reason,
|
||||
"stop_sequence": null,
|
||||
"usage": {
|
||||
"input_tokens": input_tokens,
|
||||
"output_tokens": output_tokens
|
||||
}
|
||||
});
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_openai_to_anthropic_simple() {
|
||||
let input = json!({
|
||||
"id": "chatcmpl-123",
|
||||
"object": "chat.completion",
|
||||
"created": 1234567890,
|
||||
"model": "gpt-4",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {"role": "assistant", "content": "Hello!"},
|
||||
"finish_reason": "stop"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
});
|
||||
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["id"], "chatcmpl-123");
|
||||
assert_eq!(result["type"], "message");
|
||||
assert_eq!(result["content"][0]["type"], "text");
|
||||
assert_eq!(result["content"][0]["text"], "Hello!");
|
||||
assert_eq!(result["stop_reason"], "end_turn");
|
||||
assert_eq!(result["usage"]["input_tokens"], 10);
|
||||
assert_eq!(result["usage"]["output_tokens"], 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_openai_to_anthropic_with_tool_calls() {
|
||||
let input = json!({
|
||||
"id": "chatcmpl-123",
|
||||
"object": "chat.completion",
|
||||
"created": 1234567890,
|
||||
"model": "gpt-4",
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [{
|
||||
"id": "call_123",
|
||||
"type": "function",
|
||||
"function": {"name": "get_weather", "arguments": "{\"location\": \"Tokyo\"}"}
|
||||
}]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}],
|
||||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
});
|
||||
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["content"][0]["type"], "tool_use");
|
||||
assert_eq!(result["content"][0]["id"], "call_123");
|
||||
assert_eq!(result["content"][0]["name"], "get_weather");
|
||||
assert_eq!(result["content"][0]["input"]["location"], "Tokyo");
|
||||
assert_eq!(result["stop_reason"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stop_reason_mapping() {
|
||||
// stop → end_turn
|
||||
let input = json!({
|
||||
"choices": [{"message": {"content": "Hi"}, "finish_reason": "stop"}],
|
||||
"usage": {}
|
||||
});
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["stop_reason"], "end_turn");
|
||||
|
||||
// length → max_tokens
|
||||
let input = json!({
|
||||
"choices": [{"message": {"content": "Hi"}, "finish_reason": "length"}],
|
||||
"usage": {}
|
||||
});
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["stop_reason"], "max_tokens");
|
||||
|
||||
// tool_calls → tool_use
|
||||
let input = json!({
|
||||
"choices": [{"message": {"content": null, "tool_calls": []}, "finish_reason": "tool_calls"}],
|
||||
"usage": {}
|
||||
});
|
||||
let result = openai_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["stop_reason"], "tool_use");
|
||||
}
|
||||
}
|
||||
+29
-9
@@ -6,6 +6,7 @@ use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// OpenAI 流式响应数据结构
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -73,7 +74,8 @@ pub fn create_anthropic_sse_stream(
|
||||
let mut content_index = 0;
|
||||
let mut has_sent_message_start = false;
|
||||
let mut current_block_type: Option<String> = None;
|
||||
let mut tool_call_id = None;
|
||||
// 使用 HashMap 按 index 管理多个工具调用的 ID 和 content_index
|
||||
let mut tool_calls_map: HashMap<usize, (String, usize)> = HashMap::new();
|
||||
|
||||
tokio::pin!(stream);
|
||||
|
||||
@@ -94,17 +96,17 @@ pub fn create_anthropic_sse_stream(
|
||||
for l in line.lines() {
|
||||
if let Some(data) = l.strip_prefix("data: ") {
|
||||
if data.trim() == "[DONE]" {
|
||||
log::debug!("[Claude/OpenRouter] <<< OpenAI SSE: [DONE]");
|
||||
log::debug!("[Transform] <<< OpenAI SSE: [DONE]");
|
||||
let event = json!({"type": "message_stop"});
|
||||
let sse_data = format!("event: message_stop\ndata: {}\n\n",
|
||||
serde_json::to_string(&event).unwrap_or_default());
|
||||
log::debug!("[Claude/OpenRouter] >>> Anthropic SSE: message_stop");
|
||||
log::debug!("[Transform] >>> Anthropic SSE: message_stop");
|
||||
yield Ok(Bytes::from(sse_data));
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(chunk) = serde_json::from_str::<OpenAIStreamChunk>(data) {
|
||||
log::debug!("[Claude/OpenRouter] <<< SSE chunk received");
|
||||
log::debug!("[Transform] <<< SSE chunk received");
|
||||
|
||||
if message_id.is_none() {
|
||||
message_id = Some(chunk.id.clone());
|
||||
@@ -210,7 +212,11 @@ pub fn create_anthropic_sse_stream(
|
||||
// 处理工具调用
|
||||
if let Some(tool_calls) = &choice.delta.tool_calls {
|
||||
for tool_call in tool_calls {
|
||||
let tc_index = tool_call.index;
|
||||
|
||||
// 检查是否是新的工具调用(有 id 表示开始新的工具调用)
|
||||
if let Some(id) = &tool_call.id {
|
||||
// 关闭当前的 content block(如果有)
|
||||
if current_block_type.is_some() {
|
||||
let event = json!({
|
||||
"type": "content_block_stop",
|
||||
@@ -222,30 +228,44 @@ pub fn create_anthropic_sse_stream(
|
||||
content_index += 1;
|
||||
}
|
||||
|
||||
tool_call_id = Some(id.clone());
|
||||
// 记录这个工具调用的 ID 和对应的 content_index
|
||||
tool_calls_map.insert(tc_index, (id.clone(), content_index));
|
||||
current_block_type = Some("tool_use".to_string());
|
||||
}
|
||||
|
||||
// 获取当前工具调用的信息
|
||||
let (tool_id, tool_content_index) = tool_calls_map
|
||||
.get(&tc_index)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
log::warn!(
|
||||
"[Transform] 收到未知 index 的工具调用 delta: {tc_index}"
|
||||
);
|
||||
(String::new(), content_index)
|
||||
});
|
||||
|
||||
if let Some(function) = &tool_call.function {
|
||||
// 如果有 name,发送 content_block_start
|
||||
if let Some(name) = &function.name {
|
||||
let event = json!({
|
||||
"type": "content_block_start",
|
||||
"index": content_index,
|
||||
"index": tool_content_index,
|
||||
"content_block": {
|
||||
"type": "tool_use",
|
||||
"id": tool_call_id.clone().unwrap_or_default(),
|
||||
"id": tool_id,
|
||||
"name": name
|
||||
}
|
||||
});
|
||||
let sse_data = format!("event: content_block_start\ndata: {}\n\n",
|
||||
serde_json::to_string(&event).unwrap_or_default());
|
||||
yield Ok(Bytes::from(sse_data));
|
||||
current_block_type = Some("tool_use".to_string());
|
||||
}
|
||||
|
||||
// 如果有 arguments,发送 content_block_delta
|
||||
if let Some(args) = &function.arguments {
|
||||
let event = json!({
|
||||
"type": "content_block_delta",
|
||||
"index": content_index,
|
||||
"index": tool_content_index,
|
||||
"delta": {
|
||||
"type": "input_json_delta",
|
||||
"partial_json": args
|
||||
@@ -0,0 +1,247 @@
|
||||
//! 格式转换配置
|
||||
//!
|
||||
//! 从 Provider 配置中提取格式转换设置
|
||||
|
||||
use super::format::ApiFormat;
|
||||
use crate::provider::Provider;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// 格式转换配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TransformConfig {
|
||||
/// 是否启用格式转换
|
||||
pub enabled: bool,
|
||||
/// 源格式(客户端发送的格式)
|
||||
pub source_format: ApiFormat,
|
||||
/// 目标格式(上游服务期望的格式)
|
||||
pub target_format: ApiFormat,
|
||||
/// 是否转换流式响应
|
||||
pub transform_streaming: bool,
|
||||
}
|
||||
|
||||
impl Default for TransformConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
source_format: ApiFormat::Anthropic,
|
||||
target_format: ApiFormat::OpenAI,
|
||||
transform_streaming: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TransformConfig {
|
||||
/// 从 Provider 配置中提取转换配置
|
||||
///
|
||||
/// 优先级:
|
||||
/// 1. ProviderMeta.format_transform(新配置格式,通过前端 UI 设置)
|
||||
/// 2. settings_config.format_transform(兼容旧配置)
|
||||
/// 3. settings_config.openrouter_compat_mode(兼容旧配置)
|
||||
///
|
||||
/// 注意:如果格式解析失败,将禁用转换并记录警告,而不是静默回退到默认值
|
||||
pub fn from_provider(provider: &Provider) -> Self {
|
||||
// 1. 优先从 ProviderMeta 读取(前端 UI 设置的配置)
|
||||
if let Some(meta) = &provider.meta {
|
||||
if let Some(ft) = &meta.format_transform {
|
||||
if ft.enabled {
|
||||
let source_str = ft.source_format.as_deref();
|
||||
let target_str = ft.target_format.as_deref();
|
||||
|
||||
let source_format = source_str.and_then(ApiFormat::from_str);
|
||||
let target_format = target_str.and_then(ApiFormat::from_str);
|
||||
|
||||
// 如果格式解析失败,禁用转换并记录警告
|
||||
if source_str.is_some() && source_format.is_none() {
|
||||
log::warn!(
|
||||
"[TransformConfig] 无法解析 source_format: {source_str:?},禁用格式转换"
|
||||
);
|
||||
return Self::default();
|
||||
}
|
||||
if target_str.is_some() && target_format.is_none() {
|
||||
log::warn!(
|
||||
"[TransformConfig] 无法解析 target_format: {target_str:?},禁用格式转换"
|
||||
);
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let transform_streaming = ft.transform_streaming.unwrap_or(true);
|
||||
|
||||
return Self {
|
||||
enabled: true,
|
||||
source_format: source_format.unwrap_or(ApiFormat::Anthropic),
|
||||
target_format: target_format.unwrap_or(ApiFormat::OpenAI),
|
||||
transform_streaming,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let settings = &provider.settings_config;
|
||||
|
||||
// 2. 检查是否显式启用格式转换(settings_config 中的配置)
|
||||
let format_transform = settings.get("format_transform").and_then(|v| v.as_object());
|
||||
|
||||
if let Some(config) = format_transform {
|
||||
let enabled = config
|
||||
.get("enabled")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
|
||||
if enabled {
|
||||
let source_str = config.get("source_format").and_then(|v| v.as_str());
|
||||
let target_str = config.get("target_format").and_then(|v| v.as_str());
|
||||
|
||||
let source_format = source_str.and_then(ApiFormat::from_str);
|
||||
let target_format = target_str.and_then(ApiFormat::from_str);
|
||||
|
||||
// 如果格式解析失败,禁用转换并记录警告
|
||||
if source_str.is_some() && source_format.is_none() {
|
||||
log::warn!(
|
||||
"[TransformConfig] 无法解析 source_format: {source_str:?},禁用格式转换"
|
||||
);
|
||||
return Self::default();
|
||||
}
|
||||
if target_str.is_some() && target_format.is_none() {
|
||||
log::warn!(
|
||||
"[TransformConfig] 无法解析 target_format: {target_str:?},禁用格式转换"
|
||||
);
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
let transform_streaming = config
|
||||
.get("transform_streaming")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(true);
|
||||
|
||||
return Self {
|
||||
enabled,
|
||||
source_format: source_format.unwrap_or(ApiFormat::Anthropic),
|
||||
target_format: target_format.unwrap_or(ApiFormat::OpenAI),
|
||||
transform_streaming,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 兼容旧配置:检查 openrouter_compat_mode
|
||||
let legacy_enabled = settings
|
||||
.get("openrouter_compat_mode")
|
||||
.and_then(|v| match v {
|
||||
serde_json::Value::Bool(b) => Some(*b),
|
||||
serde_json::Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
|
||||
serde_json::Value::String(s) => {
|
||||
let normalized = s.trim().to_lowercase();
|
||||
Some(normalized == "true" || normalized == "1")
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
if legacy_enabled {
|
||||
return Self {
|
||||
enabled: true,
|
||||
source_format: ApiFormat::Anthropic,
|
||||
target_format: ApiFormat::OpenAI,
|
||||
transform_streaming: true,
|
||||
};
|
||||
}
|
||||
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// 检查是否需要转换
|
||||
pub fn needs_transform(&self) -> bool {
|
||||
self.enabled && self.source_format != self.target_format
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn create_provider(settings: serde_json::Value) -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test Provider".to_string(),
|
||||
settings_config: settings,
|
||||
website_url: None,
|
||||
category: None,
|
||||
created_at: None,
|
||||
sort_index: None,
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let provider = create_provider(json!({}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(!config.enabled);
|
||||
assert!(!config.needs_transform());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_format_config() {
|
||||
let provider = create_provider(json!({
|
||||
"format_transform": {
|
||||
"enabled": true,
|
||||
"source_format": "anthropic",
|
||||
"target_format": "openai",
|
||||
"transform_streaming": true
|
||||
}
|
||||
}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.source_format, ApiFormat::Anthropic);
|
||||
assert_eq!(config.target_format, ApiFormat::OpenAI);
|
||||
assert!(config.transform_streaming);
|
||||
assert!(config.needs_transform());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_legacy_openrouter_compat_mode_bool() {
|
||||
let provider = create_provider(json!({
|
||||
"openrouter_compat_mode": true
|
||||
}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.source_format, ApiFormat::Anthropic);
|
||||
assert_eq!(config.target_format, ApiFormat::OpenAI);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_legacy_openrouter_compat_mode_string() {
|
||||
let provider = create_provider(json!({
|
||||
"openrouter_compat_mode": "true"
|
||||
}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(config.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_legacy_openrouter_compat_mode_number() {
|
||||
let provider = create_provider(json!({
|
||||
"openrouter_compat_mode": 1
|
||||
}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(config.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_same_format_no_transform() {
|
||||
let provider = create_provider(json!({
|
||||
"format_transform": {
|
||||
"enabled": true,
|
||||
"source_format": "anthropic",
|
||||
"target_format": "anthropic"
|
||||
}
|
||||
}));
|
||||
let config = TransformConfig::from_provider(&provider);
|
||||
assert!(config.enabled);
|
||||
assert!(!config.needs_transform()); // 相同格式不需要转换
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! API 格式枚举定义
|
||||
//!
|
||||
//! 定义支持的 API 格式类型,用于格式转换配置
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// API 格式枚举
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ApiFormat {
|
||||
/// Anthropic Messages API
|
||||
Anthropic,
|
||||
/// OpenAI Chat Completions API
|
||||
OpenAI,
|
||||
/// Google Gemini API (预留)
|
||||
Gemini,
|
||||
}
|
||||
|
||||
impl ApiFormat {
|
||||
/// 从字符串解析
|
||||
pub fn from_str(s: &str) -> Option<Self> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"anthropic" | "claude" => Some(Self::Anthropic),
|
||||
"openai" | "codex" => Some(Self::OpenAI),
|
||||
"gemini" | "google" => Some(Self::Gemini),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换为字符串
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Anthropic => "anthropic",
|
||||
Self::OpenAI => "openai",
|
||||
Self::Gemini => "gemini",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ApiFormat {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_from_str() {
|
||||
assert_eq!(ApiFormat::from_str("anthropic"), Some(ApiFormat::Anthropic));
|
||||
assert_eq!(ApiFormat::from_str("claude"), Some(ApiFormat::Anthropic));
|
||||
assert_eq!(ApiFormat::from_str("openai"), Some(ApiFormat::OpenAI));
|
||||
assert_eq!(ApiFormat::from_str("codex"), Some(ApiFormat::OpenAI));
|
||||
assert_eq!(ApiFormat::from_str("gemini"), Some(ApiFormat::Gemini));
|
||||
assert_eq!(ApiFormat::from_str("google"), Some(ApiFormat::Gemini));
|
||||
assert_eq!(ApiFormat::from_str("unknown"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_as_str() {
|
||||
assert_eq!(ApiFormat::Anthropic.as_str(), "anthropic");
|
||||
assert_eq!(ApiFormat::OpenAI.as_str(), "openai");
|
||||
assert_eq!(ApiFormat::Gemini.as_str(), "gemini");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! 通用格式转换模块
|
||||
//!
|
||||
//! 提供 API 格式之间的双向转换,支持:
|
||||
//! - Anthropic ↔ OpenAI
|
||||
//! - Gemini ↔ OpenAI(预留)
|
||||
//!
|
||||
//! ## 使用方式
|
||||
//!
|
||||
//! ```rust,ignore
|
||||
//! use crate::proxy::transform::{config::TransformConfig, registry::get_transformer};
|
||||
//!
|
||||
//! let config = TransformConfig::from_provider(&provider);
|
||||
//! if config.needs_transform() {
|
||||
//! if let Some(transformer) = get_transformer(config.source_format, config.target_format) {
|
||||
//! let transformed = transformer.transform_request(body)?;
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
pub mod anthropic_openai;
|
||||
pub mod config;
|
||||
pub mod format;
|
||||
pub mod registry;
|
||||
pub mod traits;
|
||||
|
||||
// 公开导出
|
||||
pub use config::TransformConfig;
|
||||
pub use registry::get_transformer;
|
||||
|
||||
// 以下导出供外部模块使用(如需扩展转换器)
|
||||
#[allow(unused_imports)]
|
||||
pub use format::ApiFormat;
|
||||
#[allow(unused_imports)]
|
||||
pub use registry::TRANSFORMER_REGISTRY;
|
||||
#[allow(unused_imports)]
|
||||
pub use traits::{BidirectionalTransformer, FormatTransformer};
|
||||
@@ -0,0 +1,95 @@
|
||||
//! 转换器注册表
|
||||
//!
|
||||
//! 管理和获取格式转换器
|
||||
|
||||
use super::{format::ApiFormat, traits::FormatTransformer};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
/// 转换器注册表
|
||||
pub struct TransformerRegistry {
|
||||
transformers: HashMap<(ApiFormat, ApiFormat), Arc<dyn FormatTransformer>>,
|
||||
}
|
||||
|
||||
impl TransformerRegistry {
|
||||
/// 创建新的注册表
|
||||
pub fn new() -> Self {
|
||||
let mut registry = Self {
|
||||
transformers: HashMap::new(),
|
||||
};
|
||||
registry.register_defaults();
|
||||
registry
|
||||
}
|
||||
|
||||
/// 注册默认转换器
|
||||
fn register_defaults(&mut self) {
|
||||
use super::anthropic_openai::{AnthropicToOpenAITransformer, OpenAIToAnthropicTransformer};
|
||||
|
||||
// Anthropic → OpenAI
|
||||
self.register(Arc::new(AnthropicToOpenAITransformer::new()));
|
||||
|
||||
// OpenAI → Anthropic
|
||||
self.register(Arc::new(OpenAIToAnthropicTransformer::new()));
|
||||
}
|
||||
|
||||
/// 注册转换器
|
||||
pub fn register(&mut self, transformer: Arc<dyn FormatTransformer>) {
|
||||
let key = (transformer.source_format(), transformer.target_format());
|
||||
self.transformers.insert(key, transformer);
|
||||
}
|
||||
|
||||
/// 获取转换器
|
||||
pub fn get(&self, source: ApiFormat, target: ApiFormat) -> Option<Arc<dyn FormatTransformer>> {
|
||||
self.transformers.get(&(source, target)).cloned()
|
||||
}
|
||||
|
||||
/// 检查是否支持指定的转换
|
||||
#[cfg(test)]
|
||||
pub fn supports(&self, source: ApiFormat, target: ApiFormat) -> bool {
|
||||
self.transformers.contains_key(&(source, target))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TransformerRegistry {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// 全局转换器注册表
|
||||
pub static TRANSFORMER_REGISTRY: LazyLock<TransformerRegistry> =
|
||||
LazyLock::new(TransformerRegistry::new);
|
||||
|
||||
/// 获取转换器的便捷函数
|
||||
pub fn get_transformer(source: ApiFormat, target: ApiFormat) -> Option<Arc<dyn FormatTransformer>> {
|
||||
TRANSFORMER_REGISTRY.get(source, target)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_registry_has_default_transformers() {
|
||||
let registry = TransformerRegistry::new();
|
||||
|
||||
// Anthropic → OpenAI
|
||||
assert!(registry.supports(ApiFormat::Anthropic, ApiFormat::OpenAI));
|
||||
|
||||
// OpenAI → Anthropic
|
||||
assert!(registry.supports(ApiFormat::OpenAI, ApiFormat::Anthropic));
|
||||
|
||||
// 不支持的转换
|
||||
assert!(!registry.supports(ApiFormat::Gemini, ApiFormat::OpenAI));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_transformer() {
|
||||
let transformer = get_transformer(ApiFormat::Anthropic, ApiFormat::OpenAI);
|
||||
assert!(transformer.is_some());
|
||||
|
||||
let t = transformer.unwrap();
|
||||
assert_eq!(t.source_format(), ApiFormat::Anthropic);
|
||||
assert_eq!(t.target_format(), ApiFormat::OpenAI);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! 格式转换器 Trait 定义
|
||||
//!
|
||||
//! 定义通用的格式转换器接口
|
||||
|
||||
use super::format::ApiFormat;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use bytes::Bytes;
|
||||
use futures::stream::Stream;
|
||||
use serde_json::Value;
|
||||
use std::pin::Pin;
|
||||
|
||||
/// 格式转换器 Trait
|
||||
pub trait FormatTransformer: Send + Sync {
|
||||
/// 转换器名称(用于日志)
|
||||
#[allow(dead_code)]
|
||||
fn name(&self) -> &'static str;
|
||||
|
||||
/// 源格式
|
||||
fn source_format(&self) -> ApiFormat;
|
||||
|
||||
/// 目标格式
|
||||
fn target_format(&self) -> ApiFormat;
|
||||
|
||||
/// 转换请求体
|
||||
fn transform_request(&self, body: Value) -> Result<Value, ProxyError>;
|
||||
|
||||
/// 转换非流式响应体
|
||||
fn transform_response(&self, body: Value) -> Result<Value, ProxyError>;
|
||||
|
||||
/// 转换流式响应
|
||||
fn transform_stream(
|
||||
&self,
|
||||
stream: Pin<Box<dyn Stream<Item = Result<Bytes, reqwest::Error>> + Send>>,
|
||||
) -> Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>;
|
||||
|
||||
/// 获取转换后的端点路径
|
||||
fn transform_endpoint(&self, endpoint: &str) -> String {
|
||||
endpoint.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 双向转换器 Trait(可选实现)
|
||||
#[allow(dead_code)]
|
||||
pub trait BidirectionalTransformer: FormatTransformer {
|
||||
/// 获取反向转换器
|
||||
fn reverse(&self) -> Box<dyn FormatTransformer>;
|
||||
}
|
||||
@@ -195,28 +195,19 @@ pub struct AppProxyConfig {
|
||||
/// 整流器配置
|
||||
///
|
||||
/// 存储在 settings 表中
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RectifierConfig {
|
||||
/// 总开关:是否启用整流器
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 请求整流:启用 thinking 签名整流器
|
||||
///
|
||||
/// 处理错误:Invalid 'signature' in 'thinking' block
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub request_thinking_signature: bool,
|
||||
}
|
||||
|
||||
impl Default for RectifierConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
@@ -270,35 +261,34 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_default_enabled() {
|
||||
// 验证 RectifierConfig::default() 返回全启用状态
|
||||
// 防止回归:#[derive(Default)] 会使 bool 默认为 false
|
||||
fn test_rectifier_config_default_disabled() {
|
||||
// 验证 RectifierConfig::default() 返回全禁用状态
|
||||
let config = RectifierConfig::default();
|
||||
assert!(config.enabled, "整流器总开关默认应为 true");
|
||||
assert!(!config.enabled, "整流器总开关默认应为 false");
|
||||
assert!(
|
||||
config.request_thinking_signature,
|
||||
"thinking 签名整流器默认应为 true"
|
||||
!config.request_thinking_signature,
|
||||
"thinking 签名整流器默认应为 false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_default() {
|
||||
// 验证反序列化缺字段时使用 default_true
|
||||
// 验证反序列化缺字段时使用默认值 false
|
||||
let json = "{}";
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(config.enabled);
|
||||
assert!(config.request_thinking_signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_explicit_false() {
|
||||
// 验证显式设置 false 时正确反序列化
|
||||
let json = r#"{"enabled": false, "requestThinkingSignature": false}"#;
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(!config.enabled);
|
||||
assert!(!config.request_thinking_signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_explicit_true() {
|
||||
// 验证显式设置 true 时正确反序列化
|
||||
let json = r#"{"enabled": true, "requestThinkingSignature": true}"#;
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(config.enabled);
|
||||
assert!(config.request_thinking_signature);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_config_default() {
|
||||
let config = LogConfig::default();
|
||||
|
||||
@@ -36,10 +36,22 @@ impl PromptService {
|
||||
|
||||
state.db.save_prompt(app.as_str(), &prompt)?;
|
||||
|
||||
// 如果是已启用的提示词,同步更新到对应的文件
|
||||
if is_enabled {
|
||||
// 启用提示词:写入内容到文件
|
||||
let target_path = prompt_file_path(&app)?;
|
||||
write_text_file(&target_path, &prompt.content)?;
|
||||
} else {
|
||||
// 禁用提示词:检查是否还有其他已启用的提示词
|
||||
let prompts = state.db.get_prompts(app.as_str())?;
|
||||
let any_enabled = prompts.values().any(|p| p.enabled);
|
||||
|
||||
if !any_enabled {
|
||||
// 所有提示词都已禁用,清空文件
|
||||
let target_path = prompt_file_path(&app)?;
|
||||
if target_path.exists() {
|
||||
write_text_file(&target_path, "")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+158
-14
@@ -21,6 +21,19 @@ use crate::error::format_skill_error;
|
||||
|
||||
// ========== 数据结构 ==========
|
||||
|
||||
/// Skill 同步方式
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SyncMethod {
|
||||
/// 自动选择:优先 symlink,失败时回退到 copy
|
||||
#[default]
|
||||
Auto,
|
||||
/// 符号链接(推荐,节省磁盘空间)
|
||||
Symlink,
|
||||
/// 文件复制(兼容模式)
|
||||
Copy,
|
||||
}
|
||||
|
||||
/// 可发现的技能(来自仓库)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DiscoverableSkill {
|
||||
@@ -239,6 +252,50 @@ impl SkillService {
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| skill.directory.clone());
|
||||
|
||||
// 检查数据库中是否已有同名 directory 的 skill(来自其他仓库)
|
||||
let existing_skills = db.get_all_installed_skills()?;
|
||||
for existing in existing_skills.values() {
|
||||
if existing.directory.eq_ignore_ascii_case(&install_name) {
|
||||
// 检查是否来自同一仓库
|
||||
let same_repo = existing.repo_owner.as_deref() == Some(&skill.repo_owner)
|
||||
&& existing.repo_name.as_deref() == Some(&skill.repo_name);
|
||||
if same_repo {
|
||||
// 同一仓库的同名 skill,返回现有记录(可能需要更新启用状态)
|
||||
let mut updated = existing.clone();
|
||||
updated.apps.set_enabled_for(current_app, true);
|
||||
db.save_skill(&updated)?;
|
||||
Self::sync_to_app_dir(&updated.directory, current_app)?;
|
||||
log::info!(
|
||||
"Skill {} 已存在,更新 {:?} 启用状态",
|
||||
updated.name,
|
||||
current_app
|
||||
);
|
||||
return Ok(updated);
|
||||
} else {
|
||||
// 不同仓库的同名 skill,报错
|
||||
return Err(anyhow!(format_skill_error(
|
||||
"SKILL_DIRECTORY_CONFLICT",
|
||||
&[
|
||||
("directory", &install_name),
|
||||
(
|
||||
"existing_repo",
|
||||
&format!(
|
||||
"{}/{}",
|
||||
existing.repo_owner.as_deref().unwrap_or("unknown"),
|
||||
existing.repo_name.as_deref().unwrap_or("unknown")
|
||||
)
|
||||
),
|
||||
(
|
||||
"new_repo",
|
||||
&format!("{}/{}", skill.repo_owner, skill.repo_name)
|
||||
),
|
||||
],
|
||||
Some("uninstallFirst"),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let dest = ssot_dir.join(&install_name);
|
||||
|
||||
// 如果已存在则跳过下载
|
||||
@@ -305,7 +362,7 @@ impl SkillService {
|
||||
db.save_skill(&installed_skill)?;
|
||||
|
||||
// 同步到当前应用目录
|
||||
Self::copy_to_app(&install_name, current_app)?;
|
||||
Self::sync_to_app_dir(&install_name, current_app)?;
|
||||
|
||||
log::info!(
|
||||
"Skill {} 安装成功,已启用 {:?}",
|
||||
@@ -368,7 +425,7 @@ impl SkillService {
|
||||
|
||||
// 同步文件
|
||||
if enabled {
|
||||
Self::copy_to_app(&skill.directory, app)?;
|
||||
Self::sync_to_app_dir(&skill.directory, app)?;
|
||||
} else {
|
||||
Self::remove_from_app(&skill.directory, app)?;
|
||||
}
|
||||
@@ -566,8 +623,41 @@ impl SkillService {
|
||||
|
||||
// ========== 文件同步方法 ==========
|
||||
|
||||
/// 复制 Skill 到应用目录
|
||||
pub fn copy_to_app(directory: &str, app: &AppType) -> Result<()> {
|
||||
/// 创建符号链接(跨平台)
|
||||
///
|
||||
/// - Unix: 使用 std::os::unix::fs::symlink
|
||||
/// - Windows: 使用 std::os::windows::fs::symlink_dir
|
||||
#[cfg(unix)]
|
||||
fn create_symlink(src: &Path, dest: &Path) -> Result<()> {
|
||||
std::os::unix::fs::symlink(src, dest)
|
||||
.with_context(|| format!("创建符号链接失败: {} -> {}", src.display(), dest.display()))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn create_symlink(src: &Path, dest: &Path) -> Result<()> {
|
||||
std::os::windows::fs::symlink_dir(src, dest)
|
||||
.with_context(|| format!("创建符号链接失败: {} -> {}", src.display(), dest.display()))
|
||||
}
|
||||
|
||||
/// 检查路径是否为符号链接
|
||||
fn is_symlink(path: &Path) -> bool {
|
||||
path.symlink_metadata()
|
||||
.map(|m| m.file_type().is_symlink())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 获取当前同步方式配置
|
||||
fn get_sync_method() -> SyncMethod {
|
||||
crate::settings::get_skill_sync_method()
|
||||
}
|
||||
|
||||
/// 同步 Skill 到应用目录(使用 symlink 或 copy)
|
||||
///
|
||||
/// 根据配置和平台选择最佳同步方式:
|
||||
/// - Auto: 优先尝试 symlink,失败时回退到 copy
|
||||
/// - Symlink: 仅使用 symlink
|
||||
/// - Copy: 仅使用文件复制
|
||||
pub fn sync_to_app_dir(directory: &str, app: &AppType) -> Result<()> {
|
||||
let ssot_dir = Self::get_ssot_dir()?;
|
||||
let source = ssot_dir.join(directory);
|
||||
|
||||
@@ -580,25 +670,77 @@ impl SkillService {
|
||||
|
||||
let dest = app_dir.join(directory);
|
||||
|
||||
// 如果已存在则先删除
|
||||
if dest.exists() {
|
||||
fs::remove_dir_all(&dest)?;
|
||||
// 如果已存在则先删除(无论是 symlink 还是真实目录)
|
||||
if dest.exists() || Self::is_symlink(&dest) {
|
||||
Self::remove_path(&dest)?;
|
||||
}
|
||||
|
||||
Self::copy_dir_recursive(&source, &dest)?;
|
||||
let sync_method = Self::get_sync_method();
|
||||
|
||||
log::debug!("Skill {directory} 已复制到 {app:?}");
|
||||
match sync_method {
|
||||
SyncMethod::Auto => {
|
||||
// 优先尝试 symlink
|
||||
match Self::create_symlink(&source, &dest) {
|
||||
Ok(()) => {
|
||||
log::debug!("Skill {directory} 已通过 symlink 同步到 {app:?}");
|
||||
return Ok(());
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Symlink 创建失败,将回退到文件复制: {} -> {}. 错误: {err:#}",
|
||||
source.display(),
|
||||
dest.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
// Fallback 到 copy
|
||||
Self::copy_dir_recursive(&source, &dest)?;
|
||||
log::debug!("Skill {directory} 已通过复制同步到 {app:?}");
|
||||
}
|
||||
SyncMethod::Symlink => {
|
||||
Self::create_symlink(&source, &dest)?;
|
||||
log::debug!("Skill {directory} 已通过 symlink 同步到 {app:?}");
|
||||
}
|
||||
SyncMethod::Copy => {
|
||||
Self::copy_dir_recursive(&source, &dest)?;
|
||||
log::debug!("Skill {directory} 已通过复制同步到 {app:?}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从应用目录删除 Skill
|
||||
/// 复制 Skill 到应用目录(保留用于向后兼容)
|
||||
#[deprecated(note = "请使用 sync_to_app_dir() 代替")]
|
||||
pub fn copy_to_app(directory: &str, app: &AppType) -> Result<()> {
|
||||
Self::sync_to_app_dir(directory, app)
|
||||
}
|
||||
|
||||
/// 删除路径(支持 symlink 和真实目录)
|
||||
fn remove_path(path: &Path) -> Result<()> {
|
||||
if Self::is_symlink(path) {
|
||||
// 符号链接:仅删除链接本身,不影响源文件
|
||||
#[cfg(unix)]
|
||||
fs::remove_file(path)?;
|
||||
#[cfg(windows)]
|
||||
fs::remove_dir(path)?; // Windows 的目录 symlink 需要用 remove_dir
|
||||
} else if path.is_dir() {
|
||||
// 真实目录:递归删除
|
||||
fs::remove_dir_all(path)?;
|
||||
} else if path.exists() {
|
||||
// 普通文件
|
||||
fs::remove_file(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 从应用目录删除 Skill(支持 symlink 和真实目录)
|
||||
pub fn remove_from_app(directory: &str, app: &AppType) -> Result<()> {
|
||||
let app_dir = Self::get_app_skills_dir(app)?;
|
||||
let skill_path = app_dir.join(directory);
|
||||
|
||||
if skill_path.exists() {
|
||||
fs::remove_dir_all(&skill_path)?;
|
||||
if skill_path.exists() || Self::is_symlink(&skill_path) {
|
||||
Self::remove_path(&skill_path)?;
|
||||
log::debug!("Skill {directory} 已从 {app:?} 删除");
|
||||
}
|
||||
|
||||
@@ -611,7 +753,7 @@ impl SkillService {
|
||||
|
||||
for skill in skills.values() {
|
||||
if skill.apps.is_enabled_for(app) {
|
||||
Self::copy_to_app(&skill.directory, app)?;
|
||||
Self::sync_to_app_dir(&skill.directory, app)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -835,10 +977,12 @@ impl SkillService {
|
||||
Ok(meta)
|
||||
}
|
||||
|
||||
/// 去重技能列表
|
||||
/// 去重技能列表(基于完整 key,不同仓库的同名 skill 分开显示)
|
||||
fn deduplicate_discoverable_skills(skills: &mut Vec<DiscoverableSkill>) {
|
||||
let mut seen = HashMap::new();
|
||||
skills.retain(|skill| {
|
||||
// 使用完整 key(owner/repo:directory)作为唯一标识
|
||||
// 这样不同仓库的同名 skill 会分开显示
|
||||
let unique_key = skill.key.to_lowercase();
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = seen.entry(unique_key) {
|
||||
e.insert(true);
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::{OnceLock, RwLock};
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::services::skill::SyncMethod;
|
||||
|
||||
/// 自定义端点配置(历史兼容,实际存储在 provider.meta.custom_endpoints)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -73,7 +74,7 @@ pub struct AppSettings {
|
||||
#[serde(default)]
|
||||
pub enable_claude_plugin_integration: bool,
|
||||
/// 是否跳过 Claude Code 初次安装确认
|
||||
#[serde(default = "default_true")]
|
||||
#[serde(default)]
|
||||
pub skip_claude_onboarding: bool,
|
||||
/// 是否开机自启
|
||||
#[serde(default)]
|
||||
@@ -108,6 +109,11 @@ pub struct AppSettings {
|
||||
/// 当前 OpenCode 供应商 ID(本地存储,对 OpenCode 可能无意义,但保持结构一致)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub current_provider_opencode: Option<String>,
|
||||
|
||||
// ===== Skill 同步设置 =====
|
||||
/// Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
|
||||
#[serde(default)]
|
||||
pub skill_sync_method: SyncMethod,
|
||||
}
|
||||
|
||||
fn default_show_in_tray() -> bool {
|
||||
@@ -124,7 +130,7 @@ impl Default for AppSettings {
|
||||
show_in_tray: true,
|
||||
minimize_to_tray_on_close: true,
|
||||
enable_claude_plugin_integration: false,
|
||||
skip_claude_onboarding: true,
|
||||
skip_claude_onboarding: false,
|
||||
launch_on_startup: false,
|
||||
language: None,
|
||||
visible_apps: None,
|
||||
@@ -136,6 +142,7 @@ impl Default for AppSettings {
|
||||
current_provider_codex: None,
|
||||
current_provider_gemini: None,
|
||||
current_provider_opencode: None,
|
||||
skill_sync_method: SyncMethod::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -382,3 +389,16 @@ pub fn get_effective_current_provider(
|
||||
// Fallback 到数据库的 is_current
|
||||
db.get_current_provider(app_type.as_str())
|
||||
}
|
||||
|
||||
// ===== Skill 同步方式管理函数 =====
|
||||
|
||||
/// 获取 Skill 同步方式配置
|
||||
pub fn get_skill_sync_method() -> SyncMethod {
|
||||
settings_store()
|
||||
.read()
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("设置锁已毒化,使用恢复值: {e}");
|
||||
e.into_inner()
|
||||
})
|
||||
.skill_sync_method
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.10.0",
|
||||
"version": "3.10.2",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
+8
-9
@@ -696,7 +696,7 @@ function App() {
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="mx-auto flex h-full max-w-[56rem] items-center justify-between gap-2 px-4"
|
||||
className="flex h-full items-center justify-between gap-2 px-6"
|
||||
data-tauri-drag-region
|
||||
style={{ WebkitAppRegion: "drag" } as any}
|
||||
>
|
||||
@@ -750,13 +750,6 @@ function App() {
|
||||
>
|
||||
CC Switch
|
||||
</a>
|
||||
<UpdateBadge
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("about");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
className="absolute -top-4 -right-4"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -770,6 +763,12 @@ function App() {
|
||||
>
|
||||
<Settings className="w-4 h-4" />
|
||||
</Button>
|
||||
<UpdateBadge
|
||||
onClick={() => {
|
||||
setSettingsDefaultTab("about");
|
||||
setCurrentView("settings");
|
||||
}}
|
||||
/>
|
||||
{isCurrentAppTakeoverActive && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -895,7 +894,7 @@ function App() {
|
||||
visibleApps={visibleApps}
|
||||
compact={
|
||||
isCurrentAppTakeoverActive &&
|
||||
Object.values(visibleApps).filter(Boolean).length >= 3
|
||||
Object.values(visibleApps).filter(Boolean).length >= 4
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -39,9 +39,13 @@ export const ProviderIcon: React.FC<ProviderIconProps> = ({
|
||||
};
|
||||
}, [size]);
|
||||
|
||||
// 获取有效颜色:优先使用传入的 color,否则从元数据获取 defaultColor
|
||||
// 获取有效颜色:优先使用传入的有效 color,否则从元数据获取 defaultColor
|
||||
const effectiveColor = useMemo(() => {
|
||||
if (color) return color;
|
||||
// 只有当 color 是有效的非空字符串时才使用
|
||||
if (color && typeof color === "string" && color.trim() !== "") {
|
||||
return color;
|
||||
}
|
||||
// 否则从元数据获取 defaultColor
|
||||
if (icon) {
|
||||
const metadata = getIconMetadata(icon);
|
||||
// 只有当 defaultColor 不是 currentColor 时才使用
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useUpdate } from "@/contexts/UpdateContext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ArrowUpCircle } from "lucide-react";
|
||||
|
||||
interface UpdateBadgeProps {
|
||||
className?: string;
|
||||
@@ -30,17 +31,12 @@ export function UpdateBadge({ className = "", onClick }: UpdateBadgeProps) {
|
||||
aria-label={title}
|
||||
onClick={onClick}
|
||||
className={`
|
||||
relative h-6 w-6 rounded-full
|
||||
${isActive ? "text-blue-600 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-500/10" : "text-muted-foreground hover:bg-muted/60"}
|
||||
relative h-8 w-8 rounded-full
|
||||
${isActive ? "text-green-600 dark:text-green-400 hover:bg-green-50 dark:hover:bg-green-500/10" : "text-muted-foreground hover:bg-muted/60"}
|
||||
${className}
|
||||
`}
|
||||
>
|
||||
<span
|
||||
className={`
|
||||
absolute inset-0 m-auto h-2 w-2 rounded-full ring-1 ring-background
|
||||
${isActive ? "bg-blue-500 dark:bg-blue-400" : "bg-blue-300/70 dark:bg-blue-300/60"}
|
||||
`}
|
||||
/>
|
||||
<ArrowUpCircle className="h-5 w-5" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ interface AgentsPanelProps {
|
||||
|
||||
export function AgentsPanel({}: AgentsPanelProps) {
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl flex flex-col h-[calc(100vh-8rem)]">
|
||||
<div className="px-6 flex flex-col h-[calc(100vh-8rem)]">
|
||||
<div className="flex-1 glass-card rounded-xl p-8 flex flex-col items-center justify-center text-center space-y-4">
|
||||
<div className="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4 animate-pulse-slow">
|
||||
<Bot className="w-10 h-10 text-muted-foreground" />
|
||||
|
||||
@@ -8,19 +8,33 @@ import {
|
||||
Eye,
|
||||
EyeOff,
|
||||
X,
|
||||
ArrowLeftRight,
|
||||
} from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ProviderTestConfig, ProviderProxyConfig } from "@/types";
|
||||
import type {
|
||||
ProviderTestConfig,
|
||||
ProviderProxyConfig,
|
||||
FormatTransformConfig,
|
||||
} from "@/types";
|
||||
|
||||
interface ProviderAdvancedConfigProps {
|
||||
testConfig: ProviderTestConfig;
|
||||
proxyConfig: ProviderProxyConfig;
|
||||
formatTransform?: FormatTransformConfig;
|
||||
onTestConfigChange: (config: ProviderTestConfig) => void;
|
||||
onProxyConfigChange: (config: ProviderProxyConfig) => void;
|
||||
onFormatTransformChange?: (config: FormatTransformConfig) => void;
|
||||
}
|
||||
|
||||
/** 从 ProviderProxyConfig 构建完整 URL */
|
||||
@@ -71,14 +85,19 @@ function parseProxyUrl(url: string): Partial<ProviderProxyConfig> {
|
||||
export function ProviderAdvancedConfig({
|
||||
testConfig,
|
||||
proxyConfig,
|
||||
formatTransform,
|
||||
onTestConfigChange,
|
||||
onProxyConfigChange,
|
||||
onFormatTransformChange,
|
||||
}: ProviderAdvancedConfigProps) {
|
||||
const { t } = useTranslation();
|
||||
const [isTestConfigOpen, setIsTestConfigOpen] = useState(testConfig.enabled);
|
||||
const [isProxyConfigOpen, setIsProxyConfigOpen] = useState(
|
||||
proxyConfig.enabled,
|
||||
);
|
||||
const [isFormatTransformOpen, setIsFormatTransformOpen] = useState(
|
||||
formatTransform?.enabled ?? false,
|
||||
);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
|
||||
// 代理 URL 输入状态(仅在初始化时从 proxyConfig 构建)
|
||||
@@ -97,6 +116,11 @@ export function ProviderAdvancedConfig({
|
||||
setIsProxyConfigOpen(proxyConfig.enabled);
|
||||
}, [proxyConfig.enabled]);
|
||||
|
||||
// 同步外部 formatTransform.enabled 变化到展开状态
|
||||
useEffect(() => {
|
||||
setIsFormatTransformOpen(formatTransform?.enabled ?? false);
|
||||
}, [formatTransform?.enabled]);
|
||||
|
||||
// 仅在外部 proxyConfig 变化且非用户输入时同步(如:重置表单、加载数据)
|
||||
useEffect(() => {
|
||||
if (!isUserTyping) {
|
||||
@@ -450,6 +474,135 @@ export function ProviderAdvancedConfig({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 格式转换配置 */}
|
||||
{onFormatTransformChange && (
|
||||
<div className="rounded-lg border border-border/50 bg-muted/20">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full items-center justify-between p-4 hover:bg-muted/30 transition-colors"
|
||||
onClick={() => setIsFormatTransformOpen(!isFormatTransformOpen)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<ArrowLeftRight className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">
|
||||
{t("providerAdvanced.formatTransform")}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="flex items-center gap-2"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<Label
|
||||
htmlFor="format-transform-enabled"
|
||||
className="text-sm text-muted-foreground"
|
||||
>
|
||||
{t("providerAdvanced.enableFormatTransform")}
|
||||
</Label>
|
||||
<Switch
|
||||
id="format-transform-enabled"
|
||||
checked={formatTransform?.enabled ?? false}
|
||||
onCheckedChange={(checked) => {
|
||||
onFormatTransformChange({
|
||||
...(formatTransform ?? { enabled: false }),
|
||||
enabled: checked,
|
||||
});
|
||||
if (checked) setIsFormatTransformOpen(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{isFormatTransformOpen ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</button>
|
||||
<div
|
||||
className={cn(
|
||||
"overflow-hidden transition-all duration-200",
|
||||
isFormatTransformOpen
|
||||
? "max-h-[500px] opacity-100"
|
||||
: "max-h-0 opacity-0",
|
||||
)}
|
||||
>
|
||||
<div className="border-t border-border/50 p-4 space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("providerAdvanced.formatTransformDesc")}
|
||||
</p>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="source-format">
|
||||
{t("providerAdvanced.sourceFormat")}
|
||||
</Label>
|
||||
<Select
|
||||
value={formatTransform?.sourceFormat ?? "anthropic"}
|
||||
onValueChange={(value) =>
|
||||
onFormatTransformChange({
|
||||
...(formatTransform ?? { enabled: false }),
|
||||
sourceFormat: value as "anthropic" | "openai",
|
||||
})
|
||||
}
|
||||
disabled={!formatTransform?.enabled}
|
||||
>
|
||||
<SelectTrigger id="source-format">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="anthropic">
|
||||
Anthropic (Claude)
|
||||
</SelectItem>
|
||||
<SelectItem value="openai">OpenAI</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="target-format">
|
||||
{t("providerAdvanced.targetFormat")}
|
||||
</Label>
|
||||
<Select
|
||||
value={formatTransform?.targetFormat ?? "openai"}
|
||||
onValueChange={(value) =>
|
||||
onFormatTransformChange({
|
||||
...(formatTransform ?? { enabled: false }),
|
||||
targetFormat: value as "anthropic" | "openai",
|
||||
})
|
||||
}
|
||||
disabled={!formatTransform?.enabled}
|
||||
>
|
||||
<SelectTrigger id="target-format">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="anthropic">
|
||||
Anthropic (Claude)
|
||||
</SelectItem>
|
||||
<SelectItem value="openai">OpenAI</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Switch
|
||||
id="transform-streaming"
|
||||
checked={formatTransform?.transformStreaming ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
onFormatTransformChange({
|
||||
...(formatTransform ?? { enabled: false }),
|
||||
transformStreaming: checked,
|
||||
})
|
||||
}
|
||||
disabled={!formatTransform?.enabled}
|
||||
/>
|
||||
<Label htmlFor="transform-streaming" className="text-sm">
|
||||
{t("providerAdvanced.transformStreaming")}
|
||||
</Label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
ProviderMeta,
|
||||
ProviderTestConfig,
|
||||
ProviderProxyConfig,
|
||||
FormatTransformConfig,
|
||||
} from "@/types";
|
||||
import {
|
||||
providerPresets,
|
||||
@@ -168,6 +169,9 @@ export function ProviderForm({
|
||||
const [proxyConfig, setProxyConfig] = useState<ProviderProxyConfig>(
|
||||
() => initialData?.meta?.proxyConfig ?? { enabled: false },
|
||||
);
|
||||
const [formatTransform, setFormatTransform] = useState<FormatTransformConfig>(
|
||||
() => initialData?.meta?.formatTransform ?? { enabled: false },
|
||||
);
|
||||
|
||||
// 使用 category hook
|
||||
const { category } = useProviderCategory({
|
||||
@@ -940,6 +944,7 @@ export function ProviderForm({
|
||||
// 添加高级配置
|
||||
testConfig: testConfig.enabled ? testConfig : undefined,
|
||||
proxyConfig: proxyConfig.enabled ? proxyConfig : undefined,
|
||||
formatTransform: formatTransform.enabled ? formatTransform : undefined,
|
||||
};
|
||||
|
||||
onSubmit(payload);
|
||||
@@ -1464,8 +1469,10 @@ export function ProviderForm({
|
||||
<ProviderAdvancedConfig
|
||||
testConfig={testConfig}
|
||||
proxyConfig={proxyConfig}
|
||||
formatTransform={formatTransform}
|
||||
onTestConfigChange={setTestConfig}
|
||||
onProxyConfigChange={setProxyConfig}
|
||||
onFormatTransformChange={setFormatTransform}
|
||||
/>
|
||||
|
||||
{showButtons && (
|
||||
|
||||
@@ -5,6 +5,42 @@ interface UseModelStateProps {
|
||||
onConfigChange: (config: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse model values from settings config JSON
|
||||
*/
|
||||
function parseModelsFromConfig(settingsConfig: string) {
|
||||
try {
|
||||
const cfg = settingsConfig ? JSON.parse(settingsConfig) : {};
|
||||
const env = cfg?.env || {};
|
||||
const model =
|
||||
typeof env.ANTHROPIC_MODEL === "string" ? env.ANTHROPIC_MODEL : "";
|
||||
const reasoning =
|
||||
typeof env.ANTHROPIC_REASONING_MODEL === "string"
|
||||
? env.ANTHROPIC_REASONING_MODEL
|
||||
: "";
|
||||
const small =
|
||||
typeof env.ANTHROPIC_SMALL_FAST_MODEL === "string"
|
||||
? env.ANTHROPIC_SMALL_FAST_MODEL
|
||||
: "";
|
||||
const haiku =
|
||||
typeof env.ANTHROPIC_DEFAULT_HAIKU_MODEL === "string"
|
||||
? env.ANTHROPIC_DEFAULT_HAIKU_MODEL
|
||||
: small || model;
|
||||
const sonnet =
|
||||
typeof env.ANTHROPIC_DEFAULT_SONNET_MODEL === "string"
|
||||
? env.ANTHROPIC_DEFAULT_SONNET_MODEL
|
||||
: model || small;
|
||||
const opus =
|
||||
typeof env.ANTHROPIC_DEFAULT_OPUS_MODEL === "string"
|
||||
? env.ANTHROPIC_DEFAULT_OPUS_MODEL
|
||||
: model || small;
|
||||
|
||||
return { model, reasoning, haiku, sonnet, opus };
|
||||
} catch {
|
||||
return { model: "", reasoning: "", haiku: "", sonnet: "", opus: "" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理模型选择状态
|
||||
* 支持 ANTHROPIC_MODEL, ANTHROPIC_REASONING_MODEL 和各类型默认模型
|
||||
@@ -13,11 +49,22 @@ export function useModelState({
|
||||
settingsConfig,
|
||||
onConfigChange,
|
||||
}: UseModelStateProps) {
|
||||
const [claudeModel, setClaudeModel] = useState("");
|
||||
const [reasoningModel, setReasoningModel] = useState("");
|
||||
const [defaultHaikuModel, setDefaultHaikuModel] = useState("");
|
||||
const [defaultSonnetModel, setDefaultSonnetModel] = useState("");
|
||||
const [defaultOpusModel, setDefaultOpusModel] = useState("");
|
||||
// Initialize state by parsing config directly (fixes edit mode backfill)
|
||||
const [claudeModel, setClaudeModel] = useState(
|
||||
() => parseModelsFromConfig(settingsConfig).model,
|
||||
);
|
||||
const [reasoningModel, setReasoningModel] = useState(
|
||||
() => parseModelsFromConfig(settingsConfig).reasoning,
|
||||
);
|
||||
const [defaultHaikuModel, setDefaultHaikuModel] = useState(
|
||||
() => parseModelsFromConfig(settingsConfig).haiku,
|
||||
);
|
||||
const [defaultSonnetModel, setDefaultSonnetModel] = useState(
|
||||
() => parseModelsFromConfig(settingsConfig).sonnet,
|
||||
);
|
||||
const [defaultOpusModel, setDefaultOpusModel] = useState(
|
||||
() => parseModelsFromConfig(settingsConfig).opus,
|
||||
);
|
||||
|
||||
const isUserEditingRef = useRef(false);
|
||||
const lastConfigRef = useRef(settingsConfig);
|
||||
|
||||
@@ -35,6 +35,7 @@ import { LanguageSettings } from "@/components/settings/LanguageSettings";
|
||||
import { ThemeSettings } from "@/components/settings/ThemeSettings";
|
||||
import { WindowSettings } from "@/components/settings/WindowSettings";
|
||||
import { AppVisibilitySettings } from "@/components/settings/AppVisibilitySettings";
|
||||
import { SkillSyncMethodSettings } from "@/components/settings/SkillSyncMethodSettings";
|
||||
import { DirectorySettings } from "@/components/settings/DirectorySettings";
|
||||
import { ImportExportSection } from "@/components/settings/ImportExportSection";
|
||||
import { AboutSection } from "@/components/settings/AboutSection";
|
||||
@@ -249,6 +250,12 @@ export function SettingsPage({
|
||||
settings={settings}
|
||||
onChange={handleAutoSave}
|
||||
/>
|
||||
<SkillSyncMethodSettings
|
||||
value={settings.skillSyncMethod ?? "auto"}
|
||||
onChange={(method) =>
|
||||
handleAutoSave({ skillSyncMethod: method })
|
||||
}
|
||||
/>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</TabsContent>
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { SkillSyncMethod } from "@/types";
|
||||
|
||||
export interface SkillSyncMethodSettingsProps {
|
||||
value: SkillSyncMethod;
|
||||
onChange: (value: SkillSyncMethod) => void;
|
||||
}
|
||||
|
||||
export function SkillSyncMethodSettings({
|
||||
value,
|
||||
onChange,
|
||||
}: SkillSyncMethodSettingsProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Handle default values: undefined or "auto" defaults to symlink display
|
||||
const displayValue = value === "copy" ? "copy" : "symlink";
|
||||
|
||||
return (
|
||||
<section className="space-y-2">
|
||||
<header className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{t("settings.skillSync.title")}</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.skillSync.description")}
|
||||
</p>
|
||||
</header>
|
||||
<div className="inline-flex gap-1 rounded-md border border-border-default bg-background p-1">
|
||||
<SyncMethodButton
|
||||
active={displayValue === "symlink"}
|
||||
onClick={() => onChange("symlink")}
|
||||
>
|
||||
{t("settings.skillSync.symlink")}
|
||||
</SyncMethodButton>
|
||||
<SyncMethodButton
|
||||
active={displayValue === "copy"}
|
||||
onClick={() => onChange("copy")}
|
||||
>
|
||||
{t("settings.skillSync.copy")}
|
||||
</SyncMethodButton>
|
||||
</div>
|
||||
{displayValue === "symlink" && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("settings.skillSync.symlinkHint")}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
interface SyncMethodButtonProps {
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
function SyncMethodButton({
|
||||
active,
|
||||
onClick,
|
||||
children,
|
||||
}: SyncMethodButtonProps) {
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
size="sm"
|
||||
variant={active ? "default" : "ghost"}
|
||||
className={cn(
|
||||
"min-w-[96px]",
|
||||
active
|
||||
? "shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-muted",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -27,16 +27,6 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
onCheckedChange={(value) => onChange({ launchOnStartup: value })}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
icon={<AppWindow className="h-4 w-4 text-blue-500" />}
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ minimizeToTrayOnClose: value })
|
||||
}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
icon={<MonitorUp className="h-4 w-4 text-purple-500" />}
|
||||
title={t("settings.enableClaudePluginIntegration")}
|
||||
@@ -54,6 +44,16 @@ export function WindowSettings({ settings, onChange }: WindowSettingsProps) {
|
||||
checked={!!settings.skipClaudeOnboarding}
|
||||
onCheckedChange={(value) => onChange({ skipClaudeOnboarding: value })}
|
||||
/>
|
||||
|
||||
<ToggleRow
|
||||
icon={<AppWindow className="h-4 w-4 text-blue-500" />}
|
||||
title={t("settings.minimizeToTray")}
|
||||
description={t("settings.minimizeToTrayDescription")}
|
||||
checked={settings.minimizeToTrayOnClose}
|
||||
onCheckedChange={(value) =>
|
||||
onChange({ minimizeToTrayOnClose: value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -65,10 +65,17 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
const addRepoMutation = useAddSkillRepo();
|
||||
const removeRepoMutation = useRemoveSkillRepo();
|
||||
|
||||
// 已安装的 directory 集合
|
||||
const installedDirs = useMemo(() => {
|
||||
// 已安装的 skill key 集合(使用 directory + repoOwner + repoName 组合判断)
|
||||
const installedKeys = useMemo(() => {
|
||||
if (!installedSkills) return new Set<string>();
|
||||
return new Set(installedSkills.map((s) => s.directory.toLowerCase()));
|
||||
return new Set(
|
||||
installedSkills.map((s) => {
|
||||
// 构建唯一 key:directory + repoOwner + repoName
|
||||
const owner = s.repoOwner?.toLowerCase() || "";
|
||||
const name = s.repoName?.toLowerCase() || "";
|
||||
return `${s.directory.toLowerCase()}:${owner}:${name}`;
|
||||
}),
|
||||
);
|
||||
}, [installedSkills]);
|
||||
|
||||
type DiscoverableSkillItem = DiscoverableSkill & { installed: boolean };
|
||||
@@ -80,12 +87,14 @@ export const SkillsPage = forwardRef<SkillsPageHandle, SkillsPageProps>(
|
||||
const installName =
|
||||
d.directory.split("/").pop()?.toLowerCase() ||
|
||||
d.directory.toLowerCase();
|
||||
// 使用 directory + repoOwner + repoName 组合判断是否已安装
|
||||
const key = `${installName}:${d.repoOwner.toLowerCase()}:${d.repoName.toLowerCase()}`;
|
||||
return {
|
||||
...d,
|
||||
installed: installedDirs.has(installName),
|
||||
installed: installedKeys.has(key),
|
||||
};
|
||||
});
|
||||
}, [discoverableSkills, installedDirs]);
|
||||
}, [discoverableSkills, installedKeys]);
|
||||
|
||||
const loading = loadingDiscoverable || fetchingDiscoverable;
|
||||
|
||||
|
||||
@@ -452,14 +452,18 @@ export const providerPresets: ProviderPreset[] = [
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=CCSWITCH",
|
||||
settingsConfig: {
|
||||
env: {
|
||||
ANTHROPIC_BASE_URL: "https://www.right.codes/claude",
|
||||
ANTHROPIC_AUTH_TOKEN: "",
|
||||
},
|
||||
},
|
||||
category: "third_party"
|
||||
category: "third_party",
|
||||
isPartner: true,
|
||||
partnerPromotionKey: "rightcode",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
},
|
||||
{
|
||||
name: "OpenRouter",
|
||||
|
||||
@@ -195,7 +195,7 @@ requires_openai_auth = true`,
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=CCSWITCH",
|
||||
auth: generateThirdPartyAuth(""),
|
||||
config: generateThirdPartyConfig(
|
||||
"rightcode",
|
||||
@@ -203,6 +203,8 @@ requires_openai_auth = true`,
|
||||
"gpt-5.2",
|
||||
),
|
||||
category: "third_party",
|
||||
isPartner: true,
|
||||
partnerPromotionKey: "rightcode",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
},
|
||||
|
||||
@@ -649,7 +649,7 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
|
||||
{
|
||||
name: "RightCode",
|
||||
websiteUrl: "https://www.right.codes",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=0bdf9bfa",
|
||||
apiKeyUrl: "https://www.right.codes/register?aff=CCSWITCH",
|
||||
settingsConfig: {
|
||||
npm: "@ai-sdk/openai",
|
||||
name: "RightCode",
|
||||
@@ -663,6 +663,8 @@ export const opencodeProviderPresets: OpenCodeProviderPreset[] = [
|
||||
},
|
||||
},
|
||||
category: "third_party",
|
||||
isPartner: true,
|
||||
partnerPromotionKey: "rightcode",
|
||||
icon: "rc",
|
||||
iconColor: "#E96B2C",
|
||||
templateValues: {
|
||||
|
||||
@@ -83,7 +83,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
minimizeToTrayOnClose: data.minimizeToTrayOnClose ?? true,
|
||||
enableClaudePluginIntegration:
|
||||
data.enableClaudePluginIntegration ?? false,
|
||||
skipClaudeOnboarding: data.skipClaudeOnboarding ?? true,
|
||||
skipClaudeOnboarding: data.skipClaudeOnboarding ?? false,
|
||||
claudeConfigDir: sanitizeDir(data.claudeConfigDir),
|
||||
codexConfigDir: sanitizeDir(data.codexConfigDir),
|
||||
language: normalizedLanguage,
|
||||
@@ -103,7 +103,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
showInTray: true,
|
||||
minimizeToTrayOnClose: true,
|
||||
enableClaudePluginIntegration: false,
|
||||
skipClaudeOnboarding: true,
|
||||
skipClaudeOnboarding: false,
|
||||
language: readPersistedLanguage(),
|
||||
} as SettingsFormState);
|
||||
|
||||
@@ -138,7 +138,7 @@ export function useSettingsForm(): UseSettingsFormResult {
|
||||
minimizeToTrayOnClose: serverData.minimizeToTrayOnClose ?? true,
|
||||
enableClaudePluginIntegration:
|
||||
serverData.enableClaudePluginIntegration ?? false,
|
||||
skipClaudeOnboarding: serverData.skipClaudeOnboarding ?? true,
|
||||
skipClaudeOnboarding: serverData.skipClaudeOnboarding ?? false,
|
||||
claudeConfigDir: sanitizeDir(serverData.claudeConfigDir),
|
||||
codexConfigDir: sanitizeDir(serverData.codexConfigDir),
|
||||
language: normalizedLanguage,
|
||||
|
||||
@@ -280,6 +280,13 @@
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"skillSync": {
|
||||
"title": "Skill Sync Method",
|
||||
"description": "Choose how to sync Skills files",
|
||||
"symlink": "Symlink",
|
||||
"copy": "Copy Files",
|
||||
"symlinkHint": "Symlinks save disk space and enable real-time sync. Note: May require admin privileges or Developer Mode on Windows"
|
||||
},
|
||||
"configDirectoryOverride": "Configuration Directory Override (Advanced)",
|
||||
"configDirectoryDescription": "When using Claude Code or Codex in environments like WSL, you can manually specify the configuration directory to the one in WSL to keep provider data consistent with the main environment.",
|
||||
"appConfigDir": "CC Switch Configuration Directory",
|
||||
@@ -393,7 +400,8 @@
|
||||
"minimax_en": "MiniMax Coding Plan Black Friday, Starter is now $2/mo (80% OFF!)",
|
||||
"dmxapi": "Claude Code exclusive model 66% OFF now!",
|
||||
"cubence": "Cubence is an official partner of CC Switch. Register using this link and enter \"CCSWITCH\" promo code during recharge to get 10% off every top-up",
|
||||
"aigocode": "AIGoCode is an official partner of CC Switch. Register using this link and get 10% bonus credit on your first top-up!"
|
||||
"aigocode": "AIGoCode is an official partner of CC Switch. Register using this link and get 10% bonus credit on your first top-up!",
|
||||
"rightcode": "RightCode is an official partner of CC Switch. Register using this link and get 5% bonus credit on every top-up!"
|
||||
},
|
||||
"parameterConfig": "Parameter Config - {{name}} *",
|
||||
"mainModel": "Main Model (optional)",
|
||||
@@ -472,7 +480,13 @@
|
||||
"useCustomProxy": "Use separate proxy",
|
||||
"proxyConfigDesc": "Configure separate network proxy for this provider. Uses system proxy or global settings when disabled.",
|
||||
"proxyUsername": "Username (optional)",
|
||||
"proxyPassword": "Password (optional)"
|
||||
"proxyPassword": "Password (optional)",
|
||||
"formatTransform": "Format Transform",
|
||||
"enableFormatTransform": "Enable Transform",
|
||||
"formatTransformDesc": "Transform requests and responses between different API formats. Useful for providers using OpenAI-compatible interfaces.",
|
||||
"sourceFormat": "Source Format (Client)",
|
||||
"targetFormat": "Target Format (Upstream)",
|
||||
"transformStreaming": "Transform Streaming Responses"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
@@ -964,6 +978,7 @@
|
||||
"downloadTimeoutHint": "Please check network connection or retry later",
|
||||
"skillPathNotFound": "Skill path '{{path}}' not found in repository {{owner}}/{{name}}",
|
||||
"skillDirNotFound": "Skill directory not found: {{path}}",
|
||||
"directoryConflict": "Skill directory '{{directory}}' is already occupied by {{existing_repo}}, cannot install from {{new_repo}}",
|
||||
"emptyArchive": "Downloaded archive is empty",
|
||||
"downloadFailed": "Download failed: HTTP {{status}}",
|
||||
"allBranchesFailed": "All branches failed, tried: {{branches}}",
|
||||
@@ -982,7 +997,8 @@
|
||||
"retryLater": "Please retry later",
|
||||
"checkRepoUrl": "Please check repository URL and branch name",
|
||||
"checkDiskSpace": "Please check disk space",
|
||||
"checkPermission": "Please check directory permissions"
|
||||
"checkPermission": "Please check directory permissions",
|
||||
"uninstallFirst": "Please uninstall the existing skill with the same name first"
|
||||
}
|
||||
},
|
||||
"repo": {
|
||||
|
||||
@@ -280,6 +280,13 @@
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"skillSync": {
|
||||
"title": "スキル同期方式",
|
||||
"description": "スキルファイルの同期方法を選択",
|
||||
"symlink": "シンボリックリンク",
|
||||
"copy": "ファイルコピー",
|
||||
"symlinkHint": "シンボリックリンクはディスク容量を節約し、リアルタイム同期を有効にします。注意:Windowsでは管理者権限または開発者モードが必要な場合があります"
|
||||
},
|
||||
"configDirectoryOverride": "設定ディレクトリの上書き(詳細)",
|
||||
"configDirectoryDescription": "WSL などで Claude Code や Codex を使う場合、ここで設定ディレクトリを WSL 側に合わせるとデータを揃えられます。",
|
||||
"appConfigDir": "CC Switch 設定ディレクトリ",
|
||||
@@ -393,7 +400,8 @@
|
||||
"minimax_en": "MiniMax Coding Plan Black Friday、Starter が月額 $2(80% OFF)",
|
||||
"dmxapi": "Claude Code 専用モデル 66% OFF 実施中!",
|
||||
"cubence": "Cubence は CC Switch の公式パートナーです。登録後チャージ時に \"CCSWITCH\" を入力すると、毎回 10% オフ",
|
||||
"aigocode": "AIGoCode は CC Switch の公式パートナーです。このリンクから登録すると、初回チャージ時に 10% のボーナスクレジットがもらえます!"
|
||||
"aigocode": "AIGoCode は CC Switch の公式パートナーです。このリンクから登録すると、初回チャージ時に 10% のボーナスクレジットがもらえます!",
|
||||
"rightcode": "RightCode は CC Switch の公式パートナーです。このリンクから登録すると、毎回のチャージに 5% のボーナスクレジットがもらえます!"
|
||||
},
|
||||
"parameterConfig": "パラメーター設定 - {{name}} *",
|
||||
"mainModel": "メインモデル(任意)",
|
||||
@@ -472,7 +480,13 @@
|
||||
"useCustomProxy": "個別プロキシを使用",
|
||||
"proxyConfigDesc": "このプロバイダーに個別のネットワークプロキシを設定します。無効の場合はシステムプロキシまたはグローバル設定を使用します。",
|
||||
"proxyUsername": "ユーザー名(任意)",
|
||||
"proxyPassword": "パスワード(任意)"
|
||||
"proxyPassword": "パスワード(任意)",
|
||||
"formatTransform": "フォーマット変換",
|
||||
"enableFormatTransform": "変換を有効化",
|
||||
"formatTransformDesc": "リクエストとレスポンスを異なる API フォーマット間で変換します。OpenAI 互換インターフェースを使用するプロバイダーに適しています。",
|
||||
"sourceFormat": "ソースフォーマット(クライアント)",
|
||||
"targetFormat": "ターゲットフォーマット(上流)",
|
||||
"transformStreaming": "ストリーミングレスポンスを変換"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
@@ -964,6 +978,7 @@
|
||||
"downloadTimeoutHint": "ネットワークを確認するか、時間をおいて再試行してください",
|
||||
"skillPathNotFound": "リポジトリ {{owner}}/{{name}} にスキルパス '{{path}}' がありません",
|
||||
"skillDirNotFound": "スキルディレクトリが見つかりません: {{path}}",
|
||||
"directoryConflict": "スキルディレクトリ '{{directory}}' は既に {{existing_repo}} で使用されています。{{new_repo}} からインストールできません",
|
||||
"emptyArchive": "ダウンロードしたアーカイブが空です",
|
||||
"downloadFailed": "ダウンロードに失敗しました: HTTP {{status}}",
|
||||
"allBranchesFailed": "すべてのブランチで失敗しました。試行: {{branches}}",
|
||||
@@ -982,7 +997,8 @@
|
||||
"retryLater": "時間をおいて再試行してください",
|
||||
"checkRepoUrl": "リポジトリ URL とブランチ名を確認してください",
|
||||
"checkDiskSpace": "ディスク容量を確認してください",
|
||||
"checkPermission": "ディレクトリの権限を確認してください"
|
||||
"checkPermission": "ディレクトリの権限を確認してください",
|
||||
"uninstallFirst": "同名のスキルを先にアンインストールしてください"
|
||||
}
|
||||
},
|
||||
"repo": {
|
||||
|
||||
@@ -280,6 +280,13 @@
|
||||
"geminiDesc": "Google Gemini CLI",
|
||||
"opencodeDesc": "OpenCode CLI"
|
||||
},
|
||||
"skillSync": {
|
||||
"title": "Skill 同步方式",
|
||||
"description": "选择 Skills 的文件同步策略",
|
||||
"symlink": "软连接",
|
||||
"copy": "文件复制",
|
||||
"symlinkHint": "软连接节省磁盘空间并支持实时同步。注意:Windows 可能需要管理员权限或开启开发者模式"
|
||||
},
|
||||
"configDirectoryOverride": "配置目录覆盖(高级)",
|
||||
"configDirectoryDescription": "在 WSL 等环境使用 Claude Code 或 Codex 的时候,可手动指定为 WSL 里的配置目录,供应商数据与主环境保持一致。",
|
||||
"appConfigDir": "CC Switch 配置目录",
|
||||
@@ -393,7 +400,8 @@
|
||||
"minimax_en": "MiniMax Coding Plan 黑五特惠,Starter 套餐现仅 $2/月(2折优惠!)",
|
||||
"dmxapi": "Claude Code 专属模型 3.4 折优惠进行中!",
|
||||
"cubence": "Cubence 是 CC Switch 的官方合作伙伴,使用此链接注册并在充值时填写 \"CCSWITCH\" 优惠码,每次充值均可享受9折优惠",
|
||||
"aigocode": "AIGoCode 是 CC Switch 的官方合作伙伴,使用此链接注册首次充值时可以获得10%额度奖励!"
|
||||
"aigocode": "AIGoCode 是 CC Switch 的官方合作伙伴,使用此链接注册首次充值时可以获得10%额度奖励!",
|
||||
"rightcode": "RightCode 是 CC Switch 的官方合作伙伴,使用此链接注册每次充值均可赠送5%额外额度!"
|
||||
},
|
||||
"parameterConfig": "参数配置 - {{name}} *",
|
||||
"mainModel": "主模型 (可选)",
|
||||
@@ -472,7 +480,13 @@
|
||||
"useCustomProxy": "使用单独代理",
|
||||
"proxyConfigDesc": "为此供应商配置单独的网络代理,不启用时使用系统代理或全局设置。",
|
||||
"proxyUsername": "用户名(可选)",
|
||||
"proxyPassword": "密码(可选)"
|
||||
"proxyPassword": "密码(可选)",
|
||||
"formatTransform": "格式转换",
|
||||
"enableFormatTransform": "启用转换",
|
||||
"formatTransformDesc": "将请求和响应在不同 API 格式之间转换。适用于使用 OpenAI 兼容接口的供应商。",
|
||||
"sourceFormat": "源格式(客户端)",
|
||||
"targetFormat": "目标格式(上游)",
|
||||
"transformStreaming": "转换流式响应"
|
||||
},
|
||||
"codexConfig": {
|
||||
"authJson": "auth.json (JSON) *",
|
||||
@@ -964,6 +978,7 @@
|
||||
"downloadTimeoutHint": "请检查网络连接或稍后重试",
|
||||
"skillPathNotFound": "仓库 {{owner}}/{{name}} 中未找到技能路径 '{{path}}'",
|
||||
"skillDirNotFound": "技能目录不存在:{{path}}",
|
||||
"directoryConflict": "技能目录 '{{directory}}' 已被 {{existing_repo}} 占用,无法从 {{new_repo}} 安装",
|
||||
"emptyArchive": "下载的压缩包为空",
|
||||
"downloadFailed": "下载失败:HTTP {{status}}",
|
||||
"allBranchesFailed": "所有分支下载失败,尝试了:{{branches}}",
|
||||
@@ -982,7 +997,8 @@
|
||||
"retryLater": "请稍后重试",
|
||||
"checkRepoUrl": "请检查仓库地址和分支名称",
|
||||
"checkDiskSpace": "请检查磁盘空间",
|
||||
"checkPermission": "请检查目录权限"
|
||||
"checkPermission": "请检查目录权限",
|
||||
"uninstallFirst": "请先卸载已安装的同名技能"
|
||||
}
|
||||
},
|
||||
"repo": {
|
||||
|
||||
@@ -50,7 +50,7 @@ export const icons: Record<string, string> = {
|
||||
zeroone: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>01.AI</title><path d="M5.246 12c0 .837-.086 1.554-.257 2.151-.172.598-.45 1.055-.837 1.373-.386.317-.898.476-1.534.476-.901 0-1.563-.353-1.985-1.059C.211 14.235 0 13.255 0 12c0-.837.086-1.554.257-2.151.172-.598.45-1.055.832-1.373C1.472 8.16 1.981 8 2.618 8c.894 0 1.555.351 1.985 1.053.429.702.643 1.685.643 2.947zm-3.883 0c0 .956.09 1.668.273 2.134.183.467.51.7.982.7.465 0 .792-.23.981-.694.19-.463.285-1.176.285-2.14 0-.956-.095-1.668-.285-2.134-.19-.467-.516-.7-.981-.7-.472 0-.8.233-.982.7-.182.466-.273 1.178-.273 2.134zm8.52 3.771H8.517l.011-6.295-1.823.324V8.571l2.04-.457h1.136v7.657zm2.497-1.6h.543c.3 0 .543.256.543.572v.571a.558.558 0 01-.543.572h-.543a.558.558 0 01-.543-.572v-.571c0-.316.243-.572.543-.572zm10.317-6.057H24v7.772h-1.303V8.114zm-3.692 0l2.606 7.772h-1.303l-.69-2.058h-3.073l-.69 2.058h-1.303l2.606-7.772h1.847zm.191 4.457l-1.115-3.323-1.114 3.323h2.23z"></path></svg>`,
|
||||
zhipu: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Zhipu</title><path d="M11.991 23.503a.24.24 0 00-.244.248.24.24 0 00.244.249.24.24 0 00.245-.249.24.24 0 00-.22-.247l-.025-.001zM9.671 5.365a1.697 1.697 0 011.099 2.132l-.071.172-.016.04-.018.054c-.07.16-.104.32-.104.498-.035.71.47 1.279 1.186 1.314h.366c1.309.053 2.338 1.173 2.286 2.523-.052 1.332-1.152 2.38-2.478 2.327h-.174c-.715.018-1.274.64-1.239 1.368 0 .124.018.23.053.337.209.373.54.658.96.8.75.23 1.517-.125 1.9-.782l.018-.035c.402-.64 1.17-.96 1.92-.711.854.284 1.378 1.226 1.099 2.167a1.661 1.661 0 01-2.077 1.102 1.711 1.711 0 01-.907-.711l-.017-.035c-.2-.323-.463-.58-.851-.711l-.056-.018a1.646 1.646 0 00-1.954.746 1.66 1.66 0 01-1.065.764 1.677 1.677 0 01-1.989-1.279c-.209-.906.332-1.83 1.257-2.043a1.51 1.51 0 01.296-.035h.018c.68-.071 1.151-.622 1.116-1.333a1.307 1.307 0 00-.227-.693 2.515 2.515 0 01-.366-1.403 2.39 2.39 0 01.366-1.208c.14-.195.21-.444.227-.693.018-.71-.506-1.261-1.186-1.332l-.07-.018a1.43 1.43 0 01-.299-.07l-.05-.019a1.7 1.7 0 01-1.047-2.114 1.68 1.68 0 012.094-1.101zm-5.575 10.11c.26-.264.639-.367.994-.27.355.096.633.379.728.74.095.362-.007.748-.267 1.013-.402.41-1.053.41-1.455 0a1.062 1.062 0 010-1.482zm14.845-.294c.359-.09.738.024.992.297.254.274.344.665.237 1.025-.107.36-.396.634-.756.718-.551.128-1.1-.22-1.23-.781a1.05 1.05 0 01.757-1.26zm-.064-4.39c.314.32.49.753.49 1.206 0 .452-.176.886-.49 1.206-.315.32-.74.5-1.185.5-.444 0-.87-.18-1.184-.5a1.727 1.727 0 010-2.412 1.654 1.654 0 012.369 0zm-11.243.163c.364.484.447 1.128.218 1.691a1.665 1.665 0 01-2.188.923c-.855-.36-1.26-1.358-.907-2.228a1.68 1.68 0 011.33-1.038c.593-.08 1.183.169 1.547.652zm11.545-4.221c.368 0 .708.2.892.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.892.524c-.568 0-1.03-.47-1.03-1.048 0-.579.462-1.048 1.03-1.048zm-14.358 0c.368 0 .707.2.891.524.184.324.184.724 0 1.048a1.026 1.026 0 01-.891.524c-.569 0-1.03-.47-1.03-1.048 0-.579.461-1.048 1.03-1.048zm10.031-1.475c.925 0 1.675.764 1.675 1.706s-.75 1.705-1.675 1.705-1.674-.763-1.674-1.705c0-.942.75-1.706 1.674-1.706zm-2.626-.684c.362-.082.653-.356.761-.718a1.062 1.062 0 00-.238-1.028 1.017 1.017 0 00-.996-.294c-.547.14-.881.7-.752 1.257.13.558.675.907 1.225.783zm0 16.876c.359-.087.644-.36.75-.72a1.062 1.062 0 00-.237-1.019 1.018 1.018 0 00-.985-.301 1.037 1.037 0 00-.762.717c-.108.361-.017.754.239 1.028.245.263.606.377.953.305l.043-.01zM17.19 3.5a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64a.631.631 0 00-.628.64c0 .355.28.64.628.64zm-10.38 0a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64a.631.631 0 00-.628.64c0 .355.279.64.628.64zm-5.182 7.852a.631.631 0 00-.628.64c0 .354.28.639.628.639a.63.63 0 00.627-.606l.001-.034a.62.62 0 00-.628-.64zm5.182 9.13a.631.631 0 00-.628.64c0 .355.279.64.628.64a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm10.38.018a.631.631 0 00-.628.64c0 .355.28.64.628.64a.631.631 0 00.628-.64c0-.355-.279-.64-.628-.64zm5.182-9.148a.631.631 0 00-.628.64c0 .354.279.639.628.639a.631.631 0 00.628-.64c0-.355-.28-.64-.628-.64zm-.384-4.992a.24.24 0 00.244-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249c0 .142.122.249.244.249zM11.991.497a.24.24 0 00.245-.248A.24.24 0 0011.99 0a.24.24 0 00-.244.249c0 .133.108.236.223.247l.021.001zM2.011 6.36a.24.24 0 00.245-.249.24.24 0 00-.244-.249.24.24 0 00-.244.249.24.24 0 00.244.249zm0 11.263a.24.24 0 00-.243.248.24.24 0 00.244.249.24.24 0 00.244-.249.252.252 0 00-.244-.248zm19.995-.018a.24.24 0 00-.245.248.24.24 0 00.245.25.24.24 0 00.244-.25.252.252 0 00-.244-.248z" fill="#3859FF" fill-rule="nonzero"></path></svg>`,
|
||||
openrouter: `<svg fill="currentColor" fill-rule="evenodd" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>OpenRouter</title><path d="M16.804 1.957l7.22 4.105v.087L16.73 10.21l.017-2.117-.821-.03c-1.059-.028-1.611.002-2.268.11-1.064.175-2.038.577-3.147 1.352L8.345 11.03c-.284.195-.495.336-.68.455l-.515.322-.397.234.385.23.53.338c.476.314 1.17.796 2.701 1.866 1.11.775 2.083 1.177 3.147 1.352l.3.045c.694.091 1.375.094 2.825.033l.022-2.159 7.22 4.105v.087L16.589 22l.014-1.862-.635.022c-1.386.042-2.137.002-3.138-.162-1.694-.28-3.26-.926-4.881-2.059l-2.158-1.5a21.997 21.997 0 00-.755-.498l-.467-.28a55.927 55.927 0 00-.76-.43C2.908 14.73.563 14.116 0 14.116V9.888l.14.004c.564-.007 2.91-.622 3.809-1.124l1.016-.58.438-.274c.428-.28 1.072-.726 2.686-1.853 1.621-1.133 3.186-1.78 4.881-2.059 1.152-.19 1.974-.213 3.814-.138l.02-1.907z"></path></svg>`,
|
||||
rc: `<svg viewBox="0 0 24 24" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg"><title>RightCode</title><path d="M3 4h6c2.2 0 4 1.8 4 4 0 1.5-.8 2.8-2 3.5L14 17h-3l-2.5-5H5v5H3V4zm2 2v4h4c1.1 0 2-.9 2-2s-.9-2-2-2H5z" fill="#E96B2C"/><path d="M21 8.5c0-2.5-2-4.5-4.5-4.5-1.5 0-2.8.7-3.6 1.8l1.5 1.2c.5-.7 1.2-1 2.1-1 1.4 0 2.5 1.1 2.5 2.5v.5h-1c-2.5 0-4.5 1.3-4.5 3.5 0 1.9 1.6 3.5 3.5 3.5 1.2 0 2.3-.6 3-1.5V16h2V8.5zM17 14c-1.1 0-2-.7-2-1.5s.9-1.5 2-1.5h2v1c0 1.1-.9 2-2 2z" fill="#E96B2C"/><rect x="3" y="18" width="18" height="2" rx="1" fill="#E96B2C"/></svg>`,
|
||||
rc: `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" style="flex:none;line-height:1" viewBox="0 0 128 128"><title>RightCode</title><path fill="#EA6C2C" fill-rule="evenodd" d="M 67.00 124.35 L 65.00 124.65 L 63.00 124.31 L 60.87 122.00 L 60.51 120.00 L 60.62 119.00 L 61.63 117.00 L 63.64 115.00 L 63.65 23.00 L 63.40 22.00 L 60.71 20.00 L 59.73 18.00 L 59.66 16.00 L 61.18 13.00 L 63.00 11.70 L 65.00 11.36 L 67.00 11.68 L 69.00 13.07 L 70.24 15.00 L 70.43 17.00 L 69.35 20.00 L 66.75 22.00 L 66.53 23.00 L 66.56 115.00 L 69.38 118.00 L 69.69 120.00 L 69.38 122.00 L 67.00 124.35 Z M 65.38 19.00 L 66.99 18.00 L 67.30 16.00 L 66.00 14.66 L 64.00 14.69 L 62.79 16.00 L 62.66 17.00 L 64.00 18.73 L 65.38 19.00 Z M 72.00 53.03 L 71.70 52.00 L 71.56 35.00 L 70.00 33.71 L 68.79 32.00 L 68.52 30.00 L 69.00 28.15 L 70.00 26.71 L 72.00 25.59 L 74.00 25.45 L 75.00 25.70 L 76.75 27.00 L 77.50 28.00 L 78.15 30.00 L 77.18 33.00 L 74.81 35.00 L 74.60 50.00 L 72.00 53.03 Z M 74.12 32.00 L 75.11 31.00 L 75.31 30.00 L 74.77 29.00 L 74.00 28.40 L 72.00 28.65 L 71.35 30.00 L 71.45 31.00 L 73.00 32.26 L 74.12 32.00 Z M 58.00 52.97 L 55.68 50.00 L 55.65 40.00 L 52.89 37.00 L 52.36 35.00 L 52.62 33.00 L 54.00 31.03 L 57.00 29.77 L 60.00 30.84 L 61.03 32.00 L 61.64 34.00 L 61.21 37.00 L 58.49 40.00 L 58.47 52.00 L 58.00 52.97 Z M 58.43 36.00 L 59.06 35.00 L 58.91 34.00 L 58.00 32.96 L 57.00 32.66 L 56.00 33.10 L 55.29 34.00 L 55.19 35.00 L 55.64 36.00 L 57.00 36.59 L 58.43 36.00 Z M 57.00 89.45 L 46.00 89.35 L 37.24 77.00 L 36.00 75.99 L 35.00 75.93 L 28.00 75.93 L 27.12 77.00 L 27.14 88.00 L 26.80 89.00 L 26.00 89.36 L 18.00 89.36 L 16.89 89.00 L 16.66 48.00 L 17.00 46.90 L 44.00 46.73 L 48.00 47.67 L 50.00 48.57 L 53.23 51.00 L 55.44 54.00 L 56.34 56.00 L 57.07 59.00 L 56.95 64.00 L 56.15 67.00 L 54.34 70.00 L 52.00 72.26 L 48.83 74.00 L 48.06 75.00 L 57.06 88.00 L 57.53 89.00 L 57.00 89.45 Z M 110.00 89.13 L 109.00 89.65 L 90.00 89.61 L 85.00 89.18 L 80.00 87.40 L 77.00 85.39 L 74.64 83.00 L 72.64 80.00 L 70.76 75.00 L 70.20 70.00 L 70.36 65.00 L 70.81 62.00 L 72.61 57.00 L 74.49 54.00 L 77.36 51.00 L 81.00 48.62 L 84.00 47.54 L 88.00 46.77 L 109.00 46.64 L 109.79 47.00 L 110.13 48.00 L 110.00 55.15 L 109.00 55.68 L 91.00 55.74 L 87.00 56.77 L 84.11 59.00 L 82.59 61.00 L 81.36 64.00 L 80.64 69.00 L 81.62 74.00 L 82.58 76.00 L 85.00 78.66 L 88.00 80.22 L 92.00 80.64 L 109.00 80.64 L 109.80 81.00 L 110.13 82.00 L 110.00 89.13 Z M 43.29 67.00 L 44.89 66.00 L 46.00 64.70 L 46.86 62.00 L 46.50 59.00 L 45.00 56.77 L 43.00 55.56 L 40.00 55.18 L 28.00 55.17 L 27.12 56.00 L 27.16 67.00 L 28.00 67.65 L 40.00 67.63 L 43.29 67.00 Z M 74.00 105.20 L 72.00 105.09 L 70.13 104.00 L 68.71 102.00 L 68.54 101.00 L 68.69 99.00 L 70.00 97.06 L 71.42 96.00 L 71.71 95.00 L 71.70 86.00 L 72.00 84.36 L 74.56 87.00 L 74.64 95.00 L 75.00 95.97 L 77.39 98.00 L 78.12 100.00 L 77.32 103.00 L 76.00 104.37 L 74.00 105.20 Z M 59.00 111.05 L 57.00 111.40 L 55.00 111.01 L 52.89 109.00 L 52.36 107.00 L 53.00 104.45 L 55.51 102.00 L 55.65 93.00 L 55.88 92.00 L 57.00 91.64 L 58.28 92.00 L 58.49 93.00 L 58.63 102.00 L 61.00 104.14 L 61.65 106.00 L 61.26 109.00 L 59.00 111.05 Z M 74.39 102.00 L 75.23 101.00 L 75.00 99.65 L 74.00 98.65 L 73.00 98.54 L 72.06 99.00 L 71.39 100.00 L 71.39 101.00 L 72.00 101.96 L 73.00 102.38 L 74.39 102.00 Z M 58.51 108.00 L 59.09 107.00 L 58.83 106.00 L 58.00 105.18 L 57.00 104.85 L 55.33 106.00 L 55.18 107.00 L 56.00 108.39 L 57.00 108.65 L 58.51 108.00 Z M 65.09 122.00 L 66.75 121.00 L 67.14 120.00 L 66.00 118.36 L 65.00 118.16 L 63.54 119.00 L 63.28 120.00 L 63.47 121.00 L 65.09 122.00 Z"/></svg>`,
|
||||
longcat: `<svg fill="currentColor" height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>LongCat</title><path clip-rule="evenodd" d="M.507 19.883a.507.507 0 01-.489-.642L4.29 3.745a1.013 1.013 0 011.533-.578l5.622 3.687a1.013 1.013 0 001.11 0L18.2 3.165a1.013 1.013 0 011.532.58l4.25 15.497a.506.506 0 01-.49.64H18.07a6.297 6.297 0 001.53-4.115v-.177a6.09 6.09 0 00-1.513-4.017l-.697-3.495a.438.438 0 00-.694-.266L14.07 9.781a.748.748 0 01-.654.121 5.156 5.156 0 00-2.833 0 .746.746 0 01-.653-.121L7.302 7.81a.435.435 0 00-.688.269l-.675 3.652a5.36 5.36 0 00-1.539 3.76v.333c0 1.474.527 2.9 1.488 4.02l.032.038H.507z" fill="#29E154" fill-rule="evenodd"></path><path d="M9.213 16.843h1.52v-3.546h-1.29l-.23 3.546zm5.573 0h-1.52v-3.546h1.29l.23 3.546z"></path></svg>`,
|
||||
modelscope: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>ModelScope</title><path d="M0 7.967h2.667v2.667H0zM8 10.633h2.667V13.3H8z" fill="#36CED0"></path><path d="M0 10.633h2.667V13.3H0zM2.667 13.3h2.666v2.667H8v2.666H2.667V13.3zM2.667 5.3H8v2.667H5.333v2.666H2.667V5.3zM10.667 13.3h2.667v2.667h-2.667z" fill="#624AFF"></path><path d="M24 7.967h-2.667v2.667H24zM16 10.633h-2.667V13.3H16z" fill="#36CED0"></path><path d="M24 10.633h-2.667V13.3H24zM21.333 13.3h-2.666v2.667H16v2.666h5.333V13.3zM21.333 5.3H16v2.667h2.667v2.666h2.666V5.3z" fill="#624AFF"></path></svg>`,
|
||||
aihubmix: `<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>AiHubMix</title><path d="M12 24c6.627 0 12-5.373 12-12S18.627 0 12 0 0 5.373 0 12s5.373 12 12 12z" fill="#006FFB"></path><path clip-rule="evenodd" d="M11.24 8.393c.095-.644.302-1.47.624-2.48L12 5.496l.136.417c.322 1.01.53 1.836.624 2.48.071.472.071 1.072 0 1.8-.072.731-.072 1.336 0 1.814.106.7.426 1.281.96 1.744a2.795 2.795 0 001.89.708 2.78 2.78 0 002.034-.84c.56-.559.842-1.234.848-2.024.003-.7.075-1.472.216-2.316.069-.422.14-.775.21-1.06l.095-.384.168.356a7.862 7.862 0 01.76 3.244v.16a7.84 7.84 0 01-.624 3.089 7.952 7.952 0 01-4.228 4.228 7.841 7.841 0 01-3.089.623 7.84 7.84 0 01-3.089-.623 7.952 7.952 0 01-4.228-4.228 7.84 7.84 0 01-.623-3.09v-.159a7.862 7.862 0 01.759-3.244l.169-.356.093.385c.072.284.143.637.211 1.059.141.844.213 1.616.216 2.316.006.79.29 1.465.848 2.024.563.56 1.241.84 2.035.84.715 0 1.345-.236 1.889-.708a2.79 2.79 0 00.96-1.744c.073-.478.073-1.083 0-1.814-.071-.728-.071-1.328 0-1.8zm.76 9.694c1.097 0 2.125-.26 3.085-.778a6.379 6.379 0 001.77-1.399c.063-.07-.01-.178-.101-.153-.37.1-.75.15-1.144.15a4.236 4.236 0 01-2.18-.59 4.253 4.253 0 01-1.35-1.233.099.099 0 00-.16 0 4.253 4.253 0 01-1.35 1.232 4.236 4.236 0 01-2.18.591c-.393 0-.774-.05-1.143-.15-.091-.025-.165.083-.102.153a6.38 6.38 0 001.77 1.399c.96.518 1.988.778 3.085.778z" fill="#fff" fill-rule="evenodd"></path></svg>`,
|
||||
|
||||
@@ -1,6 +1 @@
|
||||
<svg viewBox="0 0 24 24" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg">
|
||||
<title>RightCode</title>
|
||||
<path d="M3 4h6c2.2 0 4 1.8 4 4 0 1.5-.8 2.8-2 3.5L14 17h-3l-2.5-5H5v5H3V4zm2 2v4h4c1.1 0 2-.9 2-2s-.9-2-2-2H5z" fill="#E96B2C"/>
|
||||
<path d="M21 8.5c0-2.5-2-4.5-4.5-4.5-1.5 0-2.8.7-3.6 1.8l1.5 1.2c.5-.7 1.2-1 2.1-1 1.4 0 2.5 1.1 2.5 2.5v.5h-1c-2.5 0-4.5 1.3-4.5 3.5 0 1.9 1.6 3.5 3.5 3.5 1.2 0 2.3-.6 3-1.5V16h2V8.5zM17 14c-1.1 0-2-.7-2-1.5s.9-1.5 2-1.5h2v1c0 1.1-.9 2-2 2z" fill="#E96B2C"/>
|
||||
<rect x="3" y="18" width="18" height="2" rx="1" fill="#E96B2C"/>
|
||||
</svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><path fill="#EA6C2C" fill-rule="evenodd" d="M 67.00 124.35 L 65.00 124.65 L 63.00 124.31 L 60.87 122.00 L 60.51 120.00 L 60.62 119.00 L 61.63 117.00 L 63.64 115.00 L 63.65 23.00 L 63.40 22.00 L 60.71 20.00 L 59.73 18.00 L 59.66 16.00 L 61.18 13.00 L 63.00 11.70 L 65.00 11.36 L 67.00 11.68 L 69.00 13.07 L 70.24 15.00 L 70.43 17.00 L 69.35 20.00 L 66.75 22.00 L 66.53 23.00 L 66.56 115.00 L 69.38 118.00 L 69.69 120.00 L 69.38 122.00 L 67.00 124.35 Z M 65.38 19.00 L 66.99 18.00 L 67.30 16.00 L 66.00 14.66 L 64.00 14.69 L 62.79 16.00 L 62.66 17.00 L 64.00 18.73 L 65.38 19.00 Z M 72.00 53.03 L 71.70 52.00 L 71.56 35.00 L 70.00 33.71 L 68.79 32.00 L 68.52 30.00 L 69.00 28.15 L 70.00 26.71 L 72.00 25.59 L 74.00 25.45 L 75.00 25.70 L 76.75 27.00 L 77.50 28.00 L 78.15 30.00 L 77.18 33.00 L 74.81 35.00 L 74.60 50.00 L 72.00 53.03 Z M 74.12 32.00 L 75.11 31.00 L 75.31 30.00 L 74.77 29.00 L 74.00 28.40 L 72.00 28.65 L 71.35 30.00 L 71.45 31.00 L 73.00 32.26 L 74.12 32.00 Z M 58.00 52.97 L 55.68 50.00 L 55.65 40.00 L 52.89 37.00 L 52.36 35.00 L 52.62 33.00 L 54.00 31.03 L 57.00 29.77 L 60.00 30.84 L 61.03 32.00 L 61.64 34.00 L 61.21 37.00 L 58.49 40.00 L 58.47 52.00 L 58.00 52.97 Z M 58.43 36.00 L 59.06 35.00 L 58.91 34.00 L 58.00 32.96 L 57.00 32.66 L 56.00 33.10 L 55.29 34.00 L 55.19 35.00 L 55.64 36.00 L 57.00 36.59 L 58.43 36.00 Z M 57.00 89.45 L 46.00 89.35 L 37.24 77.00 L 36.00 75.99 L 35.00 75.93 L 28.00 75.93 L 27.12 77.00 L 27.14 88.00 L 26.80 89.00 L 26.00 89.36 L 18.00 89.36 L 16.89 89.00 L 16.66 48.00 L 17.00 46.90 L 44.00 46.73 L 48.00 47.67 L 50.00 48.57 L 53.23 51.00 L 55.44 54.00 L 56.34 56.00 L 57.07 59.00 L 56.95 64.00 L 56.15 67.00 L 54.34 70.00 L 52.00 72.26 L 48.83 74.00 L 48.06 75.00 L 57.06 88.00 L 57.53 89.00 L 57.00 89.45 Z M 110.00 89.13 L 109.00 89.65 L 90.00 89.61 L 85.00 89.18 L 80.00 87.40 L 77.00 85.39 L 74.64 83.00 L 72.64 80.00 L 70.76 75.00 L 70.20 70.00 L 70.36 65.00 L 70.81 62.00 L 72.61 57.00 L 74.49 54.00 L 77.36 51.00 L 81.00 48.62 L 84.00 47.54 L 88.00 46.77 L 109.00 46.64 L 109.79 47.00 L 110.13 48.00 L 110.00 55.15 L 109.00 55.68 L 91.00 55.74 L 87.00 56.77 L 84.11 59.00 L 82.59 61.00 L 81.36 64.00 L 80.64 69.00 L 81.62 74.00 L 82.58 76.00 L 85.00 78.66 L 88.00 80.22 L 92.00 80.64 L 109.00 80.64 L 109.80 81.00 L 110.13 82.00 L 110.00 89.13 Z M 43.29 67.00 L 44.89 66.00 L 46.00 64.70 L 46.86 62.00 L 46.50 59.00 L 45.00 56.77 L 43.00 55.56 L 40.00 55.18 L 28.00 55.17 L 27.12 56.00 L 27.16 67.00 L 28.00 67.65 L 40.00 67.63 L 43.29 67.00 Z M 74.00 105.20 L 72.00 105.09 L 70.13 104.00 L 68.71 102.00 L 68.54 101.00 L 68.69 99.00 L 70.00 97.06 L 71.42 96.00 L 71.71 95.00 L 71.70 86.00 L 72.00 84.36 L 74.56 87.00 L 74.64 95.00 L 75.00 95.97 L 77.39 98.00 L 78.12 100.00 L 77.32 103.00 L 76.00 104.37 L 74.00 105.20 Z M 59.00 111.05 L 57.00 111.40 L 55.00 111.01 L 52.89 109.00 L 52.36 107.00 L 53.00 104.45 L 55.51 102.00 L 55.65 93.00 L 55.88 92.00 L 57.00 91.64 L 58.28 92.00 L 58.49 93.00 L 58.63 102.00 L 61.00 104.14 L 61.65 106.00 L 61.26 109.00 L 59.00 111.05 Z M 74.39 102.00 L 75.23 101.00 L 75.00 99.65 L 74.00 98.65 L 73.00 98.54 L 72.06 99.00 L 71.39 100.00 L 71.39 101.00 L 72.00 101.96 L 73.00 102.38 L 74.39 102.00 Z M 58.51 108.00 L 59.09 107.00 L 58.83 106.00 L 58.00 105.18 L 57.00 104.85 L 55.33 106.00 L 55.18 107.00 L 56.00 108.39 L 57.00 108.65 L 58.51 108.00 Z M 65.09 122.00 L 66.75 121.00 L 67.14 120.00 L 66.00 118.36 L 65.00 118.16 L 63.54 119.00 L 63.28 120.00 L 63.47 121.00 L 65.09 122.00 Z"/></svg>
|
||||
|
Before Width: | Height: | Size: 581 B After Width: | Height: | Size: 3.5 KiB |
@@ -35,6 +35,7 @@ function getErrorI18nKey(code: string): string {
|
||||
DOWNLOAD_TIMEOUT: "skills.error.downloadTimeout",
|
||||
DOWNLOAD_FAILED: "skills.error.downloadFailed",
|
||||
SKILL_DIR_NOT_FOUND: "skills.error.skillDirNotFound",
|
||||
SKILL_DIRECTORY_CONFLICT: "skills.error.directoryConflict",
|
||||
EMPTY_ARCHIVE: "skills.error.emptyArchive",
|
||||
GET_HOME_DIR_FAILED: "skills.error.getHomeDirFailed",
|
||||
};
|
||||
@@ -52,6 +53,7 @@ function getSuggestionI18nKey(suggestion: string): string {
|
||||
retryLater: "skills.error.suggestion.retryLater",
|
||||
checkRepoUrl: "skills.error.suggestion.checkRepoUrl",
|
||||
checkPermission: "skills.error.suggestion.checkPermission",
|
||||
uninstallFirst: "skills.error.suggestion.uninstallFirst",
|
||||
http403: "skills.error.http403",
|
||||
http404: "skills.error.http404",
|
||||
http429: "skills.error.http429",
|
||||
|
||||
@@ -25,6 +25,9 @@ export const settingsSchema = z.object({
|
||||
currentProviderClaude: z.string().optional(),
|
||||
currentProviderCodex: z.string().optional(),
|
||||
currentProviderGemini: z.string().optional(),
|
||||
|
||||
// Skill 同步设置
|
||||
skillSyncMethod: z.enum(["auto", "symlink", "copy"]).optional(),
|
||||
});
|
||||
|
||||
export type SettingsFormData = z.infer<typeof settingsSchema>;
|
||||
|
||||
@@ -119,6 +119,18 @@ export interface ProviderProxyConfig {
|
||||
proxyPassword?: string;
|
||||
}
|
||||
|
||||
// 格式转换配置(用于 OpenRouter 等需要 API 格式转换的供应商)
|
||||
export interface FormatTransformConfig {
|
||||
// 是否启用格式转换
|
||||
enabled: boolean;
|
||||
// 源格式:anthropic, openai, gemini
|
||||
sourceFormat?: "anthropic" | "openai" | "gemini";
|
||||
// 目标格式:anthropic, openai, gemini
|
||||
targetFormat?: "anthropic" | "openai" | "gemini";
|
||||
// 是否转换流式响应(默认 true)
|
||||
transformStreaming?: boolean;
|
||||
}
|
||||
|
||||
// 供应商元数据(字段名与后端一致,保持 snake_case)
|
||||
export interface ProviderMeta {
|
||||
// 自定义端点:以 URL 为键,值为端点信息
|
||||
@@ -135,8 +147,13 @@ export interface ProviderMeta {
|
||||
testConfig?: ProviderTestConfig;
|
||||
// 供应商单独的代理配置
|
||||
proxyConfig?: ProviderProxyConfig;
|
||||
// 格式转换配置(用于 OpenRouter 等需要 API 格式转换的供应商)
|
||||
formatTransform?: FormatTransformConfig;
|
||||
}
|
||||
|
||||
// Skill 同步方式
|
||||
export type SkillSyncMethod = "auto" | "symlink" | "copy";
|
||||
|
||||
// 主页面显示的应用配置
|
||||
export interface VisibleApps {
|
||||
claude: boolean;
|
||||
@@ -182,6 +199,10 @@ export interface Settings {
|
||||
currentProviderCodex?: string;
|
||||
// 当前 Gemini 供应商 ID(优先于数据库 is_current)
|
||||
currentProviderGemini?: string;
|
||||
|
||||
// ===== Skill 同步设置 =====
|
||||
// Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
|
||||
skillSyncMethod?: SkillSyncMethod;
|
||||
}
|
||||
|
||||
// MCP 服务器连接参数(宽松:允许扩展字段)
|
||||
@@ -310,6 +331,8 @@ export interface OpenCodeModel {
|
||||
output?: number;
|
||||
};
|
||||
options?: Record<string, unknown>; // 模型级别额外选项(provider 路由等)
|
||||
// 支持任意额外字段(cost、modalities、thinking、variants 等)
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// OpenCode 供应商选项
|
||||
|
||||
Reference in New Issue
Block a user