mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 12:44:18 +08:00
Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c7ba3cf51d | |||
| 85295cf23f | |||
| 1f25411524 | |||
| 6495da03b7 | |||
| 95b21ff27e | |||
| ae1fd2b662 | |||
| f4a9021461 | |||
| 2274da0b8e | |||
| 7ac822d241 | |||
| 4dd11ab427 | |||
| 8e9452b7ec | |||
| 38709c94db | |||
| db92f2b3b0 | |||
| eb1cd17ab2 | |||
| 29a28d2a74 | |||
| 1227e29d8b | |||
| 0be75668cc | |||
| 111ddf8d73 | |||
| 08727528aa | |||
| c8d91298c7 | |||
| 21a1518f9f | |||
| a9461ad52f | |||
| f57edfd697 | |||
| abb305a82f | |||
| 3f4739365e | |||
| e10a300c80 | |||
| 185ac2be9b | |||
| b8a3534cb5 | |||
| 31fb998575 | |||
| acc6d795e4 | |||
| 088b47b08a | |||
| 041f74db18 | |||
| ce5c3e5c6a | |||
| 3255b17185 | |||
| b4e29be8a0 | |||
| 8d6353699c | |||
| 828ec2ce07 | |||
| 5056978d80 | |||
| 497a543c1b | |||
| f935bac633 | |||
| 63aa310576 | |||
| 615c430dd3 | |||
| 5d3cd7eb85 | |||
| 1684cb3233 | |||
| 83c3c3b494 | |||
| 50431b7ec9 | |||
| 8b65a31c7c | |||
| d03e6f9951 | |||
| 0ca36b9d51 | |||
| e8953c286f | |||
| 240969d8c7 | |||
| a0b585992a | |||
| 576ff53a75 | |||
| 6d0e9f4c74 | |||
| a2e9e1938b | |||
| 81af0a57f9 | |||
| 701e7d9581 | |||
| e4c34b34e7 | |||
| eab0a69d2c | |||
| 4e790ac059 | |||
| c5b15dd25e | |||
| cc77a040e2 | |||
| 1b345fbefb | |||
| 61bfc29d82 | |||
| 2c9252dec5 | |||
| 34349a2743 | |||
| 8ba92b5470 | |||
| 87635e7fc6 | |||
| 9871d3d1eb | |||
| 1126c7459d | |||
| 03a0f9661b | |||
| de23216e49 | |||
| 507bf038a9 | |||
| ef41e4da46 |
@@ -5,6 +5,102 @@ All notable changes to CC Switch will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.14.0] - 2026-04-21
|
||||
|
||||
Development since v3.13.0 focuses on onboarding Hermes Agent as a first-class managed app, rolling out Claude Opus 4.7 across the preset matrix, adding a Gemini Native API proxy, and sharpening session, usage, and proxy workflows.
|
||||
|
||||
**Stats**: 100 commits | 219 files changed | +20,548 insertions | -3,569 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **Hermes Agent Support (6th Managed App)**: Added Hermes Agent as a first-class managed app with database migration v9→v10, full Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, session manager with SQLite + JSONL support, and dedicated frontend panels. Supports four API protocols (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) aligned with Hermes Agent 0.10.0 schema. Read-only rendering for providers owned by the user-authored `providers:` dict, with deep configuration delegated to the Hermes Web UI.
|
||||
- **Hermes Memory Panel**: Added a Memory panel for editing `MEMORY.md` and `USER.md` directly from CC Switch, with an enable switch, character-count limits, and a live save flow. Replaces the Prompts entry for Hermes.
|
||||
- **Hermes Provider Presets**: Added ~50 Hermes provider presets spanning Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo.
|
||||
- **Claude Opus 4.7 Support**: Added Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix). Migrated all aggregator and Bedrock presets to Opus 4.7 as the default Opus model.
|
||||
- **Claude `max` Effort Tier**: Upgraded the Claude effort dropdown from `high` to `max` for extended reasoning capacity.
|
||||
- **Gemini Native API Proxy**: Added `api_format = "gemini_native"` so the proxy can forward to Google's `generateContent` API with full streaming, schema conversion, and shadow request support. Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module.
|
||||
- **GitHub Copilot Enterprise Server**: Added GHES authentication and endpoint configuration for Copilot-backed Claude providers, plus thinking-block stripping before upstream to preserve premium interaction quota.
|
||||
- **Session List Virtualization**: Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly; long session messages are now collapsed by default to reduce text layout cost.
|
||||
- **Codex / OpenClaw Session Title Extraction**: Added meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display; strips OpenClaw `message_id` suffix noise.
|
||||
- **Usage Date Range Picker**: Added a date range selector to the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d), a custom date + time calendar picker, and a page-jump input on paginated lists.
|
||||
- **Model Mapping Quick-Set**: Added a quick-set button next to model mapping fields in provider forms for faster edits.
|
||||
- **Stream Check Error Classification**: Classified Stream Check errors and surfaced them as color-coded toasts; refreshed default probe models and added explicit detection for "model not found" responses.
|
||||
- **Block Official Provider Switching During Local Routing**: Blocks switching to official providers while Local Routing is active, since routing official API traffic through the local proxy carries account-suspension risk. A warning toast surfaces the block.
|
||||
- **Pricing Database Refresh (v8 → v9)**: Added ~50 new model pricing entries and corrected stale prices via a reseed-on-migration step, including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, and GLM-5/5.1. DeepSeek and Kimi K2.5 prices updated.
|
||||
- **Application-Level Window Controls**: Added an opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of the system decorations, materially improving the experience on Linux Wayland where compositor-drawn buttons can become inert.
|
||||
- **Hermes in Unified Skills Management**: Added Hermes to the unified Skills surface; skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
|
||||
- **OpenClaw Config Directory Override**: Added a settings option to point CC Switch at a custom `openclaw.json` location.
|
||||
- **Hermes Config Directory Override**: Added a settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch.
|
||||
- **StepFun Step Plan Preset**: Added StepFun Step Plan (EN/ZH) provider presets.
|
||||
- **New API Usage Script Template**: Added a User-Agent header to the New API usage script template for better upstream compatibility.
|
||||
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry now offers to run `hermes dashboard` in the user's preferred terminal via a temp bash/batch script. `hermes dashboard` opens the browser itself once ready, so no polling is required. Also corrects the stale `hermes web` hint in the offline toast (the real command is `hermes dashboard`) and reorders Linux terminal detection to try `which` before stat'ing `/usr/bin`, `/bin`, `/usr/local/bin`.
|
||||
- **LemonData Provider Preset (All Six Apps)**: Registered LemonData as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes, with icon assets and zh/en/ja partner-promotion copy. Claude uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`.
|
||||
- **DDSHub Codex Preset**: Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service; base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths.
|
||||
|
||||
### Changed
|
||||
|
||||
- **"Local Proxy Takeover" → "Local Routing"**: Unified terminology across UI copy, README, and docs in all three locales. Functional behavior is unchanged.
|
||||
- **Hermes `Auto` api_mode Removed**: Users must now pick an explicit protocol; new deeplinks default to `chat_completions`. Eliminates URL-based heuristic surprises.
|
||||
- **Hermes Provider Form**: Added an API mode dropdown and per-provider model editor; bound per-provider models to the top-level `model:` when switching active providers.
|
||||
- **Hermes Deep Config Delegation**: Deep YAML knobs are now delegated to the Hermes Web UI via a direct launch action, rather than duplicated in the CC Switch form.
|
||||
- **`ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set**: Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form.
|
||||
- **Per-Provider Proxy Config Removed**: Consolidated into global Local Routing; the provider-level proxy toggle and associated storage are gone.
|
||||
- **Unified Toolbar Icon Button Width**: Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look.
|
||||
- **Rust Toolchain Pinned to 1.95**: Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift.
|
||||
- **Tray Menu ID Constant**: The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites.
|
||||
- **Copilot Request Classification**: Refined request routing inside the Copilot optimizer to further reduce unnecessary premium interaction consumption.
|
||||
- **Usage Script Intranet Support**: Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints. Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped.
|
||||
- **Failover Queue Notes**: Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues.
|
||||
- **Hermes Toolbar Layout**: Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL), and moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Header Auto-Compact Latching After Maximize**: The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes.
|
||||
- **Hermes YAML Pollution & OAuth MCP Auth Drop**: Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys; guard tests added via `tests/hermes_roundtrip.rs`.
|
||||
- **Hermes Active Provider Display**: Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions.
|
||||
- **Hermes Provider Persistence**: Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads.
|
||||
- **Codex `cache_control` Preservation**: Preserve `cache_control` when merging system prompts during Codex format conversion (#1946).
|
||||
- **Claude Prompt Cache Key Leak**: Stopped sending prompt cache keys during Claude chat conversions (#2003).
|
||||
- **Proxy Hop-by-Hop Header Stripping**: Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230.
|
||||
- **Permissive Proxy CORS Removed**: Removed the permissive CORS layer from the proxy (#1915).
|
||||
- **Copilot Premium Consumption**: Further reduced unnecessary Copilot premium interaction consumption during pass-through traffic.
|
||||
- **Backend Error Details in Proxy Toast**: Surface backend error payload details in proxy-related toast messages instead of a generic failure string.
|
||||
- **Usage Log Deduplication**: Deduplicated proxy and session-log usage records so the same request is no longer double-counted; synced the request log time range with the dashboard's 1d / 7d / 30d selector.
|
||||
- **Common Config Checkbox Persistence**: Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens.
|
||||
- **Claude Plugin `settings.json` Sync**: Editing the current provider now syncs back to `settings.json` for the Claude plugin path.
|
||||
- **Google Official Gemini Env Preservation**: Saving the Google Official Gemini provider no longer clobbers the `env` block.
|
||||
- **OpenCode JSON5 Parser for Trailing Commas**: OpenCode config reads now tolerate trailing commas via a JSON5 parser.
|
||||
- **Preset Refreshes**: Refreshed stale context windows for DeepSeek and Claude 1M; refreshed stale model IDs; backfilled Hermes model lists; fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork; pruned unused official Hermes presets.
|
||||
- **Auto-Expand Collapsed Messages on Search Hit**: Collapsed messages now auto-expand when a search match lands inside hidden content.
|
||||
- **Unknown Subscription Quota Tiers Hidden**: Provider cards no longer render unknown subscription quota tiers.
|
||||
- **Weekly Limit Label Unified**: Aligned the weekly_limit tier label with the official 7-day naming across locales.
|
||||
- **Root-Level Skill Repo Install**: Fixed skill installation when the repository root itself is a skill.
|
||||
- **Session ID Parsing Clippy**: Removed a redundant closure in session ID parsing (clippy warning).
|
||||
- **Usage Log Stat Dedup**: Deduplicated proxy-sourced and session-log-sourced usage records for accurate totals.
|
||||
- **Stream Check Default Models Refresh**: Updated stream-check default probe models to match each vendor's current lineup.
|
||||
- **Skills Import Sync**: Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database, so the UI no longer shows "installed" while the target app directory is missing the skill.
|
||||
- **Ghostty Session Restore**: Fixed Ghostty session restore launch by using shell execution with `--working-directory`, avoiding `cwd` escaping issues when the path contains spaces or special characters.
|
||||
- **Hermes Health Check Borrowing OpenClaw Schema**: Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled. Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`, and returns `bedrock_converse` as unsupported. `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url".
|
||||
- **Usage Query Modal for Hermes & OpenClaw**: `getProviderCredentials` now reads flat `settingsConfig` fields for Hermes (snake_case `base_url` / `api_key`) and OpenClaw (camelCase `baseUrl` / `apiKey`), so the "official balance" template auto-selects for matching providers like SiliconFlow. Also refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured.
|
||||
|
||||
### Docs
|
||||
|
||||
- **README Sponsor Updates**: Updated SiliconFlow signup bonus to ¥16, trimmed the SSSAiCode sponsor blurb, updated partner logos, and added LemonData as a new sponsor.
|
||||
- **Global Proxy Hint Clarified**: Clarified the global proxy hint about local routing across all three locales.
|
||||
- **Takeover → Routing Rename**: Renamed takeover docs to routing and updated anchors across all languages.
|
||||
- **PIPELLM Website URL**: Updated the PIPELLM sponsor website URL to `code.pipellm.ai`.
|
||||
|
||||
### Breaking
|
||||
|
||||
- **Hermes requires explicit `api_mode`**: The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`. Users with prior `Auto` configs will be prompted to pick a protocol.
|
||||
- **`ANTHROPIC_REASONING_MODEL` removed from Claude quick-set**: The legacy field is no longer exposed; existing settings are cleaned up automatically.
|
||||
- **Per-provider proxy configuration removed**: Migrate to the global Local Routing setting. Existing per-provider proxy values are ignored.
|
||||
- **Database schema bumped v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` (auto-migrated with `DEFAULT 0`; no data loss).
|
||||
- **Pricing table reseeded (v8 → v9)**: The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices.
|
||||
- **XCodeAPI preset removed**: Users of the XCodeAPI preset should switch to another provider.
|
||||
|
||||
---
|
||||
|
||||
## [3.13.0] - 2026-04-10
|
||||
|
||||
Development since v3.12.3 focuses on quota visibility, provider workflow upgrades, stronger proxy compatibility, and lower-overhead tray / session workflows.
|
||||
|
||||
@@ -48,7 +48,7 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
|
||||
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥20 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
|
||||
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥16 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -89,7 +89,7 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
|
||||
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, <strong>offering high cost-effective official Claude service at just ¥0.5/$ equivalent</strong>, supporting monthly and pay-as-you-go billing plans with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
|
||||
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
|
||||
+2
-3
@@ -48,7 +48,7 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
|
||||
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥20 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
|
||||
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -91,7 +91,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
|
||||
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。<strong>高コストパフォーマンスの公式 Claude サービスを 0.5¥/$ 換算で提供</strong>、月額制・Paygo など多様な課金方式に対応し、当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
|
||||
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -103,7 +103,6 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
<td>LemonData のご支援に感謝します!LemonData は高性能 AI API アグリゲーションプラットフォームで、GPT、Claude、Gemini、DeepSeek など 300 以上のモデルに 1 つの API キーでアクセス可能。全モデルが公式価格の 30〜70% オフで自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。新規ユーザーは登録だけで即座に $1 の無料クレジットを獲得 — <a href="https://lemondata.cc/r/FFX1ZDUP">こちらのリンク</a>から登録してボーナスを獲得し、すぐに開発を始めましょう!</td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
|
||||
<td>CTok.ai のご支援に感謝します!CTok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://ctok.ai">こちら</a>から登録してください!</td>
|
||||
|
||||
+2
-3
@@ -48,7 +48,7 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
|
||||
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥20 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
|
||||
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -90,7 +90,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
|
||||
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,<strong>提供高性价比折合0.5¥/$的官方Claude服务</strong>,支持包月、Paygo多种计费方式、支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
|
||||
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -102,7 +102,6 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
<td>感谢 LemonData 赞助了本项目!LemonData 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 GPT、Claude、Gemini、DeepSeek 等 300+ 模型。所有模型定价为官方价格的 30%-70%,支持自动故障转移、智能路由和无限并发。新用户注册即获 $1 免费额度——通过<a href="https://lemondata.cc/r/FFX1ZDUP">此链接</a>注册即可领取奖励,立即开始开发!</td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
|
||||
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://ctok.ai">这里</a>注册!</td>
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
# CC Switch v3.14.0
|
||||
|
||||
> Hermes Agent becomes the 6th managed app, Claude Opus 4.7 rolls out across the preset matrix, Gemini Native API proxy, "Local Routing" rename, and application-level window controls
|
||||
|
||||
**[中文版 →](v3.14.0-zh.md) | [日本語版 →](v3.14.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.14.0 is a major release centered on onboarding **Hermes Agent as the 6th first-class managed app** and rolling out **Claude Opus 4.7** across the full aggregator and Bedrock preset matrix. Hermes support covers a database v9 → v10 migration, a complete Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, and dedicated frontend panels including a Memory editor. All four API protocols aligned with Hermes Agent 0.10.0 (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) are selectable. Providers owned by the user-authored `providers:` dict are rendered as read-only cards, and deep YAML configuration is delegated directly to the Hermes Web UI.
|
||||
|
||||
Beyond Hermes, this release adds a **Gemini Native API proxy** (`api_format = "gemini_native"`) so the proxy can forward directly to Google's `generateContent` endpoint with full streaming, schema conversion, and shadow request support; renames the legacy "Local Proxy Takeover" to **Local Routing** across UI copy, README, and docs in all three locales; introduces **application-level window controls**, an opt-in setting that materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert; and bundles late additions for launching `hermes dashboard` from the toolbar, a LemonData preset across all six apps, a DDSHub Codex endpoint, plus several Hermes health-check and Usage modal fixes.
|
||||
|
||||
On the session side, the message list is **virtualized** via `@tanstack/react-virtual` so conversations with thousands of records scroll smoothly and long messages collapse by default; the Usage dashboard adds a **date range picker** (Today / 1d / 7d / 14d / 30d + custom date-time calendar) and a page-jump input; **Stream Check error classification** now surfaces color-coded toasts with refreshed default probe models and an explicit "model not found" branch; and switching to official providers is **blocked while Local Routing is active** to avoid account-suspension risk. The pricing database is reseeded from v8 → v9 with ~50 new model entries (Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1 and others) and corrected stale prices.
|
||||
|
||||
**Release Date**: 2026-04-21
|
||||
|
||||
**Update Scale**: 100 commits | 219 files changed | +20,548 / -3,569 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Hermes Agent Support (6th Managed App)**: Database v9 → v10 migration, full Rust command surface, YAML read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, dedicated frontend panels, and four API protocols (`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`)
|
||||
- **Claude Opus 4.7 Rollout**: Adaptive thinking whitelisting, per-million pricing seed, Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix); all aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
|
||||
- **Claude `max` Effort Tier**: Effort dropdown upgraded from `high` to `max`
|
||||
- **Gemini Native API Proxy**: New `api_format = "gemini_native"` forwards directly to Google's `generateContent` with full streaming / schema conversion / shadow request support
|
||||
- **GitHub Copilot Enterprise Server**: GHES authentication and endpoint configuration for Copilot-backed Claude providers
|
||||
- **Copilot Premium Consumption Deep Optimization**: Proactive thinking-block stripping before forwarding, `tool_result` classification fix, subagent detection, `x-interaction-id` billing merge, orphan `tool_result` sanitization, and default warmup downgrade — a systematic reduction in premium interaction consumption
|
||||
- **Session List Virtualization**: Long conversations scroll smoothly and long messages collapse by default to reduce text layout cost
|
||||
- **Codex / OpenClaw Session Title Extraction**: Meaningful title extraction with 2-line display; strips OpenClaw `message_id` suffix noise
|
||||
- **Usage Date Range Picker**: Today / 1d / 7d / 14d / 30d preset tabs + custom date-time calendar; page-jump input on paginated lists
|
||||
- **Stream Check Error Classification**: Color-coded error toasts; refreshed default probe models; explicit "model not found" detection
|
||||
- **Block Official Provider Switching During Local Routing**: Routing official API traffic through the local proxy carries account-suspension risk — switches are blocked with a warning toast
|
||||
- **Pricing Database Refresh (v8 → v9)**: ~50 new model entries and corrected stale prices
|
||||
- **Application-Level Window Controls**: Opt-in setting to render CC Switch's own min/max/close buttons, materially improving Linux Wayland experience
|
||||
- **Hermes in Unified Skills Management**: Skill install, enable, and filter now cover Hermes
|
||||
- **Hermes / OpenClaw Config Directory Override**: Point CC Switch at a custom `~/.hermes/config.yaml` or `openclaw.json` location
|
||||
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry offers to run `hermes dashboard` in the user's preferred terminal
|
||||
- **New Partner Presets**: LemonData across all six apps; DDSHub Codex endpoint; StepFun Step Plan
|
||||
|
||||
---
|
||||
|
||||
## Added
|
||||
|
||||
### Hermes Agent Support (6th Managed App)
|
||||
|
||||
CC Switch now treats Hermes Agent as a first-class managed app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
|
||||
|
||||
- **Database Migration v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` tables (`DEFAULT 0`, auto-migrated, no data loss)
|
||||
- **YAML Configuration Read/Write**: `~/.hermes/config.yaml` read/write with atomic backups; `tests/hermes_roundtrip.rs` guards against dropped OAuth MCP `auth` blocks or pollution of unrelated YAML keys
|
||||
- **Four API Protocols**: Aligned with Hermes Agent 0.10.0 — `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`; new deeplinks default to `chat_completions`
|
||||
- **User `providers:` Dict Read-Only Rendering**: User-authored providers in the YAML appear as read-only cards in CC Switch; deep configuration delegates to the Hermes Web UI
|
||||
- **Additive Switching**: Unlike Claude / Codex's "override" style, all Hermes providers coexist in the same YAML
|
||||
|
||||
### Hermes Memory Panel
|
||||
|
||||
- New Memory panel for editing `MEMORY.md` / `USER.md` directly, with an enable switch, character-count limits, and a live save flow
|
||||
- Replaces the Prompts entry for Hermes
|
||||
|
||||
### Hermes Provider Presets (~50)
|
||||
|
||||
- Covers Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo
|
||||
|
||||
### Launch Hermes Dashboard from Toolbar
|
||||
|
||||
- When the Hermes Web UI probe fails, the toolbar entry opens a confirm dialog offering to run `hermes dashboard` in the user's preferred terminal
|
||||
- Spawned via a temp bash / batch script; `hermes dashboard` opens the browser itself once ready, so no polling is required
|
||||
- The Memory panel and Health banner keep the existing toast behavior
|
||||
- Also corrects the stale `hermes web` hint in the offline toast (the real command is `hermes dashboard`)
|
||||
- Linux terminal detection reordered to try `which` before stat'ing `/usr/bin`, `/bin`, `/usr/local/bin`
|
||||
|
||||
### Claude Opus 4.7 Support
|
||||
|
||||
- New Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix)
|
||||
- All aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
|
||||
|
||||
### Claude `max` Effort Tier
|
||||
|
||||
- Claude effort dropdown upgraded from `high` to `max` for extended reasoning capacity
|
||||
|
||||
### Gemini Native API Proxy
|
||||
|
||||
- New `api_format = "gemini_native"` so the proxy can forward directly to Google's `generateContent` API (#1918, thanks @yovinchen)
|
||||
- Full streaming, schema conversion, and shadow request support
|
||||
- Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module
|
||||
|
||||
### GitHub Copilot Enterprise Server (GHES)
|
||||
|
||||
- GHES authentication and endpoint configuration for Copilot-backed Claude providers (#2175, thanks @hotelbe)
|
||||
|
||||
### Session List Virtualization
|
||||
|
||||
- Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly
|
||||
- Long session messages are collapsed by default to reduce text layout cost
|
||||
|
||||
### Codex / OpenClaw Session Title Extraction
|
||||
|
||||
- Meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display
|
||||
- Strips OpenClaw `message_id` suffix noise
|
||||
|
||||
### Usage Date Range Picker
|
||||
|
||||
- New date range selector on the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d) + custom date + time calendar (#2002, thanks @yovinchen)
|
||||
- Page-jump input added on paginated lists
|
||||
|
||||
### Model Mapping Quick-Set
|
||||
|
||||
- New quick-set button next to model mapping fields in provider forms for faster edits (#2179, thanks @lispking)
|
||||
|
||||
### Stream Check Error Classification
|
||||
|
||||
- Stream Check errors are classified and surfaced as color-coded toasts
|
||||
- Refreshed default probe models to match each vendor's current lineup
|
||||
- Explicit detection for "model not found" responses
|
||||
|
||||
### Block Official Provider Switching During Local Routing
|
||||
|
||||
- Switching to official providers is blocked while Local Routing is active, with a warning toast
|
||||
- Reason: routing official API traffic through the local proxy carries account-suspension risk
|
||||
|
||||
### Pricing Database Refresh (v8 → v9)
|
||||
|
||||
- Reseed-on-migration pricing table
|
||||
- ~50 new model pricing entries including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1
|
||||
- Corrected stale prices for DeepSeek, Kimi K2.5, and others
|
||||
|
||||
### Application-Level Window Controls
|
||||
|
||||
- Opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of system decorations (#1119, thanks @git1677967754)
|
||||
- Materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert
|
||||
|
||||
### Hermes in Unified Skills Management
|
||||
|
||||
- Hermes is added to the unified Skills surface
|
||||
- Skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw
|
||||
|
||||
### OpenClaw Config Directory Override
|
||||
|
||||
- New settings option to point CC Switch at a custom `openclaw.json` location (#1518, thanks @mrFranklin)
|
||||
|
||||
### Hermes Config Directory Override
|
||||
|
||||
- New settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch
|
||||
|
||||
### StepFun Step Plan Preset
|
||||
|
||||
- StepFun Step Plan (EN / ZH) provider presets (#2155, thanks @hengm3467)
|
||||
|
||||
### New API Usage Script Template
|
||||
|
||||
- Added a User-Agent header to the New API usage script template for better upstream compatibility
|
||||
|
||||
### LemonData Provider Preset (All Six Apps)
|
||||
|
||||
- LemonData registered as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes
|
||||
- Icon assets and zh / en / ja partner-promotion copy
|
||||
- Claude preset uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`
|
||||
|
||||
### DDSHub Codex Preset
|
||||
|
||||
- Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service
|
||||
- Base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths
|
||||
|
||||
---
|
||||
|
||||
## Changed
|
||||
|
||||
### "Local Proxy Takeover" → "Local Routing"
|
||||
|
||||
- Unified the terminology across UI copy, README, and docs in all three locales
|
||||
- Functional behavior is unchanged
|
||||
|
||||
### Hermes `Auto` api_mode Removed
|
||||
|
||||
- Users must pick an explicit protocol; new deeplinks default to `chat_completions`
|
||||
- Eliminates URL-based heuristic surprises
|
||||
|
||||
### Hermes Provider Form
|
||||
|
||||
- Added an API mode dropdown and per-provider model editor
|
||||
- Binds per-provider models to the top-level `model:` when switching active providers
|
||||
|
||||
### Hermes Deep Config Delegation
|
||||
|
||||
- Deep YAML knobs are no longer duplicated in the CC Switch form — they are delegated to the Hermes Web UI via a direct launch action
|
||||
|
||||
### Hermes Toolbar Layout
|
||||
|
||||
- Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL)
|
||||
- Moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout
|
||||
|
||||
### `ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set
|
||||
|
||||
- Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form
|
||||
|
||||
### Per-Provider Proxy Config Removed
|
||||
|
||||
- Consolidated into global Local Routing
|
||||
- Provider-level proxy toggle and associated storage are gone
|
||||
|
||||
### Unified Toolbar Icon Button Width
|
||||
|
||||
- Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look
|
||||
|
||||
### Rust Toolchain Pinned to 1.95
|
||||
|
||||
- Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift
|
||||
|
||||
### Tray Menu ID Constant
|
||||
|
||||
- The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites (#1978, thanks @lidaxian121)
|
||||
|
||||
### Copilot Premium Consumption Deep Optimization
|
||||
|
||||
A systematic overhaul to reduce Copilot reverse-proxy premium interaction consumption across multiple dimensions:
|
||||
|
||||
- **Proactive Thinking Block Stripping Before Forwarding**: Anthropic's `thinking` / `redacted_thinking` blocks are rejected by OpenAI-compatible endpoints. Previously, the request failed upstream, burning one premium interaction before the `thinking_rectifier` could retry. A new proactive strip step (Copilot optimization pipeline step 3.5, after `tool_result` merging) eliminates that wasted interaction
|
||||
- **Request Classification Fix**: Messages containing `tool_result` are now classified as agent continuation instead of user-initiated, preventing every tool call from being falsely counted as a premium interaction
|
||||
- **Subagent Detection**: Identifies subagents via `__SUBAGENT_MARKER__` with `metadata._agent_` fallback, setting `x-interaction-type=conversation-subagent`
|
||||
- **Deterministic `x-interaction-id` Billing Merge**: Derives `x-interaction-id` from the session ID so multiple requests within the same session collapse into a single billing interaction
|
||||
- **Orphan `tool_result` Sanitization**: Cleans up orphan `tool_result` entries to prevent upstream errors that would trigger retries and duplicate billing
|
||||
- **Warmup Downgrade Enabled by Default**: Uses `gpt-5-mini` as the default downgrade model
|
||||
- **Optimization Pipeline Reorder**: classify → sanitize → merge → warmup, so classification sees raw `tool_result` semantics
|
||||
- Fixed a `CopilotOptimizerConfig` default-value inconsistency (unified to `gpt-5-mini`)
|
||||
|
||||
### Usage Script Intranet Support
|
||||
|
||||
- Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints
|
||||
- Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped
|
||||
|
||||
### Failover Queue Notes
|
||||
|
||||
- Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues (#2138, thanks @Coconut-Fish)
|
||||
|
||||
---
|
||||
|
||||
## Fixed
|
||||
|
||||
### Header Auto-Compact Latching After Maximize
|
||||
|
||||
- The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes
|
||||
|
||||
### Hermes YAML Pollution & OAuth MCP `auth` Drop
|
||||
|
||||
- Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys
|
||||
- Guard tests added via `tests/hermes_roundtrip.rs`
|
||||
|
||||
### Hermes Active Provider Display
|
||||
|
||||
- Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions
|
||||
|
||||
### Hermes Provider Persistence
|
||||
|
||||
- Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads
|
||||
|
||||
### Hermes Health Check Borrowing OpenClaw Schema
|
||||
|
||||
- Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled
|
||||
- Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`; `bedrock_converse` returns as unsupported
|
||||
- `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url"
|
||||
|
||||
### Usage Query Modal for Hermes & OpenClaw
|
||||
|
||||
- `getProviderCredentials` now reads flat `settingsConfig` fields for Hermes (snake_case `base_url` / `api_key`) and OpenClaw (camelCase `baseUrl` / `apiKey`), so the "official balance" template auto-selects for matching providers like SiliconFlow
|
||||
- Refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured
|
||||
|
||||
### Codex `cache_control` Preservation
|
||||
|
||||
- Preserve `cache_control` when merging system prompts during Codex format conversion (#1946, thanks @yovinchen)
|
||||
|
||||
### Claude Prompt Cache Key Leak
|
||||
|
||||
- Stopped sending prompt cache keys during Claude chat conversions (#2003, thanks @yovinchen)
|
||||
|
||||
### Proxy Hop-by-Hop Header Stripping
|
||||
|
||||
- Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230 (#2060, thanks @yovinchen)
|
||||
|
||||
### Permissive Proxy CORS Removed
|
||||
|
||||
- Removed the permissive CORS layer from the proxy (#1915, thanks @zerone0x)
|
||||
|
||||
### Backend Error Details in Proxy Toast
|
||||
|
||||
- Surface backend error payload details in proxy-related toast messages instead of a generic failure string
|
||||
|
||||
### Usage Log Deduplication
|
||||
|
||||
- Deduplicated proxy and session-log usage records so the same request is no longer double-counted
|
||||
- Synced the request log time range with the dashboard's 1d / 7d / 30d selector
|
||||
|
||||
### Common Config Checkbox Persistence
|
||||
|
||||
- Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens (#2191, thanks @zxZeng)
|
||||
|
||||
### Claude Plugin `settings.json` Sync
|
||||
|
||||
- Editing the current provider now syncs back to `settings.json` for the Claude plugin path (#1905, thanks @chengww5217)
|
||||
|
||||
### Google Official Gemini Env Preservation
|
||||
|
||||
- Saving the Google Official Gemini provider no longer clobbers the `env` block
|
||||
|
||||
### OpenCode JSON5 Parser for Trailing Commas
|
||||
|
||||
- OpenCode config reads now tolerate trailing commas via a JSON5 parser (#2023, thanks @wwminger)
|
||||
|
||||
### Preset Refreshes
|
||||
|
||||
- Refreshed stale context windows for DeepSeek and Claude 1M
|
||||
- Refreshed stale model IDs; backfilled Hermes model lists
|
||||
- Fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork
|
||||
- Pruned unused official Hermes presets
|
||||
|
||||
### Auto-Expand Collapsed Messages on Search Hit
|
||||
|
||||
- Collapsed messages now auto-expand when a search match lands inside hidden content
|
||||
|
||||
### Unknown Subscription Quota Tiers Hidden
|
||||
|
||||
- Provider cards no longer render unknown subscription quota tiers
|
||||
|
||||
### Weekly Limit Label Unified
|
||||
|
||||
- Aligned the `weekly_limit` tier label with the official 7-day naming across locales
|
||||
|
||||
### Root-Level Skill Repo Install
|
||||
|
||||
- Fixed skill installation when the repository root itself is a skill
|
||||
|
||||
### Session ID Parsing Clippy
|
||||
|
||||
- Removed a redundant closure in session ID parsing (clippy warning)
|
||||
|
||||
### Stream Check Default Models Refresh
|
||||
|
||||
- Updated stream-check default probe models to match each vendor's current lineup
|
||||
|
||||
### Skills Import Sync
|
||||
|
||||
- Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database (#2101, thanks @yaoguohh)
|
||||
- The UI no longer shows "installed" while the target app directory is missing the skill
|
||||
|
||||
### Ghostty Session Restore
|
||||
|
||||
- Fixed Ghostty session restore launch by using shell execution with `--working-directory` (#1976, thanks @Suda202)
|
||||
- Avoids `cwd` escaping issues when the path contains spaces or special characters
|
||||
|
||||
---
|
||||
|
||||
## Docs
|
||||
|
||||
### README Sponsor Updates
|
||||
|
||||
- Updated SiliconFlow signup bonus to ¥16
|
||||
- Trimmed the SSSAiCode sponsor blurb
|
||||
- Updated partner logos
|
||||
- Added LemonData as a new sponsor
|
||||
|
||||
### Global Proxy Hint Clarified
|
||||
|
||||
- Clarified the global proxy hint about local routing across all three locales
|
||||
|
||||
### Takeover → Routing Rename
|
||||
|
||||
- Renamed takeover docs to routing and updated anchors across all languages
|
||||
|
||||
### PIPELLM Website URL
|
||||
|
||||
- Updated the PIPELLM sponsor website URL to `code.pipellm.ai`
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Breaking Changes
|
||||
|
||||
### Hermes requires explicit `api_mode`
|
||||
|
||||
- The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`
|
||||
- Users with prior `Auto` configs will be prompted to pick a protocol
|
||||
|
||||
### `ANTHROPIC_REASONING_MODEL` removed from Claude quick-set
|
||||
|
||||
- The legacy field is no longer exposed; existing settings are cleaned up automatically
|
||||
|
||||
### Per-provider proxy configuration removed
|
||||
|
||||
- Migrate to the global Local Routing setting
|
||||
- Existing per-provider proxy values are ignored
|
||||
|
||||
### Database schema v9 → v10
|
||||
|
||||
- Adds `enabled_hermes` columns to `mcp_servers` and `skills`
|
||||
- Auto-migrated with `DEFAULT 0`; no data loss
|
||||
|
||||
### Pricing table reseeded (v8 → v9)
|
||||
|
||||
- The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices
|
||||
|
||||
### XCodeAPI preset removed
|
||||
|
||||
- Users of the XCodeAPI preset should switch to another provider
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ Risk Notice
|
||||
|
||||
This release inherits the risk notices originally introduced in v3.12.3 / v3.13.0 for reverse-proxy-style features.
|
||||
|
||||
**GitHub Copilot Reverse Proxy**: Using Copilot's reverse-proxy path may violate GitHub / Microsoft's terms of service. See [v3.12.3 release notes](v3.12.3-en.md#️-risk-notice).
|
||||
|
||||
**Codex OAuth Reverse Proxy**: Using the Codex OAuth reverse proxy with a ChatGPT subscription may violate OpenAI's terms of service. See [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice).
|
||||
|
||||
By enabling these features, users **accept all associated risks**. CC Switch is not responsible for any account restrictions, warnings, or service suspensions that result from using these features.
|
||||
|
||||
---
|
||||
|
||||
## Download & Installation
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| OS | Minimum Version | Architecture |
|
||||
| ------- | ----------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 or later | x64 |
|
||||
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ----------------------------------------------- |
|
||||
| `CC-Switch-v3.14.0-Windows.msi` | **Recommended** - MSI installer, supports auto-update |
|
||||
| `CC-Switch-v3.14.0-Windows-Portable.zip` | Portable, extract and run, no registry writes |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | -------------------------------------------------------- |
|
||||
| `CC-Switch-v3.14.0-macOS.dmg` | **Recommended** - DMG installer, drag into Applications |
|
||||
| `CC-Switch-v3.14.0-macOS.zip` | Extract and drag into Applications, Universal Binary |
|
||||
| `CC-Switch-v3.14.0-macOS.tar.gz` | For Homebrew installation and auto-update |
|
||||
|
||||
> macOS builds are Apple code-signed and notarized — install directly.
|
||||
|
||||
### Homebrew (macOS)
|
||||
|
||||
```bash
|
||||
brew tap farion1231/ccswitch
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Update:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
| Distribution | Recommended | Installation |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| 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, or use AUR |
|
||||
| Other distros / not sure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,469 @@
|
||||
# CC Switch v3.14.0
|
||||
|
||||
> Hermes Agent が 6 番目の管理対象アプリに、Claude Opus 4.7 をプリセットマトリクス全体へ展開、Gemini Native API プロキシ、「Local Routing」への名称統一、アプリケーションレベルのウィンドウコントロール
|
||||
|
||||
**[中文版 →](v3.14.0-zh.md) | [English →](v3.14.0-en.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.14.0 は、**Hermes Agent を 6 番目の一等管理対象アプリケーション**として CC Switch に取り込み、**Claude Opus 4.7** をアグリゲーターおよび Bedrock プリセットのマトリクス全体に展開することを中心に据えた大型リリースです。Hermes サポートは、データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付きの YAML ベースな `~/.hermes/config.yaml` 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、および Memory エディターを含む専用のフロントエンドパネルをカバーします。Hermes Agent 0.10.0 スキーマに整合する 4 つの API プロトコル(`chat_completions`、`anthropic_messages`、`codex_responses`、`bedrock_converse`)すべてを選択可能です。ユーザーが直接記述した `providers:` dict のエントリは読み取り専用カードとして表示され、深い YAML 設定は Hermes Web UI に委譲されます。
|
||||
|
||||
Hermes に加えて、本リリースでは **Gemini Native API プロキシ**(`api_format = "gemini_native"`)を追加し、プロキシがリクエストを Google の `generateContent` エンドポイントに直接転送できるようにしました(完全なストリーミング、スキーマ変換、シャドウリクエストをサポート)。また、旧「Local Proxy Takeover」を三言語の UI / README / ドキュメント全体で **Local Routing** に統一リネームし、コンポジターが描画するボタンが無反応になり得る Linux Wayland などのシーンで、CC Switch が自前で最小化 / 最大化 / 閉じるボタンを描画できるオプション「**アプリケーションレベルのウィンドウコントロール**」を導入しました。さらにリリース直前に、ツールバーからの `hermes dashboard` 直接起動、LemonData の全アプリプリセット、DDSHub の Codex エンドポイント、および複数の Hermes ヘルスチェックと Usage モーダルの修正が追加されました。
|
||||
|
||||
セッション側では、`@tanstack/react-virtual` によるセッションリストの**仮想化**で数千件のレコードを持つ長い会話も滑らかにスクロールでき、長いメッセージはデフォルトで折り畳まれます。Usage ダッシュボードには**日付範囲ピッカー**(今日 / 1d / 7d / 14d / 30d + カスタム日時カレンダー)とページジャンプ入力が追加され、**Stream Check エラー分類**は色分けされたトーストで提示され、デフォルトの探索モデルが更新され、「モデルが見つからない」レスポンスを個別に識別するようになりました。また、Local Routing が有効な間に公式プロバイダーへの切り替えを**強制的にブロック**する保護を追加し、公式 API トラフィックがローカルプロキシを経由することによるアカウント停止リスクを防ぎます。Pricing データベースは v8 → v9 で再シードされ、約 50 件の新しいモデルエントリ(Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 など)を追加し、いくつかの古い価格を修正しました。
|
||||
|
||||
**リリース日**: 2026-04-21
|
||||
|
||||
**更新規模**: 100 commits | 219 files changed | +20,548 / -3,569 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **Hermes Agent サポート(6 番目の管理対象アプリ)**: データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付き YAML 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、専用フロントエンドパネル、4 つの API プロトコル(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`)
|
||||
- **Claude Opus 4.7 の全面展開**: 適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)、全アグリゲーター / Bedrock プリセットを Opus 4.7 をデフォルト Opus モデルに移行
|
||||
- **Claude `max` エフォートティア**: エフォートのドロップダウンを `high` から `max` に引き上げ
|
||||
- **Gemini Native API プロキシ**: 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` に直接転送可能に(完全なストリーミング / スキーマ変換 / シャドウリクエスト対応)
|
||||
- **GitHub Copilot Enterprise Server**: Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加
|
||||
- **Copilot 交互消費の大幅最適化**: 転送前の thinking ブロック主動削除、`tool_result` メッセージ分類修正、subagent 検出、`x-interaction-id` 課金マージ、孤立 `tool_result` のサニタイズ、Warmup ダウングレードのデフォルト有効化など、premium 交互消費を系統的に削減
|
||||
- **セッションリスト仮想化**: 長い会話が滑らかにスクロール。長いメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
|
||||
- **Codex / OpenClaw セッションタイトル抽出**: 意味のあるタイトルを自動抽出(2 行表示)、OpenClaw の `message_id` 末尾ノイズを除去
|
||||
- **Usage 日付範囲ピッカー**: Today / 1d / 7d / 14d / 30d プリセットタブ + カスタム日時カレンダー。ページネーションリストにページジャンプ入力
|
||||
- **Stream Check エラー分類**: エラーを分類し色分けトーストで提示。デフォルト探索モデル更新。「モデルが見つからない」レスポンスを明示的に検出
|
||||
- **Local Routing 有効時の公式プロバイダー切り替えブロック**: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため、切り替えを強制ブロックして警告トーストを表示
|
||||
- **Pricing データベース刷新(v8 → v9)**: 約 50 件の新しいモデルエントリを追加し、古い価格を修正
|
||||
- **アプリケーションレベルのウィンドウコントロール**: CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定。Linux Wayland での体験を大きく改善
|
||||
- **統一 Skills 管理への Hermes 追加**: Skill のインストール / 有効化 / フィルターが Hermes をカバー
|
||||
- **Hermes / OpenClaw 設定ディレクトリのカスタマイズ**: 設定で `~/.hermes/config.yaml` や `openclaw.json` のカスタム位置を指定可能
|
||||
- **ツールバーからの Hermes Dashboard 起動**: Hermes Web UI のプローブに失敗した際、ツールバーエントリからユーザーの優先ターミナルで `hermes dashboard` を実行可能
|
||||
- **新パートナープリセット**: LemonData を全 6 アプリにわたって追加、DDSHub の Codex エンドポイント、StepFun Step Plan
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### Hermes Agent サポート(6 番目の管理対象アプリ)
|
||||
|
||||
CC Switch は Hermes Agent を Claude / Codex / Gemini / OpenCode / OpenClaw と並ぶ一等の管理対象アプリとして初めてサポートします。
|
||||
|
||||
- **データベースマイグレーション v9 → v10**: `mcp_servers` と `skills` テーブルに `enabled_hermes` カラムを追加(`DEFAULT 0`、自動マイグレーション、データ損失なし)
|
||||
- **YAML 設定の読み書き**: `~/.hermes/config.yaml` をアトミックバックアップ付きで読み書き。`tests/hermes_roundtrip.rs` が OAuth MCP `auth` ブロックの消失や無関係なキーの汚染を防止
|
||||
- **4 つの API プロトコル**: Hermes Agent 0.10.0 と整合する `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`。新しいディープリンクはデフォルトで `chat_completions`
|
||||
- **ユーザー `providers:` dict の読み取り専用表示**: YAML に手書きされたプロバイダーエントリは CC Switch で読み取り専用カードとして表示され、深い設定は Hermes Web UI に委譲
|
||||
- **加算的な切り替え**: Claude / Codex の「上書き」型切り替えと異なり、Hermes ではすべてのプロバイダーが同じ YAML に共存
|
||||
|
||||
### Hermes Memory パネル
|
||||
|
||||
- `MEMORY.md` / `USER.md` を直接編集できる Memory パネルを追加(有効化スイッチ、文字数制限、ライブ保存フロー付き)
|
||||
- Hermes の Prompts エントリを置き換え
|
||||
|
||||
### Hermes プロバイダープリセット(約 50 個)
|
||||
|
||||
- Nous Research、Shengsuanyun(胜算云)、OpenRouter、DeepSeek、Together AI、StepFun、Zhipu GLM、Bailian(百炼)、Kimi、MiniMax、DouBao(豆包)、BaiLing(百灵)、ModelScope(魔搭)、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、Xiaomi MiMo をカバー
|
||||
|
||||
### ツールバーからの Hermes Dashboard 起動
|
||||
|
||||
- Hermes Web UI のプローブに失敗した際、ツールバーエントリがユーザーの優先ターミナルで `hermes dashboard` を実行する確認ダイアログを表示
|
||||
- 一時 bash / batch スクリプト経由で起動。`hermes dashboard` 自身が準備完了後にブラウザを開くため、ポーリングは不要
|
||||
- Memory パネルと Health バナーは既存のトースト動作を維持
|
||||
- オフラインのトーストにあった古い `hermes web` のヒントも修正(正しいコマンドは `hermes dashboard`)
|
||||
- Linux ターミナル検出の順序を変更し、`/usr/bin`、`/bin`、`/usr/local/bin` を stat する前に `which` を試すように
|
||||
|
||||
### Claude Opus 4.7 サポート
|
||||
|
||||
- Claude Opus 4.7 を追加。適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)
|
||||
- 全アグリゲーター / Bedrock プリセットをデフォルト Opus モデルとして Opus 4.7 に移行
|
||||
|
||||
### Claude `max` エフォートティア
|
||||
|
||||
- Claude エフォートドロップダウンを `high` から `max` に引き上げ、より強力な推論容量を解放
|
||||
|
||||
### Gemini Native API プロキシ
|
||||
|
||||
- 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` API に直接転送可能 (#1918, 感謝 @yovinchen)
|
||||
- 完全なストリーミング、スキーマ変換、シャドウリクエストに対応
|
||||
- proxy providers モジュール下に `gemini_url.rs`、`gemini_schema.rs`、`gemini_shadow.rs`、`streaming_gemini.rs`、`transform_gemini.rs` を追加
|
||||
|
||||
### GitHub Copilot Enterprise Server(GHES)
|
||||
|
||||
- Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加 (#2175, 感謝 @hotelbe)
|
||||
|
||||
### セッションリスト仮想化
|
||||
|
||||
- `@tanstack/react-virtual` によりセッションリストを仮想化。数千件のレコードを持つ長い会話も滑らかにスクロール
|
||||
- 長いセッションメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
|
||||
|
||||
### Codex / OpenClaw セッションタイトル抽出
|
||||
|
||||
- Codex と OpenClaw セッションから意味のあるタイトルを自動抽出し、2 行表示
|
||||
- OpenClaw の `message_id` 末尾ノイズを除去
|
||||
|
||||
### Usage 日付範囲ピッカー
|
||||
|
||||
- Usage ダッシュボードに日付範囲セレクターを追加。プリセットタブ(Today / 1d / 7d / 14d / 30d)+ カスタム日時カレンダー (#2002, 感謝 @yovinchen)
|
||||
- ページネーションリストにページジャンプ入力を追加
|
||||
|
||||
### モデルマッピングのクイック入力
|
||||
|
||||
- プロバイダーフォームのモデルマッピングフィールドの横にクイック入力ボタンを追加し、編集を高速化 (#2179, 感謝 @lispking)
|
||||
|
||||
### Stream Check エラー分類
|
||||
|
||||
- Stream Check エラーを分類し、色分けトーストとして提示
|
||||
- デフォルトの探索モデルを各ベンダーの現行ラインナップに合わせて更新
|
||||
- 「モデルが見つからない」レスポンスを明示的に検出
|
||||
|
||||
### Local Routing 有効時の公式プロバイダー切り替えブロック
|
||||
|
||||
- Local Routing が有効な状態で公式プロバイダーに切り替えようとすると、強制的にブロックされ警告トーストが表示される
|
||||
- 理由: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため
|
||||
|
||||
### Pricing データベース刷新(v8 → v9)
|
||||
|
||||
- マイグレーション時に定価テーブルを再シード
|
||||
- Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 などを含む約 50 件の新しいモデルエントリを追加
|
||||
- DeepSeek、Kimi K2.5 などの古い価格を修正
|
||||
|
||||
### アプリケーションレベルのウィンドウコントロール
|
||||
|
||||
- CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定を追加。システム装飾の代わりに使用 (#1119, 感謝 @git1677967754)
|
||||
- コンポジター描画ボタンが無反応になり得る Linux Wayland での体験を大きく改善
|
||||
|
||||
### 統一 Skills 管理への Hermes 追加
|
||||
|
||||
- 統一 Skills サーフェスに Hermes を追加
|
||||
- Skill のインストール / 有効化 / フィルターが、Claude / Codex / Gemini / OpenCode / OpenClaw と並んで Hermes アプリをカバー
|
||||
|
||||
### OpenClaw 設定ディレクトリのカスタマイズ
|
||||
|
||||
- CC Switch が参照する `openclaw.json` のカスタム位置を設定できるオプションを追加 (#1518, 感謝 @mrFranklin)
|
||||
|
||||
### Hermes 設定ディレクトリのカスタマイズ
|
||||
|
||||
- CC Switch が参照する `~/.hermes/config.yaml` のカスタム位置を設定できるオプションを追加。データ駆動 dispatch でサポート
|
||||
|
||||
### StepFun Step Plan プリセット
|
||||
|
||||
- StepFun Step Plan(EN / ZH)プロバイダープリセットを追加 (#2155, 感謝 @hengm3467)
|
||||
|
||||
### New API 用量スクリプトテンプレート
|
||||
|
||||
- New API の用量スクリプトテンプレートに User-Agent ヘッダーを追加し、上流互換性を向上
|
||||
|
||||
### LemonData プロバイダープリセット(全 6 アプリ)
|
||||
|
||||
- LemonData をサードパーティパートナープリセットとして Claude、Codex、Gemini、OpenCode、OpenClaw、Hermes の全 6 アプリに登録
|
||||
- アイコンアセットと zh / en / ja 三言語のパートナー推奨文面を追加
|
||||
- Claude プリセットは `ANTHROPIC_API_KEY` 認証を使用。OpenAI 互換アプリは `gpt-5.4` をターゲット
|
||||
|
||||
### DDSHub Codex プリセット
|
||||
|
||||
- DDSHub の Codex 互換エンドポイントを追加(Claude サービスと同じホスト)
|
||||
- ベース URL は `/v1` サフィックスを省略(ゲートウェイが OpenAI SDK パスを自動ルーティング)
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### 「Local Proxy Takeover」→「Local Routing」
|
||||
|
||||
- 三言語の UI 文言、README、ドキュメント全体で用語を統一リネーム
|
||||
- 機能的な動作は変更なし
|
||||
|
||||
### Hermes `Auto` api_mode の削除
|
||||
|
||||
- ユーザーは明示的にプロトコルを選択する必要あり。新しいディープリンクはデフォルトで `chat_completions`
|
||||
- URL ベースのヒューリスティックによる意外な挙動を排除
|
||||
|
||||
### Hermes プロバイダーフォーム
|
||||
|
||||
- API モードドロップダウンとプロバイダー単位のモデルエディターを追加
|
||||
- アクティブなプロバイダーを切り替える際、プロバイダー単位のモデルをトップレベルの `model:` にバインド
|
||||
|
||||
### Hermes 深い設定の委譲
|
||||
|
||||
- 深い YAML 設定は CC Switch フォームで重複させず、「Hermes Web UI を起動」ボタン経由で Web UI に直接委譲
|
||||
|
||||
### Hermes ツールバーレイアウト
|
||||
|
||||
- Hermes Web UI ボタンのアイコンを `ExternalLink` から `LayoutDashboard` に変更(クリック時に単に URL を開くのではなく `hermes dashboard` を起動する場合があるため、パネル型アイコンのほうが意味的に正確)
|
||||
- MCP をツールバーの末尾に移動し、Hermes のレイアウトを Claude / Codex / Gemini / OpenCode と揃える
|
||||
|
||||
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
|
||||
|
||||
- 推論能力とモデル選択を分離。レガシーフィールドは Quick-Set フォームから除外
|
||||
|
||||
### プロバイダー単位のプロキシ設定を削除
|
||||
|
||||
- グローバルな Local Routing に統合
|
||||
- プロバイダー単位のプロキシトグルと関連ストレージは削除済み
|
||||
|
||||
### ツールバーアイコンボタン幅の統一
|
||||
|
||||
- Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes パネルの間でアイコンボタン幅を正規化し、ヘッダーの見た目を統一
|
||||
|
||||
### Rust Toolchain を 1.95 にピン留め
|
||||
|
||||
- ワークスペース全体で clippy 1.95 の提案を採用し、nightly ドリフトを防ぐためツールチェーンをピン留め
|
||||
|
||||
### トレイメニュー ID 定数
|
||||
|
||||
- トレイ識別子をハードコーディング文字列 `"main"` から `TRAY_ID` 定数(`"cc-switch"`)に移行。すべての呼び出し箇所で同期 (#1978, 感謝 @lidaxian121)
|
||||
|
||||
### Copilot 交互消費の大幅最適化
|
||||
|
||||
Copilot リバースプロキシの premium 交互消費を削減するための系統的な最適化。以下の複数の改善をカバー:
|
||||
|
||||
- **転送前に thinking ブロックを主動削除**: Anthropic の `thinking` / `redacted_thinking` ブロックは OpenAI 互換エンドポイントに拒否される。従来は上流でリクエストが失敗して premium 交互を 1 回消費した後、`thinking_rectifier` によってリトライされていた。新しい主動削除ステップ(Copilot 最適化パイプラインの 3.5 ステップ目、`tool_result` マージ後)により、この無駄な premium 消費を直接解消
|
||||
- **リクエスト分類の修正**: `tool_result` を含むメッセージをユーザー発起の新規リクエストではなく、エージェント継続として分類。ツール呼び出しが毎回 premium 交互としてカウントされる問題を防止
|
||||
- **subagent 検出**: `__SUBAGENT_MARKER__` と `metadata._agent_` フォールバックで subagent を識別し、`x-interaction-type=conversation-subagent` を設定
|
||||
- **決定論的 `x-interaction-id` による課金マージ**: セッション ID から `x-interaction-id` を導出し、同一セッション内の複数リクエストを 1 回の課金交互に統合
|
||||
- **孤立 `tool_result` のサニタイズ**: 孤立した `tool_result` を整理し、上流エラーによるリトライおよび重複課金を防止
|
||||
- **Warmup ダウングレードをデフォルトで有効化**: `gpt-5-mini` をデフォルトのダウングレードモデルとして使用
|
||||
- **最適化パイプラインの並び替え**: classify → sanitize → merge → warmup の順序で、分類が生の `tool_result` セマンティクスを参照可能に
|
||||
- `CopilotOptimizerConfig` のデフォルト値の不一致を修正(`gpt-5-mini` に統一)
|
||||
|
||||
### 用量スクリプトのイントラネットサポート
|
||||
|
||||
- 用量スクリプトからプライベート IP / 不審なホスト名のブロッキングを削除し、エンタープライズイントラネット、Docker、自己ホスト API エンドポイントを解放
|
||||
- ビルトインテンプレートは引き続き HTTPS(localhost を除く)と同一オリジンチェックを強制。カスタムテンプレートはユーザー制御のまま、リクエスト URL のチェックをスキップ
|
||||
|
||||
### Failover キューの備考表示
|
||||
|
||||
- プロバイダーの備考が failover キューセレクターとキュー行に表示され、マルチプロバイダーキューでの識別が容易に (#2138, 感謝 @Coconut-Fish)
|
||||
|
||||
---
|
||||
|
||||
## バグ修正
|
||||
|
||||
### 最大化後のツールバー自動折り畳みラッチ
|
||||
|
||||
- ウィンドウの最大化 / 復元後、ツールバーが折り畳まれたままになる問題を修正。折り畳み判定はサイズ変更時に再評価される
|
||||
|
||||
### Hermes YAML 汚染と OAuth MCP `auth` 消失
|
||||
|
||||
- CC Switch 経由でラウンドトリップしても OAuth MCP `auth` ブロックが消失したり、無関係な YAML キーが汚染されたりしなくなった
|
||||
- `tests/hermes_roundtrip.rs` をガードテストとして追加
|
||||
|
||||
### Hermes アクティブプロバイダー表示
|
||||
|
||||
- Hermes UI がアクティブプロバイダーを正しく表示するようになり、追加 / 有効化 / 削除アクションが正しく動作
|
||||
|
||||
### Hermes プロバイダーの永続化
|
||||
|
||||
- プロバイダーは `custom_providers:` の下に永続化され、`api_mode` と `model` が再起動 / 設定再読み込みを生き延びる
|
||||
|
||||
### Hermes ヘルスチェックが OpenClaw のスキーマを流用していた問題
|
||||
|
||||
- 以前 Hermes プロバイダーは `check_additive_app_stream`(OpenClaw のディスパッチャー)にルーティングされており、これは camelCase の `baseUrl` / `apiKey` / `api` を読むため、Hermes フィールドをすべて記入しても "OpenClaw provider is missing baseUrl" と表示されていた
|
||||
- `check_hermes_stream` を導入し、Hermes 専用のエクストラクターで `api_mode`(`chat_completions` / `anthropic_messages` / `codex_responses`)を対応する `check_claude_stream` の `api_format` にマッピング。`bedrock_converse` は非対応として返す
|
||||
- URL / API キーの抽出前に `api_mode` を解決することで、`bedrock_converse` を選んだユーザーには「missing base_url」という誤解を招くメッセージではなく実際の原因が表示される
|
||||
|
||||
### Hermes / OpenClaw 向け Usage クエリモーダル
|
||||
|
||||
- `getProviderCredentials` が Hermes(snake_case の `base_url` / `api_key`)と OpenClaw(camelCase の `baseUrl` / `apiKey`)のフラットな `settingsConfig` フィールドを読むようになり、SiliconFlow などマッチするプロバイダーで「official balance」テンプレートが自動選択される
|
||||
- BALANCE と TOKEN_PLAN テストパスをリファクタリングし、`env.ANTHROPIC_*` を直接再読するのではなく、事前計算された `providerCredentials` を再利用するように変更。これにより非 Claude アプリでキーが設定されていても「empty key」エラーが出ていた問題を修正
|
||||
|
||||
### Codex `cache_control` 保持
|
||||
|
||||
- Codex フォーマット変換中に system prompt をマージする際の `cache_control` を保持 (#1946, 感謝 @yovinchen)
|
||||
|
||||
### Claude プロンプトキャッシュキーのリーク
|
||||
|
||||
- Claude chat 変換時にプロンプトキャッシュキーを送信しないように修正 (#2003, 感謝 @yovinchen)
|
||||
|
||||
### プロキシ Hop-by-Hop レスポンスヘッダーの削除
|
||||
|
||||
- RFC 7230 に従ってプロキシレスポンスの hop-by-hop ヘッダー(Connection、Keep-Alive、Transfer-Encoding など)を削除 (#2060, 感謝 @yovinchen)
|
||||
|
||||
### プロキシの寛容な CORS レイヤー削除
|
||||
|
||||
- プロキシの寛容な CORS レイヤーを削除 (#1915, 感謝 @zerone0x)
|
||||
|
||||
### プロキシトーストでのバックエンドエラー詳細表示
|
||||
|
||||
- プロキシ関連のトーストメッセージで、汎用的な失敗文字列ではなくバックエンドのエラーペイロードの詳細を表示
|
||||
|
||||
### Usage ログの重複排除
|
||||
|
||||
- プロキシとセッションログの用量レコードを重複排除し、同じリクエストが二重にカウントされないように修正
|
||||
- リクエストログの時間範囲をダッシュボードの 1d / 7d / 30d セレクターと同期
|
||||
|
||||
### Common Config チェックボックスの永続化
|
||||
|
||||
- Claude / Codex / Gemini の common-config トグルのチェック状態が再オープンをまたいで正しく保持されるように修正 (#2191, 感謝 @zxZeng)
|
||||
|
||||
### Claude プラグイン `settings.json` 同期
|
||||
|
||||
- 現在のプロバイダーを編集すると、Claude プラグインパスの `settings.json` に同期されるように修正 (#1905, 感謝 @chengww5217)
|
||||
|
||||
### Google Official Gemini の env 保持
|
||||
|
||||
- Google Official Gemini プロバイダーを保存しても `env` ブロックが消えないように修正
|
||||
|
||||
### OpenCode の JSON5 による末尾カンマ解析
|
||||
|
||||
- OpenCode 設定読み取りが JSON5 パーサーにより末尾カンマを許容するように修正 (#2023, 感謝 @wwminger)
|
||||
|
||||
### プリセットの刷新
|
||||
|
||||
- DeepSeek と Claude 1M の古いコンテキストウィンドウを刷新
|
||||
- 古いモデル ID を刷新。Hermes のモデルリストをバックフィル
|
||||
- Nous エンドポイントを修正し、Hermes のプレースホルダーアイコンを Nous ブランドのアートワークに置き換え
|
||||
- 未使用の公式 Hermes プリセットを整理
|
||||
|
||||
### 検索ヒット時の折り畳みメッセージの自動展開
|
||||
|
||||
- 隠されたコンテンツ内部で検索マッチが発生した場合、折り畳みメッセージを自動展開してマッチを示す
|
||||
|
||||
### 不明なサブスクリプション配額ティアの非表示
|
||||
|
||||
- プロバイダーカードは不明なサブスクリプション配額ティアを表示しないように変更
|
||||
|
||||
### weekly_limit ラベルの統一
|
||||
|
||||
- `weekly_limit` ティアラベルを公式の「7 日」命名にロケール間で揃えた
|
||||
|
||||
### ルートレベルの Skill リポジトリインストール
|
||||
|
||||
- リポジトリのルート自体が skill の場合のインストール失敗を修正
|
||||
|
||||
### Session ID 解析の clippy 警告
|
||||
|
||||
- session ID 解析内の冗長なクロージャを削除(clippy 警告)
|
||||
|
||||
### Stream Check デフォルトモデルの刷新
|
||||
|
||||
- Stream Check のデフォルト探索モデルを各ベンダーの現行ラインナップに合わせて更新
|
||||
|
||||
### Skills インポートの同期
|
||||
|
||||
- インポートされた Skills はデータベースに記録されるだけでなく、有効化されたアプリディレクトリにも即座に同期されるように変更 (#2101, 感謝 @yaoguohh)
|
||||
- UI が「インストール済み」と表示しているのに対象アプリディレクトリに skill が存在しない状態を解消
|
||||
|
||||
### Ghostty セッション復元
|
||||
|
||||
- Ghostty セッション復元の起動を `--working-directory` 付きのシェル実行に変更 (#1976, 感謝 @Suda202)
|
||||
- パスにスペースや特殊文字が含まれる場合の `cwd` エスケープ問題を回避
|
||||
|
||||
---
|
||||
|
||||
## ドキュメント
|
||||
|
||||
### README スポンサー更新
|
||||
|
||||
- SiliconFlow のサインアップボーナスを ¥16 に更新
|
||||
- SSSAiCode のスポンサー文面を簡潔化
|
||||
- パートナーロゴを更新
|
||||
- 新しいスポンサーとして LemonData を追加
|
||||
|
||||
### グローバルプロキシヒントの明確化
|
||||
|
||||
- 三言語でグローバルプロキシと Local Routing の関係を明確化
|
||||
|
||||
### Takeover → Routing ドキュメントのリネーム
|
||||
|
||||
- テイクオーバー関連ドキュメントを三言語で routing にリネームし、アンカーを同期更新
|
||||
|
||||
### PIPELLM ウェブサイト URL
|
||||
|
||||
- PIPELLM スポンサーのウェブサイト URL を `code.pipellm.ai` に更新
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要な変更(Breaking)
|
||||
|
||||
### Hermes は明示的な `api_mode` が必須
|
||||
|
||||
- `Auto` モードは廃止。インポートまたはディープリンクで取得したプロバイダーはデフォルトで `chat_completions`
|
||||
- 既存の `Auto` 設定のユーザーはプロトコルを選択するよう促される
|
||||
|
||||
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
|
||||
|
||||
- レガシーフィールドは公開されなくなった。既存の設定は自動的にクリーンアップされる
|
||||
|
||||
### プロバイダー単位のプロキシ設定を削除
|
||||
|
||||
- グローバル Local Routing 設定に移行
|
||||
- 既存のプロバイダー単位のプロキシ値は無視される
|
||||
|
||||
### データベーススキーマ v9 → v10
|
||||
|
||||
- `mcp_servers` と `skills` に `enabled_hermes` カラムを追加
|
||||
- `DEFAULT 0` で自動マイグレーション、データ損失なし
|
||||
|
||||
### Pricing テーブルの再シード(v8 → v9)
|
||||
|
||||
- 新しいモデルと修正済み価格を取り込むため、初回起動時に `model_pricing` テーブルがクリアされ再シードされる
|
||||
|
||||
### XCodeAPI プリセットの削除
|
||||
|
||||
- XCodeAPI プリセットを使用していたユーザーは別のプロバイダーに切り替える必要がある
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ リスクに関する注意事項
|
||||
|
||||
本リリースは、リバースプロキシ型機能について v3.12.3 / v3.13.0 で提起された既存のリスク注意事項を継承します。
|
||||
|
||||
**GitHub Copilot リバースプロキシ**: Copilot のリバースプロキシパスを使用すると、GitHub / Microsoft の利用規約に違反する可能性があります。詳細は [v3.12.3 リリースノート](v3.12.3-ja.md#️-リスクに関する注意事項) を参照してください。
|
||||
|
||||
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションで Codex OAuth リバースプロキシを使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 リリースノート](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
|
||||
|
||||
これらの機能を有効にすることで、ユーザーは**すべての関連リスクを自己責任で受諾**したものとみなされます。CC Switch はこれらの機能の使用に起因するアカウントの制限、警告、サービス停止について一切の責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロード・インストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から対応バージョンをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| OS | 最小バージョン | アーキテクチャ |
|
||||
| ------- | ---------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表参照 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | ------------------------------------------- |
|
||||
| `CC-Switch-v3.14.0-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
|
||||
| `CC-Switch-v3.14.0-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ不要 |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | -------------------------------------------------------- |
|
||||
| `CC-Switch-v3.14.0-macOS.dmg` | **推奨** - DMG インストーラー、Applications にドラッグ |
|
||||
| `CC-Switch-v3.14.0-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.14.0-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
> macOS 版は Apple のコード署名および公証済みで、直接インストールして使用できます。
|
||||
|
||||
### 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,468 @@
|
||||
# CC Switch v3.14.0
|
||||
|
||||
> Hermes Agent 成为第 6 个受管应用、Claude Opus 4.7 全面接入、Gemini Native API 代理、Local Routing 统一重命名、应用级窗口控件
|
||||
|
||||
**[English →](v3.14.0-en.md) | [日本語版 →](v3.14.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.14.0 是一次大版本更新,核心焦点是把 **Hermes Agent 作为第 6 个一等受管应用**接入 CC Switch,并把 **Claude Opus 4.7** 铺设到全部聚合器与 Bedrock 预设矩阵。Hermes 支持覆盖数据库 v9 → v10 迁移、完整的 Rust 命令面、基于 YAML 的 `~/.hermes/config.yaml` 读写(含原子备份)、MCP 同步、Skills 同步、SQLite + JSONL 会话管理,以及专属的前端面板和 Memory 编辑面板;与 Hermes Agent 0.10.0 schema 对齐的四种协议(`chat_completions`、`anthropic_messages`、`codex_responses`、`bedrock_converse`)全部可选。用户自行维护的 `providers:` dict 条目以只读卡片形式呈现,深度 YAML 配置则直接委托给 Hermes Web UI。
|
||||
|
||||
除了 Hermes,本次还新增了 **Gemini Native API 代理**(`api_format = "gemini_native"`),让代理可以把请求直接转发到 Google 的 `generateContent` 端点,完整支持流式、schema 转换和 shadow 请求;把老的 "Local Proxy Takeover" 在三语 UI / README / 文档中统一重命名为 **Local Routing**;新增 **应用级窗口控件**,在 Linux Wayland 等合成器绘制按钮失灵的场景下可选让 CC Switch 自绘最小化 / 最大化 / 关闭按钮;并在本版本发布前额外合入了从工具栏直接启动 `hermes dashboard`、LemonData 全应用预设、DDSHub Codex 端点以及若干 Hermes 健康检查与 Usage 模态框的修复。
|
||||
|
||||
会话侧通过 `@tanstack/react-virtual` **虚拟化会话列表**,让上千条记录的长会话也能流畅滚动,长消息默认折叠;Usage 面板新增**日期范围选择器**(今日 / 1d / 7d / 14d / 30d + 自定义日期时间)和翻页输入;**Stream Check 错误分类**以彩色 toast 呈现,默认探测模型重新梳理,"模型不存在"响应被单独识别;并新增在 Local Routing 激活时**阻止切换到官方供应商**的保护,以免官方流量被引入本地代理造成账号风险。Pricing 数据库 v8 → v9 重新种入约 50 个新模型条目(包括 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 等),并修正了多项陈旧价格。
|
||||
|
||||
**发布日期**:2026-04-21
|
||||
|
||||
**更新规模**:100 commits | 219 files changed | +20,548 / -3,569 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **Hermes Agent 支持(第 6 个受管应用)**:数据库 v9 → v10 迁移、完整 Rust 命令面、YAML 读写带原子备份、MCP 同步、Skills 同步、SQLite + JSONL 会话管理、专属前端面板、四种 API 协议(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`)
|
||||
- **Claude Opus 4.7 全面接入**:自适应思维白名单、按百万 token 定价种子、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀),全部聚合器 / Bedrock 预设升级为默认 Opus 模型
|
||||
- **Claude `max` 推理力度**:推理下拉从 `high` 升级到 `max`
|
||||
- **Gemini Native API 代理**:新增 `api_format = "gemini_native"`,代理可直达 Google `generateContent`,完整流式 / schema 转换 / shadow 请求
|
||||
- **GitHub Copilot 企业版**:为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置
|
||||
- **Copilot 次数消耗深度优化**:转发前主动剥离 thinking 块、`tool_result` 消息归类修正、subagent 检测、`x-interaction-id` 合并计费、orphan `tool_result` 清理、默认启用 warmup 降级 —— 系统性降低 premium 交互消耗
|
||||
- **会话列表虚拟化**:长会话流畅滚动,长消息默认折叠降低文字布局成本
|
||||
- **Codex / OpenClaw 会话标题提取**:自动抽取有意义标题,两行显示,剥离 OpenClaw `message_id` 尾噪声
|
||||
- **Usage 日期范围选择器**:Today / 1d / 7d / 14d / 30d 预设 + 自定义日期时间日历;分页列表支持页码跳转输入
|
||||
- **Stream Check 错误分类**:错误按类别分色 toast;默认探测模型刷新;单独识别 "model not found"
|
||||
- **Local Routing 激活时阻止官方供应商切换**:官方流量走本地代理有账号暂停风险,强制拦截并 toast 警告
|
||||
- **Pricing 数据库刷新(v8 → v9)**:新增 ~50 条模型条目并修正陈旧价格
|
||||
- **应用级窗口控件**:可选让 CC Switch 自绘 min/max/close,显著改善 Linux Wayland 体验
|
||||
- **Hermes 接入统一 Skills 管理**:Skills 安装 / 启用 / 过滤现覆盖 Hermes
|
||||
- **Hermes / OpenClaw 配置目录自定义**:在设置里指定 `~/.hermes/config.yaml` 或 `openclaw.json` 的自定义位置
|
||||
- **从工具栏启动 Hermes Dashboard**:Web UI 探测失败时,点击可在用户首选终端中启动 `hermes dashboard`
|
||||
- **新合作伙伴预设**:LemonData 覆盖全部 6 个应用;DDSHub 新增 Codex 端点;StepFun Step Plan
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### Hermes Agent 支持(第 6 个受管应用)
|
||||
|
||||
CC Switch 首次支持 Hermes Agent 作为一等受管应用,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列。
|
||||
|
||||
- **数据库迁移 v9 → v10**:为 `mcp_servers` 和 `skills` 表新增 `enabled_hermes` 列(`DEFAULT 0` 自动迁移,无数据丢失)
|
||||
- **YAML 配置读写**:`~/.hermes/config.yaml` 读写带原子备份;`tests/hermes_roundtrip.rs` 守护不损坏不相关键和 OAuth MCP `auth` 块
|
||||
- **四种 API 协议**:与 Hermes Agent 0.10.0 对齐的 `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`;新 deeplink 默认为 `chat_completions`
|
||||
- **用户 `providers:` dict 只读呈现**:用户在 YAML 里手写的 providers 条目在 CC Switch 中以只读卡片展示,深度配置跳转到 Hermes Web UI
|
||||
- **累加式切换**:与 Claude / Codex 的"覆盖式"切换不同,Hermes 所有供应商共存于同一 YAML
|
||||
|
||||
### Hermes Memory 面板
|
||||
|
||||
- 新增 Memory 面板直接编辑 `MEMORY.md` / `USER.md`,带启用开关、字符数限制和保存流
|
||||
- 替换 Hermes 的 Prompts 入口
|
||||
|
||||
### Hermes 供应商预设(约 50 个)
|
||||
|
||||
- 覆盖 Nous Research、胜算云、OpenRouter、DeepSeek、Together AI、StepFun、智谱 GLM、百炼、Kimi、MiniMax、豆包、百灵、魔搭、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、小米 MiMo
|
||||
|
||||
### 从工具栏启动 Hermes Dashboard
|
||||
|
||||
- Hermes Web UI 探测失败时,工具栏按钮改为弹出确认框,提供在用户首选终端里运行 `hermes dashboard`
|
||||
- 通过临时 bash / batch 脚本启动,`hermes dashboard` 就绪后自动打开浏览器,无需轮询
|
||||
- Memory 面板和 Health banner 保留原有 toast 行为
|
||||
- 顺便修正了离线 toast 里过时的 `hermes web` 提示(正确命令是 `hermes dashboard`)
|
||||
- Linux 终端探测改为先 `which` 后 stat,提升兼容性
|
||||
|
||||
### Claude Opus 4.7 支持
|
||||
|
||||
- 新增 Claude Opus 4.7 及其自适应思维白名单、按百万 token 定价种子、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀)
|
||||
- 全部聚合器 / Bedrock 预设升级为默认 Opus 模型
|
||||
|
||||
### Claude `max` 推理力度
|
||||
|
||||
- Claude 推理下拉从 `high` 升级到 `max`,解锁更强的思考容量
|
||||
|
||||
### Gemini Native API 代理
|
||||
|
||||
- 新增 `api_format = "gemini_native"`,代理可直接转发到 Google `generateContent` API (#1918, 感谢 @yovinchen)
|
||||
- 完整支持流式、schema 转换、shadow 请求
|
||||
- 在 proxy providers 模块下新增 `gemini_url.rs`、`gemini_schema.rs`、`gemini_shadow.rs`、`streaming_gemini.rs`、`transform_gemini.rs`
|
||||
|
||||
### GitHub Copilot 企业版(GHES)
|
||||
|
||||
- 为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置 (#2175, 感谢 @hotelbe)
|
||||
|
||||
### 会话列表虚拟化
|
||||
|
||||
- 通过 `@tanstack/react-virtual` 虚拟化会话列表,上千条记录流畅滚动
|
||||
- 长会话消息默认折叠,减少文字布局开销
|
||||
|
||||
### Codex / OpenClaw 会话标题提取
|
||||
|
||||
- Codex 和 OpenClaw 会话自动抽取有意义的标题,两行显示
|
||||
- 剥离 OpenClaw `message_id` 后缀噪声
|
||||
|
||||
### Usage 日期范围选择器
|
||||
|
||||
- Usage 面板新增日期范围选择器,预设 Tab(Today / 1d / 7d / 14d / 30d)+ 自定义日期 + 时间日历 (#2002, 感谢 @yovinchen)
|
||||
- 分页列表新增页码跳转输入
|
||||
|
||||
### 模型映射快速填入
|
||||
|
||||
- 供应商表单的模型映射字段旁新增快速填入按钮,加快编辑 (#2179, 感谢 @lispking)
|
||||
|
||||
### Stream Check 错误分类
|
||||
|
||||
- 按类别为 Stream Check 错误上色并以 toast 呈现
|
||||
- 刷新所有厂商默认探测模型到当前主力机型
|
||||
- 对 "model not found" 响应做单独识别
|
||||
|
||||
### Local Routing 激活时阻止官方供应商切换
|
||||
|
||||
- 在 Local Routing 激活状态下,切换到官方供应商会被强制拦截并弹出警告 toast
|
||||
- 原因:官方 API 流量经由本地代理存在账号暂停风险
|
||||
|
||||
### Pricing 数据库刷新(v8 → v9)
|
||||
|
||||
- 迁移时重新种入定价表
|
||||
- 新增约 50 条模型条目,覆盖 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1
|
||||
- 修正 DeepSeek、Kimi K2.5 等陈旧价格
|
||||
|
||||
### 应用级窗口控件
|
||||
|
||||
- 新增可选设置,让 CC Switch 自绘最小化 / 切换最大化 / 关闭按钮,代替系统装饰 (#1119, 感谢 @git1677967754)
|
||||
- 在合成器按钮可能失灵的 Linux Wayland 上显著改善体验
|
||||
|
||||
### Hermes 接入统一 Skills 管理
|
||||
|
||||
- 统一的 Skills 界面新增 Hermes
|
||||
- Skills 安装 / 启用 / 过滤现覆盖 Hermes,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列
|
||||
|
||||
### OpenClaw 配置目录自定义
|
||||
|
||||
- 新增设置项,允许把 CC Switch 指向自定义的 `openclaw.json` 位置 (#1518, 感谢 @mrFranklin)
|
||||
|
||||
### Hermes 配置目录自定义
|
||||
|
||||
- 新增设置项,允许把 CC Switch 指向自定义的 `~/.hermes/config.yaml` 位置,底层通过数据驱动 dispatch
|
||||
|
||||
### StepFun Step Plan 预设
|
||||
|
||||
- 新增 StepFun Step Plan(EN / ZH)供应商预设 (#2155, 感谢 @hengm3467)
|
||||
|
||||
### New API 用量脚本模板
|
||||
|
||||
- 为 New API 用量脚本模板新增 User-Agent 头,提升上游兼容性
|
||||
|
||||
### LemonData 全应用预设
|
||||
|
||||
- LemonData 作为第三方合作伙伴预设覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 全部 6 个应用
|
||||
- 含图标资源和 zh / en / ja 三语合作伙伴推广文案
|
||||
- Claude 预设使用 `ANTHROPIC_API_KEY` 认证,OpenAI 兼容应用目标为 `gpt-5.4`
|
||||
|
||||
### DDSHub Codex 预设
|
||||
|
||||
- 新增 DDSHub 的 Codex 兼容端点(与 Claude 服务同 host)
|
||||
- base URL 省略 `/v1` 后缀,由网关自动路由 OpenAI SDK 路径
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### "Local Proxy Takeover" → "Local Routing"
|
||||
|
||||
- 三语 UI 文案、README、文档中全部统一重命名
|
||||
- 功能行为保持不变
|
||||
|
||||
### Hermes `Auto` api_mode 移除
|
||||
|
||||
- 用户必须显式选择协议;新 deeplink 默认为 `chat_completions`
|
||||
- 消除了基于 URL 的启发式识别带来的意外
|
||||
|
||||
### Hermes 供应商表单
|
||||
|
||||
- 新增 API mode 下拉和按供应商的模型编辑器
|
||||
- 切换激活供应商时,把按供应商的模型绑定到顶层 `model:`
|
||||
|
||||
### Hermes 深度配置委托
|
||||
|
||||
- 深度 YAML 配置不再在 CC Switch 表单里重复,直接通过"启动 Hermes Web UI"按钮交给 Web UI
|
||||
|
||||
### Hermes 工具栏布局
|
||||
|
||||
- Web UI 按钮图标从 `ExternalLink` 换成 `LayoutDashboard` —— 点击可能启动 `hermes dashboard` 而非仅仅打开 URL,面板式图标语义更准
|
||||
- MCP 移到工具栏末尾,与 Claude / Codex / Gemini / OpenCode 的布局对齐
|
||||
|
||||
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
|
||||
|
||||
- 把推理能力和模型选择解耦,quick-set 表单不再暴露该遗留字段
|
||||
|
||||
### 按供应商代理配置移除
|
||||
|
||||
- 统一到全局的 Local Routing
|
||||
- 按供应商的代理开关和存储都已移除
|
||||
|
||||
### 统一工具栏图标按钮宽度
|
||||
|
||||
- 在 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 面板之间规格化图标按钮宽度,表头视觉一致
|
||||
|
||||
### Rust Toolchain 锁定 1.95
|
||||
|
||||
- 全仓库采纳 clippy 1.95 建议并锁定 toolchain,防止 nightly 漂移
|
||||
|
||||
### 托盘菜单 ID 常量
|
||||
|
||||
- 托盘标识符从硬编码字符串 `"main"` 改为 `TRAY_ID` 常量(`"cc-switch"`),所有调用点同步 (#1978, 感谢 @lidaxian121)
|
||||
|
||||
### Copilot 次数消耗深度优化
|
||||
|
||||
一次系统性优化专门降低 Copilot 反向代理的 premium 交互消耗,涵盖以下多项改进:
|
||||
|
||||
- **转发前主动剥离 thinking 块**:Anthropic 的 `thinking` / `redacted_thinking` 块会被 OpenAI 兼容端点拒绝,过去一次请求先失败消耗一次 premium 交互、再由 `thinking_rectifier` 触发重试。新增主动剥离步骤(Copilot 优化管线第 3.5 步,位于 `tool_result` 合并之后),直接省掉那一次无谓的 premium 消耗
|
||||
- **请求分类修正**:含 `tool_result` 的消息归类为代理继续,而不是用户发起的新请求 —— 避免每次工具调用都被错误计入 premium 次数
|
||||
- **subagent 检测**:通过 `__SUBAGENT_MARKER__` 和 `metadata._agent_` 回退识别 subagent,设置 `x-interaction-type=conversation-subagent`
|
||||
- **确定性 `x-interaction-id` 合并计费**:从 session ID 推导 `x-interaction-id`,把同一会话内的多次请求合并为一次计费交互
|
||||
- **Orphan `tool_result` 清理**:清理孤立的 `tool_result`,避免触发上游错误导致重试和重复计费
|
||||
- **Warmup 降级默认开启**:使用 `gpt-5-mini` 作为默认降级模型
|
||||
- **优化管线重排**:classify → sanitize → merge → warmup,让分类看到原始 `tool_result` 语义
|
||||
- 修复 `CopilotOptimizerConfig` 默认值不一致(统一到 `gpt-5-mini`)
|
||||
|
||||
### 用量脚本内网支持
|
||||
|
||||
- 移除 usage script 的私网 IP / 可疑主机名屏蔽,解锁企业内网、Docker、自建 API 端点
|
||||
- 内置模板仍强制 HTTPS(localhost 除外)和同源检查;自定义模板仍由用户控制,这类请求 URL 检查跳过
|
||||
|
||||
### Failover 队列备注
|
||||
|
||||
- 供应商备注现在在 failover 队列选择器和队列行中显示,方便在多供应商队列里识别 (#2138, 感谢 @Coconut-Fish)
|
||||
|
||||
---
|
||||
|
||||
## Bug 修复
|
||||
|
||||
### 工具栏最大化后持续折叠
|
||||
|
||||
- 窗口最大化 / 还原后,工具栏不再卡在折叠状态;折叠判定会随尺寸变化重新计算
|
||||
|
||||
### Hermes YAML 污染与 OAuth MCP `auth` 丢失
|
||||
|
||||
- 经 CC Switch 往返写入不再丢失 OAuth MCP `auth` 块、也不污染不相关的 YAML 键
|
||||
- 新增 `tests/hermes_roundtrip.rs` 作为守护测试
|
||||
|
||||
### Hermes 激活供应商展示
|
||||
|
||||
- Hermes UI 现在正确展示激活供应商,并连通添加 / 启用 / 移除动作
|
||||
|
||||
### Hermes 供应商持久化
|
||||
|
||||
- 供应商持久化到 `custom_providers:` 下,`api_mode` 和 `model` 可跨重启 / 配置重载存活
|
||||
|
||||
### Hermes 健康检查错借 OpenClaw schema
|
||||
|
||||
- 以前 Hermes 供应商被路由到 `check_additive_app_stream`(OpenClaw 的调度器),后者读 camelCase 的 `baseUrl` / `apiKey` / `api`,导致即便 Hermes 字段全填还是报 "OpenClaw provider is missing baseUrl"
|
||||
- 新增 `check_hermes_stream`,用 Hermes 专用提取器把 `api_mode`(`chat_completions` / `anthropic_messages` / `codex_responses`)映射到对应的 `check_claude_stream` `api_format`,`bedrock_converse` 明确标记为不支持
|
||||
- 先解析 `api_mode` 再抽 URL / API key,让 `bedrock_converse` 用户看到真实原因,而不是误导性的 "missing base_url"
|
||||
|
||||
### Usage 查询模态框支持 Hermes / OpenClaw
|
||||
|
||||
- `getProviderCredentials` 新增对 Hermes(snake_case `base_url` / `api_key`)和 OpenClaw(camelCase `baseUrl` / `apiKey`)的扁平 `settingsConfig` 字段读取,让 SiliconFlow 等匹配供应商自动选中 "official balance" 模板
|
||||
- 重构 BALANCE 和 TOKEN_PLAN 测试路径复用 `providerCredentials`,不再直接读 `env.ANTHROPIC_*`,修正了非 Claude 应用即使配置了 key 也报 "empty key" 的问题
|
||||
|
||||
### Codex `cache_control` 保留
|
||||
|
||||
- 在 Codex 格式转换合并 system prompt 时保留 `cache_control` (#1946, 感谢 @yovinchen)
|
||||
|
||||
### Claude prompt cache key 泄漏
|
||||
|
||||
- Claude chat 转换时不再发送 prompt cache key (#2003, 感谢 @yovinchen)
|
||||
|
||||
### 代理逐跳响应头剥离
|
||||
|
||||
- 按 RFC 7230 剥离代理响应的 hop-by-hop 头(Connection、Keep-Alive、Transfer-Encoding 等) (#2060, 感谢 @yovinchen)
|
||||
|
||||
### 代理 CORS 层移除
|
||||
|
||||
- 移除代理中过于宽松的 CORS 层 (#1915, 感谢 @zerone0x)
|
||||
|
||||
### 代理 toast 显示后端错误详情
|
||||
|
||||
- 代理相关 toast 现在展示后端错误 payload 的详情,而不是一句笼统的失败
|
||||
|
||||
### Usage 日志去重
|
||||
|
||||
- 代理和会话日志的用量记录去重,相同请求不再被重复计数
|
||||
- 请求日志时间范围与面板的 1d / 7d / 30d 选择器同步
|
||||
|
||||
### Common Config 勾选持久化
|
||||
|
||||
- Claude / Codex / Gemini common-config 勾选状态重开后正确保留 (#2191, 感谢 @zxZeng)
|
||||
|
||||
### Claude 插件 `settings.json` 同步
|
||||
|
||||
- 编辑当前供应商时,会同步回 Claude 插件路径下的 `settings.json` (#1905, 感谢 @chengww5217)
|
||||
|
||||
### Google Official Gemini env 保留
|
||||
|
||||
- 保存 Google Official Gemini 供应商时不再清空 `env` 块
|
||||
|
||||
### OpenCode JSON5 尾逗号解析
|
||||
|
||||
- OpenCode 配置读取容忍尾逗号(JSON5) (#2023, 感谢 @wwminger)
|
||||
|
||||
### 预设刷新
|
||||
|
||||
- 刷新 DeepSeek 和 Claude 1M 的陈旧 context 窗口
|
||||
- 刷新陈旧模型 ID,回填 Hermes 模型列表
|
||||
- 修正 Nous 端点,Hermes 占位图替换为 Nous 品牌图
|
||||
- 移除未使用的官方 Hermes 预设
|
||||
|
||||
### 搜索命中时折叠消息自动展开
|
||||
|
||||
- 搜索匹配落在折叠内容内部时,消息自动展开以定位匹配
|
||||
|
||||
### 未知订阅配额等级隐藏
|
||||
|
||||
- 供应商卡片不再渲染未知订阅配额等级
|
||||
|
||||
### weekly_limit 标签统一
|
||||
|
||||
- 跨语言把 `weekly_limit` 等级标签对齐到官方的"7 天"命名
|
||||
|
||||
### 根级 Skill 仓库安装
|
||||
|
||||
- 修复当仓库根本身就是一个 skill 时的安装失败
|
||||
|
||||
### Session ID 解析 clippy
|
||||
|
||||
- 移除 session ID 解析里的冗余闭包(clippy 警告)
|
||||
|
||||
### Stream Check 默认探测模型刷新
|
||||
|
||||
- 默认探测模型更新到每家厂商当前主力
|
||||
|
||||
### Skills 导入同步
|
||||
|
||||
- 导入的 Skills 即时同步到启用应用目录,不再仅记录在数据库里导致 UI 显示"已安装"但目标目录空缺 (#2101, 感谢 @yaoguohh)
|
||||
|
||||
### Ghostty 会话恢复
|
||||
|
||||
- 改为通过 shell 执行 + `--working-directory` 启动 Ghostty 会话恢复 (#1976, 感谢 @Suda202)
|
||||
- 避免路径含空格 / 特殊字符时 `cwd` 转义问题
|
||||
|
||||
---
|
||||
|
||||
## 文档
|
||||
|
||||
### README 赞助商更新
|
||||
|
||||
- SiliconFlow 注册赠送更新为 ¥16
|
||||
- 精简 SSSAiCode 赞助文案
|
||||
- 更新合作伙伴 logo
|
||||
- 新增 LemonData 赞助商
|
||||
|
||||
### 全局代理提示澄清
|
||||
|
||||
- 三语澄清全局代理与 Local Routing 的关系
|
||||
|
||||
### Takeover → Routing 文档重命名
|
||||
|
||||
- 接管相关文档在三语下重命名为 routing,同步更新锚点
|
||||
|
||||
### PIPELLM 网站 URL
|
||||
|
||||
- PIPELLM 赞助商网站 URL 更新为 `code.pipellm.ai`
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要变更(Breaking)
|
||||
|
||||
### Hermes 必须显式 `api_mode`
|
||||
|
||||
- `Auto` 模式移除;导入或 deeplink 得到的供应商默认落到 `chat_completions`
|
||||
- 既有 `Auto` 配置的用户会被提示选择协议
|
||||
|
||||
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
|
||||
|
||||
- 该遗留字段不再暴露;既有设置自动清理
|
||||
|
||||
### 按供应商代理配置移除
|
||||
|
||||
- 迁移到全局 Local Routing 设置
|
||||
- 既有按供应商代理值被忽略
|
||||
|
||||
### 数据库 schema v9 → v10
|
||||
|
||||
- 为 `mcp_servers` 和 `skills` 表新增 `enabled_hermes` 列
|
||||
- 自动迁移,`DEFAULT 0`,无数据丢失
|
||||
|
||||
### Pricing 表 v8 → v9 重置
|
||||
|
||||
- 首次启动时 `model_pricing` 表被清空并重新种入,以应用新模型和修正后的价格
|
||||
|
||||
### XCodeAPI 预设移除
|
||||
|
||||
- 使用 XCodeAPI 预设的用户请迁移到其它供应商
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 风险提示
|
||||
|
||||
本版本在涉及反向代理类功能上沿用 v3.12.3 / v3.13.0 提出的风险提示。
|
||||
|
||||
**GitHub Copilot 反向代理**:使用 Copilot 的反代路径可能违反 GitHub / Microsoft 服务条款。详情见 [v3.12.3 release notes](v3.12.3-zh.md#️-风险提示)。
|
||||
|
||||
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
|
||||
|
||||
用户启用上述功能即表示**自行承担所有风险**。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | -------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.14.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.14.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------- |
|
||||
| `CC-Switch-v3.14.0-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.14.0-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.14.0-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
|
||||
|
||||
### 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` |
|
||||
@@ -509,7 +509,7 @@ When editing Claude providers, a set of **quick toggles** is available above the
|
||||
| **Hide Attribution** | Clears commit/PR attribution metadata | Sets `attribution: {commit: "", pr: ""}` |
|
||||
| **Enable Teammates** | Enables the agent teams feature | Sets `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
|
||||
| **Enable Tool Search** | Enables tool search functionality | Sets `env.ENABLE_TOOL_SEARCH = "true"` |
|
||||
| **High Effort** | Sets effort level to high | Sets `effortLevel = "high"` |
|
||||
| **Max Effort** | Sets effort level to max | Sets `effortLevel = "max"` |
|
||||
| **Disable Auto Upgrade** | Prevents Claude Code auto-updates | Sets `env.DISABLE_AUTOUPDATER = "1"` |
|
||||
|
||||
When a toggle is unchecked, its corresponding config entry is removed entirely. Changes are reflected in the JSON editor in real-time.
|
||||
|
||||
@@ -509,7 +509,7 @@ Claude プロバイダーの編集時、JSON エディタの上部に **クイ
|
||||
| **帰属情報を非表示** | コミット/PR の帰属メタデータをクリア | `attribution: {commit: "", pr: ""}` を設定 |
|
||||
| **チームメイトを有効化** | エージェントチーム機能を有効化 | `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` を設定 |
|
||||
| **ツール検索を有効化** | ツール検索機能を有効化 | `env.ENABLE_TOOL_SEARCH = "true"` を設定 |
|
||||
| **高強度** | エフォートレベルを高に設定 | `effortLevel = "high"` を設定 |
|
||||
| **最大強度思考** | エフォートレベルを max に設定 | `effortLevel = "max"` を設定 |
|
||||
| **自動アップグレードを無効化** | Claude Code の自動更新を防止 | `env.DISABLE_AUTOUPDATER = "1"` を設定 |
|
||||
|
||||
トグルのチェックを外すと、対応する設定エントリが完全に削除されます。変更は JSON エディタにリアルタイムで反映されます。
|
||||
|
||||
@@ -509,7 +509,7 @@ v3.13.0 起新增的高级选项。默认情况下,CC Switch 会把配置的 `
|
||||
| **隐藏署名** | 清除提交/PR 的署名元数据 | 设置 `attribution: {commit: "", pr: ""}` |
|
||||
| **启用 Teammates** | 启用 Agent 团队功能 | 设置 `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
|
||||
| **启用工具搜索** | 启用工具搜索功能 | 设置 `env.ENABLE_TOOL_SEARCH = "true"` |
|
||||
| **高效能模式** | 将 effort 级别设为 high | 设置 `effortLevel = "high"` |
|
||||
| **最大强度思考** | 将 effort 级别设为 max | 设置 `effortLevel = "max"` |
|
||||
| **禁用自动更新** | 阻止 Claude Code 自动更新 | 设置 `env.DISABLE_AUTOUPDATER = "1"` |
|
||||
|
||||
取消勾选开关时,对应的配置项会被完全移除。更改会实时反映在 JSON 编辑器中。
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.13.0",
|
||||
"version": "3.14.0",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
[toolchain]
|
||||
channel = "1.95"
|
||||
components = ["rustfmt", "clippy"]
|
||||
profile = "minimal"
|
||||
Generated
+1
-1
@@ -735,7 +735,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.13.0"
|
||||
version = "3.14.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.13.0"
|
||||
version = "3.14.0"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -15,6 +15,8 @@ pub struct McpApps {
|
||||
pub gemini: bool,
|
||||
#[serde(default)]
|
||||
pub opencode: bool,
|
||||
#[serde(default)]
|
||||
pub hermes: bool,
|
||||
}
|
||||
|
||||
impl McpApps {
|
||||
@@ -26,6 +28,7 @@ impl McpApps {
|
||||
AppType::Gemini => self.gemini,
|
||||
AppType::OpenCode => self.opencode,
|
||||
AppType::OpenClaw => false, // OpenClaw doesn't support MCP
|
||||
AppType::Hermes => self.hermes,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +40,7 @@ impl McpApps {
|
||||
AppType::Gemini => self.gemini = enabled,
|
||||
AppType::OpenCode => self.opencode = enabled,
|
||||
AppType::OpenClaw => {} // OpenClaw doesn't support MCP, ignore
|
||||
AppType::Hermes => self.hermes = enabled,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,12 +59,15 @@ impl McpApps {
|
||||
if self.opencode {
|
||||
apps.push(AppType::OpenCode);
|
||||
}
|
||||
if self.hermes {
|
||||
apps.push(AppType::Hermes);
|
||||
}
|
||||
apps
|
||||
}
|
||||
|
||||
/// 检查是否所有应用都未启用
|
||||
pub fn is_empty(&self) -> bool {
|
||||
!self.claude && !self.codex && !self.gemini && !self.opencode
|
||||
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +82,8 @@ pub struct SkillApps {
|
||||
pub gemini: bool,
|
||||
#[serde(default)]
|
||||
pub opencode: bool,
|
||||
#[serde(default)]
|
||||
pub hermes: bool,
|
||||
}
|
||||
|
||||
impl SkillApps {
|
||||
@@ -85,6 +94,7 @@ impl SkillApps {
|
||||
AppType::Codex => self.codex,
|
||||
AppType::Gemini => self.gemini,
|
||||
AppType::OpenCode => self.opencode,
|
||||
AppType::Hermes => self.hermes,
|
||||
AppType::OpenClaw => false, // OpenClaw doesn't support Skills
|
||||
}
|
||||
}
|
||||
@@ -96,6 +106,7 @@ impl SkillApps {
|
||||
AppType::Codex => self.codex = enabled,
|
||||
AppType::Gemini => self.gemini = enabled,
|
||||
AppType::OpenCode => self.opencode = enabled,
|
||||
AppType::Hermes => self.hermes = enabled,
|
||||
AppType::OpenClaw => {} // OpenClaw doesn't support Skills, ignore
|
||||
}
|
||||
}
|
||||
@@ -115,12 +126,15 @@ impl SkillApps {
|
||||
if self.opencode {
|
||||
apps.push(AppType::OpenCode);
|
||||
}
|
||||
if self.hermes {
|
||||
apps.push(AppType::Hermes);
|
||||
}
|
||||
apps
|
||||
}
|
||||
|
||||
/// 检查是否所有应用都未启用
|
||||
pub fn is_empty(&self) -> bool {
|
||||
!self.claude && !self.codex && !self.gemini && !self.opencode
|
||||
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
|
||||
}
|
||||
|
||||
/// 仅启用指定应用(其他应用设为禁用)
|
||||
@@ -251,6 +265,9 @@ pub struct McpRoot {
|
||||
/// OpenClaw MCP 配置(v4.1.0+,实际使用 openclaw.json)
|
||||
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
|
||||
pub openclaw: McpConfig,
|
||||
/// Hermes MCP 配置(实际使用 config.yaml)
|
||||
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
|
||||
pub hermes: McpConfig,
|
||||
}
|
||||
|
||||
impl Default for McpRoot {
|
||||
@@ -264,6 +281,7 @@ impl Default for McpRoot {
|
||||
gemini: McpConfig::default(),
|
||||
opencode: McpConfig::default(),
|
||||
openclaw: McpConfig::default(),
|
||||
hermes: McpConfig::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -288,6 +306,8 @@ pub struct PromptRoot {
|
||||
pub opencode: PromptConfig,
|
||||
#[serde(default)]
|
||||
pub openclaw: PromptConfig,
|
||||
#[serde(default)]
|
||||
pub hermes: PromptConfig,
|
||||
}
|
||||
|
||||
use crate::config::{copy_file, get_app_config_dir, get_app_config_path, write_json_file};
|
||||
@@ -304,6 +324,7 @@ pub enum AppType {
|
||||
Gemini,
|
||||
OpenCode,
|
||||
OpenClaw,
|
||||
Hermes,
|
||||
}
|
||||
|
||||
impl AppType {
|
||||
@@ -314,15 +335,19 @@ impl AppType {
|
||||
AppType::Gemini => "gemini",
|
||||
AppType::OpenCode => "opencode",
|
||||
AppType::OpenClaw => "openclaw",
|
||||
AppType::Hermes => "hermes",
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this app uses additive mode
|
||||
///
|
||||
/// - Switch mode (false): Only the current provider is written to live config (Claude, Codex, Gemini)
|
||||
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw)
|
||||
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw, Hermes)
|
||||
pub fn is_additive_mode(&self) -> bool {
|
||||
matches!(self, AppType::OpenCode | AppType::OpenClaw)
|
||||
matches!(
|
||||
self,
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
|
||||
)
|
||||
}
|
||||
|
||||
/// Return an iterator over all app types
|
||||
@@ -333,6 +358,7 @@ impl AppType {
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
AppType::OpenClaw,
|
||||
AppType::Hermes,
|
||||
]
|
||||
.into_iter()
|
||||
}
|
||||
@@ -349,10 +375,11 @@ impl FromStr for AppType {
|
||||
"gemini" => Ok(AppType::Gemini),
|
||||
"opencode" => Ok(AppType::OpenCode),
|
||||
"openclaw" => Ok(AppType::OpenClaw),
|
||||
"hermes" => Ok(AppType::Hermes),
|
||||
other => Err(AppError::localized(
|
||||
"unsupported_app",
|
||||
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw。"),
|
||||
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw."),
|
||||
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw, hermes。"),
|
||||
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw, hermes."),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -375,6 +402,9 @@ pub struct CommonConfigSnippets {
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub openclaw: Option<String>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hermes: Option<String>,
|
||||
}
|
||||
|
||||
impl CommonConfigSnippets {
|
||||
@@ -386,6 +416,7 @@ impl CommonConfigSnippets {
|
||||
AppType::Gemini => self.gemini.as_ref(),
|
||||
AppType::OpenCode => self.opencode.as_ref(),
|
||||
AppType::OpenClaw => self.openclaw.as_ref(),
|
||||
AppType::Hermes => self.hermes.as_ref(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -397,6 +428,7 @@ impl CommonConfigSnippets {
|
||||
AppType::Gemini => self.gemini = snippet,
|
||||
AppType::OpenCode => self.opencode = snippet,
|
||||
AppType::OpenClaw => self.openclaw = snippet,
|
||||
AppType::Hermes => self.hermes = snippet,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -438,6 +470,7 @@ impl Default for MultiAppConfig {
|
||||
apps.insert("gemini".to_string(), ProviderManager::default());
|
||||
apps.insert("opencode".to_string(), ProviderManager::default());
|
||||
apps.insert("openclaw".to_string(), ProviderManager::default());
|
||||
apps.insert("hermes".to_string(), ProviderManager::default());
|
||||
|
||||
Self {
|
||||
version: 2,
|
||||
@@ -598,6 +631,7 @@ impl MultiAppConfig {
|
||||
AppType::Gemini => &self.mcp.gemini,
|
||||
AppType::OpenCode => &self.mcp.opencode,
|
||||
AppType::OpenClaw => &self.mcp.openclaw,
|
||||
AppType::Hermes => &self.mcp.hermes,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,6 +643,7 @@ impl MultiAppConfig {
|
||||
AppType::Gemini => &mut self.mcp.gemini,
|
||||
AppType::OpenCode => &mut self.mcp.opencode,
|
||||
AppType::OpenClaw => &mut self.mcp.openclaw,
|
||||
AppType::Hermes => &mut self.mcp.hermes,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -624,6 +659,7 @@ impl MultiAppConfig {
|
||||
Self::auto_import_prompt_if_exists(&mut config, AppType::Gemini)?;
|
||||
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenCode)?;
|
||||
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenClaw)?;
|
||||
Self::auto_import_prompt_if_exists(&mut config, AppType::Hermes)?;
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
@@ -645,6 +681,7 @@ impl MultiAppConfig {
|
||||
|| !self.prompts.gemini.prompts.is_empty()
|
||||
|| !self.prompts.opencode.prompts.is_empty()
|
||||
|| !self.prompts.openclaw.prompts.is_empty()
|
||||
|| !self.prompts.hermes.prompts.is_empty()
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -658,6 +695,7 @@ impl MultiAppConfig {
|
||||
AppType::Gemini,
|
||||
AppType::OpenCode,
|
||||
AppType::OpenClaw,
|
||||
AppType::Hermes,
|
||||
] {
|
||||
// 复用已有的单应用导入逻辑
|
||||
if Self::auto_import_prompt_if_exists(self, app)? {
|
||||
@@ -729,6 +767,7 @@ impl MultiAppConfig {
|
||||
AppType::Gemini => &mut config.prompts.gemini.prompts,
|
||||
AppType::OpenCode => &mut config.prompts.opencode.prompts,
|
||||
AppType::OpenClaw => &mut config.prompts.openclaw.prompts,
|
||||
AppType::Hermes => &mut config.prompts.hermes.prompts,
|
||||
};
|
||||
|
||||
prompts.insert(id, prompt);
|
||||
@@ -769,6 +808,7 @@ impl MultiAppConfig {
|
||||
AppType::Gemini => &self.mcp.gemini.servers,
|
||||
AppType::OpenCode => &self.mcp.opencode.servers,
|
||||
AppType::OpenClaw => continue, // OpenClaw MCP is still in development, skip
|
||||
AppType::Hermes => continue, // Hermes didn't exist in v3.6.x, skip
|
||||
};
|
||||
|
||||
for (id, entry) in old_servers {
|
||||
|
||||
@@ -18,6 +18,7 @@ pub struct ManagedAuthAccount {
|
||||
pub avatar_url: Option<String>,
|
||||
pub authenticated_at: i64,
|
||||
pub is_default: bool,
|
||||
pub github_domain: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
@@ -59,6 +60,7 @@ fn map_account(
|
||||
login: account.login,
|
||||
avatar_url: account.avatar_url,
|
||||
authenticated_at: account.authenticated_at,
|
||||
github_domain: account.github_domain,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +81,7 @@ fn map_device_code_response(
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn auth_start_login(
|
||||
auth_provider: String,
|
||||
github_domain: Option<String>,
|
||||
copilot_state: State<'_, CopilotAuthState>,
|
||||
codex_state: State<'_, CodexOAuthState>,
|
||||
) -> Result<ManagedAuthDeviceCodeResponse, String> {
|
||||
@@ -87,7 +90,7 @@ pub async fn auth_start_login(
|
||||
AUTH_PROVIDER_GITHUB_COPILOT => {
|
||||
let auth_manager = copilot_state.0.read().await;
|
||||
let response = auth_manager
|
||||
.start_device_flow()
|
||||
.start_device_flow(github_domain.as_deref())
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(map_device_code_response(auth_provider, response))
|
||||
@@ -108,6 +111,7 @@ pub async fn auth_start_login(
|
||||
pub async fn auth_poll_for_account(
|
||||
auth_provider: String,
|
||||
device_code: String,
|
||||
github_domain: Option<String>,
|
||||
copilot_state: State<'_, CopilotAuthState>,
|
||||
codex_state: State<'_, CodexOAuthState>,
|
||||
) -> Result<Option<ManagedAuthAccount>, String> {
|
||||
@@ -115,7 +119,10 @@ pub async fn auth_poll_for_account(
|
||||
match auth_provider {
|
||||
AUTH_PROVIDER_GITHUB_COPILOT => {
|
||||
let auth_manager = copilot_state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
match auth_manager
|
||||
.poll_for_token(&device_code, github_domain.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(account) => {
|
||||
let default_account_id = auth_manager.get_status().await.default_account_id;
|
||||
Ok(account.map(|account| {
|
||||
|
||||
@@ -101,6 +101,15 @@ pub async fn get_config_status(app: String) -> Result<ConfigStatus, String> {
|
||||
|
||||
Ok(ConfigStatus { exists, path })
|
||||
}
|
||||
AppType::Hermes => {
|
||||
let config_path = crate::hermes_config::get_hermes_config_path();
|
||||
let exists = config_path.exists();
|
||||
let path = crate::hermes_config::get_hermes_dir()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
Ok(ConfigStatus { exists, path })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +126,7 @@ pub async fn get_config_dir(app: String) -> Result<String, String> {
|
||||
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
|
||||
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
|
||||
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
|
||||
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
|
||||
};
|
||||
|
||||
Ok(dir.to_string_lossy().to_string())
|
||||
@@ -130,6 +140,7 @@ pub async fn open_config_folder(handle: AppHandle, app: String) -> Result<bool,
|
||||
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
|
||||
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
|
||||
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
|
||||
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
|
||||
};
|
||||
|
||||
if !config_dir.exists() {
|
||||
|
||||
@@ -20,11 +20,12 @@ pub struct CopilotAuthState(pub Arc<RwLock<CopilotAuthManager>>);
|
||||
/// 返回设备码和用户码,用于 OAuth 认证
|
||||
#[tauri::command]
|
||||
pub async fn copilot_start_device_flow(
|
||||
github_domain: Option<String>,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<GitHubDeviceCodeResponse, String> {
|
||||
let auth_manager = state.0.read().await;
|
||||
auth_manager
|
||||
.start_device_flow()
|
||||
.start_device_flow(github_domain.as_deref())
|
||||
.await
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
@@ -36,10 +37,14 @@ pub async fn copilot_start_device_flow(
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_poll_for_auth(
|
||||
device_code: String,
|
||||
github_domain: Option<String>,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<bool, String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
match auth_manager
|
||||
.poll_for_token(&device_code, github_domain.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(Some(_account)) => {
|
||||
log::info!("[CopilotAuth] 用户已授权");
|
||||
Ok(true)
|
||||
@@ -61,10 +66,14 @@ pub async fn copilot_poll_for_auth(
|
||||
#[tauri::command(rename_all = "camelCase")]
|
||||
pub async fn copilot_poll_for_account(
|
||||
device_code: String,
|
||||
github_domain: Option<String>,
|
||||
state: State<'_, CopilotAuthState>,
|
||||
) -> Result<Option<GitHubAccount>, String> {
|
||||
let auth_manager = state.0.write().await;
|
||||
match auth_manager.poll_for_token(&device_code).await {
|
||||
match auth_manager
|
||||
.poll_for_token(&device_code, github_domain.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(account) => Ok(account),
|
||||
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
|
||||
Ok(None)
|
||||
|
||||
@@ -162,7 +162,7 @@ pub async fn set_auto_failover_enabled(
|
||||
|
||||
// 刷新托盘菜单,确保状态同步
|
||||
if let Ok(new_menu) = crate::tray::create_tray_menu(&app, &state) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, State};
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
use crate::hermes_config;
|
||||
use crate::store::AppState;
|
||||
|
||||
/// Error string returned when `open_hermes_web_ui` cannot reach the Hermes
|
||||
/// FastAPI server. Kept in sync with the `HERMES_WEB_OFFLINE_ERROR` constant
|
||||
/// in `src/hooks/useHermes.ts` so the frontend can branch on it.
|
||||
const HERMES_WEB_OFFLINE_ERROR: &str = "hermes_web_offline";
|
||||
|
||||
// ============================================================================
|
||||
// Hermes Provider Commands
|
||||
// ============================================================================
|
||||
|
||||
/// Import providers from Hermes live config to database.
|
||||
///
|
||||
/// Hermes uses additive mode — users may already have providers
|
||||
/// configured in config.yaml.
|
||||
#[tauri::command]
|
||||
pub fn import_hermes_providers_from_live(state: State<'_, AppState>) -> Result<usize, String> {
|
||||
crate::services::provider::import_hermes_providers_from_live(state.inner())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Get provider names in the Hermes live config.
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_live_provider_ids() -> Result<Vec<String>, String> {
|
||||
hermes_config::get_providers()
|
||||
.map(|providers| providers.keys().cloned().collect())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Get a single Hermes provider fragment from live config.
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_live_provider(
|
||||
#[allow(non_snake_case)] providerId: String,
|
||||
) -> Result<Option<serde_json::Value>, String> {
|
||||
hermes_config::get_provider(&providerId).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Scan config.yaml for known configuration hazards.
|
||||
#[tauri::command]
|
||||
pub fn scan_hermes_config_health() -> Result<Vec<hermes_config::HermesHealthWarning>, String> {
|
||||
hermes_config::scan_hermes_config_health().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Model Configuration Commands
|
||||
// ============================================================================
|
||||
|
||||
/// Get Hermes model config (model section of config.yaml). Read-only — writes
|
||||
/// happen implicitly through `apply_switch_defaults` when switching providers.
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_model_config() -> Result<Option<hermes_config::HermesModelConfig>, String> {
|
||||
hermes_config::get_model_config().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Memory Files Commands
|
||||
// ============================================================================
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_memory(kind: hermes_config::MemoryKind) -> Result<String, String> {
|
||||
hermes_config::read_memory(kind).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_hermes_memory(kind: hermes_config::MemoryKind, content: String) -> Result<(), String> {
|
||||
hermes_config::write_memory(kind, &content).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_hermes_memory_limits() -> Result<hermes_config::HermesMemoryLimits, String> {
|
||||
hermes_config::read_memory_limits().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn set_hermes_memory_enabled(
|
||||
kind: hermes_config::MemoryKind,
|
||||
enabled: bool,
|
||||
) -> Result<hermes_config::HermesWriteOutcome, String> {
|
||||
hermes_config::set_memory_enabled(kind, enabled).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Hermes Web UI launcher
|
||||
// ============================================================================
|
||||
|
||||
/// Probe the local Hermes Web UI (FastAPI) and open it in the system browser.
|
||||
///
|
||||
/// Port discovery priority:
|
||||
/// 1. `HERMES_WEB_PORT` environment variable
|
||||
/// 2. Default 9119
|
||||
///
|
||||
/// Hermes wraps all `/api/*` routes in a Bearer-token middleware, so a GET
|
||||
/// against `/api/status` returning **either 200 or 401** confirms the server
|
||||
/// is live. The session token lives only in the Hermes process memory and is
|
||||
/// injected into the returned HTML via `window.__HERMES_SESSION_TOKEN__`, so
|
||||
/// there is no need (and no way) for CC Switch to inject it — we just open
|
||||
/// the URL and let Hermes handle auth.
|
||||
#[tauri::command]
|
||||
pub async fn open_hermes_web_ui(app: AppHandle, path: Option<String>) -> Result<(), String> {
|
||||
let port = std::env::var("HERMES_WEB_PORT")
|
||||
.ok()
|
||||
.and_then(|raw| raw.trim().parse::<u16>().ok())
|
||||
.unwrap_or(9119);
|
||||
|
||||
let base = format!("http://127.0.0.1:{port}");
|
||||
|
||||
// Probe /api/status with a short timeout. Hermes returns 200 when open or
|
||||
// 401 when the session token is required — either way the server is live.
|
||||
// Only a connection error / timeout means the server isn't running.
|
||||
let probe_url = format!("{base}/api/status");
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(Duration::from_millis(1200))
|
||||
.no_proxy()
|
||||
.build()
|
||||
.map_err(|e| format!("failed to build probe client: {e}"))?;
|
||||
|
||||
match client.get(&probe_url).send().await {
|
||||
Ok(_) => {}
|
||||
Err(_) => return Err(HERMES_WEB_OFFLINE_ERROR.to_string()),
|
||||
}
|
||||
|
||||
let target = match path.as_deref() {
|
||||
Some(p) if p.starts_with('/') => format!("{base}{p}"),
|
||||
Some(p) if !p.is_empty() => format!("{base}/{p}"),
|
||||
_ => format!("{base}/"),
|
||||
};
|
||||
|
||||
app.opener()
|
||||
.open_url(&target, None::<String>)
|
||||
.map_err(|e| format!("failed to open Hermes Web UI: {e}"))
|
||||
}
|
||||
|
||||
/// Open the preferred terminal and run `hermes dashboard`. Non-blocking —
|
||||
/// callers should reinvoke `open_hermes_web_ui` once the server is ready,
|
||||
/// since Hermes startup can take several seconds and may fail outright if
|
||||
/// the `hermes-agent[web]` extras are missing.
|
||||
#[tauri::command]
|
||||
pub async fn launch_hermes_dashboard() -> Result<(), String> {
|
||||
tokio::task::spawn_blocking(|| {
|
||||
crate::commands::misc::launch_terminal_running("hermes dashboard", "hermes_dashboard")
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("launch task join error: {e}"))?
|
||||
}
|
||||
@@ -202,5 +202,6 @@ pub async fn import_mcp_from_apps(state: State<'_, AppState>) -> Result<usize, S
|
||||
total += McpService::import_from_codex(&state).unwrap_or(0);
|
||||
total += McpService::import_from_gemini(&state).unwrap_or(0);
|
||||
total += McpService::import_from_opencode(&state).unwrap_or(0);
|
||||
total += McpService::import_from_hermes(&state).unwrap_or(0);
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
@@ -1310,6 +1310,188 @@ fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), S
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 打开用户首选终端并在其中执行一条命令行。脚本尾部 `read -n 1` / `pause`
|
||||
/// 是刻意设计的——让命令退出后窗口不要瞬间关闭,用户才看得到 `command
|
||||
/// not found` / `ModuleNotFoundError` 这类诊断信息。
|
||||
///
|
||||
/// **Security**:`command_line` 会被原样拼进 shell/batch 脚本,调用方必须
|
||||
/// 保证它是可信字符串(当前只由后端硬编码调用)。
|
||||
pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result<(), String> {
|
||||
let temp_dir = std::env::temp_dir();
|
||||
let pid = std::process::id();
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
let (script_file, script_content) = {
|
||||
let file = temp_dir.join(format!("cc_switch_{}_{}.sh", label, pid));
|
||||
let content = format!(
|
||||
r#"#!/bin/bash
|
||||
trap 'rm -f "{script_path}"' EXIT
|
||||
echo "[cc-switch] Starting: {cmd}"
|
||||
echo ""
|
||||
{cmd}
|
||||
echo ""
|
||||
echo "[cc-switch] Command exited. Press any key to close."
|
||||
read -n 1 -s
|
||||
"#,
|
||||
script_path = file.display(),
|
||||
cmd = command_line,
|
||||
);
|
||||
(file, content)
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
std::fs::write(&script_file, &script_content)
|
||||
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
|
||||
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
|
||||
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
let terminal = preferred.as_deref().unwrap_or("terminal");
|
||||
|
||||
let result = match terminal {
|
||||
"iterm2" => launch_macos_iterm2(&script_file),
|
||||
"alacritty" => launch_macos_open_app("Alacritty", &script_file, true),
|
||||
"kitty" => launch_macos_open_app("kitty", &script_file, false),
|
||||
"ghostty" => launch_macos_open_app("Ghostty", &script_file, true),
|
||||
"wezterm" => launch_macos_open_app("WezTerm", &script_file, true),
|
||||
"kaku" => launch_macos_open_app("Kaku", &script_file, true),
|
||||
_ => launch_macos_terminal_app(&script_file),
|
||||
};
|
||||
|
||||
if result.is_err() && terminal != "terminal" {
|
||||
log::warn!(
|
||||
"首选终端 {} 启动失败,回退到 Terminal.app: {:?}",
|
||||
terminal,
|
||||
result.as_ref().err()
|
||||
);
|
||||
return launch_macos_terminal_app(&script_file);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::process::Command;
|
||||
|
||||
std::fs::write(&script_file, &script_content)
|
||||
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
|
||||
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
|
||||
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
|
||||
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
let default_terminals = [
|
||||
("gnome-terminal", vec!["--"]),
|
||||
("konsole", vec!["-e"]),
|
||||
("xfce4-terminal", vec!["-e"]),
|
||||
("mate-terminal", vec!["--"]),
|
||||
("lxterminal", vec!["-e"]),
|
||||
("alacritty", vec!["-e"]),
|
||||
("kitty", vec!["-e"]),
|
||||
("ghostty", vec!["-e"]),
|
||||
];
|
||||
|
||||
let terminals_to_try: Vec<(&str, Vec<&str>)> = if let Some(ref pref) = preferred {
|
||||
let pref_args = default_terminals
|
||||
.iter()
|
||||
.find(|(name, _)| *name == pref.as_str())
|
||||
.map(|(_, args)| args.to_vec())
|
||||
.unwrap_or_else(|| vec!["-e"]);
|
||||
let mut list = vec![(pref.as_str(), pref_args)];
|
||||
for (name, args) in &default_terminals {
|
||||
if *name != pref.as_str() {
|
||||
list.push((*name, args.to_vec()));
|
||||
}
|
||||
}
|
||||
list
|
||||
} else {
|
||||
default_terminals
|
||||
.iter()
|
||||
.map(|(name, args)| (*name, args.to_vec()))
|
||||
.collect()
|
||||
};
|
||||
|
||||
let mut last_error = String::from("未找到可用的终端");
|
||||
|
||||
for (terminal, args) in terminals_to_try {
|
||||
let terminal_exists = which_command(terminal)
|
||||
|| ["/usr/bin", "/bin", "/usr/local/bin"]
|
||||
.iter()
|
||||
.any(|dir| std::path::Path::new(&format!("{}/{}", dir, terminal)).exists());
|
||||
|
||||
if terminal_exists {
|
||||
let spawn_result = Command::new(terminal)
|
||||
.args(&args)
|
||||
.arg("bash")
|
||||
.arg(script_file.to_string_lossy().as_ref())
|
||||
.spawn();
|
||||
match spawn_result {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) => {
|
||||
last_error = format!("执行 {} 失败: {}", terminal, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_file(&script_file);
|
||||
Err(last_error)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let preferred = crate::settings::get_preferred_terminal();
|
||||
let terminal = preferred.as_deref().unwrap_or("cmd");
|
||||
|
||||
let bat_file = temp_dir.join(format!("cc_switch_{}_{}.bat", label, pid));
|
||||
let content = format!(
|
||||
"@echo off\r\necho [cc-switch] Starting: {cmd}\r\necho.\r\n{cmd}\r\necho.\r\necho [cc-switch] Command exited. Press any key to close.\r\npause >nul\r\ndel \"%~f0\" >nul 2>&1\r\n",
|
||||
cmd = command_line,
|
||||
);
|
||||
std::fs::write(&bat_file, &content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
|
||||
|
||||
let bat_path = bat_file.to_string_lossy();
|
||||
let ps_cmd = format!("& '{}'", bat_path);
|
||||
|
||||
let result = match terminal {
|
||||
"powershell" => run_windows_start_command(
|
||||
&["powershell", "-NoExit", "-Command", &ps_cmd],
|
||||
"PowerShell",
|
||||
),
|
||||
"wt" => run_windows_start_command(&["wt", "cmd", "/K", &bat_path], "Windows Terminal"),
|
||||
_ => run_windows_start_command(&["cmd", "/K", &bat_path], "cmd"),
|
||||
};
|
||||
|
||||
let final_result = if result.is_err() && terminal != "cmd" {
|
||||
log::warn!(
|
||||
"首选终端 {} 启动失败,回退到 cmd: {:?}",
|
||||
terminal,
|
||||
result.as_ref().err()
|
||||
);
|
||||
run_windows_start_command(&["cmd", "/K", &bat_path], "cmd")
|
||||
} else {
|
||||
result
|
||||
};
|
||||
|
||||
// The .bat self-deletes (`del "%~f0"`) after it runs, but that only
|
||||
// fires if *some* terminal actually launched it. If every attempt
|
||||
// failed, sweep the temp file ourselves to avoid pollution.
|
||||
if final_result.is_err() {
|
||||
let _ = std::fs::remove_file(&bat_file);
|
||||
}
|
||||
final_result
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
|
||||
{
|
||||
let _ = (temp_dir, pid, command_line, label);
|
||||
Err("不支持的操作系统".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置窗口主题(Windows/macOS 标题栏颜色)
|
||||
/// theme: "dark" | "light" | "system"
|
||||
#[tauri::command]
|
||||
|
||||
@@ -10,6 +10,7 @@ mod deeplink;
|
||||
mod env;
|
||||
mod failover;
|
||||
mod global_proxy;
|
||||
mod hermes;
|
||||
mod import_export;
|
||||
mod mcp;
|
||||
mod misc;
|
||||
@@ -42,6 +43,7 @@ pub use deeplink::*;
|
||||
pub use env::*;
|
||||
pub use failover::*;
|
||||
pub use global_proxy::*;
|
||||
pub use hermes::*;
|
||||
pub use import_export::*;
|
||||
pub use mcp::*;
|
||||
pub use misc::*;
|
||||
|
||||
@@ -25,6 +25,7 @@ fn parse_app_type(app: &str) -> Result<AppType, String> {
|
||||
"codex" => Ok(AppType::Codex),
|
||||
"gemini" => Ok(AppType::Gemini),
|
||||
"opencode" => Ok(AppType::OpenCode),
|
||||
"hermes" => Ok(AppType::Hermes),
|
||||
_ => Err(format!("不支持的 app 类型: {app}")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,6 +133,7 @@ pub async fn stream_check_all_providers(
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: 0,
|
||||
error_category: None,
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -35,18 +35,26 @@ pub fn get_usage_trends(
|
||||
#[tauri::command]
|
||||
pub fn get_provider_stats(
|
||||
state: State<'_, AppState>,
|
||||
start_date: Option<i64>,
|
||||
end_date: Option<i64>,
|
||||
app_type: Option<String>,
|
||||
) -> Result<Vec<ProviderStats>, AppError> {
|
||||
state.db.get_provider_stats(app_type.as_deref())
|
||||
state
|
||||
.db
|
||||
.get_provider_stats(start_date, end_date, app_type.as_deref())
|
||||
}
|
||||
|
||||
/// 获取模型统计
|
||||
#[tauri::command]
|
||||
pub fn get_model_stats(
|
||||
state: State<'_, AppState>,
|
||||
start_date: Option<i64>,
|
||||
end_date: Option<i64>,
|
||||
app_type: Option<String>,
|
||||
) -> Result<Vec<ModelStats>, AppError> {
|
||||
state.db.get_model_stats(app_type.as_deref())
|
||||
state
|
||||
.db
|
||||
.get_model_stats(start_date, end_date, app_type.as_deref())
|
||||
}
|
||||
|
||||
/// 获取请求日志列表
|
||||
|
||||
@@ -14,6 +14,8 @@ pub struct FailoverQueueItem {
|
||||
pub provider_id: String,
|
||||
pub provider_name: String,
|
||||
pub sort_index: Option<usize>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub provider_notes: Option<String>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
@@ -23,7 +25,7 @@ impl Database {
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, name, sort_index
|
||||
"SELECT id, name, sort_index, notes
|
||||
FROM providers
|
||||
WHERE app_type = ?1 AND in_failover_queue = 1
|
||||
ORDER BY COALESCE(sort_index, 999999), id ASC",
|
||||
@@ -36,6 +38,7 @@ impl Database {
|
||||
provider_id: row.get(0)?,
|
||||
provider_name: row.get(1)?,
|
||||
sort_index: row.get(2)?,
|
||||
provider_notes: row.get(3)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?
|
||||
|
||||
@@ -13,7 +13,7 @@ impl Database {
|
||||
pub fn get_all_mcp_servers(&self) -> Result<IndexMap<String, McpServer>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
|
||||
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
|
||||
FROM mcp_servers
|
||||
ORDER BY name ASC, id ASC"
|
||||
).map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -31,6 +31,7 @@ impl Database {
|
||||
let enabled_codex: bool = row.get(8)?;
|
||||
let enabled_gemini: bool = row.get(9)?;
|
||||
let enabled_opencode: bool = row.get(10)?;
|
||||
let enabled_hermes: bool = row.get(11)?;
|
||||
|
||||
let server = serde_json::from_str(&server_config_str).unwrap_or_default();
|
||||
let tags = serde_json::from_str(&tags_str).unwrap_or_default();
|
||||
@@ -46,6 +47,7 @@ impl Database {
|
||||
codex: enabled_codex,
|
||||
gemini: enabled_gemini,
|
||||
opencode: enabled_opencode,
|
||||
hermes: enabled_hermes,
|
||||
},
|
||||
description,
|
||||
homepage,
|
||||
@@ -70,8 +72,8 @@ impl Database {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO mcp_servers (
|
||||
id, name, server_config, description, homepage, docs, tags,
|
||||
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
|
||||
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
params![
|
||||
server.id,
|
||||
server.name,
|
||||
@@ -87,6 +89,7 @@ impl Database {
|
||||
server.apps.codex,
|
||||
server.apps.gemini,
|
||||
server.apps.opencode,
|
||||
server.apps.hermes,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Database {
|
||||
.prepare(
|
||||
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
|
||||
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
|
||||
installed_at, content_hash, updated_at
|
||||
enabled_hermes, installed_at, content_hash, updated_at
|
||||
FROM skills ORDER BY name ASC",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -44,10 +44,11 @@ impl Database {
|
||||
codex: row.get(9)?,
|
||||
gemini: row.get(10)?,
|
||||
opencode: row.get(11)?,
|
||||
hermes: row.get(12)?,
|
||||
},
|
||||
installed_at: row.get(12)?,
|
||||
content_hash: row.get(13)?,
|
||||
updated_at: row.get::<_, i64>(14).unwrap_or(0),
|
||||
installed_at: row.get(13)?,
|
||||
content_hash: row.get(14)?,
|
||||
updated_at: row.get::<_, i64>(15).unwrap_or(0),
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -67,7 +68,7 @@ impl Database {
|
||||
.prepare(
|
||||
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
|
||||
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
|
||||
installed_at, content_hash, updated_at
|
||||
enabled_hermes, installed_at, content_hash, updated_at
|
||||
FROM skills WHERE id = ?1",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
@@ -87,10 +88,11 @@ impl Database {
|
||||
codex: row.get(9)?,
|
||||
gemini: row.get(10)?,
|
||||
opencode: row.get(11)?,
|
||||
hermes: row.get(12)?,
|
||||
},
|
||||
installed_at: row.get(12)?,
|
||||
content_hash: row.get(13)?,
|
||||
updated_at: row.get::<_, i64>(14).unwrap_or(0),
|
||||
installed_at: row.get(13)?,
|
||||
content_hash: row.get(14)?,
|
||||
updated_at: row.get::<_, i64>(15).unwrap_or(0),
|
||||
})
|
||||
});
|
||||
|
||||
@@ -107,9 +109,9 @@ impl Database {
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO skills
|
||||
(id, name, description, directory, repo_owner, repo_name, repo_branch,
|
||||
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
|
||||
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes,
|
||||
installed_at, content_hash, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
|
||||
params![
|
||||
skill.id,
|
||||
skill.name,
|
||||
@@ -123,6 +125,7 @@ impl Database {
|
||||
skill.apps.codex,
|
||||
skill.apps.gemini,
|
||||
skill.apps.opencode,
|
||||
skill.apps.hermes,
|
||||
skill.installed_at,
|
||||
skill.content_hash,
|
||||
skill.updated_at,
|
||||
@@ -154,8 +157,8 @@ impl Database {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let affected = conn
|
||||
.execute(
|
||||
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4 WHERE id = ?5",
|
||||
params![apps.claude, apps.codex, apps.gemini, apps.opencode, id],
|
||||
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4, enabled_hermes = ?5 WHERE id = ?6",
|
||||
params![apps.claude, apps.codex, apps.gemini, apps.opencode, apps.hermes, id],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(affected > 0)
|
||||
|
||||
@@ -4,13 +4,61 @@
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use chrono::{Duration, Local, TimeZone};
|
||||
|
||||
/// Compute the rollup/prune cutoff aligned to a local-day boundary.
|
||||
///
|
||||
/// Anything strictly older than the returned timestamp will be aggregated into
|
||||
/// `usage_daily_rollups` and deleted from `proxy_request_logs`. Aligning to the
|
||||
/// next local midnight after `(now - retain_days)` guarantees that the youngest
|
||||
/// rollup row always represents a *complete* local day. Without this alignment
|
||||
/// the cutoff falls mid-day, leaving the day half-rolled-up and half-pruned —
|
||||
/// which would silently under-count any range query that touches that day
|
||||
/// after `compute_rollup_date_bounds` trims partial-coverage rollup days.
|
||||
fn compute_local_midnight_cutoff(
|
||||
now: chrono::DateTime<Local>,
|
||||
retain_days: i64,
|
||||
) -> Result<i64, AppError> {
|
||||
let target_day = now
|
||||
.checked_sub_signed(Duration::days(retain_days))
|
||||
.ok_or_else(|| AppError::Database("rollup cutoff overflow".to_string()))?
|
||||
.date_naive();
|
||||
|
||||
// Use the *next* day's midnight so anything before it has fully been bucketed.
|
||||
let next_day = target_day
|
||||
.succ_opt()
|
||||
.ok_or_else(|| AppError::Database("rollup cutoff next-day overflow".to_string()))?;
|
||||
let naive_midnight = next_day
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.ok_or_else(|| AppError::Database("rollup cutoff midnight overflow".to_string()))?;
|
||||
|
||||
let local_dt = match Local.from_local_datetime(&naive_midnight) {
|
||||
chrono::LocalResult::Single(dt) => dt,
|
||||
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
|
||||
chrono::LocalResult::None => {
|
||||
// DST gap: fall back to one hour later, which always exists.
|
||||
let bumped = naive_midnight + Duration::hours(1);
|
||||
match Local.from_local_datetime(&bumped) {
|
||||
chrono::LocalResult::Single(dt) => dt,
|
||||
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
|
||||
chrono::LocalResult::None => {
|
||||
return Err(AppError::Database(
|
||||
"rollup cutoff fell into DST gap".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(local_dt.timestamp())
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Aggregate proxy_request_logs older than `retain_days` into usage_daily_rollups,
|
||||
/// then delete the aggregated detail rows.
|
||||
/// Returns the number of deleted detail rows.
|
||||
pub fn rollup_and_prune(&self, retain_days: i64) -> Result<u64, AppError> {
|
||||
let cutoff = chrono::Utc::now().timestamp() - retain_days * 86400;
|
||||
let cutoff = compute_local_midnight_cutoff(Local::now(), retain_days)?;
|
||||
let conn = lock_conn!(self.conn);
|
||||
|
||||
// Check if there are any rows to process
|
||||
@@ -110,8 +158,49 @@ impl Database {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::compute_local_midnight_cutoff;
|
||||
use crate::database::Database;
|
||||
use crate::error::AppError;
|
||||
use chrono::{Local, TimeZone};
|
||||
|
||||
fn local_dt(
|
||||
year: i32,
|
||||
month: u32,
|
||||
day: u32,
|
||||
hour: u32,
|
||||
minute: u32,
|
||||
second: u32,
|
||||
) -> chrono::DateTime<Local> {
|
||||
match Local.with_ymd_and_hms(year, month, day, hour, minute, second) {
|
||||
chrono::LocalResult::Single(dt) => dt,
|
||||
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
|
||||
chrono::LocalResult::None => panic!("invalid local datetime in test fixture"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cutoff_is_aligned_to_local_midnight_after_target_day() -> Result<(), AppError> {
|
||||
// now = 2026-04-16 14:32:17 local; retain_days = 30
|
||||
// target day = 2026-03-17; cutoff should be 2026-03-18 00:00 local.
|
||||
let now = local_dt(2026, 4, 16, 14, 32, 17);
|
||||
let cutoff_ts = compute_local_midnight_cutoff(now, 30)?;
|
||||
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
|
||||
let expected = local_dt(2026, 3, 18, 0, 0, 0);
|
||||
assert_eq!(cutoff_dt, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cutoff_at_local_midnight_now_still_lands_on_midnight() -> Result<(), AppError> {
|
||||
// If `now` is itself local midnight, the math should not introduce drift.
|
||||
let now = local_dt(2026, 4, 16, 0, 0, 0);
|
||||
let cutoff_ts = compute_local_midnight_cutoff(now, 7)?;
|
||||
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
|
||||
// (2026-04-16 - 7d) = 2026-04-09; cutoff = 2026-04-10 00:00 local.
|
||||
let expected = local_dt(2026, 4, 10, 0, 0, 0);
|
||||
assert_eq!(cutoff_dt, expected);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rollup_and_prune() -> Result<(), AppError> {
|
||||
|
||||
@@ -44,7 +44,7 @@ use std::sync::Mutex;
|
||||
|
||||
/// 当前 Schema 版本号
|
||||
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
|
||||
pub(crate) const SCHEMA_VERSION: i32 = 9;
|
||||
pub(crate) const SCHEMA_VERSION: i32 = 10;
|
||||
|
||||
/// 安全地序列化 JSON,避免 unwrap panic
|
||||
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
|
||||
|
||||
@@ -65,7 +65,8 @@ impl Database {
|
||||
id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL,
|
||||
description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]',
|
||||
enabled_claude BOOLEAN NOT NULL DEFAULT 0, enabled_codex BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0
|
||||
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_hermes BOOLEAN NOT NULL DEFAULT 0
|
||||
)",
|
||||
[],
|
||||
)
|
||||
@@ -93,6 +94,7 @@ impl Database {
|
||||
enabled_codex BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_gemini BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
|
||||
enabled_hermes BOOLEAN NOT NULL DEFAULT 0,
|
||||
installed_at INTEGER NOT NULL DEFAULT 0,
|
||||
content_hash TEXT,
|
||||
updated_at INTEGER NOT NULL DEFAULT 0
|
||||
@@ -423,6 +425,11 @@ impl Database {
|
||||
Self::migrate_v8_to_v9(conn)?;
|
||||
Self::set_user_version(conn, 9)?;
|
||||
}
|
||||
9 => {
|
||||
log::info!("迁移数据库从 v9 到 v10(添加 Hermes Agent 支持)");
|
||||
Self::migrate_v9_to_v10(conn)?;
|
||||
Self::set_user_version(conn, 10)?;
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::Database(format!(
|
||||
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
|
||||
@@ -1168,11 +1175,43 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// v9 -> v10 迁移:添加 Hermes Agent 支持
|
||||
fn migrate_v9_to_v10(conn: &Connection) -> Result<(), AppError> {
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"mcp_servers",
|
||||
"enabled_hermes",
|
||||
"BOOLEAN NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
|
||||
// skills table may not exist in databases migrated from very old versions
|
||||
if Self::table_exists(conn, "skills")? {
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"skills",
|
||||
"enabled_hermes",
|
||||
"BOOLEAN NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
}
|
||||
|
||||
log::info!("v9 -> v10 迁移完成:已添加 Hermes Agent 支持");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 插入默认模型定价数据
|
||||
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
|
||||
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
|
||||
fn seed_model_pricing(conn: &Connection) -> Result<(), AppError> {
|
||||
let pricing_data = [
|
||||
// Claude 4.7 系列
|
||||
(
|
||||
"claude-opus-4-7",
|
||||
"Claude Opus 4.7",
|
||||
"5",
|
||||
"25",
|
||||
"0.50",
|
||||
"6.25",
|
||||
),
|
||||
// Claude 4.6 系列
|
||||
(
|
||||
"claude-opus-4-6-20260206",
|
||||
@@ -1600,6 +1639,7 @@ impl Database {
|
||||
"0",
|
||||
),
|
||||
("kimi-k2.5", "Kimi K2.5", "0.60", "2.50", "0.10", "0"),
|
||||
("kimi-k2.6", "Kimi K2.6", "0.95", "4.00", "0.16", "0"),
|
||||
// MiniMax 系列
|
||||
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
|
||||
(
|
||||
|
||||
@@ -167,6 +167,7 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
};
|
||||
|
||||
for app in apps_str.split(',') {
|
||||
@@ -179,6 +180,7 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
|
||||
// OpenClaw doesn't support MCP, ignore silently
|
||||
log::debug!("OpenClaw doesn't support MCP, ignoring in apps parameter");
|
||||
}
|
||||
"hermes" => apps.hermes = true,
|
||||
other => {
|
||||
return Err(AppError::InvalidInput(format!(
|
||||
"Invalid app in 'apps': {other}"
|
||||
|
||||
@@ -31,7 +31,7 @@ pub use skill::import_skill_from_deeplink;
|
||||
///
|
||||
/// Represents a parsed ccswitch:// URL ready for processing.
|
||||
/// This struct contains all possible fields for all resource types.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeepLinkImportRequest {
|
||||
/// Protocol version (e.g., "v1")
|
||||
|
||||
@@ -81,10 +81,10 @@ fn parse_provider_deeplink(
|
||||
// Validate app type
|
||||
if !matches!(
|
||||
app.as_str(),
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
|
||||
) {
|
||||
return Err(AppError::InvalidInput(format!(
|
||||
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
|
||||
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -190,10 +190,10 @@ fn parse_prompt_deeplink(
|
||||
// Validate app type
|
||||
if !matches!(
|
||||
app.as_str(),
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
|
||||
) {
|
||||
return Err(AppError::InvalidInput(format!(
|
||||
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
|
||||
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -262,10 +262,10 @@ fn parse_mcp_deeplink(
|
||||
let trimmed = app.trim();
|
||||
if !matches!(
|
||||
trimmed,
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
|
||||
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
|
||||
) {
|
||||
return Err(AppError::InvalidInput(format!(
|
||||
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{trimmed}'"
|
||||
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{trimmed}'"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,8 @@ pub(crate) fn build_provider_from_request(
|
||||
AppType::Codex => build_codex_settings(request),
|
||||
AppType::Gemini => build_gemini_settings(request),
|
||||
AppType::OpenCode => build_opencode_settings(request),
|
||||
AppType::OpenClaw => build_openclaw_settings(request),
|
||||
AppType::OpenClaw => build_additive_app_settings(request),
|
||||
AppType::Hermes => build_hermes_settings(request),
|
||||
};
|
||||
|
||||
// Build usage script configuration if provided
|
||||
@@ -393,11 +394,11 @@ fn build_opencode_settings(request: &DeepLinkImportRequest) -> serde_json::Value
|
||||
})
|
||||
}
|
||||
|
||||
fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
|
||||
/// Build settings for OpenClaw (camelCase live config).
|
||||
/// Format: { baseUrl, apiKey, api, models }
|
||||
fn build_additive_app_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
|
||||
let endpoint = get_primary_endpoint(request);
|
||||
|
||||
// Build OpenClaw provider config
|
||||
// Format: { baseUrl, apiKey, api, models }
|
||||
let mut config = serde_json::Map::new();
|
||||
|
||||
if !endpoint.is_empty() {
|
||||
@@ -408,10 +409,49 @@ fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value
|
||||
config.insert("apiKey".to_string(), json!(api_key));
|
||||
}
|
||||
|
||||
// Default to OpenAI-compatible API
|
||||
config.insert("api".to_string(), json!("openai-completions"));
|
||||
|
||||
// Build models array
|
||||
if let Some(model) = &request.model {
|
||||
config.insert(
|
||||
"models".to_string(),
|
||||
json!([{ "id": model, "name": model }]),
|
||||
);
|
||||
}
|
||||
|
||||
json!(config)
|
||||
}
|
||||
|
||||
/// Build Hermes provider settings (snake_case YAML-native fields).
|
||||
///
|
||||
/// Hermes' `custom_providers:` entries use `base_url` / `api_key` / `api_mode`
|
||||
/// (see `_VALID_CUSTOM_PROVIDER_FIELDS` in upstream `hermes_cli/config.py`).
|
||||
/// Emitting camelCase here — as the OpenClaw path does — would poison the
|
||||
/// YAML with unknown root fields the Hermes runtime ignores.
|
||||
///
|
||||
/// `api_mode` is always written explicitly. Deeplinks have no field to carry
|
||||
/// it, so we default to `chat_completions` (the most widely compatible
|
||||
/// protocol) and let the user adjust via the UI after import. We never rely
|
||||
/// on Hermes' built-in URL heuristics, which only recognize a handful of
|
||||
/// official endpoints.
|
||||
fn build_hermes_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
|
||||
let endpoint = get_primary_endpoint(request);
|
||||
|
||||
let mut config = serde_json::Map::new();
|
||||
|
||||
if let Some(name) = request.name.as_deref().filter(|s| !s.is_empty()) {
|
||||
config.insert("name".to_string(), json!(name));
|
||||
}
|
||||
|
||||
if !endpoint.is_empty() {
|
||||
config.insert("base_url".to_string(), json!(endpoint));
|
||||
}
|
||||
|
||||
if let Some(api_key) = &request.api_key {
|
||||
config.insert("api_key".to_string(), json!(api_key));
|
||||
}
|
||||
|
||||
config.insert("api_mode".to_string(), json!("chat_completions"));
|
||||
|
||||
if let Some(model) = &request.model {
|
||||
config.insert(
|
||||
"models".to_string(),
|
||||
@@ -484,7 +524,7 @@ pub fn parse_and_merge_config(
|
||||
"codex" => merge_codex_config(&mut merged, &config_value)?,
|
||||
"gemini" => merge_gemini_config(&mut merged, &config_value)?,
|
||||
// Additive mode apps use JSON config directly; pass through as-is
|
||||
"openclaw" | "opencode" => {
|
||||
"openclaw" | "opencode" | "hermes" => {
|
||||
merge_additive_config(&mut merged, &config_value)?;
|
||||
}
|
||||
"" => {
|
||||
@@ -711,3 +751,89 @@ fn extract_codex_base_url(toml_value: &toml::Value) -> Option<String> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hermes_request() -> DeepLinkImportRequest {
|
||||
DeepLinkImportRequest {
|
||||
resource: "provider".to_string(),
|
||||
app: Some("hermes".to_string()),
|
||||
name: Some("MyHermes".to_string()),
|
||||
endpoint: Some("https://api.example.com/v1".to_string()),
|
||||
api_key: Some("sk-test".to_string()),
|
||||
model: Some("anthropic/claude-opus-4-7".to_string()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_hermes_settings_emits_snake_case() {
|
||||
let settings = build_hermes_settings(&hermes_request());
|
||||
let obj = settings.as_object().expect("settings must be object");
|
||||
|
||||
assert_eq!(obj.get("name").unwrap(), "MyHermes");
|
||||
assert_eq!(obj.get("base_url").unwrap(), "https://api.example.com/v1");
|
||||
assert_eq!(obj.get("api_key").unwrap(), "sk-test");
|
||||
|
||||
// camelCase and legacy fields must NOT be present
|
||||
assert!(obj.get("baseUrl").is_none(), "no camelCase baseUrl");
|
||||
assert!(obj.get("apiKey").is_none(), "no camelCase apiKey");
|
||||
assert!(obj.get("api").is_none(), "no legacy 'api' field");
|
||||
|
||||
// models array with the deeplink model id
|
||||
let models = obj.get("models").unwrap().as_array().unwrap();
|
||||
assert_eq!(models.len(), 1);
|
||||
assert_eq!(models[0]["id"], "anthropic/claude-opus-4-7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_hermes_settings_writes_default_api_mode() {
|
||||
let settings = build_hermes_settings(&hermes_request());
|
||||
assert_eq!(
|
||||
settings.as_object().unwrap().get("api_mode").unwrap(),
|
||||
"chat_completions",
|
||||
"api_mode must be written explicitly so Hermes never falls back to URL auto-detection"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_hermes_settings_skips_missing_optional_fields() {
|
||||
let request = DeepLinkImportRequest {
|
||||
resource: "provider".to_string(),
|
||||
app: Some("hermes".to_string()),
|
||||
name: Some("Minimal".to_string()),
|
||||
endpoint: None,
|
||||
api_key: None,
|
||||
model: None,
|
||||
..Default::default()
|
||||
};
|
||||
let settings = build_hermes_settings(&request);
|
||||
let obj = settings.as_object().unwrap();
|
||||
|
||||
assert_eq!(obj.get("name").unwrap(), "Minimal");
|
||||
assert!(obj.get("base_url").is_none());
|
||||
assert!(obj.get("api_key").is_none());
|
||||
assert!(obj.get("models").is_none());
|
||||
assert_eq!(obj.get("api_mode").unwrap(), "chat_completions");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openclaw_still_uses_camel_case() {
|
||||
// OpenClaw's live config natively uses camelCase; guard against a
|
||||
// refactor accidentally flipping it to snake_case.
|
||||
let request = DeepLinkImportRequest {
|
||||
resource: "provider".to_string(),
|
||||
app: Some("openclaw".to_string()),
|
||||
name: Some("c".to_string()),
|
||||
endpoint: Some("https://api.example.com".to_string()),
|
||||
api_key: Some("k".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
let settings = build_additive_app_settings(&request);
|
||||
let obj = settings.as_object().unwrap();
|
||||
assert!(obj.contains_key("baseUrl"));
|
||||
assert!(obj.contains_key("apiKey"));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+31
-2
@@ -11,6 +11,7 @@ mod deeplink;
|
||||
mod error;
|
||||
mod gemini_config;
|
||||
mod gemini_mcp;
|
||||
pub mod hermes_config;
|
||||
mod init_status;
|
||||
mod lightweight;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -168,7 +169,7 @@ async fn update_tray_menu(
|
||||
) -> Result<bool, String> {
|
||||
match tray::create_tray_menu(&app, state.inner()) {
|
||||
Ok(new_menu) => {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(tray::TRAY_ID) {
|
||||
tray.set_menu(Some(new_menu))
|
||||
.map_err(|e| format!("更新托盘菜单失败: {e}"))?;
|
||||
return Ok(true);
|
||||
@@ -540,6 +541,13 @@ pub fn run() {
|
||||
Ok(_) => log::debug!("○ No new OpenClaw providers to import"),
|
||||
Err(e) => log::warn!("✗ Failed to import OpenClaw providers: {e}"),
|
||||
}
|
||||
match crate::services::provider::import_hermes_providers_from_live(&app_state) {
|
||||
Ok(count) if count > 0 => {
|
||||
log::info!("✓ Imported {count} Hermes provider(s) from live config");
|
||||
}
|
||||
Ok(_) => log::debug!("○ No new Hermes providers to import"),
|
||||
Err(e) => log::warn!("✗ Failed to import Hermes providers: {e}"),
|
||||
}
|
||||
|
||||
// 2. OMO 配置导入(当数据库中无 OMO provider 时,从本地文件导入)
|
||||
{
|
||||
@@ -627,6 +635,14 @@ pub fn run() {
|
||||
Ok(_) => log::debug!("○ No OpenCode MCP servers found to import"),
|
||||
Err(e) => log::warn!("✗ Failed to import OpenCode MCP: {e}"),
|
||||
}
|
||||
|
||||
match crate::services::mcp::McpService::import_from_hermes(&app_state) {
|
||||
Ok(count) if count > 0 => {
|
||||
log::info!("✓ Imported {count} MCP server(s) from Hermes");
|
||||
}
|
||||
Ok(_) => log::debug!("○ No Hermes MCP servers found to import"),
|
||||
Err(e) => log::warn!("✗ Failed to import Hermes MCP: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 导入提示词文件(表空时触发)
|
||||
@@ -639,6 +655,7 @@ pub fn run() {
|
||||
crate::app_config::AppType::Gemini,
|
||||
crate::app_config::AppType::OpenCode,
|
||||
crate::app_config::AppType::OpenClaw,
|
||||
crate::app_config::AppType::Hermes,
|
||||
] {
|
||||
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
|
||||
&app_state,
|
||||
@@ -728,7 +745,7 @@ pub fn run() {
|
||||
let menu = tray::create_tray_menu(app.handle(), &app_state)?;
|
||||
|
||||
// 构建托盘
|
||||
let mut tray_builder = TrayIconBuilder::with_id("main")
|
||||
let mut tray_builder = TrayIconBuilder::with_id(tray::TRAY_ID)
|
||||
.on_tray_icon_event(|_tray, event| match event {
|
||||
// 左键点击已通过 show_menu_on_left_click(true) 打开菜单,这里不再额外处理
|
||||
TrayIconEvent::Click { .. } => {}
|
||||
@@ -1234,6 +1251,18 @@ pub fn run() {
|
||||
commands::set_openclaw_env,
|
||||
commands::get_openclaw_tools,
|
||||
commands::set_openclaw_tools,
|
||||
// Hermes specific
|
||||
commands::import_hermes_providers_from_live,
|
||||
commands::get_hermes_live_provider_ids,
|
||||
commands::get_hermes_live_provider,
|
||||
commands::scan_hermes_config_health,
|
||||
commands::get_hermes_model_config,
|
||||
commands::open_hermes_web_ui,
|
||||
commands::launch_hermes_dashboard,
|
||||
commands::get_hermes_memory,
|
||||
commands::set_hermes_memory,
|
||||
commands::get_hermes_memory_limits,
|
||||
commands::set_hermes_memory_enabled,
|
||||
// Global upstream proxy
|
||||
commands::get_global_proxy_url,
|
||||
commands::set_global_proxy_url,
|
||||
|
||||
@@ -92,6 +92,7 @@ pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -236,6 +236,7 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
|
||||
codex: true,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -88,6 +88,7 @@ pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError
|
||||
codex: false,
|
||||
gemini: true,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
//! Hermes MCP sync and import module
|
||||
//!
|
||||
//! Handles conversion between CC Switch unified MCP format and Hermes config.yaml format.
|
||||
//!
|
||||
//! ## Format mapping
|
||||
//!
|
||||
//! | CC Switch unified (JSON) | Hermes config.yaml (YAML) |
|
||||
//! |-------------------------------------------------|---------------------------------|
|
||||
//! | `{"type":"stdio","command":"npx","args":[...],"env":{}}` | `command: npx`, `args: [...]`, `env: {}` |
|
||||
//! | `{"type":"sse"/"http","url":"...","headers":{}}` | `url: "..."`, `headers: {}` |
|
||||
//!
|
||||
//! Key differences from Claude format:
|
||||
//! - Hermes has NO explicit `type` field -- it infers stdio (has `command`) vs HTTP (has `url`)
|
||||
//! - Hermes has extra fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
|
||||
//! - These Hermes-specific fields are preserved on merge-on-write and stripped on import
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::app_config::{McpApps, McpServer, MultiAppConfig};
|
||||
use crate::error::AppError;
|
||||
use crate::hermes_config;
|
||||
|
||||
use super::validation::validate_server_spec;
|
||||
|
||||
/// Hermes-specific fields preserved on merge-on-write, stripped on import.
|
||||
/// Update this list when Hermes adds new per-server config fields.
|
||||
///
|
||||
/// `auth` ("oauth" / absent) is an OAuth-type declaration read by Hermes —
|
||||
/// CC Switch has no OAuth UI, but losing the field on round-trip downgrades
|
||||
/// the server to unauthenticated calls.
|
||||
const HERMES_EXTRA_FIELDS: &[&str] = &[
|
||||
"enabled",
|
||||
"timeout",
|
||||
"connect_timeout",
|
||||
"tools",
|
||||
"sampling",
|
||||
"roots",
|
||||
"auth",
|
||||
];
|
||||
|
||||
// ============================================================================
|
||||
// Helper Functions
|
||||
// ============================================================================
|
||||
|
||||
/// Check if Hermes MCP sync should proceed
|
||||
fn should_sync_hermes_mcp() -> bool {
|
||||
hermes_config::get_hermes_dir().exists()
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Format Conversion: CC Switch -> Hermes
|
||||
// ============================================================================
|
||||
|
||||
/// Convert CC Switch unified format to Hermes format
|
||||
///
|
||||
/// Conversion rules:
|
||||
/// - `stdio`: output `command`, `args`, `env` (strip `type` field)
|
||||
/// - `sse`/`http`: output `url`, `headers` (strip `type` field)
|
||||
/// - Always add `enabled: true`
|
||||
fn convert_to_hermes_format(spec: &Value) -> Result<Value, AppError> {
|
||||
let obj = spec
|
||||
.as_object()
|
||||
.ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
|
||||
|
||||
let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
|
||||
|
||||
let mut result = serde_json::Map::new();
|
||||
|
||||
match typ {
|
||||
"stdio" => {
|
||||
if let Some(command) = obj.get("command") {
|
||||
result.insert("command".into(), command.clone());
|
||||
}
|
||||
if let Some(args) = obj.get("args") {
|
||||
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
|
||||
result.insert("args".into(), args.clone());
|
||||
}
|
||||
}
|
||||
if let Some(env) = obj.get("env") {
|
||||
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
|
||||
result.insert("env".into(), env.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
"sse" | "http" => {
|
||||
if let Some(url) = obj.get("url") {
|
||||
result.insert("url".into(), url.clone());
|
||||
}
|
||||
if let Some(headers) = obj.get("headers") {
|
||||
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
|
||||
{
|
||||
result.insert("headers".into(), headers.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
|
||||
}
|
||||
}
|
||||
|
||||
result.insert("enabled".into(), json!(true));
|
||||
|
||||
Ok(Value::Object(result))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Format Conversion: Hermes -> CC Switch
|
||||
// ============================================================================
|
||||
|
||||
/// Convert Hermes format to CC Switch unified format
|
||||
///
|
||||
/// Conversion rules:
|
||||
/// - If `command` exists: set `type: "stdio"`, extract `command`, `args`, `env`
|
||||
/// - If `url` exists: set `type: "sse"`, extract `url`, `headers`
|
||||
/// - Strip Hermes-specific fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
|
||||
fn convert_from_hermes_format(id: &str, spec: &Value) -> Result<Value, AppError> {
|
||||
let obj = spec
|
||||
.as_object()
|
||||
.ok_or_else(|| AppError::McpValidation("Hermes MCP spec must be a JSON object".into()))?;
|
||||
|
||||
let mut result = serde_json::Map::new();
|
||||
|
||||
if obj.contains_key("command") {
|
||||
// stdio type
|
||||
result.insert("type".into(), json!("stdio"));
|
||||
|
||||
if let Some(command) = obj.get("command") {
|
||||
result.insert("command".into(), command.clone());
|
||||
}
|
||||
if let Some(args) = obj.get("args") {
|
||||
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
|
||||
result.insert("args".into(), args.clone());
|
||||
}
|
||||
}
|
||||
if let Some(env) = obj.get("env") {
|
||||
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
|
||||
result.insert("env".into(), env.clone());
|
||||
}
|
||||
}
|
||||
} else if obj.contains_key("url") {
|
||||
// HTTP/SSE type
|
||||
result.insert("type".into(), json!("sse"));
|
||||
|
||||
if let Some(url) = obj.get("url") {
|
||||
result.insert("url".into(), url.clone());
|
||||
}
|
||||
if let Some(headers) = obj.get("headers") {
|
||||
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true) {
|
||||
result.insert("headers".into(), headers.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(AppError::McpValidation(format!(
|
||||
"Hermes MCP server '{id}' has neither 'command' nor 'url' field"
|
||||
)));
|
||||
}
|
||||
|
||||
// Note: Hermes-specific fields (enabled, timeout, connect_timeout, tools, sampling)
|
||||
// are intentionally NOT copied -- they are stripped on import.
|
||||
|
||||
Ok(Value::Object(result))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Public API: Sync Functions
|
||||
// ============================================================================
|
||||
|
||||
/// Sync a single MCP server to Hermes live config (merge-on-write)
|
||||
///
|
||||
/// Strategy:
|
||||
/// 1. Read existing mcp_servers from config.yaml
|
||||
/// 2. If server already exists, merge: keep Hermes-specific fields, overwrite core fields
|
||||
/// 3. Set `enabled: true`
|
||||
/// 4. Write back
|
||||
pub fn sync_single_server_to_hermes(
|
||||
_config: &MultiAppConfig,
|
||||
id: &str,
|
||||
server_spec: &Value,
|
||||
) -> Result<(), AppError> {
|
||||
if !should_sync_hermes_mcp() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let hermes_spec = convert_to_hermes_format(server_spec)?;
|
||||
let id_owned = id.to_string();
|
||||
|
||||
hermes_config::update_mcp_servers_yaml(|servers| {
|
||||
let id_yaml = serde_yaml::Value::String(id_owned.clone());
|
||||
|
||||
let merged_json = if let Some(existing_yaml) = servers.get(&id_yaml) {
|
||||
let existing_json = hermes_config::yaml_to_json(existing_yaml)?;
|
||||
merge_hermes_spec(&existing_json, &hermes_spec)
|
||||
} else {
|
||||
hermes_spec.clone()
|
||||
};
|
||||
|
||||
let merged_yaml_value = hermes_config::json_to_yaml(&merged_json)?;
|
||||
servers.insert(id_yaml, merged_yaml_value);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Merge new spec into existing Hermes spec, preserving Hermes-specific fields.
|
||||
///
|
||||
/// Core fields (command, args, env, url, headers) come from `new_spec`.
|
||||
/// Hermes-specific fields (enabled, tools, sampling, etc.) are kept from
|
||||
/// `existing` — this prevents CC Switch from overwriting user customizations.
|
||||
fn merge_hermes_spec(existing: &Value, new_spec: &Value) -> Value {
|
||||
let mut result = serde_json::Map::new();
|
||||
|
||||
// Copy Hermes-specific fields from existing config
|
||||
if let Some(existing_obj) = existing.as_object() {
|
||||
for &field in HERMES_EXTRA_FIELDS {
|
||||
if let Some(val) = existing_obj.get(field) {
|
||||
result.insert(field.to_string(), val.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Overwrite with core fields from new spec; for Hermes-specific fields,
|
||||
// only apply from new_spec if existing didn't already have them
|
||||
if let Some(new_obj) = new_spec.as_object() {
|
||||
for (key, val) in new_obj {
|
||||
if HERMES_EXTRA_FIELDS.contains(&key.as_str()) && result.contains_key(key) {
|
||||
continue; // Existing Hermes-specific field takes precedence
|
||||
}
|
||||
result.insert(key.clone(), val.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Value::Object(result)
|
||||
}
|
||||
|
||||
/// Remove a single MCP server from Hermes live config
|
||||
pub fn remove_server_from_hermes(id: &str) -> Result<(), AppError> {
|
||||
if !should_sync_hermes_mcp() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let id_owned = id.to_string();
|
||||
hermes_config::update_mcp_servers_yaml(|servers| {
|
||||
servers.remove(serde_yaml::Value::String(id_owned.clone()));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Import MCP servers from Hermes config to unified structure
|
||||
///
|
||||
/// Existing servers will have Hermes app enabled without overwriting other fields.
|
||||
pub fn import_from_hermes(config: &mut MultiAppConfig) -> Result<usize, AppError> {
|
||||
let yaml_map = hermes_config::get_mcp_servers_yaml()?;
|
||||
if yaml_map.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// Ensure servers map exists
|
||||
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
|
||||
|
||||
let mut changed = 0;
|
||||
let mut errors = Vec::new();
|
||||
|
||||
for (key, spec_yaml) in &yaml_map {
|
||||
let id = match key.as_str() {
|
||||
Some(s) => s.to_string(),
|
||||
None => {
|
||||
log::warn!("Skip Hermes MCP server with non-string key");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Convert YAML value to JSON
|
||||
let spec_json = match hermes_config::yaml_to_json(spec_yaml) {
|
||||
Ok(j) => j,
|
||||
Err(e) => {
|
||||
log::warn!("Skip Hermes MCP server '{id}': failed to convert YAML to JSON: {e}");
|
||||
errors.push(format!("{id}: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Convert from Hermes format to unified format
|
||||
let unified_spec = match convert_from_hermes_format(&id, &spec_json) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Skip invalid Hermes MCP server '{id}': {e}");
|
||||
errors.push(format!("{id}: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Validate the converted spec
|
||||
if let Err(e) = validate_server_spec(&unified_spec) {
|
||||
log::warn!("Skip invalid MCP server '{id}' after conversion: {e}");
|
||||
errors.push(format!("{id}: {e}"));
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(existing) = servers.get_mut(&id) {
|
||||
// Existing server: just enable Hermes app
|
||||
if !existing.apps.hermes {
|
||||
existing.apps.hermes = true;
|
||||
changed += 1;
|
||||
log::info!("MCP server '{id}' enabled for Hermes");
|
||||
}
|
||||
} else {
|
||||
// New server: default to only Hermes enabled
|
||||
servers.insert(
|
||||
id.clone(),
|
||||
McpServer {
|
||||
id: id.clone(),
|
||||
name: id.clone(),
|
||||
server: unified_spec,
|
||||
apps: McpApps {
|
||||
claude: false,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: true,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
docs: None,
|
||||
tags: Vec::new(),
|
||||
},
|
||||
);
|
||||
changed += 1;
|
||||
log::info!("Imported new MCP server '{id}' from Hermes");
|
||||
}
|
||||
}
|
||||
|
||||
if !errors.is_empty() {
|
||||
log::warn!(
|
||||
"Import completed with {} failures: {:?}",
|
||||
errors.len(),
|
||||
errors
|
||||
);
|
||||
}
|
||||
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// ========================================================================
|
||||
// convert_to_hermes_format tests
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn test_convert_stdio_to_hermes() {
|
||||
let spec = json!({
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
|
||||
"env": { "HOME": "/Users/test" }
|
||||
});
|
||||
|
||||
let result = convert_to_hermes_format(&spec).unwrap();
|
||||
// No type field in Hermes format
|
||||
assert!(result.get("type").is_none());
|
||||
assert_eq!(result["command"], "npx");
|
||||
assert_eq!(result["args"][0], "-y");
|
||||
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
|
||||
assert_eq!(result["env"]["HOME"], "/Users/test");
|
||||
assert_eq!(result["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_http_to_hermes() {
|
||||
let spec = json!({
|
||||
"type": "sse",
|
||||
"url": "https://example.com/mcp",
|
||||
"headers": { "Authorization": "Bearer xxx" }
|
||||
});
|
||||
|
||||
let result = convert_to_hermes_format(&spec).unwrap();
|
||||
assert!(result.get("type").is_none());
|
||||
assert_eq!(result["url"], "https://example.com/mcp");
|
||||
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
|
||||
assert_eq!(result["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_http_type_to_hermes() {
|
||||
let spec = json!({
|
||||
"type": "http",
|
||||
"url": "https://example.com/mcp"
|
||||
});
|
||||
|
||||
let result = convert_to_hermes_format(&spec).unwrap();
|
||||
assert!(result.get("type").is_none());
|
||||
assert_eq!(result["url"], "https://example.com/mcp");
|
||||
assert_eq!(result["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_stdio_empty_env_to_hermes() {
|
||||
let spec = json!({
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"args": [],
|
||||
"env": {}
|
||||
});
|
||||
|
||||
let result = convert_to_hermes_format(&spec).unwrap();
|
||||
assert_eq!(result["command"], "node");
|
||||
// Empty args and env should be omitted
|
||||
assert!(result.get("args").is_none());
|
||||
assert!(result.get("env").is_none());
|
||||
assert_eq!(result["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_unknown_type_to_hermes_fails() {
|
||||
let spec = json!({ "type": "grpc", "command": "foo" });
|
||||
assert!(convert_to_hermes_format(&spec).is_err());
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// convert_from_hermes_format tests
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn test_convert_hermes_stdio_to_unified() {
|
||||
let spec = json!({
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
|
||||
"env": { "HOME": "/Users/test" },
|
||||
"enabled": true,
|
||||
"timeout": 30,
|
||||
"connect_timeout": 10,
|
||||
"tools": { "include": ["read_file"] },
|
||||
"sampling": { "enabled": true }
|
||||
});
|
||||
|
||||
let result = convert_from_hermes_format("filesystem", &spec).unwrap();
|
||||
assert_eq!(result["type"], "stdio");
|
||||
assert_eq!(result["command"], "npx");
|
||||
assert_eq!(result["args"][0], "-y");
|
||||
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
|
||||
assert_eq!(result["env"]["HOME"], "/Users/test");
|
||||
// Hermes-specific fields should be stripped
|
||||
assert!(result.get("enabled").is_none());
|
||||
assert!(result.get("timeout").is_none());
|
||||
assert!(result.get("connect_timeout").is_none());
|
||||
assert!(result.get("tools").is_none());
|
||||
assert!(result.get("sampling").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_hermes_http_to_unified() {
|
||||
let spec = json!({
|
||||
"url": "https://example.com/mcp",
|
||||
"headers": { "Authorization": "Bearer xxx" },
|
||||
"enabled": true,
|
||||
"timeout": 60
|
||||
});
|
||||
|
||||
let result = convert_from_hermes_format("remote-server", &spec).unwrap();
|
||||
assert_eq!(result["type"], "sse");
|
||||
assert_eq!(result["url"], "https://example.com/mcp");
|
||||
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
|
||||
// Hermes-specific fields should be stripped
|
||||
assert!(result.get("enabled").is_none());
|
||||
assert!(result.get("timeout").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_hermes_no_command_no_url_fails() {
|
||||
let spec = json!({ "enabled": true, "timeout": 30 });
|
||||
assert!(convert_from_hermes_format("bad-server", &spec).is_err());
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Merge-on-write tests
|
||||
// ========================================================================
|
||||
|
||||
#[test]
|
||||
fn test_merge_preserves_hermes_specific_fields() {
|
||||
let existing = json!({
|
||||
"command": "old-cmd",
|
||||
"args": ["old-arg"],
|
||||
"enabled": true,
|
||||
"timeout": 30,
|
||||
"connect_timeout": 10,
|
||||
"tools": { "include": ["read_file"] },
|
||||
"sampling": { "enabled": true }
|
||||
});
|
||||
|
||||
let new_spec = json!({
|
||||
"command": "new-cmd",
|
||||
"args": ["new-arg"],
|
||||
"env": { "KEY": "value" },
|
||||
"enabled": true
|
||||
});
|
||||
|
||||
let merged = merge_hermes_spec(&existing, &new_spec);
|
||||
|
||||
// Core fields should be overwritten
|
||||
assert_eq!(merged["command"], "new-cmd");
|
||||
assert_eq!(merged["args"][0], "new-arg");
|
||||
assert_eq!(merged["env"]["KEY"], "value");
|
||||
|
||||
// Hermes-specific fields should be preserved from existing
|
||||
assert_eq!(merged["timeout"], 30);
|
||||
assert_eq!(merged["connect_timeout"], 10);
|
||||
assert_eq!(merged["tools"]["include"][0], "read_file");
|
||||
assert_eq!(merged["sampling"]["enabled"], true);
|
||||
assert_eq!(merged["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_preserves_auth_field() {
|
||||
let existing = json!({
|
||||
"url": "https://mcp.example.com",
|
||||
"auth": "oauth",
|
||||
"enabled": true
|
||||
});
|
||||
|
||||
let new_spec = json!({
|
||||
"url": "https://mcp.example.com/updated",
|
||||
"headers": { "X-Trace": "abc" },
|
||||
"enabled": true
|
||||
});
|
||||
|
||||
let merged = merge_hermes_spec(&existing, &new_spec);
|
||||
|
||||
assert_eq!(merged["url"], "https://mcp.example.com/updated");
|
||||
assert_eq!(merged["headers"]["X-Trace"], "abc");
|
||||
assert_eq!(
|
||||
merged["auth"], "oauth",
|
||||
"auth declaration must survive CC Switch round-trip"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_convert_hermes_strips_auth_on_import() {
|
||||
let spec = json!({
|
||||
"url": "https://mcp.example.com",
|
||||
"auth": "oauth",
|
||||
"enabled": true
|
||||
});
|
||||
|
||||
let result = convert_from_hermes_format("remote", &spec).unwrap();
|
||||
assert_eq!(result["type"], "sse");
|
||||
assert_eq!(result["url"], "https://mcp.example.com");
|
||||
assert!(
|
||||
result.get("auth").is_none(),
|
||||
"auth stays Hermes-specific; stripped from unified format"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_new_server_no_existing_extra_fields() {
|
||||
let existing = json!({
|
||||
"command": "old-cmd"
|
||||
});
|
||||
|
||||
let new_spec = json!({
|
||||
"command": "new-cmd",
|
||||
"args": ["arg1"],
|
||||
"enabled": true
|
||||
});
|
||||
|
||||
let merged = merge_hermes_spec(&existing, &new_spec);
|
||||
assert_eq!(merged["command"], "new-cmd");
|
||||
assert_eq!(merged["args"][0], "arg1");
|
||||
assert_eq!(merged["enabled"], true);
|
||||
// No extra fields to preserve
|
||||
assert!(merged.get("timeout").is_none());
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,12 @@
|
||||
//! - `codex` - Codex MCP 同步和导入(含 TOML 转换)
|
||||
//! - `gemini` - Gemini MCP 同步和导入
|
||||
//! - `opencode` - OpenCode MCP 同步和导入(含 local/remote 格式转换)
|
||||
//! - `hermes` - Hermes MCP 同步和导入
|
||||
|
||||
mod claude;
|
||||
mod codex;
|
||||
mod gemini;
|
||||
mod hermes;
|
||||
mod opencode;
|
||||
mod validation;
|
||||
|
||||
@@ -28,6 +30,7 @@ pub use gemini::{
|
||||
import_from_gemini, remove_server_from_gemini, sync_enabled_to_gemini,
|
||||
sync_single_server_to_gemini,
|
||||
};
|
||||
pub use hermes::{import_from_hermes, remove_server_from_hermes, sync_single_server_to_hermes};
|
||||
pub use opencode::{
|
||||
import_from_opencode, remove_server_from_opencode, sync_single_server_to_opencode,
|
||||
};
|
||||
|
||||
@@ -259,6 +259,7 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: true,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -914,6 +914,7 @@ pub fn set_tools_config(tools: &OpenClawToolsConfig) -> Result<OpenClawWriteOutc
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serial_test::serial;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
fn test_guard() -> std::sync::MutexGuard<'static, ()> {
|
||||
@@ -966,6 +967,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn default_model_write_preserves_top_level_comments() {
|
||||
let source = r#"{
|
||||
// top-level comment
|
||||
@@ -994,6 +996,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn default_model_noop_write_skips_backup() {
|
||||
let source = r#"{
|
||||
models: {
|
||||
@@ -1028,6 +1031,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn save_detects_external_conflict() {
|
||||
let source = r#"{
|
||||
models: {
|
||||
@@ -1050,6 +1054,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn remove_last_provider_writes_empty_providers_without_panic() {
|
||||
let source = r#"{
|
||||
models: {
|
||||
|
||||
@@ -16,14 +16,14 @@ pub fn prompt_file_path(app: &AppType) -> Result<PathBuf, AppError> {
|
||||
AppType::Gemini => get_gemini_dir(),
|
||||
AppType::OpenCode => get_opencode_dir(),
|
||||
AppType::OpenClaw => get_openclaw_dir(),
|
||||
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
|
||||
};
|
||||
|
||||
let filename = match app {
|
||||
AppType::Claude => "CLAUDE.md",
|
||||
AppType::Codex => "AGENTS.md",
|
||||
AppType::Gemini => "GEMINI.md",
|
||||
AppType::OpenCode => "AGENTS.md",
|
||||
AppType::OpenClaw => "AGENTS.md", // OpenClaw uses AGENTS.md for agent instructions
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => "AGENTS.md",
|
||||
};
|
||||
|
||||
Ok(base_dir.join(filename))
|
||||
|
||||
@@ -443,6 +443,41 @@ pub fn sanitize_orphan_tool_results(mut body: Value) -> Value {
|
||||
body
|
||||
}
|
||||
|
||||
/// 请求前主动剥离所有 assistant 消息里的 thinking / redacted_thinking block
|
||||
///
|
||||
/// Copilot 的三条目标端点(`/chat/completions`、`/v1/responses`、`/v1/chat/completions`)
|
||||
/// 均为 OpenAI 兼容格式,不识别 Anthropic 的 thinking block。若原样转发,上游会
|
||||
/// 拒绝并返回 invalid_request_error —— 届时 `thinking_rectifier` 才做反应式清理并
|
||||
/// 重试。那次已经失败的请求依旧消耗一次 premium quota,所以此处提前剥离。
|
||||
///
|
||||
/// 与 `thinking_rectifier::rectify_anthropic_request` 的区别:
|
||||
/// - 本函数只剥 thinking / redacted_thinking 两类 block,不触碰 signature,也不
|
||||
/// 移除顶层 thinking 字段——那些是错误路径上的激进整流,常规路径不需要。
|
||||
/// - 保持与 `merge_tool_results` / `sanitize_orphan_tool_results` 一致的"消费 body、
|
||||
/// 返回新 body"签名,便于接入 forwarder 管道。
|
||||
pub fn strip_thinking_blocks(mut body: Value) -> Value {
|
||||
let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) else {
|
||||
return body;
|
||||
};
|
||||
|
||||
for msg in messages.iter_mut() {
|
||||
if msg.get("role").and_then(|r| r.as_str()) != Some("assistant") {
|
||||
continue;
|
||||
}
|
||||
let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) else {
|
||||
continue;
|
||||
};
|
||||
content.retain(|block| {
|
||||
!matches!(
|
||||
block.get("type").and_then(|t| t.as_str()),
|
||||
Some("thinking") | Some("redacted_thinking")
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
// ─── 内部辅助 ─────────────────────────────────
|
||||
|
||||
/// 从请求体的 `system` 字段提取文本(处理 string/array 两种格式)。
|
||||
@@ -1371,4 +1406,138 @@ mod tests {
|
||||
assert_eq!(content[0]["type"], "text");
|
||||
assert_eq!(content[1]["type"], "text");
|
||||
}
|
||||
|
||||
// === strip_thinking_blocks 测试 ===
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_removes_assistant_thinking_blocks() {
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "user", "content": [{"type": "text", "text": "hi"}]},
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "thinking", "thinking": "let me ponder", "signature": "sig"},
|
||||
{"type": "redacted_thinking", "data": "opaque"},
|
||||
{"type": "text", "text": "hello"},
|
||||
{"type": "tool_use", "id": "t1", "name": "read", "input": {}}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let content = result["messages"][1]["content"].as_array().unwrap();
|
||||
assert_eq!(content.len(), 2);
|
||||
assert_eq!(content[0]["type"], "text");
|
||||
assert_eq!(content[1]["type"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_leaves_user_messages_untouched() {
|
||||
// 仅处理 assistant,user 的 thinking 块(极少见,但可能)不动
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "user", "content": [
|
||||
{"type": "thinking", "thinking": "x"},
|
||||
{"type": "text", "text": "hi"}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let content = result["messages"][0]["content"].as_array().unwrap();
|
||||
assert_eq!(content.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_handles_missing_messages() {
|
||||
let body = serde_json::json!({ "model": "claude-3-5-sonnet" });
|
||||
let result = strip_thinking_blocks(body.clone());
|
||||
assert_eq!(result, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_leaves_empty_content_array() {
|
||||
// 仅含 thinking 的 assistant 消息剥完后 content 为空——保留上游自处理
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "thinking", "thinking": "solo"}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let content = result["messages"][0]["content"].as_array().unwrap();
|
||||
assert_eq!(content.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_preserves_signature_on_non_thinking_blocks() {
|
||||
// signature 留给 thinking_rectifier 在错误路径处理,此处不动
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "tool_use", "id": "t1", "name": "x", "input": {}, "signature": "s"}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let block = &result["messages"][0]["content"][0];
|
||||
assert_eq!(block["signature"], "s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_multiple_assistant_turns() {
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "user", "content": [{"type": "text", "text": "q1"}]},
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "thinking", "thinking": "a"},
|
||||
{"type": "text", "text": "r1"}
|
||||
]},
|
||||
{"role": "user", "content": [{"type": "text", "text": "q2"}]},
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "redacted_thinking", "data": "x"},
|
||||
{"type": "text", "text": "r2"}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let a1 = result["messages"][1]["content"].as_array().unwrap();
|
||||
let a2 = result["messages"][3]["content"].as_array().unwrap();
|
||||
assert_eq!(a1.len(), 1);
|
||||
assert_eq!(a1[0]["text"], "r1");
|
||||
assert_eq!(a2.len(), 1);
|
||||
assert_eq!(a2[0]["text"], "r2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_ignores_string_content() {
|
||||
// assistant.content 是字符串而非 block 数组 — 历史请求或极简客户端会这样
|
||||
// 不应崩溃,也不应转换结构
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "assistant", "content": "plain text response"}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body.clone());
|
||||
assert_eq!(result, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_thinking_preserves_block_order() {
|
||||
let body = serde_json::json!({
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "thinking", "thinking": "pre"},
|
||||
{"type": "text", "text": "A"},
|
||||
{"type": "tool_use", "id": "t1", "name": "x", "input": {}},
|
||||
{"type": "redacted_thinking", "data": "mid"},
|
||||
{"type": "text", "text": "B"}
|
||||
]}
|
||||
]
|
||||
});
|
||||
let result = strip_thinking_blocks(body);
|
||||
let content = result["messages"][0]["content"].as_array().unwrap();
|
||||
assert_eq!(content.len(), 3);
|
||||
assert_eq!(content[0]["text"], "A");
|
||||
assert_eq!(content[1]["type"], "tool_use");
|
||||
assert_eq!(content[2]["text"], "B");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ impl FailoverSwitchManager {
|
||||
}
|
||||
|
||||
if let Ok(new_menu) = crate::tray::create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
|
||||
if let Err(e) = tray.set_menu(Some(new_menu)) {
|
||||
log::error!("[Failover] 更新托盘菜单失败: {e}");
|
||||
}
|
||||
|
||||
@@ -9,7 +9,10 @@ use super::{
|
||||
failover_switch::FailoverSwitchManager,
|
||||
log_codes::fwd as log_fwd,
|
||||
provider_router::ProviderRouter,
|
||||
providers::{get_adapter, AuthInfo, AuthStrategy, ProviderAdapter, ProviderType},
|
||||
providers::{
|
||||
gemini_shadow::GeminiShadowStore, get_adapter, AuthInfo, AuthStrategy, ProviderAdapter,
|
||||
ProviderType,
|
||||
},
|
||||
thinking_budget_rectifier::{rectify_thinking_budget, should_rectify_thinking_budget},
|
||||
thinking_rectifier::{
|
||||
normalize_thinking_type, rectify_anthropic_request, should_rectify_thinking_signature,
|
||||
@@ -43,12 +46,15 @@ pub struct RequestForwarder {
|
||||
router: Arc<ProviderRouter>,
|
||||
status: Arc<RwLock<ProxyStatus>>,
|
||||
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
gemini_shadow: Arc<GeminiShadowStore>,
|
||||
/// 故障转移切换管理器
|
||||
failover_manager: Arc<FailoverSwitchManager>,
|
||||
/// AppHandle,用于发射事件和更新托盘
|
||||
app_handle: Option<tauri::AppHandle>,
|
||||
/// 请求开始时的"当前供应商 ID"(用于判断是否需要同步 UI/托盘)
|
||||
current_provider_id_at_start: String,
|
||||
/// 代理会话 ID(用于 Gemini Native shadow replay)
|
||||
session_id: String,
|
||||
/// 整流器配置
|
||||
rectifier_config: RectifierConfig,
|
||||
/// 优化器配置
|
||||
@@ -66,9 +72,11 @@ impl RequestForwarder {
|
||||
non_streaming_timeout: u64,
|
||||
status: Arc<RwLock<ProxyStatus>>,
|
||||
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
gemini_shadow: Arc<GeminiShadowStore>,
|
||||
failover_manager: Arc<FailoverSwitchManager>,
|
||||
app_handle: Option<tauri::AppHandle>,
|
||||
current_provider_id_at_start: String,
|
||||
session_id: String,
|
||||
_streaming_first_byte_timeout: u64,
|
||||
_streaming_idle_timeout: u64,
|
||||
rectifier_config: RectifierConfig,
|
||||
@@ -79,9 +87,11 @@ impl RequestForwarder {
|
||||
router,
|
||||
status,
|
||||
current_providers,
|
||||
gemini_shadow,
|
||||
failover_manager,
|
||||
app_handle,
|
||||
current_provider_id_at_start,
|
||||
session_id,
|
||||
rectifier_config,
|
||||
optimizer_config,
|
||||
copilot_optimizer_config,
|
||||
@@ -811,6 +821,12 @@ impl RequestForwarder {
|
||||
mapped_body = super::copilot_optimizer::merge_tool_results(mapped_body);
|
||||
}
|
||||
|
||||
// 3.5. 主动剥离 thinking block — Copilot 走 OpenAI 兼容端点不识别该块
|
||||
// 避免上游拒绝后由 rectifier 反应式重试(首次请求已消耗 quota)
|
||||
if self.copilot_optimizer_config.strip_thinking {
|
||||
mapped_body = super::copilot_optimizer::strip_thinking_blocks(mapped_body);
|
||||
}
|
||||
|
||||
// 4. Warmup 小模型降级
|
||||
if self.copilot_optimizer_config.warmup_downgrade && classification.is_warmup {
|
||||
log::info!(
|
||||
@@ -918,7 +934,7 @@ impl RequestForwarder {
|
||||
let api_format = resolved_claude_api_format
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| super::providers::get_claude_api_format(provider));
|
||||
rewrite_claude_transform_endpoint(endpoint, api_format, is_copilot)
|
||||
rewrite_claude_transform_endpoint(endpoint, api_format, is_copilot, &mapped_body)
|
||||
} else {
|
||||
(
|
||||
endpoint.to_string(),
|
||||
@@ -928,7 +944,13 @@ impl RequestForwarder {
|
||||
)
|
||||
};
|
||||
|
||||
let url = if is_full_url {
|
||||
let url = if matches!(resolved_claude_api_format.as_deref(), Some("gemini_native")) {
|
||||
super::gemini_url::resolve_gemini_native_url(
|
||||
&base_url,
|
||||
&effective_endpoint,
|
||||
is_full_url,
|
||||
)
|
||||
} else if is_full_url {
|
||||
append_query_to_full_url(&base_url, passthrough_query.as_deref())
|
||||
} else {
|
||||
adapter.build_url(&base_url, &effective_endpoint)
|
||||
@@ -944,6 +966,8 @@ impl RequestForwarder {
|
||||
mapped_body,
|
||||
provider,
|
||||
api_format,
|
||||
Some(&self.session_id),
|
||||
Some(self.gemini_shadow.as_ref()),
|
||||
)?
|
||||
} else {
|
||||
adapter.transform_request(mapped_body, provider)?
|
||||
@@ -1143,8 +1167,11 @@ impl RequestForwarder {
|
||||
.ok()
|
||||
.and_then(|u| u.authority().map(|a| a.to_string()));
|
||||
|
||||
let should_send_anthropic_headers = adapter.name() == "Claude"
|
||||
&& matches!(resolved_claude_api_format.as_deref(), Some("anthropic"));
|
||||
|
||||
// 预计算 anthropic-beta 值(仅 Claude)
|
||||
let anthropic_beta_value = if adapter.name() == "Claude" {
|
||||
let anthropic_beta_value = if should_send_anthropic_headers {
|
||||
const CLAUDE_CODE_BETA: &str = "claude-code-20250219";
|
||||
Some(if let Some(beta) = headers.get("anthropic-beta") {
|
||||
if let Ok(beta_str) = beta.to_str() {
|
||||
@@ -1264,8 +1291,10 @@ impl RequestForwarder {
|
||||
|
||||
// --- anthropic-version — 透传客户端值 ---
|
||||
if key_str.eq_ignore_ascii_case("anthropic-version") {
|
||||
saw_anthropic_version = true;
|
||||
ordered_headers.append(key.clone(), value.clone());
|
||||
if should_send_anthropic_headers {
|
||||
saw_anthropic_version = true;
|
||||
ordered_headers.append(key.clone(), value.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1306,7 +1335,7 @@ impl RequestForwarder {
|
||||
}
|
||||
|
||||
// anthropic-version:仅在缺失时补充默认值
|
||||
if adapter.name() == "Claude" && !saw_anthropic_version {
|
||||
if should_send_anthropic_headers && !saw_anthropic_version {
|
||||
ordered_headers.append(
|
||||
"anthropic-version",
|
||||
http::HeaderValue::from_static("2023-06-01"),
|
||||
@@ -1650,6 +1679,7 @@ fn rewrite_claude_transform_endpoint(
|
||||
endpoint: &str,
|
||||
api_format: &str,
|
||||
is_copilot: bool,
|
||||
body: &Value,
|
||||
) -> (String, Option<String>) {
|
||||
let (path, query) = split_endpoint_and_query(endpoint);
|
||||
let passthrough_query = if is_claude_messages_path(path) {
|
||||
@@ -1662,6 +1692,36 @@ fn rewrite_claude_transform_endpoint(
|
||||
return (endpoint.to_string(), passthrough_query);
|
||||
}
|
||||
|
||||
if api_format == "gemini_native" {
|
||||
let model =
|
||||
super::providers::transform_gemini::extract_gemini_model(body).unwrap_or("unknown");
|
||||
// Accept both bare ids (`gemini-2.5-pro`) and the resource-name
|
||||
// form (`models/gemini-2.5-pro`) that Gemini SDKs emit. See
|
||||
// `normalize_gemini_model_id` for rationale.
|
||||
let model = super::gemini_url::normalize_gemini_model_id(model);
|
||||
let is_stream = body
|
||||
.get("stream")
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or(false);
|
||||
let target_path = if is_stream {
|
||||
format!("/v1beta/models/{model}:streamGenerateContent")
|
||||
} else {
|
||||
format!("/v1beta/models/{model}:generateContent")
|
||||
};
|
||||
|
||||
let rewritten_query = merge_query_params(
|
||||
passthrough_query.as_deref(),
|
||||
if is_stream { Some("alt=sse") } else { None },
|
||||
);
|
||||
|
||||
let rewritten = match rewritten_query.as_deref() {
|
||||
Some(query) if !query.is_empty() => format!("{target_path}?{query}"),
|
||||
_ => target_path,
|
||||
};
|
||||
|
||||
return (rewritten, rewritten_query);
|
||||
}
|
||||
|
||||
let target_path = if is_copilot && api_format == "openai_responses" {
|
||||
"/v1/responses"
|
||||
} else if is_copilot {
|
||||
@@ -1680,6 +1740,26 @@ fn rewrite_claude_transform_endpoint(
|
||||
(rewritten, passthrough_query)
|
||||
}
|
||||
|
||||
fn merge_query_params(base_query: Option<&str>, extra_param: Option<&str>) -> Option<String> {
|
||||
let mut params: Vec<String> = base_query
|
||||
.into_iter()
|
||||
.flat_map(|query| query.split('&'))
|
||||
.filter(|pair| !pair.is_empty())
|
||||
.filter(|pair| !pair.starts_with("alt="))
|
||||
.map(ToString::to_string)
|
||||
.collect();
|
||||
|
||||
if let Some(extra_param) = extra_param {
|
||||
params.push(extra_param.to_string());
|
||||
}
|
||||
|
||||
if params.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(params.join("&"))
|
||||
}
|
||||
}
|
||||
|
||||
fn append_query_to_full_url(base_url: &str, query: Option<&str>) -> String {
|
||||
match query {
|
||||
Some(query) if !query.is_empty() => {
|
||||
@@ -1808,6 +1888,7 @@ mod tests {
|
||||
"/v1/messages?beta=true&foo=bar",
|
||||
"openai_chat",
|
||||
false,
|
||||
&json!({ "model": "gpt-5.4" }),
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/chat/completions?foo=bar");
|
||||
@@ -1820,6 +1901,7 @@ mod tests {
|
||||
"/claude/v1/messages?beta=true&x-id=1",
|
||||
"openai_responses",
|
||||
false,
|
||||
&json!({ "model": "gpt-5.4" }),
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/responses?x-id=1");
|
||||
@@ -1828,8 +1910,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_uses_copilot_path() {
|
||||
let (endpoint, passthrough_query) =
|
||||
rewrite_claude_transform_endpoint("/v1/messages?beta=true&x-id=1", "anthropic", true);
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages?beta=true&x-id=1",
|
||||
"anthropic",
|
||||
true,
|
||||
&json!({ "model": "claude-sonnet-4-6" }),
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/chat/completions?x-id=1");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
@@ -1841,12 +1927,60 @@ mod tests {
|
||||
"/v1/messages?beta=true&x-id=1",
|
||||
"openai_responses",
|
||||
true,
|
||||
&json!({ "model": "gpt-5.4" }),
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1/responses?x-id=1");
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_maps_gemini_generate_content() {
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages?beta=true&x-id=1",
|
||||
"gemini_native",
|
||||
false,
|
||||
&json!({ "model": "gemini-2.5-pro" }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
endpoint,
|
||||
"/v1beta/models/gemini-2.5-pro:generateContent?x-id=1"
|
||||
);
|
||||
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
|
||||
}
|
||||
|
||||
/// Regression: body.model arriving as the resource-name form
|
||||
/// `models/gemini-2.5-pro` must not produce a doubled
|
||||
/// `/v1beta/models/models/...` path.
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_strips_gemini_model_resource_prefix() {
|
||||
let (endpoint, _) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages",
|
||||
"gemini_native",
|
||||
false,
|
||||
&json!({ "model": "models/gemini-2.5-pro" }),
|
||||
);
|
||||
|
||||
assert_eq!(endpoint, "/v1beta/models/gemini-2.5-pro:generateContent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrite_claude_transform_endpoint_maps_gemini_streaming() {
|
||||
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
|
||||
"/v1/messages?beta=true",
|
||||
"gemini_native",
|
||||
false,
|
||||
&json!({ "model": "gemini-2.5-flash", "stream": true }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
endpoint,
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
assert_eq!(passthrough_query.as_deref(), Some("alt=sse"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_query_to_full_url_preserves_existing_query_string() {
|
||||
let url = append_query_to_full_url("https://relay.example/api?foo=bar", Some("x-id=1"));
|
||||
@@ -1854,6 +1988,43 @@ mod tests {
|
||||
assert_eq!(url, "https://relay.example/api?foo=bar&x-id=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_gemini_native_url_uses_origin_when_base_ends_with_v1beta() {
|
||||
let url = crate::proxy::gemini_url::build_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta",
|
||||
"/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_gemini_native_url_uses_origin_when_base_already_contains_models_prefix() {
|
||||
let url = crate::proxy::gemini_url::build_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_gemini_native_url_keeps_opaque_full_url_as_is() {
|
||||
let url = crate::proxy::gemini_url::resolve_gemini_native_url(
|
||||
"https://relay.example/custom/generate-content",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_identity_for_stream_flag_requests() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
@@ -0,0 +1,665 @@
|
||||
//! Gemini Native URL helpers.
|
||||
//!
|
||||
//! Normalizes legacy Gemini/OpenAI-compatible base URLs into the canonical
|
||||
//! Gemini Native `models/*:generateContent` endpoints.
|
||||
|
||||
/// Normalize a Gemini model identifier to its bare form, stripping an
|
||||
/// optional leading `models/` (and any leading `/`) so that the value can
|
||||
/// be safely interpolated into a URL template like
|
||||
/// `/v1beta/models/{model}:generateContent`.
|
||||
///
|
||||
/// Gemini SDKs and documentation commonly surface model ids as
|
||||
/// `models/gemini-2.5-pro` (the resource-name form). Passing that value
|
||||
/// through to the format string would otherwise yield a doubled prefix
|
||||
/// like `/v1beta/models/models/gemini-2.5-pro:generateContent`, which is
|
||||
/// rejected by the upstream API and turns any health check or live
|
||||
/// request into a false negative.
|
||||
pub fn normalize_gemini_model_id(model: &str) -> &str {
|
||||
let trimmed = model.strip_prefix('/').unwrap_or(model);
|
||||
trimmed.strip_prefix("models/").unwrap_or(trimmed)
|
||||
}
|
||||
|
||||
pub fn resolve_gemini_native_url(base_url: &str, endpoint: &str, is_full_url: bool) -> String {
|
||||
if !is_full_url || should_normalize_gemini_full_url(base_url) {
|
||||
return build_gemini_native_url(base_url, endpoint);
|
||||
}
|
||||
|
||||
let base_url = base_url
|
||||
.split_once('#')
|
||||
.map_or(base_url, |(base, _)| base)
|
||||
.trim_end_matches('/');
|
||||
let (base_without_query, base_query) = split_query(base_url);
|
||||
let (_, endpoint_query) = split_query(endpoint);
|
||||
|
||||
let mut url = base_without_query.to_string();
|
||||
if let Some(query) = merge_queries(base_query, endpoint_query) {
|
||||
url.push('?');
|
||||
url.push_str(&query);
|
||||
}
|
||||
|
||||
url
|
||||
}
|
||||
|
||||
pub fn build_gemini_native_url(base_url: &str, endpoint: &str) -> String {
|
||||
let base_url = base_url
|
||||
.split_once('#')
|
||||
.map_or(base_url, |(base, _)| base)
|
||||
.trim_end_matches('/');
|
||||
let (base_without_query, base_query) = split_query(base_url);
|
||||
let (endpoint_without_query, endpoint_query) = split_query(endpoint);
|
||||
|
||||
let endpoint_path = format!("/{}", endpoint_without_query.trim_start_matches('/'));
|
||||
let (origin, raw_path) = split_origin_and_path(base_without_query);
|
||||
let prefix_path = normalize_gemini_base_path(raw_path);
|
||||
|
||||
let mut url = if prefix_path.is_empty() {
|
||||
format!("{origin}{endpoint_path}")
|
||||
} else {
|
||||
format!("{origin}{prefix_path}{endpoint_path}")
|
||||
};
|
||||
|
||||
if let Some(query) = merge_queries(base_query, endpoint_query) {
|
||||
url.push('?');
|
||||
url.push_str(&query);
|
||||
}
|
||||
|
||||
url
|
||||
}
|
||||
|
||||
fn should_normalize_gemini_full_url(base_url: &str) -> bool {
|
||||
let base_url = base_url
|
||||
.split_once('#')
|
||||
.map_or(base_url, |(base, _)| base)
|
||||
.trim_end_matches('/');
|
||||
let (base_without_query, _) = split_query(base_url);
|
||||
let (origin, path) = split_origin_and_path(base_without_query);
|
||||
|
||||
if path.is_empty() || path == "/" {
|
||||
return true;
|
||||
}
|
||||
|
||||
let path = path.trim_end_matches('/');
|
||||
let on_google_host = is_google_gemini_host(extract_host(origin));
|
||||
|
||||
// Unconditional layer: only paths whose grammar is *intrinsically*
|
||||
// Gemini-specific — the `/models/...:generateContent` method-call
|
||||
// shape and the deep OpenAI-compat endpoints (`/openai/chat/completions`,
|
||||
// `/openai/responses`) that are implausibly used as a relay's fixed
|
||||
// terminal path — get rewritten regardless of host.
|
||||
if matches_structured_gemini_models_path(path)
|
||||
|| path.ends_with("/v1beta/openai/chat/completions")
|
||||
|| path.ends_with("/v1beta/openai/responses")
|
||||
|| path.ends_with("/openai/chat/completions")
|
||||
|| path.ends_with("/openai/responses")
|
||||
|| path.ends_with("/v1/openai/chat/completions")
|
||||
|| path.ends_with("/v1/openai/responses")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// All other version / resource-root suffixes — `/v1beta`, `/v1`,
|
||||
// `/models`, `/openai`, and variants — could legitimately be an
|
||||
// opaque relay's fixed endpoint (`https://relay.example/custom/v1beta`
|
||||
// is a real deployment shape, even if uncommon outside Google's
|
||||
// ecosystem). Only rewrite when the host itself is Google's Gemini
|
||||
// or Vertex AI endpoint.
|
||||
if on_google_host
|
||||
&& (path.ends_with("/v1beta")
|
||||
|| path.ends_with("/v1beta/models")
|
||||
|| path.ends_with("/v1beta/openai")
|
||||
|| path.ends_with("/v1")
|
||||
|| path.ends_with("/v1/models")
|
||||
|| path.ends_with("/models")
|
||||
|| path.ends_with("/v1/openai")
|
||||
|| path.ends_with("/openai"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Extract the host portion of an origin like `https://host:port` or
|
||||
/// `https://host`. Returns an empty string if no host can be found (e.g.
|
||||
/// bare `http://`).
|
||||
fn extract_host(origin: &str) -> &str {
|
||||
let after_scheme = origin.split_once("://").map_or(origin, |(_, rest)| rest);
|
||||
// authority may carry credentials (`user:pass@host`) and a port
|
||||
// (`host:port`). Strip userinfo first, then port.
|
||||
let without_userinfo = after_scheme
|
||||
.rsplit_once('@')
|
||||
.map_or(after_scheme, |(_, h)| h);
|
||||
let without_port = without_userinfo
|
||||
.split_once(':')
|
||||
.map_or(without_userinfo, |(h, _)| h);
|
||||
// Strip trailing `/` defensively (split_origin_and_path already handled
|
||||
// it, but this helper may be reused elsewhere).
|
||||
without_port.trim_end_matches('/')
|
||||
}
|
||||
|
||||
/// Returns true when `host` is one of Google's Gemini / Vertex AI endpoints.
|
||||
/// Case-insensitive. Requires exact match or a real `-aiplatform.googleapis.com`
|
||||
/// subdomain suffix — not a substring match, so lookalikes like
|
||||
/// `aiplatform.example.com` are rejected.
|
||||
fn is_google_gemini_host(host: &str) -> bool {
|
||||
if host.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let host_lower = host.to_ascii_lowercase();
|
||||
host_lower == "generativelanguage.googleapis.com"
|
||||
|| host_lower == "aiplatform.googleapis.com"
|
||||
|| host_lower.ends_with("-aiplatform.googleapis.com")
|
||||
}
|
||||
|
||||
fn split_query(input: &str) -> (&str, Option<&str>) {
|
||||
input
|
||||
.split_once('?')
|
||||
.map_or((input, None), |(path, query)| (path, Some(query)))
|
||||
}
|
||||
|
||||
fn split_origin_and_path(base_url: &str) -> (&str, &str) {
|
||||
let Some(scheme_sep) = base_url.find("://") else {
|
||||
return (base_url, "");
|
||||
};
|
||||
let authority_start = scheme_sep + 3;
|
||||
let Some(path_start_rel) = base_url[authority_start..].find('/') else {
|
||||
return (base_url, "");
|
||||
};
|
||||
let path_start = authority_start + path_start_rel;
|
||||
(&base_url[..path_start], &base_url[path_start..])
|
||||
}
|
||||
|
||||
fn normalize_gemini_base_path(path: &str) -> String {
|
||||
let path = path.trim_end_matches('/');
|
||||
if path.is_empty() || path == "/" {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
for marker in ["/v1beta/models/", "/v1/models/", "/models/"] {
|
||||
if let Some(index) = path.find(marker) {
|
||||
return normalize_prefix(&path[..index]);
|
||||
}
|
||||
}
|
||||
|
||||
for suffix in [
|
||||
"/v1beta/openai/chat/completions",
|
||||
"/v1/openai/chat/completions",
|
||||
"/openai/chat/completions",
|
||||
"/v1beta/openai/responses",
|
||||
"/v1/openai/responses",
|
||||
"/openai/responses",
|
||||
"/v1beta/openai",
|
||||
"/v1/openai",
|
||||
"/openai",
|
||||
"/v1beta/models",
|
||||
"/v1/models",
|
||||
"/models",
|
||||
"/v1beta",
|
||||
"/v1",
|
||||
] {
|
||||
if path == suffix {
|
||||
return String::new();
|
||||
}
|
||||
if let Some(prefix) = path.strip_suffix(suffix) {
|
||||
return normalize_prefix(prefix);
|
||||
}
|
||||
}
|
||||
|
||||
path.to_string()
|
||||
}
|
||||
|
||||
fn normalize_prefix(prefix: &str) -> String {
|
||||
let prefix = prefix.trim_end_matches('/');
|
||||
if prefix.is_empty() || prefix == "/" {
|
||||
String::new()
|
||||
} else {
|
||||
prefix.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true when `path` contains a `/models/` segment followed by a
|
||||
/// canonical Gemini method call (`*:generateContent` or
|
||||
/// `*:streamGenerateContent`). The `/models/` segment alone is not enough:
|
||||
/// opaque relay routes such as `/v1/models/invoke` or `/custom/models/foo`
|
||||
/// also contain `/models/` but are not Gemini-structured and must not be
|
||||
/// rewritten.
|
||||
fn matches_structured_gemini_models_path(path: &str) -> bool {
|
||||
let mut cursor = path;
|
||||
while let Some(idx) = cursor.find("/models/") {
|
||||
let after = &cursor[idx + "/models/".len()..];
|
||||
if after.contains(":generateContent") || after.contains(":streamGenerateContent") {
|
||||
return true;
|
||||
}
|
||||
// Advance past this `/models/` occurrence so a later Gemini-style
|
||||
// segment in the same path (unusual but cheap to handle) can still
|
||||
// match.
|
||||
cursor = &cursor[idx + "/models/".len()..];
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn merge_queries(base_query: Option<&str>, endpoint_query: Option<&str>) -> Option<String> {
|
||||
let parts: Vec<&str> = [base_query, endpoint_query]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flat_map(|query| query.split('&'))
|
||||
.filter(|part| !part.is_empty())
|
||||
.collect();
|
||||
|
||||
if parts.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parts.join("&"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{build_gemini_native_url, normalize_gemini_model_id, resolve_gemini_native_url};
|
||||
|
||||
#[test]
|
||||
fn strips_version_root_for_official_base() {
|
||||
let url = build_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta",
|
||||
"/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_openai_compat_path_for_official_base() {
|
||||
let url = build_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
||||
"/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_custom_proxy_prefix_while_stripping_openai_suffix() {
|
||||
let url = build_gemini_native_url(
|
||||
"https://proxy.example.com/google/v1beta/openai/chat/completions",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://proxy.example.com/google/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strips_model_method_path_from_full_url_base() {
|
||||
let url = build_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_structured_full_url_by_normalizing_to_requested_method() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_opaque_full_url_without_appending_gemini_models_path() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/generate-content",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_containing_models_segment() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/models/invoke",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/models/invoke?alt=sse");
|
||||
}
|
||||
|
||||
/// Regression: a relay whose fixed path starts with `/v1/models/` is an
|
||||
/// opaque route, not a Gemini-structured endpoint. The previous
|
||||
/// heuristic matched any `contains("/v1/models/")` and rewrote it to
|
||||
/// `/v1beta/models/{model}:generateContent`, dropping the relay's own
|
||||
/// route component (`/invoke`) and sending traffic to the wrong place.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_v1_models_prefix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/v1/models/invoke",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/v1/models/invoke?alt=sse");
|
||||
}
|
||||
|
||||
/// Same regression, `/v1beta/models/` variant — relays may use Google's
|
||||
/// path layout defensively for routing while still being opaque.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_v1beta_models_prefix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/v1beta/models/route",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/v1beta/models/route?alt=sse");
|
||||
}
|
||||
|
||||
/// Counter-case: a full URL that *does* carry a genuine Gemini method
|
||||
/// segment (`:generateContent`) under `/v1/models/` should still be
|
||||
/// recognized as structured and normalized to the requested model.
|
||||
#[test]
|
||||
fn normalizes_structured_v1_models_path_with_method_segment() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/v1/models/gemini-2.5-pro:generateContent",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://relay.example/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Google-host whitelist tests (generic REST suffix handling)
|
||||
//
|
||||
// Generic REST conventions like `/v1`, `/models`, `/openai` legitimately
|
||||
// appear on opaque relays. `should_normalize_gemini_full_url` only
|
||||
// treats these as structured Gemini endpoints when the host itself is
|
||||
// Google's Gemini or Vertex AI endpoint.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Regression: a relay whose fixed path ends with `/v1` (a ubiquitous
|
||||
/// REST convention) used to be rewritten to
|
||||
/// `/v1beta/models/{model}:generateContent`, dropping the relay's own
|
||||
/// `/v1` endpoint.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_v1_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/v1?alt=sse");
|
||||
}
|
||||
|
||||
/// Companion case: bare `/models` suffix on a non-Google host is a
|
||||
/// generic REST path, not a Gemini-structured endpoint.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_models_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/models",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/models?alt=sse");
|
||||
}
|
||||
|
||||
/// Companion case: `/v1/models` — same ambiguity as `/models`, with the
|
||||
/// version prefix. Must stay as-is on non-Google hosts.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_v1_models_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1/models",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/v1/models?alt=sse");
|
||||
}
|
||||
|
||||
/// Companion case: a relay that exposes an `/openai` compatibility
|
||||
/// surface without the deep `/openai/chat/completions` path. Must stay
|
||||
/// as-is on non-Google hosts.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_openai_suffix_on_non_google_host() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/openai",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/openai?alt=sse");
|
||||
}
|
||||
|
||||
/// Counter-case: `/v1` on the official Gemini host must still be
|
||||
/// normalized to the full `/v1beta/models/...` endpoint — users who
|
||||
/// paste `https://generativelanguage.googleapis.com/v1` as their base
|
||||
/// URL expect the proxy to resolve the method path.
|
||||
#[test]
|
||||
fn normalizes_google_host_with_v1_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
/// Counter-case: `/models` on the official Gemini host is recognized
|
||||
/// and normalized.
|
||||
#[test]
|
||||
fn normalizes_google_host_with_models_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/models",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
/// Counter-case: Vertex AI regional endpoints live under
|
||||
/// `*-aiplatform.googleapis.com`. Those should also be treated as
|
||||
/// Google-host for the whitelist.
|
||||
#[test]
|
||||
fn normalizes_vertex_aiplatform_host_with_v1_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://us-central1-aiplatform.googleapis.com/v1",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://us-central1-aiplatform.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
/// Safety: the Google-host whitelist must do an exact/suffix match, not
|
||||
/// a `contains`. A lookalike host like `aiplatform.example.com` must
|
||||
/// NOT be treated as Google.
|
||||
#[test]
|
||||
fn preserves_non_google_aiplatform_lookalike_host() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://aiplatform.example.com/v1",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://aiplatform.example.com/v1?alt=sse");
|
||||
}
|
||||
|
||||
/// Regression: `/v1beta` by itself is Google-conventional but not
|
||||
/// literally impossible on other hosts. An opaque relay fronting a
|
||||
/// non-Gemini service at `https://relay.example/custom/v1beta` would
|
||||
/// be silently rewritten if `/v1beta` were classified as unconditional
|
||||
/// structured Gemini. Require the Google-host whitelist instead.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_bare_v1beta_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1beta",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/v1beta?alt=sse");
|
||||
}
|
||||
|
||||
/// Companion case: `/v1beta/models` (no method segment) on a non-Google
|
||||
/// host stays as-is too.
|
||||
#[test]
|
||||
fn preserves_opaque_full_url_with_v1beta_models_suffix_no_method() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1beta/models",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/v1beta/models?alt=sse");
|
||||
}
|
||||
|
||||
/// Counter-case: `/v1beta` on the official Gemini host must still
|
||||
/// normalize — this is the canonical base URL shape users paste from
|
||||
/// AI Studio documentation.
|
||||
#[test]
|
||||
fn normalizes_google_host_with_v1beta_suffix() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression guard: in non-full-URL mode, a versioned third-party
|
||||
/// relay base must have its `/v1beta` suffix **stripped** so the
|
||||
/// appended standard endpoint (`/v1beta/models/{model}:method`) does
|
||||
/// not produce a doubled `/v1beta/v1beta/models/...` path. Non-full
|
||||
/// mode's contract is "base URL + cc-switch appends the canonical
|
||||
/// Gemini endpoint" — a user who wants a relay's custom namespace
|
||||
/// (e.g. `/v1/models/...`) must use full-URL mode instead.
|
||||
///
|
||||
/// This test pins the intentional asymmetry with
|
||||
/// `preserves_opaque_full_url_with_bare_v1beta_suffix` (full-URL
|
||||
/// preserves, non-full strips) so nobody "fixes" one side into
|
||||
/// breaking the other.
|
||||
#[test]
|
||||
fn strips_versioned_relay_base_suffix_in_non_full_url_mode() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1beta",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://relay.example/custom/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
/// Companion case: `/v1` base suffix also stripped in non-full-URL
|
||||
/// mode regardless of host.
|
||||
#[test]
|
||||
fn strips_v1_relay_base_suffix_in_non_full_url_mode() {
|
||||
let url = resolve_gemini_native_url(
|
||||
"https://relay.example/custom/v1",
|
||||
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://relay.example/custom/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Model ID normalization tests.
|
||||
//
|
||||
// Gemini SDKs and documentation commonly surface model identifiers as
|
||||
// `models/gemini-2.5-pro` (resource-name form). If that value flows
|
||||
// straight into our URL builder, the format string
|
||||
// `/v1beta/models/{model}:generateContent` produces a doubled prefix
|
||||
// `/v1beta/models/models/gemini-2.5-pro:generateContent`, which is
|
||||
// rejected upstream. `normalize_gemini_model_id` is the single source
|
||||
// of truth callers should run the model through first.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn normalize_model_id_strips_models_prefix() {
|
||||
assert_eq!(
|
||||
normalize_gemini_model_id("models/gemini-2.5-pro"),
|
||||
"gemini-2.5-pro"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_model_id_leaves_bare_id_unchanged() {
|
||||
assert_eq!(
|
||||
normalize_gemini_model_id("gemini-2.5-pro"),
|
||||
"gemini-2.5-pro"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_model_id_preserves_nested_slashes_after_prefix() {
|
||||
// e.g. tuned model resource like `models/gemini-2.5-pro/tunedModels/xxx`
|
||||
// — the caller asked for a specific tuned model resource, keep its
|
||||
// identity intact after stripping only the single leading prefix.
|
||||
assert_eq!(
|
||||
normalize_gemini_model_id("models/tunedModels/my-tuned"),
|
||||
"tunedModels/my-tuned"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_model_id_tolerates_leading_slash() {
|
||||
assert_eq!(
|
||||
normalize_gemini_model_id("/models/gemini-2.5-flash"),
|
||||
"gemini-2.5-flash"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_model_id_preserves_empty_input() {
|
||||
// Edge: caller has no model at all. Pass through so the URL error
|
||||
// surfaces at the request layer rather than producing a misleading
|
||||
// empty segment here.
|
||||
assert_eq!(normalize_gemini_model_id(""), "");
|
||||
}
|
||||
}
|
||||
@@ -218,9 +218,11 @@ impl RequestContext {
|
||||
non_streaming_timeout,
|
||||
state.status.clone(),
|
||||
state.current_providers.clone(),
|
||||
state.gemini_shadow.clone(),
|
||||
state.failover_manager.clone(),
|
||||
state.app_handle.clone(),
|
||||
self.current_provider_id.clone(),
|
||||
self.session_id.clone(),
|
||||
first_byte_timeout,
|
||||
idle_timeout,
|
||||
self.rectifier_config.clone(),
|
||||
|
||||
@@ -15,12 +15,14 @@ use super::{
|
||||
handler_context::RequestContext,
|
||||
providers::{
|
||||
get_adapter, get_claude_api_format, streaming::create_anthropic_sse_stream,
|
||||
streaming_gemini::create_anthropic_sse_stream_from_gemini,
|
||||
streaming_responses::create_anthropic_sse_stream_from_responses, transform,
|
||||
transform_responses,
|
||||
transform_gemini, transform_responses,
|
||||
},
|
||||
response_processor::{
|
||||
create_logged_passthrough_stream, process_response, read_decoded_body,
|
||||
strip_entity_headers_for_rebuilt_body, SseUsageCollector,
|
||||
strip_entity_headers_for_rebuilt_body, strip_hop_by_hop_response_headers,
|
||||
SseUsageCollector,
|
||||
},
|
||||
server::ProxyState,
|
||||
types::*,
|
||||
@@ -144,11 +146,13 @@ async fn handle_claude_transform(
|
||||
response: super::hyper_client::ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
_original_body: &Value,
|
||||
original_body: &Value,
|
||||
is_stream: bool,
|
||||
api_format: &str,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = response.status();
|
||||
let tool_schema_hints = transform_gemini::extract_anthropic_tool_schema_hints(original_body);
|
||||
let tool_schema_hints = (!tool_schema_hints.is_empty()).then_some(tool_schema_hints);
|
||||
|
||||
if is_stream {
|
||||
// 根据 api_format 选择流式转换器
|
||||
@@ -157,6 +161,14 @@ async fn handle_claude_transform(
|
||||
dyn futures::Stream<Item = Result<Bytes, std::io::Error>> + Send + Unpin,
|
||||
> = if api_format == "openai_responses" {
|
||||
Box::new(Box::pin(create_anthropic_sse_stream_from_responses(stream)))
|
||||
} else if api_format == "gemini_native" {
|
||||
Box::new(Box::pin(create_anthropic_sse_stream_from_gemini(
|
||||
stream,
|
||||
Some(state.gemini_shadow.clone()),
|
||||
Some(ctx.provider.id.clone()),
|
||||
Some(ctx.session_id.clone()),
|
||||
tool_schema_hints.clone(),
|
||||
)))
|
||||
} else {
|
||||
Box::new(Box::pin(create_anthropic_sse_stream(stream)))
|
||||
};
|
||||
@@ -216,10 +228,6 @@ async fn handle_claude_transform(
|
||||
"Cache-Control",
|
||||
axum::http::HeaderValue::from_static("no-cache"),
|
||||
);
|
||||
headers.insert(
|
||||
"Connection",
|
||||
axum::http::HeaderValue::from_static("keep-alive"),
|
||||
);
|
||||
|
||||
let body = axum::body::Body::from_stream(logged_stream);
|
||||
return Ok((headers, body).into_response());
|
||||
@@ -245,6 +253,14 @@ async fn handle_claude_transform(
|
||||
// 根据 api_format 选择非流式转换器
|
||||
let anthropic_response = if api_format == "openai_responses" {
|
||||
transform_responses::responses_to_anthropic(upstream_response)
|
||||
} else if api_format == "gemini_native" {
|
||||
transform_gemini::gemini_to_anthropic_with_shadow_and_hints(
|
||||
upstream_response,
|
||||
Some(state.gemini_shadow.as_ref()),
|
||||
Some(&ctx.provider.id),
|
||||
Some(&ctx.session_id),
|
||||
tool_schema_hints.as_ref(),
|
||||
)
|
||||
} else {
|
||||
transform::openai_to_anthropic(upstream_response)
|
||||
}
|
||||
@@ -287,6 +303,7 @@ async fn handle_claude_transform(
|
||||
// 构建响应
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
strip_entity_headers_for_rebuilt_body(&mut response_headers);
|
||||
strip_hop_by_hop_response_headers(&mut response_headers);
|
||||
|
||||
for (key, value) in response_headers.iter() {
|
||||
builder = builder.header(key, value);
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod error;
|
||||
pub mod error_mapper;
|
||||
pub(crate) mod failover_switch;
|
||||
mod forwarder;
|
||||
pub mod gemini_url;
|
||||
pub mod handler_config;
|
||||
pub mod handler_context;
|
||||
mod handlers;
|
||||
|
||||
@@ -11,7 +11,6 @@ pub struct ModelMapping {
|
||||
pub sonnet_model: Option<String>,
|
||||
pub opus_model: Option<String>,
|
||||
pub default_model: Option<String>,
|
||||
pub reasoning_model: Option<String>,
|
||||
}
|
||||
|
||||
impl ModelMapping {
|
||||
@@ -40,11 +39,6 @@ impl ModelMapping {
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
reasoning_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_REASONING_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,21 +48,13 @@ impl ModelMapping {
|
||||
|| self.sonnet_model.is_some()
|
||||
|| self.opus_model.is_some()
|
||||
|| self.default_model.is_some()
|
||||
|| self.reasoning_model.is_some()
|
||||
}
|
||||
|
||||
/// 根据原始模型名称获取映射后的模型
|
||||
pub fn map_model(&self, original_model: &str, has_thinking: bool) -> String {
|
||||
pub fn map_model(&self, original_model: &str) -> String {
|
||||
let model_lower = original_model.to_lowercase();
|
||||
|
||||
// 1. thinking 模式优先使用推理模型
|
||||
if has_thinking {
|
||||
if let Some(ref m) = self.reasoning_model {
|
||||
return m.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 按模型类型匹配
|
||||
// 1. 按模型类型匹配
|
||||
if model_lower.contains("haiku") {
|
||||
if let Some(ref m) = self.haiku_model {
|
||||
return m.clone();
|
||||
@@ -85,35 +71,16 @@ impl ModelMapping {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 默认模型
|
||||
// 2. 默认模型
|
||||
if let Some(ref m) = self.default_model {
|
||||
return m.clone();
|
||||
}
|
||||
|
||||
// 4. 无映射,保持原样
|
||||
// 3. 无映射,保持原样
|
||||
original_model.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 检测请求是否启用了 thinking 模式
|
||||
pub fn has_thinking_enabled(body: &Value) -> bool {
|
||||
match body
|
||||
.get("thinking")
|
||||
.and_then(|v| v.as_object())
|
||||
.and_then(|o| o.get("type"))
|
||||
.and_then(|t| t.as_str())
|
||||
{
|
||||
Some("enabled") | Some("adaptive") => true,
|
||||
Some("disabled") | None => false,
|
||||
Some(other) => {
|
||||
log::warn!(
|
||||
"[ModelMapper] 未知 thinking.type='{other}',按 disabled 处理以避免误路由 reasoning 模型"
|
||||
);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 对请求体应用模型映射
|
||||
///
|
||||
/// 返回 (映射后的请求体, 原始模型名, 映射后模型名)
|
||||
@@ -133,8 +100,7 @@ pub fn apply_model_mapping(
|
||||
let original_model = body.get("model").and_then(|m| m.as_str()).map(String::from);
|
||||
|
||||
if let Some(ref original) = original_model {
|
||||
let has_thinking = has_thinking_enabled(&body);
|
||||
let mapped = mapping.map_model(original, has_thinking);
|
||||
let mapped = mapping.map_model(original);
|
||||
|
||||
if mapped != *original {
|
||||
log::debug!("[ModelMapper] 模型映射: {original} → {mapped}");
|
||||
@@ -160,8 +126,7 @@ mod tests {
|
||||
"ANTHROPIC_MODEL": "default-model",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped",
|
||||
"ANTHROPIC_REASONING_MODEL": "reasoning-model"
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped"
|
||||
}
|
||||
}),
|
||||
website_url: None,
|
||||
@@ -193,27 +158,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_provider_with_reasoning_only() -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test".to_string(),
|
||||
settings_config: json!({
|
||||
"env": {
|
||||
"ANTHROPIC_REASONING_MODEL": "reasoning-only-model"
|
||||
}
|
||||
}),
|
||||
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_sonnet_mapping() {
|
||||
let provider = create_provider_with_mapping();
|
||||
@@ -243,40 +187,29 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_mode() {
|
||||
fn test_thinking_does_not_affect_model_mapping() {
|
||||
// Issue #2081: thinking 参数不应影响模型映射
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "enabled"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "reasoning-model");
|
||||
assert_eq!(mapped, Some("reasoning-model".to_string()));
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_only_mapping_in_thinking_mode() {
|
||||
let provider = create_provider_with_reasoning_only();
|
||||
fn test_thinking_adaptive_does_not_affect_model_mapping() {
|
||||
// Issue #2081: adaptive thinking 也不应影响模型映射
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "enabled"}
|
||||
"thinking": {"type": "adaptive"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "reasoning-only-model");
|
||||
assert_eq!(mapped, Some("reasoning-only-model".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_only_mapping_does_not_affect_non_thinking() {
|
||||
let provider = create_provider_with_reasoning_only();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "disabled"}
|
||||
});
|
||||
let (result, original, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "claude-sonnet-4-5");
|
||||
assert_eq!(original, Some("claude-sonnet-4-5".to_string()));
|
||||
assert!(mapped.is_none());
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -310,30 +243,6 @@ mod tests {
|
||||
assert!(mapped.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_adaptive() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "adaptive"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "reasoning-model");
|
||||
assert_eq!(mapped, Some("reasoning-model".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_thinking_unknown_type() {
|
||||
let provider = create_provider_with_mapping();
|
||||
let body = json!({
|
||||
"model": "claude-sonnet-4-5",
|
||||
"thinking": {"type": "some_future_type"}
|
||||
});
|
||||
let (result, _, mapped) = apply_model_mapping(body, &provider);
|
||||
assert_eq!(result["model"], "sonnet-mapped");
|
||||
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_case_insensitive() {
|
||||
let provider = create_provider_with_mapping();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
//! - **anthropic** (默认): Anthropic Messages API 格式,直接透传
|
||||
//! - **openai_chat**: OpenAI Chat Completions 格式,需要 Anthropic ↔ OpenAI 转换
|
||||
//! - **openai_responses**: OpenAI Responses API 格式,需要 Anthropic ↔ Responses 转换
|
||||
//! - **gemini_native**: Google Gemini Native generateContent 格式,需要 Anthropic ↔ Gemini 转换
|
||||
//!
|
||||
//! ## 认证模式
|
||||
//! - **Claude**: Anthropic 官方 API (x-api-key + anthropic-version)
|
||||
@@ -35,6 +36,7 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
|
||||
return match api_format {
|
||||
"openai_chat" => "openai_chat",
|
||||
"openai_responses" => "openai_responses",
|
||||
"gemini_native" => "gemini_native",
|
||||
_ => "anthropic",
|
||||
};
|
||||
}
|
||||
@@ -49,6 +51,7 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
|
||||
return match api_format {
|
||||
"openai_chat" => "openai_chat",
|
||||
"openai_responses" => "openai_responses",
|
||||
"gemini_native" => "gemini_native",
|
||||
_ => "anthropic",
|
||||
};
|
||||
}
|
||||
@@ -73,13 +76,18 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
|
||||
}
|
||||
|
||||
pub fn claude_api_format_needs_transform(api_format: &str) -> bool {
|
||||
matches!(api_format, "openai_chat" | "openai_responses")
|
||||
matches!(
|
||||
api_format,
|
||||
"openai_chat" | "openai_responses" | "gemini_native"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn transform_claude_request_for_api_format(
|
||||
body: serde_json::Value,
|
||||
provider: &Provider,
|
||||
api_format: &str,
|
||||
session_id: Option<&str>,
|
||||
shadow_store: Option<&super::gemini_shadow::GeminiShadowStore>,
|
||||
) -> Result<serde_json::Value, ProxyError> {
|
||||
// Copilot 场景:优先从 metadata.user_id 提取 session ID 作为 cache key
|
||||
// 格式: "uuid_sessionId" → 提取 "_" 后面的部分作为 session 标识
|
||||
@@ -138,7 +146,24 @@ pub fn transform_claude_request_for_api_format(
|
||||
is_codex_oauth,
|
||||
)
|
||||
}
|
||||
"openai_chat" => super::transform::anthropic_to_openai(body),
|
||||
"openai_chat" => {
|
||||
let mut result = super::transform::anthropic_to_openai(body)?;
|
||||
// Inject prompt_cache_key only if explicitly configured in meta
|
||||
if let Some(key) = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.prompt_cache_key.as_deref())
|
||||
{
|
||||
result["prompt_cache_key"] = serde_json::json!(key);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
"gemini_native" => super::transform_gemini::anthropic_to_gemini_with_shadow(
|
||||
body,
|
||||
shadow_store,
|
||||
Some(&provider.id),
|
||||
session_id,
|
||||
),
|
||||
_ => Ok(body),
|
||||
}
|
||||
}
|
||||
@@ -160,6 +185,16 @@ impl ClaudeAdapter {
|
||||
/// - ClaudeAuth: auth_mode 为 bearer_only
|
||||
/// - Claude: 默认 Anthropic 官方
|
||||
pub fn provider_type(&self, provider: &Provider) -> ProviderType {
|
||||
// 检测 Gemini Native 格式
|
||||
if self.get_api_format(provider) == "gemini_native" {
|
||||
return match self.extract_key(provider) {
|
||||
Some(key) if key.starts_with("ya29.") || key.starts_with('{') => {
|
||||
ProviderType::GeminiCli
|
||||
}
|
||||
_ => ProviderType::Gemini,
|
||||
};
|
||||
}
|
||||
|
||||
// 检测 Codex OAuth (ChatGPT Plus/Pro)
|
||||
if self.is_codex_oauth(provider) {
|
||||
return ProviderType::CodexOAuth;
|
||||
@@ -262,6 +297,7 @@ impl ClaudeAdapter {
|
||||
if let Some(key) = env
|
||||
.get("ANTHROPIC_AUTH_TOKEN")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
log::debug!("[Claude] 使用 ANTHROPIC_AUTH_TOKEN");
|
||||
@@ -270,6 +306,7 @@ impl ClaudeAdapter {
|
||||
if let Some(key) = env
|
||||
.get("ANTHROPIC_API_KEY")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
log::debug!("[Claude] 使用 ANTHROPIC_API_KEY");
|
||||
@@ -279,6 +316,7 @@ impl ClaudeAdapter {
|
||||
if let Some(key) = env
|
||||
.get("OPENROUTER_API_KEY")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
log::debug!("[Claude] 使用 OPENROUTER_API_KEY");
|
||||
@@ -288,6 +326,7 @@ impl ClaudeAdapter {
|
||||
if let Some(key) = env
|
||||
.get("OPENAI_API_KEY")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
log::debug!("[Claude] 使用 OPENAI_API_KEY");
|
||||
@@ -301,6 +340,7 @@ impl ClaudeAdapter {
|
||||
.get("apiKey")
|
||||
.or_else(|| provider.settings_config.get("api_key"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
log::debug!("[Claude] 使用 apiKey/api_key");
|
||||
@@ -388,14 +428,43 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
));
|
||||
}
|
||||
|
||||
let strategy = match provider_type {
|
||||
ProviderType::OpenRouter => AuthStrategy::Bearer,
|
||||
ProviderType::ClaudeAuth => AuthStrategy::ClaudeAuth,
|
||||
_ => AuthStrategy::Anthropic,
|
||||
};
|
||||
let key = self.extract_key(provider)?;
|
||||
|
||||
self.extract_key(provider)
|
||||
.map(|key| AuthInfo::new(key, strategy))
|
||||
match provider_type {
|
||||
ProviderType::GeminiCli => {
|
||||
// Parse stored OAuth JSON and only attach access_token when
|
||||
// it's actually usable. `parse_oauth_credentials` accepts
|
||||
// refresh-token-only JSON (which is legitimate before the
|
||||
// first refresh) and also surfaces `{"access_token": "", ...}`
|
||||
// for expired credentials. In both cases we would otherwise
|
||||
// send `Authorization: Bearer ` to upstream and get a 401.
|
||||
//
|
||||
// CC Switch does not currently exchange the refresh_token for
|
||||
// a fresh access_token. Until that path exists, degrade to
|
||||
// plain GoogleOAuth strategy (which still sends the raw key
|
||||
// as a fallback) and log loudly so users know to refresh
|
||||
// their `~/.gemini/oauth_creds.json`.
|
||||
match super::gemini::GeminiAdapter::new().parse_oauth_credentials(&key) {
|
||||
Some(creds) if !creds.access_token.is_empty() => {
|
||||
Some(AuthInfo::with_access_token(key, creds.access_token))
|
||||
}
|
||||
Some(_) => {
|
||||
log::warn!(
|
||||
"[Gemini OAuth] access_token missing or empty for provider `{}`; \
|
||||
bearer auth will likely fail with 401. Refresh \
|
||||
~/.gemini/oauth_creds.json via the gemini CLI to obtain a new token.",
|
||||
provider.id
|
||||
);
|
||||
Some(AuthInfo::new(key, AuthStrategy::GoogleOAuth))
|
||||
}
|
||||
None => Some(AuthInfo::new(key, AuthStrategy::GoogleOAuth)),
|
||||
}
|
||||
}
|
||||
ProviderType::Gemini => Some(AuthInfo::new(key, AuthStrategy::Google)),
|
||||
ProviderType::OpenRouter => Some(AuthInfo::new(key, AuthStrategy::Bearer)),
|
||||
ProviderType::ClaudeAuth => Some(AuthInfo::new(key, AuthStrategy::ClaudeAuth)),
|
||||
_ => Some(AuthInfo::new(key, AuthStrategy::Anthropic)),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_url(&self, base_url: &str, endpoint: &str) -> String {
|
||||
@@ -437,6 +506,23 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
HeaderValue::from_str(&bearer).unwrap(),
|
||||
)]
|
||||
}
|
||||
AuthStrategy::Google => vec![(
|
||||
HeaderName::from_static("x-goog-api-key"),
|
||||
HeaderValue::from_str(&auth.api_key).unwrap(),
|
||||
)],
|
||||
AuthStrategy::GoogleOAuth => {
|
||||
let token = auth.access_token.as_ref().unwrap_or(&auth.api_key);
|
||||
vec![
|
||||
(
|
||||
HeaderName::from_static("authorization"),
|
||||
HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("x-goog-api-client"),
|
||||
HeaderValue::from_static("GeminiCLI/1.0"),
|
||||
),
|
||||
]
|
||||
}
|
||||
AuthStrategy::CodexOAuth => {
|
||||
// 注意:bearer token 由 forwarder 动态注入到 auth.api_key
|
||||
// ChatGPT-Account-Id 由 forwarder 注入额外 header
|
||||
@@ -507,7 +593,6 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
),
|
||||
]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,7 +613,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
// - "openai_responses": 需要 Anthropic ↔ OpenAI Responses API 格式转换
|
||||
matches!(
|
||||
self.get_api_format(provider),
|
||||
"openai_chat" | "openai_responses"
|
||||
"openai_chat" | "openai_responses" | "gemini_native"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -537,7 +622,13 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
body: serde_json::Value,
|
||||
provider: &Provider,
|
||||
) -> Result<serde_json::Value, ProxyError> {
|
||||
transform_claude_request_for_api_format(body, provider, self.get_api_format(provider))
|
||||
transform_claude_request_for_api_format(
|
||||
body,
|
||||
provider,
|
||||
self.get_api_format(provider),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn transform_response(&self, body: serde_json::Value) -> Result<serde_json::Value, ProxyError> {
|
||||
@@ -546,7 +637,9 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
// config, so we can't check api_format here. Instead we rely on the fact that
|
||||
// Responses API always returns "output" while Chat Completions returns "choices".
|
||||
// This is safe because the two formats are structurally disjoint.
|
||||
if body.get("output").is_some() {
|
||||
if body.get("candidates").is_some() || body.get("promptFeedback").is_some() {
|
||||
super::transform_gemini::gemini_to_anthropic(body)
|
||||
} else if body.get("output").is_some() {
|
||||
super::transform_responses::responses_to_anthropic(body)
|
||||
} else {
|
||||
super::transform::openai_to_anthropic(body)
|
||||
@@ -684,6 +777,146 @@ mod tests {
|
||||
assert_eq!(auth.strategy, AuthStrategy::ClaudeAuth);
|
||||
}
|
||||
|
||||
/// Regression: a Gemini OAuth credential JSON that carries only a
|
||||
/// refresh_token (no active access_token) must not be surfaced as an
|
||||
/// `AuthInfo` whose bearer would be empty. Without the guard, downstream
|
||||
/// header injection produces `Authorization: Bearer ` and a deterministic
|
||||
/// 401 from upstream.
|
||||
#[test]
|
||||
fn test_extract_auth_gemini_cli_refresh_only_json_does_not_expose_empty_bearer() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let refresh_only_json =
|
||||
r#"{"refresh_token":"rt-abc","client_id":"cid","client_secret":"cs"}"#;
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": refresh_only_json
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
// access_token must not be surfaced as `Some("")` — the OAuth header
|
||||
// builder uses `access_token.as_ref().unwrap_or(&api_key)`, so a
|
||||
// `Some("")` would win over the raw key and emit `Bearer `.
|
||||
assert!(
|
||||
auth.access_token.as_deref().is_none_or(|t| !t.is_empty()),
|
||||
"empty access_token leaked into AuthInfo"
|
||||
);
|
||||
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
|
||||
}
|
||||
|
||||
/// Companion case: a JSON credential with an empty-string `access_token`
|
||||
/// field (the shape an expired credential can take after partial writes)
|
||||
/// must degrade the same way.
|
||||
#[test]
|
||||
fn test_extract_auth_gemini_cli_empty_access_token_degrades_to_raw_key() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let expired_json = r#"{"access_token":"","refresh_token":"rt-abc","client_id":"cid","client_secret":"cs"}"#;
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": expired_json
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert!(
|
||||
auth.access_token.as_deref().is_none_or(|t| !t.is_empty()),
|
||||
"empty access_token leaked into AuthInfo"
|
||||
);
|
||||
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
|
||||
}
|
||||
|
||||
/// Counter-case: a well-formed JSON credential with a non-empty
|
||||
/// access_token must still flow through the OAuth path unchanged.
|
||||
#[test]
|
||||
fn test_extract_auth_gemini_cli_valid_json_keeps_access_token() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let valid_json = r#"{"access_token":"ya29.valid","refresh_token":"rt"}"#;
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": valid_json
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert_eq!(auth.access_token.as_deref(), Some("ya29.valid"));
|
||||
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
|
||||
}
|
||||
|
||||
/// 回归:从 oauth_creds.json 复制时常带前导换行/空格。未 trim 时
|
||||
/// `starts_with('{')` 会落空,导致误分类为 `ProviderType::Gemini`,再
|
||||
/// 以 raw JSON 当 `x-goog-api-key` 发出去触发 401。trim 应在 provider
|
||||
/// 类型判定和 OAuth 解析前统一生效。
|
||||
#[test]
|
||||
fn test_extract_auth_gemini_cli_json_with_leading_whitespace_classifies_correctly() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let valid_json = r#"{"access_token":"ya29.valid","refresh_token":"rt"}"#;
|
||||
let key_with_whitespace = format!("\n {valid_json}\n");
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": key_with_whitespace
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(adapter.provider_type(&provider), ProviderType::GeminiCli);
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert_eq!(auth.access_token.as_deref(), Some("ya29.valid"));
|
||||
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
|
||||
}
|
||||
|
||||
/// 回归:裸 `ya29.` access_token 若带前导换行,也应被 trim 后识别为
|
||||
/// Gemini CLI OAuth,避免前导空白把 `starts_with("ya29.")` 检查顶穿。
|
||||
#[test]
|
||||
fn test_extract_auth_gemini_cli_access_token_with_leading_newline_classifies_correctly() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": "\nya29.raw-token-value\n"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(adapter.provider_type(&provider), ProviderType::GeminiCli);
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert_eq!(auth.access_token.as_deref(), Some("ya29.raw-token-value"));
|
||||
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_provider_type_detection() {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
@@ -850,6 +1083,24 @@ mod tests {
|
||||
);
|
||||
assert!(adapter.needs_transform(&openai_responses_provider));
|
||||
|
||||
let gemini_native_provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(adapter.needs_transform(&gemini_native_provider));
|
||||
assert_eq!(
|
||||
adapter.provider_type(&gemini_native_provider),
|
||||
ProviderType::Gemini
|
||||
);
|
||||
|
||||
// meta takes precedence over legacy settings_config fields
|
||||
let meta_precedence_over_settings = create_provider_with_meta(
|
||||
json!({
|
||||
@@ -957,11 +1208,106 @@ mod tests {
|
||||
"max_tokens": 128
|
||||
});
|
||||
|
||||
let transformed =
|
||||
transform_claude_request_for_api_format(body, &provider, "openai_responses").unwrap();
|
||||
let transformed = transform_claude_request_for_api_format(
|
||||
body,
|
||||
&provider,
|
||||
"openai_responses",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(transformed["model"], "gpt-5.4");
|
||||
assert!(transformed.get("input").is_some());
|
||||
assert!(transformed.get("max_output_tokens").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform_claude_request_for_api_format_gemini_native() {
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("gemini_native".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = json!({
|
||||
"model": "gemini-2.5-pro",
|
||||
"system": "You are helpful.",
|
||||
"messages": [{ "role": "user", "content": "hello" }],
|
||||
"max_tokens": 64
|
||||
});
|
||||
|
||||
let transformed =
|
||||
transform_claude_request_for_api_format(body, &provider, "gemini_native", None, None)
|
||||
.unwrap();
|
||||
|
||||
assert!(transformed.get("contents").is_some());
|
||||
assert_eq!(
|
||||
transformed["systemInstruction"]["parts"][0]["text"],
|
||||
"You are helpful."
|
||||
);
|
||||
assert_eq!(transformed["generationConfig"]["maxOutputTokens"], 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform_claude_request_for_api_format_openai_chat_skips_prompt_cache_key_by_default()
|
||||
{
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.example.com",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("openai_chat".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = json!({
|
||||
"model": "gpt-5.4",
|
||||
"messages": [{ "role": "user", "content": "hello" }],
|
||||
"max_tokens": 64
|
||||
});
|
||||
|
||||
let transformed =
|
||||
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
|
||||
.unwrap();
|
||||
|
||||
assert!(transformed.get("prompt_cache_key").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform_claude_request_for_api_format_openai_chat_keeps_explicit_prompt_cache_key() {
|
||||
let provider = create_provider_with_meta(
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.example.com",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}),
|
||||
ProviderMeta {
|
||||
api_format: Some("openai_chat".to_string()),
|
||||
prompt_cache_key: Some("claude-cache-route".to_string()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = json!({
|
||||
"model": "gpt-5.4",
|
||||
"messages": [{ "role": "user", "content": "hello" }],
|
||||
"max_tokens": 64
|
||||
});
|
||||
|
||||
let transformed =
|
||||
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(transformed["prompt_cache_key"], "claude-cache-route");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,7 @@ impl From<&CodexAccountData> for GitHubAccount {
|
||||
.unwrap_or_else(|| format!("ChatGPT ({})", &data.account_id)),
|
||||
avatar_url: None,
|
||||
authenticated_at: data.authenticated_at,
|
||||
github_domain: "github.com".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,26 +24,114 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
/// GitHub OAuth 客户端 ID(VS Code 使用的 ID)
|
||||
/// GitHub OAuth 客户端 ID(VS Code)- 用于 github.com
|
||||
const GITHUB_CLIENT_ID: &str = "Iv1.b507a08c87ecfe98";
|
||||
|
||||
/// GitHub OAuth 客户端 ID(与 OpenCode 相同)- 在所有 GHES Copilot 实例上预注册
|
||||
const GITHUB_CLIENT_ID_GHES: &str = "Ov23li8tweQw6odWQebz";
|
||||
|
||||
/// 默认 GitHub 域名
|
||||
const DEFAULT_GITHUB_DOMAIN: &str = "github.com";
|
||||
|
||||
/// 根据域名选择 OAuth 客户端 ID
|
||||
fn github_client_id(domain: &str) -> &'static str {
|
||||
if domain == DEFAULT_GITHUB_DOMAIN {
|
||||
GITHUB_CLIENT_ID
|
||||
} else {
|
||||
GITHUB_CLIENT_ID_GHES
|
||||
}
|
||||
}
|
||||
|
||||
fn default_github_domain() -> String {
|
||||
DEFAULT_GITHUB_DOMAIN.to_string()
|
||||
}
|
||||
|
||||
/// GitHub 设备码 URL
|
||||
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
|
||||
fn github_device_code_url(domain: &str) -> String {
|
||||
format!("https://{domain}/login/device/code")
|
||||
}
|
||||
|
||||
/// GitHub OAuth Token URL
|
||||
const GITHUB_OAUTH_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
|
||||
fn github_oauth_token_url(domain: &str) -> String {
|
||||
format!("https://{domain}/login/oauth/access_token")
|
||||
}
|
||||
|
||||
/// GitHub API 基础 URL(github.com 用 api.github.com,GHES 用 {domain}/api/v3)
|
||||
fn github_api_base(domain: &str) -> String {
|
||||
if domain == DEFAULT_GITHUB_DOMAIN {
|
||||
"https://api.github.com".to_string()
|
||||
} else {
|
||||
format!("https://{domain}/api/v3")
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot Token URL
|
||||
const COPILOT_TOKEN_URL: &str = "https://api.github.com/copilot_internal/v2/token";
|
||||
fn copilot_token_url(domain: &str) -> String {
|
||||
format!("{}/copilot_internal/v2/token", github_api_base(domain))
|
||||
}
|
||||
|
||||
/// GitHub User API URL
|
||||
const GITHUB_USER_URL: &str = "https://api.github.com/user";
|
||||
fn github_user_url(domain: &str) -> String {
|
||||
format!("{}/user", github_api_base(domain))
|
||||
}
|
||||
|
||||
/// Copilot 使用量 API URL
|
||||
fn copilot_usage_url(domain: &str) -> String {
|
||||
format!("{}/copilot_internal/user", github_api_base(domain))
|
||||
}
|
||||
|
||||
/// Copilot API 基础地址(github.com 用 api.githubcopilot.com,GHES 用 copilot-api.{domain})
|
||||
fn copilot_api_base(domain: &str) -> String {
|
||||
if domain == DEFAULT_GITHUB_DOMAIN {
|
||||
"https://api.githubcopilot.com".to_string()
|
||||
} else {
|
||||
format!("https://copilot-api.{domain}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Token 刷新提前量(秒)
|
||||
const TOKEN_REFRESH_BUFFER_SECONDS: i64 = 60;
|
||||
|
||||
/// Copilot API 端点
|
||||
const COPILOT_MODELS_URL: &str = "https://api.githubcopilot.com/models";
|
||||
/// 判断是否为 GitHub Enterprise Server(非 github.com)
|
||||
fn is_ghes(domain: &str) -> bool {
|
||||
domain != DEFAULT_GITHUB_DOMAIN
|
||||
}
|
||||
|
||||
/// 归一化 GitHub 域名(SSOT):
|
||||
/// - 小写化
|
||||
/// - 剥离协议(https:// http://)
|
||||
/// - 剥离尾斜杠、path、query、fragment
|
||||
/// - 拒绝包含 userinfo(@)的输入
|
||||
/// - 保留端口号(如有)
|
||||
fn normalize_github_domain(raw: &str) -> Result<String, CopilotAuthError> {
|
||||
let s = raw.trim();
|
||||
// 剥离协议
|
||||
let s = s
|
||||
.strip_prefix("https://")
|
||||
.or_else(|| s.strip_prefix("http://"))
|
||||
.unwrap_or(s);
|
||||
// 取 host 部分(到第一个 / 或 ? 或 #)
|
||||
let host = s.split(&['/', '?', '#'][..]).next().unwrap_or(s);
|
||||
// 拒绝 userinfo
|
||||
if host.contains('@') {
|
||||
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
|
||||
}
|
||||
let normalized = host.to_lowercase();
|
||||
if normalized.is_empty() {
|
||||
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// 生成复合账号 ID,确保不同 GHES 实例的 user ID 不会冲突。
|
||||
/// github.com 账号保持原格式(向后兼容),GHES 账号使用 `domain:user_id` 格式。
|
||||
fn composite_account_id(domain: &str, user_id: u64) -> String {
|
||||
if domain == DEFAULT_GITHUB_DOMAIN {
|
||||
user_id.to_string()
|
||||
} else {
|
||||
format!("{}:{}", domain, user_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot API Header 常量
|
||||
pub const COPILOT_EDITOR_VERSION: &str = "vscode/1.110.1";
|
||||
@@ -52,12 +140,6 @@ pub const COPILOT_USER_AGENT: &str = "GitHubCopilotChat/0.38.2";
|
||||
pub const COPILOT_API_VERSION: &str = "2025-10-01";
|
||||
pub const COPILOT_INTEGRATION_ID: &str = "vscode-chat";
|
||||
|
||||
/// Copilot 使用量 API URL
|
||||
const COPILOT_USAGE_URL: &str = "https://api.github.com/copilot_internal/user";
|
||||
|
||||
/// 默认 Copilot API 端点
|
||||
const DEFAULT_COPILOT_API_ENDPOINT: &str = "https://api.githubcopilot.com";
|
||||
|
||||
/// Copilot 使用量响应
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CopilotUsageResponse {
|
||||
@@ -169,6 +251,9 @@ pub enum CopilotAuthError {
|
||||
|
||||
#[error("账号不存在: {0}")]
|
||||
AccountNotFound(String),
|
||||
|
||||
#[error("无效的 GitHub 域名: {0}")]
|
||||
InvalidDomain(String),
|
||||
}
|
||||
|
||||
impl From<reqwest::Error> for CopilotAuthError {
|
||||
@@ -253,15 +338,19 @@ pub struct GitHubAccount {
|
||||
pub avatar_url: Option<String>,
|
||||
/// 认证时间戳
|
||||
pub authenticated_at: i64,
|
||||
/// GitHub 域名(github.com 或 GHES 域名)
|
||||
#[serde(default = "default_github_domain")]
|
||||
pub github_domain: String,
|
||||
}
|
||||
|
||||
impl From<&GitHubAccountData> for GitHubAccount {
|
||||
fn from(data: &GitHubAccountData) -> Self {
|
||||
GitHubAccount {
|
||||
id: data.user.id.to_string(),
|
||||
id: composite_account_id(&data.github_domain, data.user.id),
|
||||
login: data.user.login.clone(),
|
||||
avatar_url: data.user.avatar_url.clone(),
|
||||
authenticated_at: data.authenticated_at,
|
||||
github_domain: data.github_domain.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,6 +384,9 @@ struct GitHubAccountData {
|
||||
pub user: GitHubUser,
|
||||
/// 认证时间戳
|
||||
pub authenticated_at: i64,
|
||||
/// GitHub 域名(github.com 或 GHES 域名)
|
||||
#[serde(default = "default_github_domain")]
|
||||
pub github_domain: String,
|
||||
}
|
||||
|
||||
/// 持久化存储结构(v3 多账号 + 默认账号格式)
|
||||
@@ -437,14 +529,16 @@ impl CopilotAuthManager {
|
||||
&self,
|
||||
github_token: String,
|
||||
user: GitHubUser,
|
||||
github_domain: String,
|
||||
) -> Result<GitHubAccount, CopilotAuthError> {
|
||||
let account_id = user.id.to_string();
|
||||
let account_id = composite_account_id(&github_domain, user.id);
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
|
||||
let account_data = GitHubAccountData {
|
||||
github_token,
|
||||
user: user.clone(),
|
||||
authenticated_at: now,
|
||||
github_domain: github_domain.clone(),
|
||||
};
|
||||
|
||||
let account = GitHubAccount {
|
||||
@@ -452,6 +546,7 @@ impl CopilotAuthManager {
|
||||
login: user.login.clone(),
|
||||
avatar_url: user.avatar_url.clone(),
|
||||
authenticated_at: now,
|
||||
github_domain,
|
||||
};
|
||||
|
||||
{
|
||||
@@ -497,15 +592,25 @@ impl CopilotAuthManager {
|
||||
// ==================== 设备码流程 ====================
|
||||
|
||||
/// 启动设备码流程
|
||||
pub async fn start_device_flow(&self) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
|
||||
log::info!("[CopilotAuth] 启动设备码流程");
|
||||
pub async fn start_device_flow(
|
||||
&self,
|
||||
github_domain: Option<&str>,
|
||||
) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
|
||||
let domain = match github_domain {
|
||||
Some(d) => normalize_github_domain(d)?,
|
||||
None => DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
};
|
||||
log::info!("[CopilotAuth] 启动设备码流程 (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.post(GITHUB_DEVICE_CODE_URL)
|
||||
.post(github_device_code_url(&domain))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
.form(&[("client_id", GITHUB_CLIENT_ID), ("scope", "read:user")])
|
||||
.form(&[
|
||||
("client_id", github_client_id(&domain)),
|
||||
("scope", "read:user"),
|
||||
])
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -534,16 +639,21 @@ impl CopilotAuthManager {
|
||||
pub async fn poll_for_token(
|
||||
&self,
|
||||
device_code: &str,
|
||||
github_domain: Option<&str>,
|
||||
) -> Result<Option<GitHubAccount>, CopilotAuthError> {
|
||||
log::debug!("[CopilotAuth] 轮询 OAuth Token");
|
||||
let domain = match github_domain {
|
||||
Some(d) => normalize_github_domain(d)?,
|
||||
None => DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
};
|
||||
log::debug!("[CopilotAuth] 轮询 OAuth Token (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.post(GITHUB_OAUTH_TOKEN_URL)
|
||||
.post(github_oauth_token_url(&domain))
|
||||
.header("Accept", "application/json")
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
.form(&[
|
||||
("client_id", GITHUB_CLIENT_ID),
|
||||
("client_id", github_client_id(&domain)),
|
||||
("device_code", device_code),
|
||||
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
|
||||
])
|
||||
@@ -578,14 +688,28 @@ impl CopilotAuthManager {
|
||||
log::info!("[CopilotAuth] OAuth Token 获取成功");
|
||||
|
||||
// 获取用户信息
|
||||
let user = self.fetch_user_info_with_token(&access_token).await?;
|
||||
|
||||
// 验证 Copilot 订阅(获取 Copilot Token)
|
||||
self.fetch_copilot_token_with_github_token(&access_token, &user.id.to_string())
|
||||
let user = self
|
||||
.fetch_user_info_with_token(&access_token, &domain)
|
||||
.await?;
|
||||
|
||||
// GHES 无需换取 Copilot Token,直接使用 OAuth token 作为 Bearer
|
||||
// 参考 OpenCode 的实现:GHE Copilot 直接用 OAuth token 调用 copilot-api.{domain}
|
||||
if !is_ghes(&domain) {
|
||||
// github.com:验证 Copilot 订阅(获取 Copilot Token)
|
||||
self.fetch_copilot_token_with_github_token(
|
||||
&access_token,
|
||||
&user.id.to_string(),
|
||||
&domain,
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
log::info!("[CopilotAuth] GHES 账号,跳过 Copilot Token 兑换,直接使用 OAuth token");
|
||||
}
|
||||
|
||||
// 添加账号
|
||||
let account = self.add_account_internal(access_token, user).await?;
|
||||
let account = self
|
||||
.add_account_internal(access_token, user, domain)
|
||||
.await?;
|
||||
|
||||
Ok(Some(account))
|
||||
}
|
||||
@@ -600,6 +724,16 @@ impl CopilotAuthManager {
|
||||
// 确保迁移完成
|
||||
self.ensure_migration_complete().await?;
|
||||
|
||||
// GHES 账号直接使用 GitHub OAuth token,无需 Copilot token 交换
|
||||
let domain = self.get_account_domain(account_id).await;
|
||||
if is_ghes(&domain) {
|
||||
let accounts = self.accounts.read().await;
|
||||
return accounts
|
||||
.get(account_id)
|
||||
.map(|a| a.github_token.clone())
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()));
|
||||
}
|
||||
|
||||
// 检查缓存的 token
|
||||
{
|
||||
let tokens = self.copilot_tokens.read().await;
|
||||
@@ -627,16 +761,16 @@ impl CopilotAuthManager {
|
||||
}
|
||||
|
||||
// 获取账号的 GitHub token
|
||||
let github_token = {
|
||||
let (github_token, domain) = {
|
||||
let accounts = self.accounts.read().await;
|
||||
accounts
|
||||
let account = accounts
|
||||
.get(account_id)
|
||||
.map(|a| a.github_token.clone())
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
|
||||
(account.github_token.clone(), account.github_domain.clone())
|
||||
};
|
||||
|
||||
// 刷新 Copilot token
|
||||
self.fetch_copilot_token_with_github_token(&github_token, account_id)
|
||||
self.fetch_copilot_token_with_github_token(&github_token, account_id, &domain)
|
||||
.await?;
|
||||
|
||||
// 返回新 token
|
||||
@@ -687,11 +821,19 @@ impl CopilotAuthManager {
|
||||
) -> Result<Vec<CopilotModel>, CopilotAuthError> {
|
||||
let copilot_token = self.get_valid_token_for_account(account_id).await?;
|
||||
|
||||
// 使用 get_api_endpoint() 动态解析 Copilot API 基础 URL。
|
||||
// 对于 github.com 账号,会查询 /copilot_internal/user 获取 endpoints.api 字段。
|
||||
// 对于 GHES 账号,/copilot_internal/user 可能不返回 endpoints——此时
|
||||
// get_api_endpoint() 会回退到 copilot_api_base(&domain),与之前的静态 URL
|
||||
// 拼接结果一致。该回退行为是安全且符合预期的。
|
||||
let api_base = self.get_api_endpoint(account_id).await;
|
||||
let models_url = format!("{}/models", api_base);
|
||||
|
||||
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 可用模型");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.get(COPILOT_MODELS_URL)
|
||||
.get(&models_url)
|
||||
.header("Authorization", format!("Bearer {copilot_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("copilot-integration-id", "vscode-chat")
|
||||
@@ -767,19 +909,19 @@ impl CopilotAuthManager {
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> Result<CopilotUsageResponse, CopilotAuthError> {
|
||||
let github_token = {
|
||||
let (github_token, domain) = {
|
||||
let accounts = self.accounts.read().await;
|
||||
accounts
|
||||
let account = accounts
|
||||
.get(account_id)
|
||||
.map(|a| a.github_token.clone())
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
|
||||
(account.github_token.clone(), account.github_domain.clone())
|
||||
};
|
||||
|
||||
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 使用量");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.get(COPILOT_USAGE_URL)
|
||||
.get(copilot_usage_url(&domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("editor-version", COPILOT_EDITOR_VERSION)
|
||||
@@ -862,7 +1004,8 @@ impl CopilotAuthManager {
|
||||
log::debug!(
|
||||
"[CopilotAuth] 获取账号 {account_id} 动态 API 端点失败: {e},使用默认值"
|
||||
);
|
||||
DEFAULT_COPILOT_API_ENDPOINT.to_string()
|
||||
let domain = self.get_account_domain(account_id).await;
|
||||
copilot_api_base(&domain)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -873,24 +1016,27 @@ impl CopilotAuthManager {
|
||||
|
||||
match self.resolve_default_account_id().await {
|
||||
Some(id) => self.get_api_endpoint(&id).await,
|
||||
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
|
||||
None => {
|
||||
// 无账号时回退到 github.com 的默认端点
|
||||
copilot_api_base(DEFAULT_GITHUB_DOMAIN)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_and_cache_endpoint(&self, account_id: &str) -> Result<String, CopilotAuthError> {
|
||||
let github_token = {
|
||||
let (github_token, domain) = {
|
||||
let accounts = self.accounts.read().await;
|
||||
accounts
|
||||
let account = accounts
|
||||
.get(account_id)
|
||||
.map(|a| a.github_token.clone())
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
|
||||
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
|
||||
(account.github_token.clone(), account.github_domain.clone())
|
||||
};
|
||||
|
||||
log::debug!("[CopilotAuth] 为账号 {account_id} 惰性拉取动态 API 端点");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.get(COPILOT_USAGE_URL)
|
||||
.get(copilot_usage_url(&domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("editor-version", COPILOT_EDITOR_VERSION)
|
||||
@@ -918,7 +1064,7 @@ impl CopilotAuthManager {
|
||||
|
||||
let endpoint = match usage.endpoints {
|
||||
Some(endpoints) => endpoints.api.clone(),
|
||||
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
|
||||
None => copilot_api_base(&domain),
|
||||
};
|
||||
|
||||
// 缓存端点(包括默认值),避免重复请求
|
||||
@@ -1075,6 +1221,15 @@ impl CopilotAuthManager {
|
||||
Self::fallback_default_account_id(&accounts)
|
||||
}
|
||||
|
||||
/// 获取指定账号的 GitHub 域名
|
||||
async fn get_account_domain(&self, account_id: &str) -> String {
|
||||
let accounts = self.accounts.read().await;
|
||||
accounts
|
||||
.get(account_id)
|
||||
.map(|a| a.github_domain.clone())
|
||||
.unwrap_or_else(|| DEFAULT_GITHUB_DOMAIN.to_string())
|
||||
}
|
||||
|
||||
async fn get_refresh_lock(&self, account_id: &str) -> Arc<Mutex<()>> {
|
||||
{
|
||||
let refresh_locks = self.refresh_locks.read().await;
|
||||
@@ -1155,10 +1310,11 @@ impl CopilotAuthManager {
|
||||
async fn fetch_user_info_with_token(
|
||||
&self,
|
||||
github_token: &str,
|
||||
domain: &str,
|
||||
) -> Result<GitHubUser, CopilotAuthError> {
|
||||
let response = self
|
||||
.http_client
|
||||
.get(GITHUB_USER_URL)
|
||||
.get(github_user_url(domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
.header("Editor-Version", COPILOT_EDITOR_VERSION)
|
||||
@@ -1185,12 +1341,13 @@ impl CopilotAuthManager {
|
||||
&self,
|
||||
github_token: &str,
|
||||
account_id: &str,
|
||||
domain: &str,
|
||||
) -> Result<(), CopilotAuthError> {
|
||||
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token");
|
||||
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token (domain: {domain})");
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.get(COPILOT_TOKEN_URL)
|
||||
.get(copilot_token_url(domain))
|
||||
.header("Authorization", format!("token {github_token}"))
|
||||
.header("User-Agent", COPILOT_USER_AGENT)
|
||||
.header("Editor-Version", COPILOT_EDITOR_VERSION)
|
||||
@@ -1284,20 +1441,32 @@ impl CopilotAuthManager {
|
||||
log::info!("[CopilotAuth] 执行旧格式迁移");
|
||||
|
||||
// 获取用户信息
|
||||
match self.fetch_user_info_with_token(&legacy_token).await {
|
||||
match self
|
||||
.fetch_user_info_with_token(&legacy_token, DEFAULT_GITHUB_DOMAIN)
|
||||
.await
|
||||
{
|
||||
Ok(user) => {
|
||||
let account_id = user.id.to_string();
|
||||
let account_id = composite_account_id(DEFAULT_GITHUB_DOMAIN, user.id);
|
||||
|
||||
// 尝试获取 Copilot token 验证订阅
|
||||
if let Err(e) = self
|
||||
.fetch_copilot_token_with_github_token(&legacy_token, &account_id)
|
||||
.fetch_copilot_token_with_github_token(
|
||||
&legacy_token,
|
||||
&account_id,
|
||||
DEFAULT_GITHUB_DOMAIN,
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::warn!("[CopilotAuth] 迁移时验证 Copilot 订阅失败: {e}");
|
||||
}
|
||||
|
||||
// 添加账号
|
||||
self.add_account_internal(legacy_token, user).await?;
|
||||
self.add_account_internal(
|
||||
legacy_token,
|
||||
user,
|
||||
DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
)
|
||||
.await?;
|
||||
self.set_migration_error(None).await;
|
||||
|
||||
log::info!("[CopilotAuth] 旧格式迁移完成");
|
||||
@@ -1387,6 +1556,7 @@ mod tests {
|
||||
login: "testuser".to_string(),
|
||||
avatar_url: Some("https://example.com/avatar.png".to_string()),
|
||||
authenticated_at: 1234567890,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
}],
|
||||
default_account_id: Some("12345".to_string()),
|
||||
migration_error: None,
|
||||
@@ -1420,6 +1590,7 @@ mod tests {
|
||||
avatar_url: Some("https://example.com/alice.png".to_string()),
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
accounts.insert(
|
||||
@@ -1432,6 +1603,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000001,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1479,6 +1651,7 @@ mod tests {
|
||||
avatar_url: Some("https://example.com/avatar.png".to_string()),
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
};
|
||||
|
||||
let account = GitHubAccount::from(&data);
|
||||
@@ -1504,6 +1677,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
accounts.insert(
|
||||
@@ -1516,6 +1690,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000001,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1546,6 +1721,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1630,6 +1806,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1664,6 +1841,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1746,6 +1924,7 @@ mod tests {
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1801,7 +1980,7 @@ mod tests {
|
||||
let manager = CopilotAuthManager::new(temp_dir.path().to_path_buf());
|
||||
|
||||
let endpoint = manager.get_api_endpoint("12345").await;
|
||||
assert_eq!(endpoint, DEFAULT_COPILOT_API_ENDPOINT);
|
||||
assert_eq!(endpoint, copilot_api_base(DEFAULT_GITHUB_DOMAIN));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1817,4 +1996,99 @@ mod tests {
|
||||
other => panic!("期望 AccountNotFound 错误,实际: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_normalize_github_domain() {
|
||||
// 基本用法
|
||||
assert_eq!(normalize_github_domain("github.com").unwrap(), "github.com");
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
|
||||
// 剥离协议
|
||||
assert_eq!(
|
||||
normalize_github_domain("https://company.ghe.com").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_github_domain("http://company.ghe.com").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
|
||||
// 小写化
|
||||
assert_eq!(normalize_github_domain("GitHub.COM").unwrap(), "github.com");
|
||||
assert_eq!(
|
||||
normalize_github_domain("Company.GHE.Com").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
|
||||
// 剥离尾斜杠和 path
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com/").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com/api/v3").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
|
||||
// 剥离 query 和 fragment
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com?foo=bar").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com#section").unwrap(),
|
||||
"company.ghe.com"
|
||||
);
|
||||
|
||||
// 保留端口
|
||||
assert_eq!(
|
||||
normalize_github_domain("company.ghe.com:8443").unwrap(),
|
||||
"company.ghe.com:8443"
|
||||
);
|
||||
|
||||
// 拒绝 userinfo
|
||||
assert!(normalize_github_domain("user@company.ghe.com").is_err());
|
||||
|
||||
// 拒绝空输入
|
||||
assert!(normalize_github_domain("").is_err());
|
||||
assert!(normalize_github_domain(" ").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_composite_account_id() {
|
||||
// github.com 保持原格式(向后兼容)
|
||||
assert_eq!(composite_account_id("github.com", 12345), "12345");
|
||||
|
||||
// GHES 使用复合格式
|
||||
assert_eq!(
|
||||
composite_account_id("company.ghe.com", 12345),
|
||||
"company.ghe.com:12345"
|
||||
);
|
||||
|
||||
// 不同 GHES 实例,相同 user ID,不冲突
|
||||
assert_ne!(
|
||||
composite_account_id("a.ghe.com", 1),
|
||||
composite_account_id("b.ghe.com", 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_github_account_from_data_ghes_uses_composite_id() {
|
||||
let data = GitHubAccountData {
|
||||
github_token: "gho_test".to_string(),
|
||||
user: GitHubUser {
|
||||
login: "testuser".to_string(),
|
||||
id: 99999,
|
||||
avatar_url: None,
|
||||
},
|
||||
authenticated_at: 1700000000,
|
||||
github_domain: "company.ghe.com".to_string(),
|
||||
};
|
||||
|
||||
let account = GitHubAccount::from(&data);
|
||||
assert_eq!(account.id, "company.ghe.com:99999");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,6 +70,11 @@ impl GeminiAdapter {
|
||||
|
||||
/// 解析 OAuth 凭证
|
||||
pub fn parse_oauth_credentials(&self, key: &str) -> Option<OAuthCredentials> {
|
||||
// 防御性 trim:前端在 input 事件中会 trim,但 JSON 编辑器 / deeplink
|
||||
// 导入 / live 回填等路径会绕过。带前导换行的 oauth_creds.json 粘贴
|
||||
// 是常见场景,此处统一兜底。
|
||||
let key = key.trim();
|
||||
|
||||
// 直接是 access_token
|
||||
if key.starts_with("ya29.") {
|
||||
return Some(OAuthCredentials {
|
||||
@@ -120,7 +125,12 @@ impl GeminiAdapter {
|
||||
fn extract_key_raw(&self, provider: &Provider) -> Option<String> {
|
||||
if let Some(env) = provider.settings_config.get("env") {
|
||||
// 使用 GEMINI_API_KEY
|
||||
if let Some(key) = env.get("GEMINI_API_KEY").and_then(|v| v.as_str()) {
|
||||
if let Some(key) = env
|
||||
.get("GEMINI_API_KEY")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
return Some(key.to_string());
|
||||
}
|
||||
}
|
||||
@@ -131,6 +141,8 @@ impl GeminiAdapter {
|
||||
.get("apiKey")
|
||||
.or_else(|| provider.settings_config.get("api_key"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
return Some(key.to_string());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Gemini tool schema helpers.
|
||||
//!
|
||||
//! Gemini `FunctionDeclaration` supports two schema channels:
|
||||
//! - `parameters`: a restricted `Schema` subset
|
||||
//! - `parametersJsonSchema`: richer JSON Schema via arbitrary JSON `Value`
|
||||
//!
|
||||
//! Anthropic tool schemas are closer to JSON Schema, so we choose the richer
|
||||
//! channel when unsupported `Schema` fields are present.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum GeminiFunctionParameters {
|
||||
Schema(Value),
|
||||
JsonSchema(Value),
|
||||
}
|
||||
|
||||
pub fn build_gemini_function_parameters(input_schema: Value) -> GeminiFunctionParameters {
|
||||
let schema = ensure_object_schema(normalize_json_schema(input_schema));
|
||||
|
||||
if requires_parameters_json_schema(&schema) {
|
||||
GeminiFunctionParameters::JsonSchema(schema)
|
||||
} else {
|
||||
GeminiFunctionParameters::Schema(to_gemini_schema(schema))
|
||||
}
|
||||
}
|
||||
|
||||
/// Vertex AI rejects FunctionDeclarations whose `parameters` schema lacks an
|
||||
/// explicit `type: "object"`, returning:
|
||||
///
|
||||
/// > functionDeclaration parameters schema should be of type OBJECT.
|
||||
///
|
||||
/// Anthropic tools sometimes arrive with empty or type-less `input_schema`
|
||||
/// (e.g. no-argument tools like Claude Code's `TodoRead`). Normalize those to
|
||||
/// `{type: "object", properties: {}}` so the Gemini upstream accepts them.
|
||||
///
|
||||
/// References: google-gemini/generative-ai-python#423, BerriAI/litellm#5055.
|
||||
fn ensure_object_schema(schema: Value) -> Value {
|
||||
match schema {
|
||||
Value::Object(mut obj) => {
|
||||
obj.entry("type".to_string())
|
||||
.or_insert_with(|| json!("object"));
|
||||
if obj.get("type").and_then(|v| v.as_str()) == Some("object") {
|
||||
obj.entry("properties".to_string())
|
||||
.or_insert_with(|| json!({}));
|
||||
}
|
||||
Value::Object(obj)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_json_schema(schema: Value) -> Value {
|
||||
match schema {
|
||||
Value::Object(mut obj) => {
|
||||
obj.remove("$schema");
|
||||
obj.remove("$id");
|
||||
|
||||
if let Some(properties) = obj
|
||||
.get_mut("properties")
|
||||
.and_then(|value| value.as_object_mut())
|
||||
{
|
||||
for value in properties.values_mut() {
|
||||
*value = normalize_json_schema(value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(items) = obj.get_mut("items") {
|
||||
*items = normalize_json_schema(items.clone());
|
||||
}
|
||||
|
||||
for key in ["anyOf", "oneOf", "allOf", "prefixItems"] {
|
||||
if let Some(values) = obj.get_mut(key).and_then(|value| value.as_array_mut()) {
|
||||
for value in values.iter_mut() {
|
||||
*value = normalize_json_schema(value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for key in ["not", "if", "then", "else", "additionalProperties"] {
|
||||
if let Some(value) = obj.get_mut(key) {
|
||||
*value = normalize_json_schema(value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Value::Object(obj)
|
||||
}
|
||||
Value::Array(values) => {
|
||||
Value::Array(values.into_iter().map(normalize_json_schema).collect())
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
fn requires_parameters_json_schema(schema: &Value) -> bool {
|
||||
match schema {
|
||||
Value::Object(obj) => object_requires_parameters_json_schema(obj),
|
||||
Value::Array(values) => values.iter().any(requires_parameters_json_schema),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn object_requires_parameters_json_schema(obj: &Map<String, Value>) -> bool {
|
||||
for (key, value) in obj {
|
||||
match key.as_str() {
|
||||
"type" => {
|
||||
if value.is_array() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
"format" | "title" | "description" | "nullable" | "enum" | "maxItems" | "minItems"
|
||||
| "required" | "minProperties" | "maxProperties" | "minLength" | "maxLength"
|
||||
| "pattern" | "example" | "propertyOrdering" | "default" | "minimum" | "maximum" => {}
|
||||
"properties" => {
|
||||
let Some(properties) = value.as_object() else {
|
||||
return true;
|
||||
};
|
||||
if properties.values().any(requires_parameters_json_schema) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
"items" => {
|
||||
if !value.is_object() || requires_parameters_json_schema(value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
"anyOf" => {
|
||||
let Some(values) = value.as_array() else {
|
||||
return true;
|
||||
};
|
||||
if values.iter().any(requires_parameters_json_schema) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// JSON Schema keywords that Gemini `parameters` does not accept.
|
||||
"$ref"
|
||||
| "$defs"
|
||||
| "definitions"
|
||||
| "additionalProperties"
|
||||
| "unevaluatedProperties"
|
||||
| "patternProperties"
|
||||
| "oneOf"
|
||||
| "allOf"
|
||||
| "const"
|
||||
| "not"
|
||||
| "if"
|
||||
| "then"
|
||||
| "else"
|
||||
| "dependentRequired"
|
||||
| "dependentSchemas"
|
||||
| "contains"
|
||||
| "minContains"
|
||||
| "maxContains"
|
||||
| "prefixItems"
|
||||
| "exclusiveMinimum"
|
||||
| "exclusiveMaximum"
|
||||
| "multipleOf"
|
||||
| "examples" => return true,
|
||||
// Be conservative for unknown keywords.
|
||||
_ => return true,
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn to_gemini_schema(schema: Value) -> Value {
|
||||
match schema {
|
||||
Value::Object(obj) => {
|
||||
let mut result = Map::new();
|
||||
|
||||
for (key, value) in obj {
|
||||
match key.as_str() {
|
||||
"type" | "format" | "title" | "description" | "nullable" | "enum"
|
||||
| "maxItems" | "minItems" | "required" | "minProperties" | "maxProperties"
|
||||
| "minLength" | "maxLength" | "pattern" | "example" | "propertyOrdering"
|
||||
| "default" | "minimum" | "maximum" => {
|
||||
result.insert(key, value);
|
||||
}
|
||||
"properties" => {
|
||||
if let Some(properties) = value.as_object() {
|
||||
let converted = properties
|
||||
.iter()
|
||||
.map(|(name, property_schema)| {
|
||||
(name.clone(), to_gemini_schema(property_schema.clone()))
|
||||
})
|
||||
.collect();
|
||||
result.insert("properties".to_string(), Value::Object(converted));
|
||||
}
|
||||
}
|
||||
"items" if value.is_object() => {
|
||||
result.insert("items".to_string(), to_gemini_schema(value));
|
||||
}
|
||||
"anyOf" => {
|
||||
if let Some(values) = value.as_array() {
|
||||
result.insert(
|
||||
"anyOf".to_string(),
|
||||
Value::Array(
|
||||
values
|
||||
.iter()
|
||||
.map(|value| to_gemini_schema(value.clone()))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
Value::Object(result)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_gemini_function_declaration(
|
||||
name: &str,
|
||||
description: Option<&str>,
|
||||
input_schema: Value,
|
||||
) -> Value {
|
||||
let mut declaration = Map::new();
|
||||
declaration.insert("name".to_string(), json!(name));
|
||||
declaration.insert("description".to_string(), json!(description.unwrap_or("")));
|
||||
|
||||
match build_gemini_function_parameters(input_schema) {
|
||||
GeminiFunctionParameters::Schema(schema) => {
|
||||
declaration.insert("parameters".to_string(), schema);
|
||||
}
|
||||
GeminiFunctionParameters::JsonSchema(schema) => {
|
||||
declaration.insert("parametersJsonSchema".to_string(), schema);
|
||||
}
|
||||
}
|
||||
|
||||
Value::Object(declaration)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn uses_schema_for_simple_openapi_subset() {
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": { "type": "string", "description": "Target city" }
|
||||
},
|
||||
"required": ["city"]
|
||||
});
|
||||
|
||||
let result = build_gemini_function_declaration("weather", Some("Weather lookup"), schema);
|
||||
|
||||
assert!(result.get("parameters").is_some());
|
||||
assert!(result.get("parametersJsonSchema").is_none());
|
||||
assert_eq!(result["parameters"]["properties"]["city"]["type"], "string");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_parameters_json_schema_for_additional_properties() {
|
||||
let schema = json!({
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"city": { "type": "string" }
|
||||
},
|
||||
"required": ["city"],
|
||||
"additionalProperties": false
|
||||
});
|
||||
|
||||
let result = build_gemini_function_declaration("weather", Some("Weather lookup"), schema);
|
||||
|
||||
assert!(result.get("parameters").is_none());
|
||||
assert!(result.get("parametersJsonSchema").is_some());
|
||||
assert!(result["parametersJsonSchema"].get("$schema").is_none());
|
||||
assert_eq!(
|
||||
result["parametersJsonSchema"]["additionalProperties"],
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_parameters_json_schema_for_one_of() {
|
||||
let schema = json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"target": {
|
||||
"oneOf": [
|
||||
{ "type": "string" },
|
||||
{ "type": "integer" }
|
||||
]
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = build_gemini_function_declaration("search", Some("Search"), schema);
|
||||
|
||||
assert!(result.get("parameters").is_none());
|
||||
assert!(result.get("parametersJsonSchema").is_some());
|
||||
}
|
||||
|
||||
/// Regression for P2 (Vertex AI rejecting empty schemas): zero-argument
|
||||
/// Anthropic tools (no `input_schema`) must produce `parameters` with an
|
||||
/// explicit `type: "object"` and an empty `properties` map so the Gemini
|
||||
/// upstream does not return `schema should be of type OBJECT`.
|
||||
#[test]
|
||||
fn empty_input_schema_produces_explicit_object_type() {
|
||||
let result = build_gemini_function_declaration("ping", Some("no-arg"), json!({}));
|
||||
|
||||
assert_eq!(result["parameters"]["type"], "object");
|
||||
assert!(result["parameters"]["properties"].is_object());
|
||||
}
|
||||
|
||||
/// A schema that carries descriptive fields but no `type` is still a
|
||||
/// zero-arg object for Gemini purposes — promote it explicitly.
|
||||
#[test]
|
||||
fn input_schema_missing_type_is_promoted_to_object() {
|
||||
let result = build_gemini_function_declaration(
|
||||
"noop",
|
||||
None,
|
||||
json!({ "description": "does nothing" }),
|
||||
);
|
||||
|
||||
assert_eq!(result["parameters"]["type"], "object");
|
||||
assert!(result["parameters"]["properties"].is_object());
|
||||
}
|
||||
|
||||
/// Defensive: an atomic (non-object) schema is left untouched, because
|
||||
/// forcing `type: "object"` here would corrupt primitive parameter types
|
||||
/// that happen to flow through this path.
|
||||
#[test]
|
||||
fn non_object_schema_is_not_mutated() {
|
||||
let result = build_gemini_function_declaration("bare", None, json!({ "type": "string" }));
|
||||
|
||||
assert_eq!(result["parameters"]["type"], "string");
|
||||
assert!(result["parameters"].get("properties").is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
//! Gemini Native shadow state
|
||||
//!
|
||||
//! Keeps provider/session-scoped assistant content snapshots and tool call metadata
|
||||
//! so Gemini thought signatures and tool turns can be replayed without bloating
|
||||
//! the main proxy files.
|
||||
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::RwLock;
|
||||
|
||||
/// Composite key for a Gemini shadow session.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct GeminiShadowKey {
|
||||
pub provider_id: String,
|
||||
pub session_id: String,
|
||||
}
|
||||
|
||||
impl GeminiShadowKey {
|
||||
pub fn new(provider_id: impl Into<String>, session_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
provider_id: provider_id.into(),
|
||||
session_id: session_id.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gemini function call metadata captured from an assistant turn.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GeminiToolCallMeta {
|
||||
pub id: Option<String>,
|
||||
pub name: String,
|
||||
pub args: Value,
|
||||
pub thought_signature: Option<String>,
|
||||
}
|
||||
|
||||
impl GeminiToolCallMeta {
|
||||
pub fn new(
|
||||
id: Option<impl Into<String>>,
|
||||
name: impl Into<String>,
|
||||
args: Value,
|
||||
thought_signature: Option<impl Into<String>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: id.map(Into::into),
|
||||
name: name.into(),
|
||||
args,
|
||||
thought_signature: thought_signature.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stored assistant turn snapshot.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GeminiAssistantTurn {
|
||||
pub assistant_content: Value,
|
||||
pub tool_calls: Vec<GeminiToolCallMeta>,
|
||||
}
|
||||
|
||||
impl GeminiAssistantTurn {
|
||||
pub fn new(assistant_content: Value, tool_calls: Vec<GeminiToolCallMeta>) -> Self {
|
||||
Self {
|
||||
assistant_content,
|
||||
tool_calls,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Session snapshot returned by read APIs.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GeminiShadowSessionSnapshot {
|
||||
pub provider_id: String,
|
||||
pub session_id: String,
|
||||
pub turns: Vec<GeminiAssistantTurn>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct GeminiShadowSession {
|
||||
turns: VecDeque<GeminiAssistantTurn>,
|
||||
}
|
||||
|
||||
impl GeminiShadowSession {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
turns: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct GeminiShadowInner {
|
||||
sessions: HashMap<GeminiShadowKey, GeminiShadowSession>,
|
||||
session_order: VecDeque<GeminiShadowKey>,
|
||||
}
|
||||
|
||||
impl GeminiShadowInner {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
sessions: HashMap::new(),
|
||||
session_order: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thread-safe shadow store for Gemini Native replay state.
|
||||
///
|
||||
/// The store is intentionally small and explicit:
|
||||
/// - sessions are keyed by `(provider_id, session_id)`
|
||||
/// - each session keeps only a bounded number of recent assistant turns
|
||||
/// - the oldest session is evicted first when the store is full
|
||||
#[derive(Debug)]
|
||||
pub struct GeminiShadowStore {
|
||||
max_sessions: usize,
|
||||
max_turns_per_session: usize,
|
||||
inner: RwLock<GeminiShadowInner>,
|
||||
}
|
||||
|
||||
impl Default for GeminiShadowStore {
|
||||
fn default() -> Self {
|
||||
Self::with_limits(200, 64)
|
||||
}
|
||||
}
|
||||
|
||||
impl GeminiShadowStore {
|
||||
#[allow(dead_code)]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_limits(max_sessions: usize, max_turns_per_session: usize) -> Self {
|
||||
Self {
|
||||
max_sessions: max_sessions.max(1),
|
||||
max_turns_per_session: max_turns_per_session.max(1),
|
||||
inner: RwLock::new(GeminiShadowInner::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a Gemini assistant turn for later replay.
|
||||
pub fn record_assistant_turn(
|
||||
&self,
|
||||
provider_id: impl Into<String>,
|
||||
session_id: impl Into<String>,
|
||||
assistant_content: Value,
|
||||
tool_calls: Vec<GeminiToolCallMeta>,
|
||||
) -> GeminiShadowSessionSnapshot {
|
||||
let key = GeminiShadowKey::new(provider_id, session_id);
|
||||
let turn = GeminiAssistantTurn::new(assistant_content, tool_calls);
|
||||
|
||||
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
|
||||
Self::touch_session_order(&mut inner.session_order, &key);
|
||||
|
||||
let snapshot = {
|
||||
let session = inner
|
||||
.sessions
|
||||
.entry(key.clone())
|
||||
.or_insert_with(GeminiShadowSession::new);
|
||||
session.turns.push_back(turn);
|
||||
while session.turns.len() > self.max_turns_per_session {
|
||||
session.turns.pop_front();
|
||||
}
|
||||
Self::snapshot_session(&key, session)
|
||||
};
|
||||
Self::prune_sessions(&mut inner, self.max_sessions);
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// Get the latest assistant content for a provider/session pair.
|
||||
#[allow(dead_code)]
|
||||
pub fn latest_assistant_content(&self, provider_id: &str, session_id: &str) -> Option<Value> {
|
||||
self.get_session(provider_id, session_id)
|
||||
.and_then(|snapshot| {
|
||||
snapshot
|
||||
.turns
|
||||
.last()
|
||||
.map(|turn| turn.assistant_content.clone())
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the latest tool calls for a provider/session pair.
|
||||
#[allow(dead_code)]
|
||||
pub fn latest_tool_calls(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
session_id: &str,
|
||||
) -> Option<Vec<GeminiToolCallMeta>> {
|
||||
self.get_session(provider_id, session_id)
|
||||
.and_then(|snapshot| snapshot.turns.last().map(|turn| turn.tool_calls.clone()))
|
||||
}
|
||||
|
||||
/// Read a full session snapshot.
|
||||
pub fn get_session(
|
||||
&self,
|
||||
provider_id: &str,
|
||||
session_id: &str,
|
||||
) -> Option<GeminiShadowSessionSnapshot> {
|
||||
let key = GeminiShadowKey::new(provider_id, session_id);
|
||||
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
|
||||
let snapshot = inner
|
||||
.sessions
|
||||
.get(&key)
|
||||
.map(|session| Self::snapshot_session(&key, session));
|
||||
if snapshot.is_some() {
|
||||
Self::touch_session_order(&mut inner.session_order, &key);
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
/// Remove a single session from the store.
|
||||
#[allow(dead_code)]
|
||||
pub fn clear_session(&self, provider_id: &str, session_id: &str) -> bool {
|
||||
let key = GeminiShadowKey::new(provider_id, session_id);
|
||||
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
|
||||
let removed = inner.sessions.remove(&key).is_some();
|
||||
if removed {
|
||||
Self::remove_key_from_order(&mut inner.session_order, &key);
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
/// Remove all sessions for a provider.
|
||||
#[allow(dead_code)]
|
||||
pub fn clear_provider(&self, provider_id: &str) -> usize {
|
||||
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
|
||||
let keys: Vec<_> = inner
|
||||
.sessions
|
||||
.keys()
|
||||
.filter(|key| key.provider_id == provider_id)
|
||||
.cloned()
|
||||
.collect();
|
||||
for key in &keys {
|
||||
inner.sessions.remove(key);
|
||||
Self::remove_key_from_order(&mut inner.session_order, key);
|
||||
}
|
||||
keys.len()
|
||||
}
|
||||
|
||||
/// Number of tracked sessions.
|
||||
#[allow(dead_code)]
|
||||
pub fn session_count(&self) -> usize {
|
||||
self.inner
|
||||
.read()
|
||||
.expect("gemini shadow lock poisoned")
|
||||
.sessions
|
||||
.len()
|
||||
}
|
||||
|
||||
fn snapshot_session(
|
||||
key: &GeminiShadowKey,
|
||||
session: &GeminiShadowSession,
|
||||
) -> GeminiShadowSessionSnapshot {
|
||||
GeminiShadowSessionSnapshot {
|
||||
provider_id: key.provider_id.clone(),
|
||||
session_id: key.session_id.clone(),
|
||||
turns: session.turns.iter().cloned().collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn touch_session_order(order: &mut VecDeque<GeminiShadowKey>, key: &GeminiShadowKey) {
|
||||
if let Some(pos) = order.iter().position(|existing| existing == key) {
|
||||
order.remove(pos);
|
||||
}
|
||||
order.push_back(key.clone());
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn remove_key_from_order(order: &mut VecDeque<GeminiShadowKey>, key: &GeminiShadowKey) {
|
||||
if let Some(pos) = order.iter().position(|existing| existing == key) {
|
||||
order.remove(pos);
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_sessions(inner: &mut GeminiShadowInner, max_sessions: usize) {
|
||||
while inner.sessions.len() > max_sessions {
|
||||
let Some(evicted_key) = inner.session_order.pop_front() else {
|
||||
break;
|
||||
};
|
||||
inner.sessions.remove(&evicted_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn record_and_read_latest_turn() {
|
||||
let store = GeminiShadowStore::with_limits(8, 4);
|
||||
let snapshot = store.record_assistant_turn(
|
||||
"provider-a",
|
||||
"session-1",
|
||||
json!({"parts": [{"text": "hello", "thoughtSignature": "sig-1"}]}),
|
||||
vec![GeminiToolCallMeta::new(
|
||||
Some("call-1"),
|
||||
"get_weather",
|
||||
json!({"location": "Tokyo"}),
|
||||
Some("sig-1"),
|
||||
)],
|
||||
);
|
||||
|
||||
assert_eq!(snapshot.provider_id, "provider-a");
|
||||
assert_eq!(snapshot.session_id, "session-1");
|
||||
assert_eq!(snapshot.turns.len(), 1);
|
||||
|
||||
let content = store
|
||||
.latest_assistant_content("provider-a", "session-1")
|
||||
.expect("content");
|
||||
assert_eq!(content["parts"][0]["text"], "hello");
|
||||
assert_eq!(content["parts"][0]["thoughtSignature"], "sig-1");
|
||||
|
||||
let tool_calls = store
|
||||
.latest_tool_calls("provider-a", "session-1")
|
||||
.expect("tool calls");
|
||||
assert_eq!(tool_calls.len(), 1);
|
||||
assert_eq!(tool_calls[0].id.as_deref(), Some("call-1"));
|
||||
assert_eq!(tool_calls[0].name, "get_weather");
|
||||
assert_eq!(tool_calls[0].args["location"], "Tokyo");
|
||||
assert_eq!(tool_calls[0].thought_signature.as_deref(), Some("sig-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sessions_are_isolated_by_provider_and_session_id() {
|
||||
let store = GeminiShadowStore::with_limits(8, 4);
|
||||
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"text": "a"}), vec![]);
|
||||
store.record_assistant_turn("provider-b", "session-1", json!({"text": "b"}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-2", json!({"text": "c"}), vec![]);
|
||||
|
||||
assert_eq!(store.session_count(), 3);
|
||||
assert_eq!(
|
||||
store.latest_assistant_content("provider-a", "session-1"),
|
||||
Some(json!({"text": "a"}))
|
||||
);
|
||||
assert_eq!(
|
||||
store.latest_assistant_content("provider-b", "session-1"),
|
||||
Some(json!({"text": "b"}))
|
||||
);
|
||||
assert_eq!(
|
||||
store.latest_assistant_content("provider-a", "session-2"),
|
||||
Some(json!({"text": "c"}))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retains_only_latest_turns_per_session() {
|
||||
let store = GeminiShadowStore::with_limits(8, 2);
|
||||
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 2}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 3}), vec![]);
|
||||
|
||||
let snapshot = store
|
||||
.get_session("provider-a", "session-1")
|
||||
.expect("snapshot");
|
||||
assert_eq!(snapshot.turns.len(), 2);
|
||||
assert_eq!(snapshot.turns[0].assistant_content, json!({"idx": 2}));
|
||||
assert_eq!(snapshot.turns[1].assistant_content, json!({"idx": 3}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evicts_oldest_session_when_capacity_is_exceeded() {
|
||||
let store = GeminiShadowStore::with_limits(2, 2);
|
||||
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-2", json!({"idx": 2}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-3", json!({"idx": 3}), vec![]);
|
||||
|
||||
assert!(store.get_session("provider-a", "session-1").is_none());
|
||||
assert!(store.get_session("provider-a", "session-2").is_some());
|
||||
assert!(store.get_session("provider-a", "session-3").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_session_and_provider_work() {
|
||||
let store = GeminiShadowStore::with_limits(8, 4);
|
||||
|
||||
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
|
||||
store.record_assistant_turn("provider-a", "session-2", json!({"idx": 2}), vec![]);
|
||||
store.record_assistant_turn("provider-b", "session-3", json!({"idx": 3}), vec![]);
|
||||
|
||||
assert!(store.clear_session("provider-a", "session-1"));
|
||||
assert!(store.get_session("provider-a", "session-1").is_none());
|
||||
|
||||
let removed = store.clear_provider("provider-a");
|
||||
assert_eq!(removed, 1);
|
||||
assert!(store.get_session("provider-a", "session-2").is_none());
|
||||
assert!(store.get_session("provider-b", "session-3").is_some());
|
||||
}
|
||||
}
|
||||
@@ -18,10 +18,14 @@ mod codex;
|
||||
pub mod codex_oauth_auth;
|
||||
pub mod copilot_auth;
|
||||
mod gemini;
|
||||
pub(crate) mod gemini_schema;
|
||||
pub mod gemini_shadow;
|
||||
pub mod models;
|
||||
pub mod streaming;
|
||||
pub mod streaming_gemini;
|
||||
pub mod streaming_responses;
|
||||
pub mod transform;
|
||||
pub mod transform_gemini;
|
||||
pub mod transform_responses;
|
||||
|
||||
use crate::app_config::AppType;
|
||||
@@ -101,6 +105,14 @@ impl ProviderType {
|
||||
pub fn from_app_type_and_config(app_type: &AppType, provider: &Provider) -> Self {
|
||||
match app_type {
|
||||
AppType::Claude => {
|
||||
if get_claude_api_format(provider) == "gemini_native" {
|
||||
let adapter = ClaudeAdapter::new();
|
||||
return match adapter.extract_auth(provider).map(|auth| auth.strategy) {
|
||||
Some(AuthStrategy::GoogleOAuth) => ProviderType::GeminiCli,
|
||||
_ => ProviderType::Gemini,
|
||||
};
|
||||
}
|
||||
|
||||
// 检测是否为 GitHub Copilot
|
||||
if let Some(meta) = provider.meta.as_ref() {
|
||||
if meta.provider_type.as_deref() == Some("github_copilot") {
|
||||
@@ -162,13 +174,9 @@ impl ProviderType {
|
||||
}
|
||||
ProviderType::Gemini
|
||||
}
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy, but return a default type for completeness
|
||||
ProviderType::Codex // Fallback to Codex-like type
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy, but return a default type for completeness
|
||||
ProviderType::Codex // Fallback to Codex-like type
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy, fallback to Codex-like type
|
||||
ProviderType::Codex
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,12 +228,8 @@ pub fn get_adapter(app_type: &AppType) -> Box<dyn ProviderAdapter> {
|
||||
AppType::Claude => Box::new(ClaudeAdapter::new()),
|
||||
AppType::Codex => Box::new(CodexAdapter::new()),
|
||||
AppType::Gemini => Box::new(GeminiAdapter::new()),
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy, fallback to Codex adapter
|
||||
Box::new(CodexAdapter::new())
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy, fallback to Codex adapter
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy, fallback to Codex adapter
|
||||
Box::new(CodexAdapter::new())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! 实现 OpenAI SSE → Anthropic SSE 格式转换
|
||||
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use crate::proxy::sse::{strip_sse_field, take_sse_block};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -118,10 +118,7 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
|
||||
Ok(bytes) => {
|
||||
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
|
||||
|
||||
while let Some(pos) = buffer.find("\n\n") {
|
||||
let line = buffer[..pos].to_string();
|
||||
buffer = buffer[pos + 2..].to_string();
|
||||
|
||||
while let Some(line) = take_sse_block(&mut buffer) {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@
|
||||
//! 与 Chat Completions 的 delta chunk 模型完全不同,需要独立的状态机处理。
|
||||
|
||||
use super::transform_responses::{build_anthropic_usage_from_responses, map_responses_stop_reason};
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use crate::proxy::sse::{strip_sse_field, take_sse_block};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
@@ -122,10 +122,7 @@ pub fn create_anthropic_sse_stream_from_responses<E: std::error::Error + Send +
|
||||
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
|
||||
|
||||
// SSE 事件由 \n\n 分隔
|
||||
while let Some(pos) = buffer.find("\n\n") {
|
||||
let block = buffer[..pos].to_string();
|
||||
buffer = buffer[pos + 2..].to_string();
|
||||
|
||||
while let Some(block) = take_sse_block(&mut buffer) {
|
||||
if block.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -194,24 +194,16 @@ pub(crate) fn map_responses_stop_reason(
|
||||
incomplete_reason: Option<&str>,
|
||||
) -> Option<&'static str> {
|
||||
status.map(|s| match s {
|
||||
"completed" => {
|
||||
if has_tool_use {
|
||||
"tool_use"
|
||||
} else {
|
||||
"end_turn"
|
||||
}
|
||||
}
|
||||
"incomplete" => {
|
||||
"completed" if has_tool_use => "tool_use",
|
||||
"incomplete"
|
||||
if matches!(
|
||||
incomplete_reason,
|
||||
Some("max_output_tokens") | Some("max_tokens")
|
||||
) || incomplete_reason.is_none()
|
||||
{
|
||||
"max_tokens"
|
||||
} else {
|
||||
"end_turn"
|
||||
}
|
||||
) || incomplete_reason.is_none() =>
|
||||
{
|
||||
"max_tokens"
|
||||
}
|
||||
"incomplete" => "end_turn",
|
||||
_ => "end_turn",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
use super::session::ProxySession;
|
||||
use super::usage::parser::TokenUsage;
|
||||
use super::ProxyError;
|
||||
use crate::proxy::sse::strip_sse_field;
|
||||
use crate::proxy::sse::{strip_sse_field, take_sse_block};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use serde_json::Value;
|
||||
@@ -86,10 +86,7 @@ impl StreamHandler {
|
||||
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
|
||||
|
||||
// 提取完整事件
|
||||
while let Some(pos) = buffer.find("\n\n") {
|
||||
let event_text = buffer[..pos].to_string();
|
||||
buffer = buffer[pos + 2..].to_string();
|
||||
|
||||
while let Some(event_text) = take_sse_block(&mut buffer) {
|
||||
for line in event_text.lines() {
|
||||
if let Some(data) = strip_sse_field(line, "data") {
|
||||
if data.trim() != "[DONE]" {
|
||||
|
||||
@@ -7,11 +7,11 @@ use super::{
|
||||
handler_context::{RequestContext, StreamingTimeoutConfig},
|
||||
hyper_client::ProxyResponse,
|
||||
server::ProxyState,
|
||||
sse::strip_sse_field,
|
||||
sse::{strip_sse_field, take_sse_block},
|
||||
usage::parser::TokenUsage,
|
||||
ProxyError,
|
||||
};
|
||||
use axum::http::header::HeaderMap;
|
||||
use axum::http::{header::HeaderMap, HeaderName};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
@@ -68,6 +68,41 @@ fn get_content_encoding(headers: &HeaderMap) -> Option<String> {
|
||||
.filter(|s| !s.is_empty() && s != "identity")
|
||||
}
|
||||
|
||||
/// RFC 2616 / RFC 7230 中定义的不应被代理继续转发的响应头。
|
||||
const HOP_BY_HOP_RESPONSE_HEADERS: &[&str] = &[
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"proxy-connection",
|
||||
"te",
|
||||
"trailer",
|
||||
"trailers",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
];
|
||||
|
||||
/// 移除响应侧 hop-by-hop 头,以及 `Connection` 中点名的扩展头。
|
||||
pub(crate) fn strip_hop_by_hop_response_headers(headers: &mut HeaderMap) {
|
||||
let connection_listed_headers: Vec<HeaderName> = headers
|
||||
.get_all(axum::http::header::CONNECTION)
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(','))
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.filter_map(|name| HeaderName::from_bytes(name.as_bytes()).ok())
|
||||
.collect();
|
||||
|
||||
for name in HOP_BY_HOP_RESPONSE_HEADERS {
|
||||
headers.remove(*name);
|
||||
}
|
||||
|
||||
for name in connection_listed_headers {
|
||||
headers.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
/// 移除在重建响应体后会失真的实体头。
|
||||
pub(crate) fn strip_entity_headers_for_rebuilt_body(headers: &mut HeaderMap) {
|
||||
headers.remove(axum::http::header::CONTENT_ENCODING);
|
||||
@@ -163,10 +198,13 @@ pub async fn handle_streaming(
|
||||
);
|
||||
}
|
||||
|
||||
let mut response_headers = response.headers().clone();
|
||||
strip_hop_by_hop_response_headers(&mut response_headers);
|
||||
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
|
||||
// 复制响应头
|
||||
for (key, value) in response.headers() {
|
||||
for (key, value) in &response_headers {
|
||||
builder = builder.header(key, value);
|
||||
}
|
||||
|
||||
@@ -207,8 +245,9 @@ pub async fn handle_non_streaming(
|
||||
} else {
|
||||
Duration::ZERO
|
||||
};
|
||||
let (response_headers, status, body_bytes) =
|
||||
let (mut response_headers, status, body_bytes) =
|
||||
read_decoded_body(response, ctx.tag, body_timeout).await?;
|
||||
strip_hop_by_hop_response_headers(&mut response_headers);
|
||||
|
||||
log::debug!(
|
||||
"[{}] 上游响应体内容: {}",
|
||||
@@ -623,10 +662,7 @@ pub fn create_logged_passthrough_stream(
|
||||
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
|
||||
|
||||
// 尝试解析并记录完整的 SSE 事件
|
||||
while let Some(pos) = buffer.find("\n\n") {
|
||||
let event_text = buffer[..pos].to_string();
|
||||
buffer = buffer[pos + 2..].to_string();
|
||||
|
||||
while let Some(event_text) = take_sse_block(&mut buffer) {
|
||||
if !event_text.trim().is_empty() {
|
||||
// 提取 data 部分并尝试解析为 JSON
|
||||
for line in event_text.lines() {
|
||||
@@ -687,6 +723,7 @@ mod tests {
|
||||
use crate::provider::ProviderMeta;
|
||||
use crate::proxy::failover_switch::FailoverSwitchManager;
|
||||
use crate::proxy::provider_router::ProviderRouter;
|
||||
use crate::proxy::providers::gemini_shadow::GeminiShadowStore;
|
||||
use crate::proxy::types::{ProxyConfig, ProxyStatus};
|
||||
use rust_decimal::Decimal;
|
||||
use std::collections::HashMap;
|
||||
@@ -715,6 +752,90 @@ mod tests {
|
||||
assert_eq!(super::strip_sse_field("id:1", "data"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_hop_by_hop_response_headers_removes_standard_headers() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
axum::http::header::CONNECTION,
|
||||
axum::http::HeaderValue::from_static("keep-alive"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::HeaderName::from_static("keep-alive"),
|
||||
axum::http::HeaderValue::from_static("timeout=5"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::TRANSFER_ENCODING,
|
||||
axum::http::HeaderValue::from_static("chunked"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::HeaderName::from_static("proxy-connection"),
|
||||
axum::http::HeaderValue::from_static("keep-alive"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_LENGTH,
|
||||
axum::http::HeaderValue::from_static("12"),
|
||||
);
|
||||
|
||||
strip_hop_by_hop_response_headers(&mut headers);
|
||||
|
||||
assert!(!headers.contains_key(axum::http::header::CONNECTION));
|
||||
assert!(!headers.contains_key("keep-alive"));
|
||||
assert!(!headers.contains_key(axum::http::header::TRANSFER_ENCODING));
|
||||
assert!(!headers.contains_key("proxy-connection"));
|
||||
assert_eq!(
|
||||
headers.get(axum::http::header::CONTENT_TYPE),
|
||||
Some(&axum::http::HeaderValue::from_static("application/json"))
|
||||
);
|
||||
assert_eq!(
|
||||
headers.get(axum::http::header::CONTENT_LENGTH),
|
||||
Some(&axum::http::HeaderValue::from_static("12"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_strip_hop_by_hop_response_headers_removes_connection_listed_extensions() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.append(
|
||||
axum::http::header::CONNECTION,
|
||||
axum::http::HeaderValue::from_static("x-trace-hop, x-debug-hop"),
|
||||
);
|
||||
headers.append(
|
||||
axum::http::header::CONNECTION,
|
||||
axum::http::HeaderValue::from_static("upgrade"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::HeaderName::from_static("x-trace-hop"),
|
||||
axum::http::HeaderValue::from_static("trace"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::HeaderName::from_static("x-debug-hop"),
|
||||
axum::http::HeaderValue::from_static("debug"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::UPGRADE,
|
||||
axum::http::HeaderValue::from_static("websocket"),
|
||||
);
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderValue::from_static("text/event-stream"),
|
||||
);
|
||||
|
||||
strip_hop_by_hop_response_headers(&mut headers);
|
||||
|
||||
assert!(!headers.contains_key(axum::http::header::CONNECTION));
|
||||
assert!(!headers.contains_key("x-trace-hop"));
|
||||
assert!(!headers.contains_key("x-debug-hop"));
|
||||
assert!(!headers.contains_key(axum::http::header::UPGRADE));
|
||||
assert_eq!(
|
||||
headers.get(axum::http::header::CONTENT_TYPE),
|
||||
Some(&axum::http::HeaderValue::from_static("text/event-stream"))
|
||||
);
|
||||
}
|
||||
|
||||
fn build_state(db: Arc<Database>) -> ProxyState {
|
||||
ProxyState {
|
||||
db: db.clone(),
|
||||
@@ -723,6 +844,7 @@ mod tests {
|
||||
start_time: Arc::new(RwLock::new(None)),
|
||||
current_providers: Arc::new(RwLock::new(HashMap::new())),
|
||||
provider_router: Arc::new(ProviderRouter::new(db.clone())),
|
||||
gemini_shadow: Arc::new(GeminiShadowStore::default()),
|
||||
app_handle: None,
|
||||
failover_manager: Arc::new(FailoverSwitchManager::new(db)),
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
|
||||
use super::{
|
||||
failover_switch::FailoverSwitchManager, handlers, log_codes::srv as log_srv,
|
||||
provider_router::ProviderRouter, types::*, ProxyError,
|
||||
provider_router::ProviderRouter, providers::gemini_shadow::GeminiShadowStore, types::*,
|
||||
ProxyError,
|
||||
};
|
||||
use crate::database::Database;
|
||||
use axum::{
|
||||
@@ -35,6 +36,8 @@ pub struct ProxyState {
|
||||
pub current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
|
||||
/// 共享的 ProviderRouter(持有熔断器状态,跨请求保持)
|
||||
pub provider_router: Arc<ProviderRouter>,
|
||||
/// Gemini Native shadow state,用于 thoughtSignature / tool call 回放
|
||||
pub gemini_shadow: Arc<GeminiShadowStore>,
|
||||
/// AppHandle,用于发射事件和更新托盘菜单
|
||||
pub app_handle: Option<tauri::AppHandle>,
|
||||
/// 故障转移切换管理器
|
||||
@@ -68,6 +71,7 @@ impl ProxyServer {
|
||||
start_time: Arc::new(RwLock::new(None)),
|
||||
current_providers: Arc::new(RwLock::new(std::collections::HashMap::new())),
|
||||
provider_router,
|
||||
gemini_shadow: Arc::new(GeminiShadowStore::default()),
|
||||
app_handle,
|
||||
failover_manager,
|
||||
};
|
||||
|
||||
@@ -242,6 +242,12 @@ pub fn extract_session_id(
|
||||
body: &serde_json::Value,
|
||||
client_format: &str,
|
||||
) -> SessionIdResult {
|
||||
if client_format == "claude" {
|
||||
if let Some(result) = extract_claude_session(headers, body) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Codex 请求特殊处理
|
||||
if client_format == "codex" || client_format == "openai" {
|
||||
if let Some(result) = extract_codex_session(headers, body) {
|
||||
@@ -258,6 +264,28 @@ pub fn extract_session_id(
|
||||
generate_new_session_id()
|
||||
}
|
||||
|
||||
/// 提取 Claude Session ID
|
||||
fn extract_claude_session(
|
||||
headers: &HeaderMap,
|
||||
body: &serde_json::Value,
|
||||
) -> Option<SessionIdResult> {
|
||||
for header_name in &["x-claude-code-session-id", "claude-code-session-id"] {
|
||||
if let Some(value) = headers.get(*header_name) {
|
||||
if let Ok(session_id) = value.to_str() {
|
||||
if !session_id.is_empty() {
|
||||
return Some(SessionIdResult {
|
||||
session_id: session_id.to_string(),
|
||||
source: SessionIdSource::Header,
|
||||
client_provided: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extract_from_metadata(body)
|
||||
}
|
||||
|
||||
/// 提取 Codex Session ID
|
||||
fn extract_codex_session(headers: &HeaderMap, body: &serde_json::Value) -> Option<SessionIdResult> {
|
||||
// 1. 从 headers 提取
|
||||
@@ -515,6 +543,47 @@ mod tests {
|
||||
assert!(result.client_provided);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_session_from_claude_header() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-claude-code-session-id",
|
||||
"d937243f-2702-4f20-97b6-c9682235ab81".parse().unwrap(),
|
||||
);
|
||||
let body = json!({
|
||||
"model": "claude-3-5-sonnet",
|
||||
"messages": [{"role": "user", "content": "Hello"}]
|
||||
});
|
||||
|
||||
let result = extract_session_id(&headers, &body, "claude");
|
||||
|
||||
assert_eq!(result.session_id, "d937243f-2702-4f20-97b6-c9682235ab81");
|
||||
assert_eq!(result.source, SessionIdSource::Header);
|
||||
assert!(result.client_provided);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_session_from_claude_header_precedes_metadata() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-claude-code-session-id",
|
||||
"header-session-123".parse().unwrap(),
|
||||
);
|
||||
let body = json!({
|
||||
"model": "claude-3-5-sonnet",
|
||||
"messages": [{"role": "user", "content": "Hello"}],
|
||||
"metadata": {
|
||||
"session_id": "my-session-123"
|
||||
}
|
||||
});
|
||||
|
||||
let result = extract_session_id(&headers, &body, "claude");
|
||||
|
||||
assert_eq!(result.session_id, "header-session-123");
|
||||
assert_eq!(result.source, SessionIdSource::Header);
|
||||
assert!(result.client_provided);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_session_from_codex_previous_response_id() {
|
||||
let headers = HeaderMap::new();
|
||||
|
||||
@@ -4,6 +4,24 @@ pub(crate) fn strip_sse_field<'a>(line: &'a str, field: &str) -> Option<&'a str>
|
||||
.or_else(|| line.strip_prefix(&format!("{field}:")))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn take_sse_block(buffer: &mut String) -> Option<String> {
|
||||
let mut best: Option<(usize, usize)> = None;
|
||||
|
||||
for (delimiter, len) in [("\r\n\r\n", 4usize), ("\n\n", 2usize)] {
|
||||
if let Some(pos) = buffer.find(delimiter) {
|
||||
if best.is_none_or(|(best_pos, _)| pos < best_pos) {
|
||||
best = Some((pos, len));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (pos, len) = best?;
|
||||
let block = buffer[..pos].to_string();
|
||||
buffer.drain(..pos + len);
|
||||
Some(block)
|
||||
}
|
||||
|
||||
/// Append raw bytes to a UTF-8 `String` buffer, correctly handling multi-byte
|
||||
/// characters that are split across chunk boundaries.
|
||||
///
|
||||
@@ -68,7 +86,7 @@ pub(crate) fn append_utf8_safe(buffer: &mut String, remainder: &mut Vec<u8>, new
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{append_utf8_safe, strip_sse_field};
|
||||
use super::{append_utf8_safe, strip_sse_field, take_sse_block};
|
||||
|
||||
#[test]
|
||||
fn strip_sse_field_accepts_optional_space() {
|
||||
@@ -91,6 +109,28 @@ mod tests {
|
||||
assert_eq!(strip_sse_field("id:1", "data"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_sse_block_supports_lf_delimiters() {
|
||||
let mut buffer = "data: {\"ok\":true}\n\nrest".to_string();
|
||||
|
||||
assert_eq!(
|
||||
take_sse_block(&mut buffer),
|
||||
Some("data: {\"ok\":true}".to_string())
|
||||
);
|
||||
assert_eq!(buffer, "rest");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn take_sse_block_supports_crlf_delimiters() {
|
||||
let mut buffer = "data: {\"ok\":true}\r\n\r\nrest".to_string();
|
||||
|
||||
assert_eq!(
|
||||
take_sse_block(&mut buffer),
|
||||
Some("data: {\"ok\":true}".to_string())
|
||||
);
|
||||
assert_eq!(buffer, "rest");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// append_utf8_safe tests
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{json, Value};
|
||||
///
|
||||
/// 三路径分发:
|
||||
/// - skip: haiku 模型直接跳过
|
||||
/// - adaptive: opus-4-6 / sonnet-4-6 使用 adaptive thinking
|
||||
/// - adaptive: opus-4-7 / opus-4-6 / sonnet-4-6 使用 adaptive thinking
|
||||
/// - legacy: 其他模型注入 enabled thinking + budget_tokens
|
||||
pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
if !config.thinking_optimizer {
|
||||
@@ -24,7 +24,7 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
return;
|
||||
}
|
||||
|
||||
if model.contains("opus-4-6") || model.contains("sonnet-4-6") {
|
||||
if model.contains("opus-4-7") || model.contains("opus-4-6") || model.contains("sonnet-4-6") {
|
||||
log::info!("[OPT] thinking: adaptive({model})");
|
||||
body["thinking"] = json!({"type": "adaptive"});
|
||||
body["output_config"] = json!({"effort": "max"});
|
||||
|
||||
@@ -52,6 +52,14 @@ pub fn should_rectify_thinking_signature(
|
||||
return true;
|
||||
}
|
||||
|
||||
// 场景1b: Gemini/第三方渠道返回 "Thought signature is not valid"
|
||||
// 错误示例: "Unable to submit request because Thought signature is not valid"
|
||||
if lower.contains("thought signature")
|
||||
&& (lower.contains("not valid") || lower.contains("invalid"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// 场景2: assistant 消息必须以 thinking block 开头
|
||||
// 错误示例: "must start with a thinking block"
|
||||
if lower.contains("must start with a thinking block") {
|
||||
@@ -280,6 +288,16 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_invalid_thought_signature_message() {
|
||||
assert!(should_rectify_thinking_signature(
|
||||
Some(
|
||||
"Unable to submit request because Thought signature is not valid.. Learn more: https://example.com/help"
|
||||
),
|
||||
&enabled_config()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_invalid_signature_nested_json() {
|
||||
// 测试嵌套 JSON 格式的错误消息(第三方渠道常见格式)
|
||||
@@ -290,6 +308,15 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_invalid_thought_signature_nested_json() {
|
||||
let nested_error = r#"{"error":{"message":"Unable to submit request because Thought signature is not valid.. Learn more: https://example.com/help","type":"upstream_error","param":"","code":400}}"#;
|
||||
assert!(should_rectify_thinking_signature(
|
||||
Some(nested_error),
|
||||
&enabled_config()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_thinking_expected() {
|
||||
assert!(should_rectify_thinking_signature(
|
||||
|
||||
@@ -298,9 +298,15 @@ pub struct CopilotOptimizerConfig {
|
||||
/// Warmup 小模型降级(默认开启 — 与参考实现对齐,避免探针请求消耗 premium quota)
|
||||
#[serde(default = "default_true")]
|
||||
pub warmup_downgrade: bool,
|
||||
/// Warmup 降级使用的模型(默认 "gpt-4o-mini")
|
||||
/// Warmup 降级使用的模型(默认 "gpt-5-mini")
|
||||
#[serde(default = "default_warmup_model")]
|
||||
pub warmup_model: String,
|
||||
/// 请求前主动剥离 assistant 消息里的 thinking / redacted_thinking block
|
||||
///
|
||||
/// Copilot 走 OpenAI 兼容端点,thinking block 会被上游拒绝并触发 rectifier 反应式
|
||||
/// 重试,那时第一次请求已经消耗了一次 premium quota。主动剥离避免这次浪费。
|
||||
#[serde(default = "default_true")]
|
||||
pub strip_thinking: bool,
|
||||
}
|
||||
|
||||
fn default_warmup_model() -> String {
|
||||
@@ -317,7 +323,8 @@ impl Default for CopilotOptimizerConfig {
|
||||
deterministic_request_id: true,
|
||||
subagent_detection: true,
|
||||
warmup_downgrade: true,
|
||||
warmup_model: "gpt-4o-mini".to_string(),
|
||||
warmup_model: "gpt-5-mini".to_string(),
|
||||
strip_thinking: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,6 +130,9 @@ impl ConfigService {
|
||||
// OpenClaw uses additive mode, no live sync needed
|
||||
// OpenClaw providers are managed directly in the config file
|
||||
}
|
||||
AppType::Hermes => {
|
||||
// Hermes uses additive mode, no live sync needed
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -40,6 +40,9 @@ impl McpService {
|
||||
if prev_apps.opencode && !server.apps.opencode {
|
||||
Self::remove_server_from_app(state, &server.id, &AppType::OpenCode)?;
|
||||
}
|
||||
if prev_apps.hermes && !server.apps.hermes {
|
||||
Self::remove_server_from_app(state, &server.id, &AppType::Hermes)?;
|
||||
}
|
||||
|
||||
// 同步到各个启用的应用
|
||||
Self::sync_server_to_apps(state, &server)?;
|
||||
@@ -128,6 +131,9 @@ impl McpService {
|
||||
// Skip for now
|
||||
log::debug!("OpenClaw MCP support is still in development, skipping sync");
|
||||
}
|
||||
AppType::Hermes => {
|
||||
mcp::sync_single_server_to_hermes(&Default::default(), &server.id, &server.server)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -157,6 +163,9 @@ impl McpService {
|
||||
// OpenClaw MCP support is still in development
|
||||
log::debug!("OpenClaw MCP support is still in development, skipping remove");
|
||||
}
|
||||
AppType::Hermes => {
|
||||
mcp::remove_server_from_hermes(id)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -381,4 +390,42 @@ impl McpService {
|
||||
|
||||
Ok(new_count)
|
||||
}
|
||||
|
||||
/// 从 Hermes 导入 MCP
|
||||
pub fn import_from_hermes(state: &AppState) -> Result<usize, AppError> {
|
||||
// 创建临时 MultiAppConfig 用于导入
|
||||
let mut temp_config = crate::app_config::MultiAppConfig::default();
|
||||
|
||||
// 调用导入逻辑(从 mcp/hermes.rs)
|
||||
let count = crate::mcp::import_from_hermes(&mut temp_config)?;
|
||||
|
||||
let mut new_count = 0;
|
||||
|
||||
// 如果有导入的服务器,保存到数据库
|
||||
if count > 0 {
|
||||
if let Some(servers) = &temp_config.mcp.servers {
|
||||
let mut existing = state.db.get_all_mcp_servers()?;
|
||||
for server in servers.values() {
|
||||
// 已存在:仅启用 Hermes,不覆盖其他字段(与导入模块语义保持一致)
|
||||
let to_save = if let Some(existing_server) = existing.get(&server.id) {
|
||||
let mut merged = existing_server.clone();
|
||||
merged.apps.hermes = true;
|
||||
merged
|
||||
} else {
|
||||
// 真正的新服务器
|
||||
new_count += 1;
|
||||
server.clone()
|
||||
};
|
||||
|
||||
state.db.save_mcp_server(&to_save)?;
|
||||
existing.insert(to_save.id.clone(), to_save.clone());
|
||||
|
||||
// 同步到对应应用 live 配置
|
||||
Self::sync_server_to_apps(state, &to_save)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(new_count)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn get_custom_endpoints(
|
||||
}
|
||||
|
||||
let mut result: Vec<_> = meta.custom_endpoints.values().cloned().collect();
|
||||
result.sort_by(|a, b| b.added_at.cmp(&a.added_at));
|
||||
result.sort_by_key(|ep| std::cmp::Reverse(ep.added_at));
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ pub(crate) fn provider_exists_in_live_config(
|
||||
.map(|providers| providers.contains_key(provider_id)),
|
||||
AppType::OpenClaw => crate::openclaw_config::get_providers()
|
||||
.map(|providers| providers.contains_key(provider_id)),
|
||||
AppType::Hermes => crate::hermes_config::get_providers()
|
||||
.map(|providers| providers.contains_key(provider_id)),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -345,7 +347,7 @@ fn settings_contain_common_config(app_type: &AppType, settings: &Value, snippet:
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
AppType::OpenCode | AppType::OpenClaw => false,
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -415,7 +417,7 @@ pub(crate) fn remove_common_config_from_settings(
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -470,7 +472,7 @@ fn apply_common_config_to_settings(
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -790,6 +792,10 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
|
||||
}
|
||||
}
|
||||
}
|
||||
AppType::Hermes => {
|
||||
crate::hermes_config::set_provider(&provider.id, provider.settings_config.clone())?;
|
||||
log::debug!("Hermes provider '{}' written to live config", provider.id);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -985,6 +991,19 @@ pub fn read_live_settings(app_type: AppType) -> Result<Value, AppError> {
|
||||
let config = read_openclaw_config()?;
|
||||
Ok(config)
|
||||
}
|
||||
AppType::Hermes => {
|
||||
let config_path = crate::hermes_config::get_hermes_config_path();
|
||||
if !config_path.exists() {
|
||||
return Err(AppError::localized(
|
||||
"hermes.config.missing",
|
||||
"Hermes 配置文件不存在",
|
||||
"Hermes configuration file not found",
|
||||
));
|
||||
}
|
||||
let yaml_config = crate::hermes_config::read_hermes_config()?;
|
||||
let config = crate::hermes_config::yaml_to_json(&yaml_config)?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1067,8 +1086,8 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool
|
||||
"config": config_obj
|
||||
})
|
||||
}
|
||||
// OpenCode and OpenClaw use additive mode and are handled by early return above
|
||||
AppType::OpenCode | AppType::OpenClaw => {
|
||||
// OpenCode, OpenClaw and Hermes use additive mode and are handled by early return above
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
unreachable!("additive mode apps are handled by early return")
|
||||
}
|
||||
};
|
||||
@@ -1316,6 +1335,74 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
/// Import all providers from Hermes live config to database
|
||||
///
|
||||
/// This imports existing providers from ~/.hermes/config.yaml
|
||||
/// into the CC Switch database. Each provider found will be added to the
|
||||
/// database with is_current set to false.
|
||||
pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppError> {
|
||||
use crate::hermes_config;
|
||||
|
||||
let providers = hermes_config::get_providers()?;
|
||||
if providers.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let mut imported = 0;
|
||||
let existing_ids = state.db.get_provider_ids("hermes")?;
|
||||
|
||||
for (name, config) in providers {
|
||||
// Validate: skip entries with empty name
|
||||
if name.trim().is_empty() {
|
||||
log::warn!("Skipping Hermes provider with empty name");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if already exists in database
|
||||
if existing_ids.contains(&name) {
|
||||
log::debug!("Hermes provider '{name}' already exists in database, skipping");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create provider
|
||||
let mut provider = Provider::with_id(name.clone(), name.clone(), config, None);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
live_config_managed: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Save to database
|
||||
if let Err(e) = state.db.save_provider("hermes", &provider) {
|
||||
log::warn!("Failed to import Hermes provider '{name}': {e}");
|
||||
continue;
|
||||
}
|
||||
|
||||
imported += 1;
|
||||
log::info!("Imported Hermes provider '{name}' from live config");
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
/// Remove a Hermes provider from live config
|
||||
///
|
||||
/// This removes a specific provider from ~/.hermes/config.yaml
|
||||
/// without affecting other providers in the file.
|
||||
pub fn remove_hermes_provider_from_live(provider_id: &str) -> Result<(), AppError> {
|
||||
use crate::hermes_config;
|
||||
|
||||
// Check if Hermes config directory exists
|
||||
if !hermes_config::get_hermes_dir().exists() {
|
||||
log::debug!("Hermes config directory doesn't exist, skipping removal of '{provider_id}'");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
hermes_config::remove_provider(provider_id)?;
|
||||
log::info!("Hermes provider '{provider_id}' removed from live config");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove an OpenClaw provider from live config
|
||||
///
|
||||
/// This removes a specific provider from ~/.openclaw/openclaw.json
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::store::AppState;
|
||||
|
||||
// Re-export sub-module functions for external access
|
||||
pub use live::{
|
||||
import_default_config, import_openclaw_providers_from_live,
|
||||
import_default_config, import_hermes_providers_from_live, import_openclaw_providers_from_live,
|
||||
import_opencode_providers_from_live, read_live_settings, sync_current_to_live,
|
||||
};
|
||||
|
||||
@@ -35,7 +35,8 @@ pub(crate) use live::{
|
||||
|
||||
// Internal re-exports
|
||||
use live::{
|
||||
remove_openclaw_provider_from_live, remove_opencode_provider_from_live, write_gemini_live,
|
||||
remove_hermes_provider_from_live, remove_openclaw_provider_from_live,
|
||||
remove_opencode_provider_from_live, write_gemini_live,
|
||||
};
|
||||
use usage::validate_usage_script;
|
||||
|
||||
@@ -1282,6 +1283,7 @@ impl ProviderService {
|
||||
match app_type {
|
||||
AppType::OpenCode => remove_opencode_provider_from_live(id)?,
|
||||
AppType::OpenClaw => remove_openclaw_provider_from_live(id)?,
|
||||
AppType::Hermes => remove_hermes_provider_from_live(id)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -1344,6 +1346,9 @@ impl ProviderService {
|
||||
AppType::OpenClaw => {
|
||||
remove_openclaw_provider_from_live(id)?;
|
||||
}
|
||||
AppType::Hermes => {
|
||||
remove_hermes_provider_from_live(id)?;
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::Message(format!(
|
||||
"App {} does not support remove from live config",
|
||||
@@ -1518,6 +1523,25 @@ impl ProviderService {
|
||||
// Sync to live (write_gemini_live handles security flag internally for Gemini)
|
||||
write_live_with_common_config(state.db.as_ref(), &app_type, provider)?;
|
||||
|
||||
// Hermes is additive, so "switching" doesn't overwrite a live config file
|
||||
// — we instead update the top-level `model:` section to point at this
|
||||
// provider's first declared model. Without this, clicking "switch" would
|
||||
// only shuffle entries in custom_providers[] while Hermes keeps using
|
||||
// whatever `model.provider` was set before.
|
||||
if matches!(app_type, AppType::Hermes) {
|
||||
if let Err(e) =
|
||||
crate::hermes_config::apply_switch_defaults(&provider.id, &provider.settings_config)
|
||||
{
|
||||
log::warn!(
|
||||
"Failed to update Hermes model defaults after switching to '{}': {e}",
|
||||
provider.id
|
||||
);
|
||||
result
|
||||
.warnings
|
||||
.push(format!("hermes_model_defaults_failed:{}", provider.id));
|
||||
}
|
||||
}
|
||||
|
||||
// For additive-mode providers that were DB-only (live_config_managed == Some(false)),
|
||||
// flip the flag to true now that the provider has been successfully written to the live
|
||||
// file. This ensures sync_all_providers_to_live() will include it on future syncs.
|
||||
@@ -1532,6 +1556,7 @@ impl ProviderService {
|
||||
let rollback_result = match app_type {
|
||||
AppType::OpenCode => remove_opencode_provider_from_live(&provider.id),
|
||||
AppType::OpenClaw => remove_openclaw_provider_from_live(&provider.id),
|
||||
AppType::Hermes => remove_hermes_provider_from_live(&provider.id),
|
||||
_ => Ok(()),
|
||||
};
|
||||
|
||||
@@ -1708,6 +1733,7 @@ impl ProviderService {
|
||||
AppType::Gemini => Self::extract_gemini_common_config(&provider.settings_config),
|
||||
AppType::OpenCode => Self::extract_opencode_common_config(&provider.settings_config),
|
||||
AppType::OpenClaw => Self::extract_openclaw_common_config(&provider.settings_config),
|
||||
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1722,6 +1748,7 @@ impl ProviderService {
|
||||
AppType::Gemini => Self::extract_gemini_common_config(settings_config),
|
||||
AppType::OpenCode => Self::extract_opencode_common_config(settings_config),
|
||||
AppType::OpenClaw => Self::extract_openclaw_common_config(settings_config),
|
||||
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1734,9 +1761,9 @@ impl ProviderService {
|
||||
// Auth
|
||||
"ANTHROPIC_API_KEY",
|
||||
"ANTHROPIC_AUTH_TOKEN",
|
||||
// Models (5 fields)
|
||||
// Models (4 fields + 1 legacy)
|
||||
"ANTHROPIC_MODEL",
|
||||
"ANTHROPIC_REASONING_MODEL",
|
||||
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
||||
@@ -2087,6 +2114,16 @@ impl ProviderService {
|
||||
));
|
||||
}
|
||||
}
|
||||
AppType::Hermes => {
|
||||
// Hermes: accept any JSON object for now
|
||||
if !provider.settings_config.is_object() {
|
||||
return Err(AppError::localized(
|
||||
"provider.hermes.settings.not_object",
|
||||
"Hermes 配置必须是 JSON 对象",
|
||||
"Hermes configuration must be a JSON object",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and clean UsageScript configuration (common for all app types)
|
||||
@@ -2258,8 +2295,8 @@ impl ProviderService {
|
||||
|
||||
Ok((api_key, base_url))
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw uses apiKey and baseUrl directly on the object
|
||||
AppType::OpenClaw | AppType::Hermes => {
|
||||
// OpenClaw/Hermes use apiKey and baseUrl directly on the object
|
||||
let api_key = provider
|
||||
.settings_config
|
||||
.get("apiKey")
|
||||
|
||||
@@ -27,7 +27,7 @@ const PROXY_TOKEN_PLACEHOLDER: &str = "PROXY_MANAGED";
|
||||
/// Claude Code 会继续以旧模型名发起请求,导致新供应商不支持时失败。
|
||||
const CLAUDE_MODEL_OVERRIDE_ENV_KEYS: [&str; 6] = [
|
||||
"ANTHROPIC_MODEL",
|
||||
"ANTHROPIC_REASONING_MODEL",
|
||||
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
@@ -466,13 +466,9 @@ impl ProxyService {
|
||||
AppType::Claude => self.read_claude_live()?,
|
||||
AppType::Codex => self.read_codex_live()?,
|
||||
AppType::Gemini => self.read_gemini_live()?,
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features
|
||||
return Err("OpenCode 不支持代理功能".to_string());
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features
|
||||
return Err("OpenClaw 不支持代理功能".to_string());
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features
|
||||
return Err("该应用不支持代理功能".to_string());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -687,11 +683,8 @@ impl ProxyService {
|
||||
}
|
||||
}
|
||||
}
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features, skip silently
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features, skip silently
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features, skip silently
|
||||
}
|
||||
}
|
||||
|
||||
@@ -871,13 +864,9 @@ impl ProxyService {
|
||||
AppType::Claude => ("claude", self.read_claude_live()?),
|
||||
AppType::Codex => ("codex", self.read_codex_live()?),
|
||||
AppType::Gemini => ("gemini", self.read_gemini_live()?),
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features
|
||||
return Err("OpenCode 不支持代理功能".to_string());
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features
|
||||
return Err("OpenClaw 不支持代理功能".to_string());
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features
|
||||
return Err("该应用不支持代理功能".to_string());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1019,13 +1008,9 @@ impl ProxyService {
|
||||
self.write_gemini_live(&live_config)?;
|
||||
log::info!("Gemini Live 配置已接管,代理地址: {proxy_url}");
|
||||
}
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features
|
||||
return Err("OpenCode 不支持代理功能".to_string());
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features
|
||||
return Err("OpenClaw 不支持代理功能".to_string());
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features
|
||||
return Err("该应用不支持代理功能".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1076,11 +1061,8 @@ impl ProxyService {
|
||||
let _ = self.write_gemini_live(&live_config);
|
||||
}
|
||||
}
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features, skip silently
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features, skip silently
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features, skip silently
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1119,11 +1101,8 @@ impl ProxyService {
|
||||
log::info!("Gemini Live 配置已恢复");
|
||||
}
|
||||
}
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features, skip silently
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features, skip silently
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features, skip silently
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1213,13 +1192,9 @@ impl ProxyService {
|
||||
AppType::Claude => self.write_claude_live(config),
|
||||
AppType::Codex => self.write_codex_live(config),
|
||||
AppType::Gemini => self.write_gemini_live(config),
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features
|
||||
Err("OpenCode 不支持代理功能".to_string())
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features
|
||||
Err("OpenClaw 不支持代理功能".to_string())
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features
|
||||
Err("该应用不支持代理功能".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1238,12 +1213,8 @@ impl ProxyService {
|
||||
Ok(config) => Self::is_gemini_live_taken_over(&config),
|
||||
Err(_) => false,
|
||||
},
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy takeover
|
||||
false
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy takeover
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy takeover
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -1285,12 +1256,8 @@ impl ProxyService {
|
||||
AppType::Claude => self.cleanup_claude_takeover_placeholders_in_live(),
|
||||
AppType::Codex => self.cleanup_codex_takeover_placeholders_in_live(),
|
||||
AppType::Gemini => self.cleanup_gemini_takeover_placeholders_in_live(),
|
||||
AppType::OpenCode => {
|
||||
// OpenCode doesn't support proxy features
|
||||
Ok(())
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw doesn't support proxy features
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// These apps don't support proxy features
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1540,7 +1507,7 @@ impl ProxyService {
|
||||
serde_json::to_string(&env_backup)
|
||||
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?
|
||||
}
|
||||
AppType::OpenCode | AppType::OpenClaw => {
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
return Err(format!("未知的应用类型: {app_type}"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -297,18 +297,16 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
|
||||
};
|
||||
|
||||
match event_type {
|
||||
"session_meta" => {
|
||||
if state.session_id.is_none() {
|
||||
let payload = value.get("payload");
|
||||
state.session_id = payload
|
||||
.and_then(|p| {
|
||||
p.get("session_id")
|
||||
.or_else(|| p.get("sessionId"))
|
||||
.or_else(|| p.get("id"))
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
}
|
||||
"session_meta" if state.session_id.is_none() => {
|
||||
let payload = value.get("payload");
|
||||
state.session_id = payload
|
||||
.and_then(|p| {
|
||||
p.get("session_id")
|
||||
.or_else(|| p.get("sessionId"))
|
||||
.or_else(|| p.get("id"))
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
}
|
||||
"turn_context" => {
|
||||
if let Some(payload) = value.get("payload") {
|
||||
|
||||
@@ -529,6 +529,11 @@ impl SkillService {
|
||||
return Ok(custom.join("skills"));
|
||||
}
|
||||
}
|
||||
AppType::Hermes => {
|
||||
if let Some(custom) = crate::settings::get_hermes_override_dir() {
|
||||
return Ok(custom.join("skills"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 默认路径:回退到用户主目录下的标准位置
|
||||
@@ -544,6 +549,7 @@ impl SkillService {
|
||||
AppType::Gemini => home.join(".gemini").join("skills"),
|
||||
AppType::OpenCode => home.join(".config").join("opencode").join("skills"),
|
||||
AppType::OpenClaw => home.join(".openclaw").join("skills"),
|
||||
AppType::Hermes => crate::hermes_config::get_hermes_dir().join("skills"),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1268,7 +1274,7 @@ impl SkillService {
|
||||
}
|
||||
}
|
||||
|
||||
entries.sort_by(|a, b| b.created_at.cmp(&a.created_at));
|
||||
entries.sort_by_key(|entry| std::cmp::Reverse(entry.created_at));
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
@@ -1549,6 +1555,20 @@ impl SkillService {
|
||||
|
||||
// 保存到数据库
|
||||
db.save_skill(&skill)?;
|
||||
|
||||
// 同步到已启用的应用目录(创建 symlink 或复制文件)
|
||||
for app in AppType::all() {
|
||||
if skill.apps.is_enabled_for(&app) {
|
||||
if let Err(e) = Self::sync_to_app_dir(&skill.directory, &app) {
|
||||
log::warn!(
|
||||
"导入后同步 Skill '{}' 到 {:?} 失败: {e:#}",
|
||||
skill.directory,
|
||||
app
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
imported.push(skill);
|
||||
}
|
||||
|
||||
@@ -1772,7 +1792,7 @@ impl SkillService {
|
||||
let results: Vec<Result<Vec<DiscoverableSkill>>> =
|
||||
futures::future::join_all(fetch_tasks).await;
|
||||
|
||||
for (repo, result) in enabled_repos.into_iter().zip(results.into_iter()) {
|
||||
for (repo, result) in enabled_repos.into_iter().zip(results) {
|
||||
match result {
|
||||
Ok(repo_skills) => skills.extend(repo_skills),
|
||||
Err(e) => log::warn!("获取仓库 {}/{} 技能失败: {}", repo.owner, repo.name, e),
|
||||
@@ -1781,7 +1801,7 @@ impl SkillService {
|
||||
|
||||
// 去重并排序
|
||||
Self::deduplicate_discoverable_skills(&mut skills);
|
||||
skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
skills.sort_by_key(|skill| skill.name.to_lowercase());
|
||||
|
||||
Ok(skills)
|
||||
}
|
||||
@@ -1848,7 +1868,7 @@ impl SkillService {
|
||||
}
|
||||
}
|
||||
|
||||
skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||
skills.sort_by_key(|skill| skill.name.to_lowercase());
|
||||
|
||||
Ok(skills)
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@ use std::time::Instant;
|
||||
use crate::app_config::AppType;
|
||||
use crate::error::AppError;
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::gemini_url::{normalize_gemini_model_id, resolve_gemini_native_url};
|
||||
use crate::proxy::providers::copilot_auth;
|
||||
use crate::proxy::providers::transform::anthropic_to_openai;
|
||||
use crate::proxy::providers::transform_gemini::anthropic_to_gemini;
|
||||
use crate::proxy::providers::transform_responses::anthropic_to_responses;
|
||||
use crate::proxy::providers::{get_adapter, AuthInfo, AuthStrategy};
|
||||
|
||||
@@ -55,8 +57,8 @@ impl Default for StreamCheckConfig {
|
||||
max_retries: 2,
|
||||
degraded_threshold_ms: 6000,
|
||||
claude_model: "claude-haiku-4-5-20251001".to_string(),
|
||||
codex_model: "gpt-5.1-codex@low".to_string(),
|
||||
gemini_model: "gemini-3-pro-preview".to_string(),
|
||||
codex_model: "gpt-5.4@low".to_string(),
|
||||
gemini_model: "gemini-3-flash-preview".to_string(),
|
||||
test_prompt: default_test_prompt(),
|
||||
}
|
||||
}
|
||||
@@ -74,6 +76,9 @@ pub struct StreamCheckResult {
|
||||
pub model_used: String,
|
||||
pub tested_at: i64,
|
||||
pub retry_count: u32,
|
||||
/// 细粒度错误分类(如 "modelNotFound"),前端据此渲染专门的文案
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_category: Option<String>,
|
||||
}
|
||||
|
||||
/// 流式健康检查服务
|
||||
@@ -143,6 +148,7 @@ impl StreamCheckService {
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: effective_config.max_retries,
|
||||
error_category: None,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -201,7 +207,10 @@ impl StreamCheckService {
|
||||
// OpenCode / OpenClaw 的 settings_config 结构与 Claude/Codex/Gemini 不同
|
||||
// (baseUrl / apiKey 直接作为根字段而非嵌套在 env),并且协议由 `api`
|
||||
// 或 `npm` 字段显式指定。它们不走 get_adapter 路径,而是直接分发。
|
||||
if matches!(app_type, AppType::OpenCode | AppType::OpenClaw) {
|
||||
if matches!(
|
||||
app_type,
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
|
||||
) {
|
||||
return Self::check_once_without_adapter(app_type, provider, config, start).await;
|
||||
}
|
||||
|
||||
@@ -264,9 +273,9 @@ impl StreamCheckService {
|
||||
)
|
||||
.await
|
||||
}
|
||||
AppType::OpenCode | AppType::OpenClaw => {
|
||||
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
|
||||
// Already handled via early dispatch above
|
||||
unreachable!("OpenCode/OpenClaw 已通过 check_once_without_adapter 处理")
|
||||
unreachable!("OpenCode/OpenClaw/Hermes 已通过 check_once_without_adapter 处理")
|
||||
}
|
||||
};
|
||||
|
||||
@@ -275,6 +284,7 @@ impl StreamCheckService {
|
||||
result,
|
||||
response_time,
|
||||
config.degraded_threshold_ms,
|
||||
&model_to_test,
|
||||
))
|
||||
}
|
||||
|
||||
@@ -283,6 +293,8 @@ impl StreamCheckService {
|
||||
/// 根据供应商的 api_format 选择请求格式:
|
||||
/// - "anthropic" (默认): Anthropic Messages API (/v1/messages)
|
||||
/// - "openai_chat": OpenAI Chat Completions API (/v1/chat/completions)
|
||||
/// - "openai_responses": OpenAI Responses API (/v1/responses)
|
||||
/// - "gemini_native": Gemini Native streamGenerateContent
|
||||
///
|
||||
/// `extra_headers` 是一个可选的供应商级自定义 header 集合(从 OpenClaw
|
||||
/// 的 `settings_config.headers` 或 OpenCode 的 `settings_config.options.headers`
|
||||
@@ -324,8 +336,14 @@ impl StreamCheckService {
|
||||
.unwrap_or(false);
|
||||
let is_openai_chat = effective_api_format == "openai_chat";
|
||||
let is_openai_responses = effective_api_format == "openai_responses";
|
||||
let url =
|
||||
Self::resolve_claude_stream_url(base, auth.strategy, effective_api_format, is_full_url);
|
||||
let is_gemini_native = effective_api_format == "gemini_native";
|
||||
let url = Self::resolve_claude_stream_url(
|
||||
base,
|
||||
auth.strategy,
|
||||
effective_api_format,
|
||||
is_full_url,
|
||||
model,
|
||||
);
|
||||
|
||||
let max_tokens = if is_openai_responses { 16 } else { 1 };
|
||||
|
||||
@@ -347,6 +365,9 @@ impl StreamCheckService {
|
||||
let body = if is_openai_responses {
|
||||
anthropic_to_responses(anthropic_body, Some(&provider.id), is_codex_oauth)
|
||||
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
|
||||
} else if is_gemini_native {
|
||||
anthropic_to_gemini(anthropic_body)
|
||||
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
|
||||
} else if is_openai_chat {
|
||||
anthropic_to_openai(anthropic_body)
|
||||
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
|
||||
@@ -382,6 +403,23 @@ impl StreamCheckService {
|
||||
.header("x-vscode-user-agent-library-version", "electron-fetch")
|
||||
.header("x-request-id", &request_id)
|
||||
.header("x-agent-task-id", &request_id);
|
||||
} else if is_gemini_native {
|
||||
request_builder = match auth.strategy {
|
||||
AuthStrategy::GoogleOAuth => {
|
||||
let token = auth.access_token.as_ref().unwrap_or(&auth.api_key);
|
||||
request_builder
|
||||
.header("authorization", format!("Bearer {token}"))
|
||||
.header("x-goog-api-client", "GeminiCLI/1.0")
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", "text/event-stream")
|
||||
.header("accept-encoding", "identity")
|
||||
}
|
||||
_ => request_builder
|
||||
.header("x-goog-api-key", &auth.api_key)
|
||||
.header("content-type", "application/json")
|
||||
.header("accept", "text/event-stream")
|
||||
.header("accept-encoding", "identity"),
|
||||
};
|
||||
} else if is_openai_chat || is_openai_responses {
|
||||
// OpenAI-compatible targets: Bearer auth + SSE headers only
|
||||
request_builder = request_builder
|
||||
@@ -428,8 +466,7 @@ impl StreamCheckService {
|
||||
.header("x-stainless-retry-count", "0")
|
||||
.header("x-stainless-timeout", "600")
|
||||
// Other headers
|
||||
.header("sec-fetch-mode", "cors")
|
||||
.header("connection", "keep-alive");
|
||||
.header("sec-fetch-mode", "cors");
|
||||
}
|
||||
|
||||
// 供应商自定义 headers 最后追加,允许覆盖内置默认值(例如 user-agent)
|
||||
@@ -564,13 +601,16 @@ impl StreamCheckService {
|
||||
extra_headers: Option<&serde_json::Map<String, serde_json::Value>>,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
let base = base_url.trim_end_matches('/');
|
||||
// Strip `models/` resource-name prefix from the model id — see
|
||||
// `normalize_gemini_model_id` for rationale.
|
||||
let normalized_model = normalize_gemini_model_id(model);
|
||||
// Gemini 原生 API: /v1beta/models/{model}:streamGenerateContent?alt=sse
|
||||
// 智能处理 /v1beta 路径:如果 base_url 不包含版本路径,则添加 /v1beta
|
||||
// alt=sse 参数使 API 返回 SSE 格式(text/event-stream)而非 JSON 数组
|
||||
let url = if base.contains("/v1beta") || base.contains("/v1/") {
|
||||
format!("{base}/models/{model}:streamGenerateContent?alt=sse")
|
||||
format!("{base}/models/{normalized_model}:streamGenerateContent?alt=sse")
|
||||
} else {
|
||||
format!("{base}/v1beta/models/{model}:streamGenerateContent?alt=sse")
|
||||
format!("{base}/v1beta/models/{normalized_model}:streamGenerateContent?alt=sse")
|
||||
};
|
||||
|
||||
// Gemini 原生请求体格式
|
||||
@@ -644,7 +684,7 @@ impl StreamCheckService {
|
||||
|
||||
let result = match app_type {
|
||||
AppType::OpenClaw => {
|
||||
Self::check_openclaw_stream(
|
||||
Self::check_additive_app_stream(
|
||||
&client,
|
||||
provider,
|
||||
&model_to_test,
|
||||
@@ -663,7 +703,17 @@ impl StreamCheckService {
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw"),
|
||||
AppType::Hermes => {
|
||||
Self::check_hermes_stream(
|
||||
&client,
|
||||
provider,
|
||||
&model_to_test,
|
||||
test_prompt,
|
||||
request_timeout,
|
||||
)
|
||||
.await
|
||||
}
|
||||
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw/Hermes"),
|
||||
};
|
||||
|
||||
let response_time = start.elapsed().as_millis() as u64;
|
||||
@@ -671,16 +721,21 @@ impl StreamCheckService {
|
||||
result,
|
||||
response_time,
|
||||
config.degraded_threshold_ms,
|
||||
&model_to_test,
|
||||
))
|
||||
}
|
||||
|
||||
/// 将 check_*_stream 的原始结果包装成 StreamCheckResult
|
||||
///
|
||||
/// 抽取自 check_once 的末尾逻辑,以便 OpenCode/OpenClaw 的独立分支复用。
|
||||
///
|
||||
/// `model_tested` 是本次探测使用的模型名,用于在失败场景下仍能把模型信息透传给前端,
|
||||
/// 方便针对"模型不存在 / 已下架"这类错误渲染专门的提示。
|
||||
fn build_stream_check_result(
|
||||
result: Result<(u16, String), AppError>,
|
||||
response_time: u64,
|
||||
degraded_threshold_ms: u64,
|
||||
model_tested: &str,
|
||||
) -> StreamCheckResult {
|
||||
let tested_at = chrono::Utc::now().timestamp();
|
||||
match result {
|
||||
@@ -693,14 +748,19 @@ impl StreamCheckService {
|
||||
model_used: model,
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
error_category: None,
|
||||
},
|
||||
Err(e) => {
|
||||
let (http_status, message) = match &e {
|
||||
AppError::HttpStatus { status, .. } => (
|
||||
Some(*status),
|
||||
Self::classify_http_status(*status).to_string(),
|
||||
),
|
||||
_ => (None, e.to_string()),
|
||||
let (http_status, message, error_category) = match &e {
|
||||
AppError::HttpStatus { status, body } => {
|
||||
let category = Self::detect_error_category(*status, body);
|
||||
(
|
||||
Some(*status),
|
||||
Self::classify_http_status(*status).to_string(),
|
||||
category.map(|s| s.to_string()),
|
||||
)
|
||||
}
|
||||
_ => (None, e.to_string(), None),
|
||||
};
|
||||
StreamCheckResult {
|
||||
status: HealthStatus::Failed,
|
||||
@@ -708,14 +768,47 @@ impl StreamCheckService {
|
||||
message,
|
||||
response_time_ms: Some(response_time),
|
||||
http_status,
|
||||
model_used: String::new(),
|
||||
model_used: model_tested.to_string(),
|
||||
tested_at,
|
||||
retry_count: 0,
|
||||
error_category,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 基于 HTTP 状态码和响应体识别细粒度错误分类。
|
||||
///
|
||||
/// 目前仅识别"模型不存在 / 已下架":各厂商该类错误通常返回 4xx,body 中会包含
|
||||
/// 如 `model_not_found`(OpenAI)、`does not exist`、`invalid model`、`not_found_error`
|
||||
/// + `model` 字样(Anthropic)等标记。
|
||||
pub(crate) fn detect_error_category(status: u16, body: &str) -> Option<&'static str> {
|
||||
// 只检查 4xx;5xx 的错误信息里可能巧合出现"model"之类的词,容易误判
|
||||
if !(400..500).contains(&status) {
|
||||
return None;
|
||||
}
|
||||
let lower = body.to_lowercase();
|
||||
// 必须提到 "model",避免通用 404 / 400 被误判
|
||||
if !lower.contains("model") {
|
||||
return None;
|
||||
}
|
||||
let indicators = [
|
||||
"model_not_found",
|
||||
"model not found",
|
||||
"does not exist",
|
||||
"invalid_model",
|
||||
"invalid model",
|
||||
"unknown_model",
|
||||
"unknown model",
|
||||
"is not a valid model",
|
||||
"not_found_error", // Anthropic 的 type 字段
|
||||
];
|
||||
if indicators.iter().any(|s| lower.contains(s)) {
|
||||
return Some("modelNotFound");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// OpenClaw 流式检查分发器
|
||||
///
|
||||
/// 根据 `settings_config.api` 字段分发到对应协议的检查器。
|
||||
@@ -725,7 +818,7 @@ impl StreamCheckService {
|
||||
/// - `anthropic-messages` → check_claude_stream + api_format="anthropic" (ClaudeAuth 策略)
|
||||
/// - `google-generative-ai` → check_gemini_stream (Google API Key 策略)
|
||||
/// - `bedrock-converse-stream` → 不支持(需要 AWS SigV4 签名)
|
||||
async fn check_openclaw_stream(
|
||||
async fn check_additive_app_stream(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
model: &str,
|
||||
@@ -735,7 +828,7 @@ impl StreamCheckService {
|
||||
// 自定义认证头(如 Longcat 的 `apikey` 头)不走标准 Bearer,
|
||||
// 具体头名由 OpenClaw 网关内部决定,cc-switch 无法准确构造,
|
||||
// 因此直接返回友好错误而不是让用户看到一个误导性的 401。
|
||||
if Self::openclaw_uses_auth_header(provider) {
|
||||
if Self::additive_app_uses_auth_header(provider) {
|
||||
return Err(AppError::localized(
|
||||
"openclaw_auth_header_not_supported",
|
||||
"该供应商使用自定义认证头,暂不支持流式健康检查。建议直接通过 OpenClaw 测试。",
|
||||
@@ -828,8 +921,8 @@ impl StreamCheckService {
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断 OpenClaw 供应商是否使用自定义认证头(`authHeader: true`)
|
||||
fn openclaw_uses_auth_header(provider: &Provider) -> bool {
|
||||
/// 判断 additive-mode 供应商是否使用自定义认证头(`authHeader: true`)
|
||||
fn additive_app_uses_auth_header(provider: &Provider) -> bool {
|
||||
provider
|
||||
.settings_config
|
||||
.get("authHeader")
|
||||
@@ -889,6 +982,112 @@ impl StreamCheckService {
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
// Hermes 的 settings_config 用 snake_case(base_url / api_key / api_mode),
|
||||
// 与 OpenClaw 的 camelCase(baseUrl / apiKey / api)是两套独立命名。
|
||||
// 见 src/config/hermesProviderPresets.ts 的 HermesProviderSettingsConfig。
|
||||
fn extract_hermes_base_url(provider: &Provider) -> Result<String, AppError> {
|
||||
provider
|
||||
.settings_config
|
||||
.get("base_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| {
|
||||
AppError::localized(
|
||||
"hermes_base_url_missing",
|
||||
"Hermes 供应商缺少 base_url",
|
||||
"Hermes provider is missing `base_url`",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_hermes_api_key(provider: &Provider) -> Result<String, AppError> {
|
||||
provider
|
||||
.settings_config
|
||||
.get("api_key")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| {
|
||||
AppError::localized(
|
||||
"hermes_api_key_missing",
|
||||
"Hermes 供应商缺少 api_key",
|
||||
"Hermes provider is missing `api_key`",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_hermes_api_mode(provider: &Provider) -> Option<String> {
|
||||
provider
|
||||
.settings_config
|
||||
.get("api_mode")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// Hermes 流式检查分发器
|
||||
///
|
||||
/// Hermes 以 `api_mode` 字段显式指定协议,取值来自
|
||||
/// `HermesApiMode`(hermesProviderPresets.ts):
|
||||
/// - `chat_completions` → check_claude_stream + api_format="openai_chat"(Bearer)
|
||||
/// - `anthropic_messages` → check_claude_stream + api_format="anthropic"(ClaudeAuth,与 OpenClaw 的 anthropic-messages 同策略)
|
||||
/// - `codex_responses` → check_claude_stream + api_format="openai_responses"(Bearer)
|
||||
/// - `bedrock_converse` → 不支持(需要 AWS SigV4 签名)
|
||||
async fn check_hermes_stream(
|
||||
client: &Client,
|
||||
provider: &Provider,
|
||||
model: &str,
|
||||
test_prompt: &str,
|
||||
timeout: std::time::Duration,
|
||||
) -> Result<(u16, String), AppError> {
|
||||
// 先把 api_mode 路由出协议格式与认证策略。
|
||||
// 纯错误路径(bedrock / 未知 / 缺失)直接 return,避免在用户
|
||||
// 选了 bedrock_converse 时被"缺 base_url"的二级错误盖住真正原因。
|
||||
let (api_format, auth_strategy) = match Self::extract_hermes_api_mode(provider).as_deref() {
|
||||
Some("chat_completions") => ("openai_chat", AuthStrategy::Bearer),
|
||||
Some("anthropic_messages") => ("anthropic", AuthStrategy::ClaudeAuth),
|
||||
Some("codex_responses") => ("openai_responses", AuthStrategy::Bearer),
|
||||
Some("bedrock_converse") => {
|
||||
return Err(AppError::localized(
|
||||
"hermes_bedrock_not_supported",
|
||||
"AWS Bedrock 需要 SigV4 签名,当前不支持健康检查。",
|
||||
"AWS Bedrock requires SigV4 signing and is not supported by stream health check.",
|
||||
));
|
||||
}
|
||||
Some(other) => {
|
||||
return Err(AppError::localized(
|
||||
"hermes_protocol_not_yet_supported",
|
||||
format!("Hermes 暂不支持协议: {other}"),
|
||||
format!("Hermes protocol not yet supported: {other}"),
|
||||
));
|
||||
}
|
||||
None => {
|
||||
return Err(AppError::localized(
|
||||
"hermes_api_mode_missing",
|
||||
"Hermes 供应商缺少 api_mode 字段",
|
||||
"Hermes provider is missing the `api_mode` field",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let base_url = Self::extract_hermes_base_url(provider)?;
|
||||
let api_key = Self::extract_hermes_api_key(provider)?;
|
||||
let auth = AuthInfo::new(api_key, auth_strategy);
|
||||
Self::check_claude_stream(
|
||||
client,
|
||||
&base_url,
|
||||
&auth,
|
||||
model,
|
||||
test_prompt,
|
||||
timeout,
|
||||
provider,
|
||||
Some(api_format),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// OpenCode 流式检查分发器
|
||||
///
|
||||
/// OpenCode 用 `npm` 字段(AI SDK 包名)隐式指定协议。映射关系参见
|
||||
@@ -946,7 +1145,7 @@ impl StreamCheckService {
|
||||
.await
|
||||
}
|
||||
Some("@ai-sdk/anthropic") => {
|
||||
// 见 check_openclaw_stream 对 anthropic-messages 的注释:
|
||||
// 见 check_additive_app_stream 对 anthropic-messages 的处理:
|
||||
// 用 ClaudeAuth(Bearer-only)兼容中转服务。
|
||||
let auth = AuthInfo::new(api_key, AuthStrategy::ClaudeAuth);
|
||||
Self::check_claude_stream(
|
||||
@@ -1161,8 +1360,8 @@ impl StreamCheckService {
|
||||
// Try to extract first model from the models object
|
||||
Self::extract_opencode_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
|
||||
}
|
||||
AppType::OpenClaw => {
|
||||
// OpenClaw uses models array in settings_config
|
||||
AppType::OpenClaw | AppType::Hermes => {
|
||||
// OpenClaw/Hermes use models array in settings_config
|
||||
// Try to extract first model from the models array
|
||||
Self::extract_openclaw_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
|
||||
}
|
||||
@@ -1245,7 +1444,19 @@ impl StreamCheckService {
|
||||
auth_strategy: AuthStrategy,
|
||||
api_format: &str,
|
||||
is_full_url: bool,
|
||||
model: &str,
|
||||
) -> String {
|
||||
if api_format == "gemini_native" {
|
||||
// Strip an optional `models/` resource-name prefix so that model
|
||||
// identifiers copied from Gemini SDK outputs (e.g.
|
||||
// `models/gemini-2.5-pro`) don't produce a doubled
|
||||
// `/v1beta/models/models/...` URL.
|
||||
let normalized_model = normalize_gemini_model_id(model);
|
||||
let endpoint =
|
||||
format!("/v1beta/models/{normalized_model}:streamGenerateContent?alt=sse");
|
||||
return resolve_gemini_native_url(base_url, &endpoint, is_full_url);
|
||||
}
|
||||
|
||||
if is_full_url {
|
||||
return base_url.to_string();
|
||||
}
|
||||
@@ -1314,24 +1525,24 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_openclaw_uses_auth_header_true() {
|
||||
fn test_additive_app_uses_auth_header_true() {
|
||||
let p = make_provider(serde_json::json!({
|
||||
"baseUrl": "https://api.longcat.chat/v1",
|
||||
"apiKey": "k",
|
||||
"api": "openai-completions",
|
||||
"authHeader": true,
|
||||
}));
|
||||
assert!(StreamCheckService::openclaw_uses_auth_header(&p));
|
||||
assert!(StreamCheckService::additive_app_uses_auth_header(&p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_openclaw_uses_auth_header_default_false() {
|
||||
fn test_additive_app_uses_auth_header_default_false() {
|
||||
let p = make_provider(serde_json::json!({
|
||||
"baseUrl": "https://api.deepseek.com/v1",
|
||||
"apiKey": "k",
|
||||
"api": "openai-completions",
|
||||
}));
|
||||
assert!(!StreamCheckService::openclaw_uses_auth_header(&p));
|
||||
assert!(!StreamCheckService::additive_app_uses_auth_header(&p));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1475,6 +1686,51 @@ mod tests {
|
||||
assert_eq!(effort, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detect_model_not_found() {
|
||||
// OpenAI 典型响应:404 + model_not_found 错误码
|
||||
let openai_404 = r#"{"error":{"message":"The model `gpt-5.1-codex` does not exist or you do not have access to it","type":"invalid_request_error","param":null,"code":"model_not_found"}}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(404, openai_404),
|
||||
Some("modelNotFound")
|
||||
);
|
||||
|
||||
// Anthropic 典型响应:404 + not_found_error + 提到 model
|
||||
let anthropic_404 = r#"{"type":"error","error":{"type":"not_found_error","message":"model: claude-deprecated"}}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(404, anthropic_404),
|
||||
Some("modelNotFound")
|
||||
);
|
||||
|
||||
// 400 + invalid model 也算
|
||||
let bad_req = r#"{"error":{"message":"invalid model specified"}}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(400, bad_req),
|
||||
Some("modelNotFound")
|
||||
);
|
||||
|
||||
// 通用 404(比如 Base URL 错误),body 里没有 model 字样 → 不应误判
|
||||
let generic_404 = r#"{"error":"Not Found"}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(404, generic_404),
|
||||
None
|
||||
);
|
||||
|
||||
// 5xx 就算 body 里有 "model does not exist" 也不分类(避免误判)
|
||||
let server_error = r#"{"error":"model does not exist"}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(500, server_error),
|
||||
None
|
||||
);
|
||||
|
||||
// 401 鉴权错误(body 里没有 model 字样)
|
||||
let auth_err = r#"{"error":"Invalid API key"}"#;
|
||||
assert_eq!(
|
||||
StreamCheckService::detect_error_category(401, auth_err),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_os_name() {
|
||||
let os_name = StreamCheckService::get_os_name();
|
||||
@@ -1529,6 +1785,7 @@ mod tests {
|
||||
AuthStrategy::Bearer,
|
||||
"openai_chat",
|
||||
true,
|
||||
"gpt-5.4",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/v1/chat/completions");
|
||||
@@ -1541,6 +1798,7 @@ mod tests {
|
||||
AuthStrategy::GitHubCopilot,
|
||||
"openai_chat",
|
||||
false,
|
||||
"gpt-5.4",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.githubcopilot.com/chat/completions");
|
||||
@@ -1553,6 +1811,7 @@ mod tests {
|
||||
AuthStrategy::GitHubCopilot,
|
||||
"openai_responses",
|
||||
false,
|
||||
"gpt-5.4",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.githubcopilot.com/v1/responses");
|
||||
@@ -1565,6 +1824,7 @@ mod tests {
|
||||
AuthStrategy::Bearer,
|
||||
"openai_chat",
|
||||
false,
|
||||
"gpt-5.4",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://example.com/v1/chat/completions");
|
||||
@@ -1577,6 +1837,7 @@ mod tests {
|
||||
AuthStrategy::Bearer,
|
||||
"openai_responses",
|
||||
false,
|
||||
"gpt-5.4",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://example.com/v1/responses");
|
||||
@@ -1589,11 +1850,78 @@ mod tests {
|
||||
AuthStrategy::Anthropic,
|
||||
"anthropic",
|
||||
false,
|
||||
"claude-sonnet-4-6",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://api.anthropic.com/v1/messages");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_gemini_native() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://generativelanguage.googleapis.com",
|
||||
AuthStrategy::Google,
|
||||
"gemini_native",
|
||||
false,
|
||||
"gemini-2.5-flash",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_gemini_native_full_url_openai_compat_base() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
|
||||
AuthStrategy::Google,
|
||||
"gemini_native",
|
||||
true,
|
||||
"gemini-2.5-flash",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_gemini_native_opaque_full_url() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://relay.example/custom/generate-content",
|
||||
AuthStrategy::Google,
|
||||
"gemini_native",
|
||||
true,
|
||||
"gemini-2.5-flash",
|
||||
);
|
||||
|
||||
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
|
||||
}
|
||||
|
||||
/// Regression: Gemini SDK outputs commonly surface model ids as the
|
||||
/// resource-name form `models/gemini-2.5-pro`. Interpolating that raw
|
||||
/// value used to produce `/v1beta/models/models/gemini-2.5-pro:...`
|
||||
/// which the upstream rejects and the health check records as a
|
||||
/// false-negative for an otherwise valid provider.
|
||||
#[test]
|
||||
fn test_resolve_claude_stream_url_for_gemini_native_strips_models_prefix() {
|
||||
let url = StreamCheckService::resolve_claude_stream_url(
|
||||
"https://generativelanguage.googleapis.com",
|
||||
AuthStrategy::Google,
|
||||
"gemini_native",
|
||||
false,
|
||||
"models/gemini-2.5-pro",
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
url,
|
||||
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_codex_stream_urls_for_full_url_mode() {
|
||||
let urls = StreamCheckService::resolve_codex_stream_urls(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -173,10 +173,7 @@ async fn run_worker_loop(
|
||||
let started_at = Instant::now();
|
||||
let mut merged_count = 1usize;
|
||||
|
||||
loop {
|
||||
let Some(wait_for) = auto_sync_wait_duration(started_at, Instant::now()) else {
|
||||
break;
|
||||
};
|
||||
while let Some(wait_for) = auto_sync_wait_duration(started_at, Instant::now()) {
|
||||
let timeout = tokio::time::timeout(wait_for, rx.recv()).await;
|
||||
|
||||
match timeout {
|
||||
|
||||
@@ -4,7 +4,7 @@ pub mod terminal;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use providers::{claude, codex, gemini, openclaw, opencode};
|
||||
use providers::{claude, codex, gemini, hermes, openclaw, opencode};
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -56,18 +56,20 @@ pub struct DeleteSessionOutcome {
|
||||
}
|
||||
|
||||
pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
let (r1, r2, r3, r4, r5) = std::thread::scope(|s| {
|
||||
let (r1, r2, r3, r4, r5, r6) = std::thread::scope(|s| {
|
||||
let h1 = s.spawn(codex::scan_sessions);
|
||||
let h2 = s.spawn(claude::scan_sessions);
|
||||
let h3 = s.spawn(opencode::scan_sessions);
|
||||
let h4 = s.spawn(openclaw::scan_sessions);
|
||||
let h5 = s.spawn(gemini::scan_sessions);
|
||||
let h6 = s.spawn(hermes::scan_sessions);
|
||||
(
|
||||
h1.join().unwrap_or_default(),
|
||||
h2.join().unwrap_or_default(),
|
||||
h3.join().unwrap_or_default(),
|
||||
h4.join().unwrap_or_default(),
|
||||
h5.join().unwrap_or_default(),
|
||||
h6.join().unwrap_or_default(),
|
||||
)
|
||||
});
|
||||
|
||||
@@ -77,6 +79,7 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
sessions.extend(r3);
|
||||
sessions.extend(r4);
|
||||
sessions.extend(r5);
|
||||
sessions.extend(r6);
|
||||
|
||||
sessions.sort_by(|a, b| {
|
||||
let a_ts = a.last_active_at.or(a.created_at).unwrap_or(0);
|
||||
@@ -88,10 +91,13 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
}
|
||||
|
||||
pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<SessionMessage>, String> {
|
||||
// OpenCode SQLite sessions use a "sqlite:" prefixed source_path
|
||||
// SQLite sessions use a "sqlite:" prefixed source_path
|
||||
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
|
||||
return opencode::load_messages_sqlite(source_path);
|
||||
}
|
||||
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
|
||||
return hermes::load_messages_sqlite(source_path);
|
||||
}
|
||||
|
||||
let path = Path::new(source_path);
|
||||
match provider_id {
|
||||
@@ -100,6 +106,7 @@ pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<Session
|
||||
"opencode" => opencode::load_messages(path),
|
||||
"openclaw" => openclaw::load_messages(path),
|
||||
"gemini" => gemini::load_messages(path),
|
||||
"hermes" => hermes::load_messages(path),
|
||||
_ => Err(format!("Unsupported provider: {provider_id}")),
|
||||
}
|
||||
}
|
||||
@@ -109,10 +116,13 @@ pub fn delete_session(
|
||||
session_id: &str,
|
||||
source_path: &str,
|
||||
) -> Result<bool, String> {
|
||||
// OpenCode SQLite sessions bypass the file-based deletion path
|
||||
// SQLite sessions bypass the file-based deletion path
|
||||
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
|
||||
return opencode::delete_session_sqlite(session_id, source_path);
|
||||
}
|
||||
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
|
||||
return hermes::delete_session_sqlite(session_id, source_path);
|
||||
}
|
||||
|
||||
let root = provider_root(provider_id)?;
|
||||
delete_session_with_root(provider_id, session_id, Path::new(source_path), &root)
|
||||
@@ -150,6 +160,7 @@ fn delete_session_with_root(
|
||||
"opencode" => opencode::delete_session(&validated_root, &validated_source, session_id),
|
||||
"openclaw" => openclaw::delete_session(&validated_root, &validated_source, session_id),
|
||||
"gemini" => gemini::delete_session(&validated_root, &validated_source, session_id),
|
||||
"hermes" => hermes::delete_session(&validated_root, &validated_source, session_id),
|
||||
_ => Err(format!("Unsupported provider: {provider_id}")),
|
||||
}
|
||||
}
|
||||
@@ -161,6 +172,7 @@ fn provider_root(provider_id: &str) -> Result<PathBuf, String> {
|
||||
"opencode" => opencode::get_opencode_data_dir(),
|
||||
"openclaw" => crate::openclaw_config::get_openclaw_dir().join("agents"),
|
||||
"gemini" => crate::gemini_config::get_gemini_dir().join("tmp"),
|
||||
"hermes" => crate::hermes_config::get_hermes_dir().join("sessions"),
|
||||
_ => return Err(format!("Unsupported provider: {provider_id}")),
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,603 @@
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rusqlite::Connection;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::hermes_config::get_hermes_dir;
|
||||
use crate::session_manager::{SessionMessage, SessionMeta};
|
||||
|
||||
use super::utils::{
|
||||
extract_text, parse_timestamp_to_ms, read_head_tail_lines, truncate_summary, TITLE_MAX_CHARS,
|
||||
};
|
||||
|
||||
const PROVIDER_ID: &str = "hermes";
|
||||
|
||||
fn get_hermes_db_path() -> PathBuf {
|
||||
get_hermes_dir().join("state.db")
|
||||
}
|
||||
|
||||
fn get_hermes_sessions_dir() -> PathBuf {
|
||||
get_hermes_dir().join("sessions")
|
||||
}
|
||||
|
||||
/// Scan sessions from both SQLite database and JSONL transcript files,
|
||||
/// with SQLite taking precedence on ID conflicts.
|
||||
pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
let sqlite_sessions = scan_sessions_sqlite();
|
||||
let jsonl_sessions = scan_sessions_jsonl();
|
||||
|
||||
if sqlite_sessions.is_empty() {
|
||||
return jsonl_sessions;
|
||||
}
|
||||
if jsonl_sessions.is_empty() {
|
||||
return sqlite_sessions;
|
||||
}
|
||||
|
||||
let sqlite_ids: std::collections::HashSet<String> = sqlite_sessions
|
||||
.iter()
|
||||
.map(|s| s.session_id.clone())
|
||||
.collect();
|
||||
|
||||
let mut merged = sqlite_sessions;
|
||||
for s in jsonl_sessions {
|
||||
if !sqlite_ids.contains(&s.session_id) {
|
||||
merged.push(s);
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
// ── SQLite scanning ─────────────────────────────────────────────────
|
||||
|
||||
fn scan_sessions_sqlite() -> Vec<SessionMeta> {
|
||||
let db_path = get_hermes_db_path();
|
||||
if !db_path.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let conn = match Connection::open_with_flags(
|
||||
&db_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
// Check if sessions table exists
|
||||
let has_sessions: bool = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='sessions'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap_or(false);
|
||||
|
||||
if !has_sessions {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Query sessions — use flexible column access via pragma
|
||||
let columns = get_table_columns(&conn, "sessions");
|
||||
|
||||
let query = "SELECT * FROM sessions ORDER BY rowid DESC LIMIT 500";
|
||||
let mut stmt = match conn.prepare(query) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut sessions = Vec::new();
|
||||
let rows = match stmt.query_map([], |row| Ok(row_to_json(row, &columns))) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let db_source = format!("sqlite:{}", db_path.display());
|
||||
|
||||
for row_result in rows.flatten() {
|
||||
if let Some(meta) = sqlite_row_to_session_meta(&row_result, &db_source) {
|
||||
sessions.push(meta);
|
||||
}
|
||||
}
|
||||
|
||||
sessions
|
||||
}
|
||||
|
||||
fn sqlite_row_to_session_meta(row: &Value, db_source: &str) -> Option<SessionMeta> {
|
||||
let obj = row.as_object()?;
|
||||
|
||||
let session_id = obj.get("id").and_then(Value::as_str)?.to_string();
|
||||
|
||||
let title = obj
|
||||
.get("title")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| truncate_summary(s, TITLE_MAX_CHARS).to_string());
|
||||
|
||||
let cwd = obj
|
||||
.get("cwd")
|
||||
.or_else(|| obj.get("directory"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let started_at = obj
|
||||
.get("started_at")
|
||||
.or_else(|| obj.get("created_at"))
|
||||
.and_then(parse_timestamp_to_ms);
|
||||
|
||||
let ended_at = obj
|
||||
.get("ended_at")
|
||||
.or_else(|| obj.get("updated_at"))
|
||||
.and_then(parse_timestamp_to_ms);
|
||||
|
||||
let source_path = format!("{}#{}", db_source, session_id);
|
||||
|
||||
Some(SessionMeta {
|
||||
provider_id: PROVIDER_ID.to_string(),
|
||||
session_id,
|
||||
title,
|
||||
summary: None,
|
||||
project_dir: cwd,
|
||||
created_at: started_at,
|
||||
last_active_at: ended_at.or(started_at),
|
||||
source_path: Some(source_path),
|
||||
resume_command: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get column names for a table.
|
||||
fn get_table_columns(conn: &Connection, table: &str) -> Vec<String> {
|
||||
let query = format!("PRAGMA table_info({table})");
|
||||
let mut stmt = match conn.prepare(&query) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
let rows = match stmt.query_map([], |row| {
|
||||
let name: String = row.get(1)?;
|
||||
Ok(name)
|
||||
}) {
|
||||
Ok(r) => r,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
rows.flatten().collect()
|
||||
}
|
||||
|
||||
/// Convert a SQLite row to a JSON Value using known column names.
|
||||
fn row_to_json(row: &rusqlite::Row, columns: &[String]) -> Value {
|
||||
let mut map = serde_json::Map::new();
|
||||
for (i, col) in columns.iter().enumerate() {
|
||||
// Try string first, then integer, then float, then null
|
||||
if let Ok(val) = row.get::<_, String>(i) {
|
||||
map.insert(col.clone(), Value::String(val));
|
||||
} else if let Ok(val) = row.get::<_, i64>(i) {
|
||||
map.insert(col.clone(), Value::Number(val.into()));
|
||||
} else if let Ok(val) = row.get::<_, f64>(i) {
|
||||
if let Some(n) = serde_json::Number::from_f64(val) {
|
||||
map.insert(col.clone(), Value::Number(n));
|
||||
}
|
||||
} else {
|
||||
map.insert(col.clone(), Value::Null);
|
||||
}
|
||||
}
|
||||
Value::Object(map)
|
||||
}
|
||||
|
||||
/// Load messages from the Hermes SQLite database.
|
||||
pub fn load_messages_sqlite(source: &str) -> Result<Vec<SessionMessage>, String> {
|
||||
let (db_path, session_id) = parse_sqlite_source(source)
|
||||
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
|
||||
|
||||
let conn = Connection::open_with_flags(
|
||||
&db_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(|e| format!("Failed to open Hermes database: {e}"))?;
|
||||
|
||||
// Try querying with common column names
|
||||
let query =
|
||||
"SELECT role, content, created_at FROM messages WHERE session_id = ?1 ORDER BY created_at ASC";
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(query)
|
||||
.map_err(|e| format!("Failed to prepare messages query: {e}"))?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map([session_id.as_str()], |row| {
|
||||
let role: String = row.get(0)?;
|
||||
let content: String = row.get(1)?;
|
||||
let ts: Option<i64> = row.get(2).ok();
|
||||
Ok((role, content, ts))
|
||||
})
|
||||
.map_err(|e| format!("Failed to query messages: {e}"))?;
|
||||
|
||||
let mut messages = Vec::new();
|
||||
for row in rows.flatten() {
|
||||
let (role, content, ts) = row;
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let ts_ms = ts.and_then(|v| parse_timestamp_to_ms(&Value::Number(v.into())));
|
||||
messages.push(SessionMessage {
|
||||
role,
|
||||
content,
|
||||
ts: ts_ms,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Delete a session from the Hermes SQLite database.
|
||||
pub fn delete_session_sqlite(session_id: &str, source: &str) -> Result<bool, String> {
|
||||
let (db_path, ref_session_id) = parse_sqlite_source(source)
|
||||
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
|
||||
let db_path = db_path
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Failed to canonicalize Hermes database path: {e}"))?;
|
||||
let expected_db_path = get_hermes_db_path()
|
||||
.canonicalize()
|
||||
.map_err(|e| format!("Failed to canonicalize expected Hermes database path: {e}"))?;
|
||||
|
||||
if ref_session_id != session_id {
|
||||
return Err(format!(
|
||||
"Hermes SQLite session ID mismatch: expected {session_id}, found {ref_session_id}"
|
||||
));
|
||||
}
|
||||
if db_path != expected_db_path {
|
||||
return Err("SQLite path does not match expected Hermes database".to_string());
|
||||
}
|
||||
|
||||
let conn =
|
||||
Connection::open(&db_path).map_err(|e| format!("Failed to open Hermes database: {e}"))?;
|
||||
|
||||
let tx = conn
|
||||
.unchecked_transaction()
|
||||
.map_err(|e| format!("Failed to begin transaction: {e}"))?;
|
||||
|
||||
// Delete messages first (child records)
|
||||
let _ = tx.execute("DELETE FROM messages WHERE session_id = ?1", [session_id]);
|
||||
|
||||
let deleted = tx
|
||||
.execute("DELETE FROM sessions WHERE id = ?1", [session_id])
|
||||
.map_err(|e| format!("Failed to delete Hermes session: {e}"))?;
|
||||
|
||||
tx.commit()
|
||||
.map_err(|e| format!("Failed to commit session deletion: {e}"))?;
|
||||
|
||||
Ok(deleted > 0)
|
||||
}
|
||||
|
||||
fn parse_sqlite_source(source: &str) -> Option<(PathBuf, String)> {
|
||||
let rest = source.strip_prefix("sqlite:")?;
|
||||
let hash_pos = rest.rfind('#')?;
|
||||
let db_path = PathBuf::from(&rest[..hash_pos]);
|
||||
let session_id = rest[hash_pos + 1..].to_string();
|
||||
if session_id.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((db_path, session_id))
|
||||
}
|
||||
|
||||
// ── JSONL scanning ──────────────────────────────────────────────────
|
||||
|
||||
fn scan_sessions_jsonl() -> Vec<SessionMeta> {
|
||||
let sessions_dir = get_hermes_sessions_dir();
|
||||
if !sessions_dir.exists() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let entries = match std::fs::read_dir(&sessions_dir) {
|
||||
Ok(e) => e,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut sessions = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let ext = path.extension().and_then(|e| e.to_str());
|
||||
if ext != Some("jsonl") && ext != Some("json") {
|
||||
continue;
|
||||
}
|
||||
if let Some(meta) = parse_jsonl_session(&path) {
|
||||
sessions.push(meta);
|
||||
}
|
||||
}
|
||||
sessions
|
||||
}
|
||||
|
||||
fn parse_jsonl_session(path: &Path) -> Option<SessionMeta> {
|
||||
// Read head (metadata + first user message) and tail (last timestamp)
|
||||
let (head, tail) = read_head_tail_lines(path, 30, 10).ok()?;
|
||||
|
||||
let mut first_user_msg: Option<String> = None;
|
||||
let mut first_ts: Option<i64> = None;
|
||||
let mut last_ts: Option<i64> = None;
|
||||
let mut session_id: Option<String> = None;
|
||||
let mut title: Option<String> = None;
|
||||
let mut cwd: Option<String> = None;
|
||||
|
||||
// Process head lines for metadata and first user message
|
||||
for line in &head {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
let ts = value
|
||||
.get("timestamp")
|
||||
.or_else(|| value.get("ts"))
|
||||
.and_then(parse_timestamp_to_ms);
|
||||
|
||||
if first_ts.is_none() {
|
||||
first_ts = ts;
|
||||
}
|
||||
last_ts = ts.or(last_ts);
|
||||
|
||||
let line_type = value.get("type").and_then(Value::as_str).unwrap_or("");
|
||||
|
||||
// Extract session metadata from session-type lines
|
||||
if line_type == "session" || line_type == "init" {
|
||||
if session_id.is_none() {
|
||||
session_id = value
|
||||
.get("id")
|
||||
.or_else(|| value.get("sessionId"))
|
||||
.and_then(Value::as_str)
|
||||
.map(|s| s.to_string());
|
||||
}
|
||||
if title.is_none() {
|
||||
title = value
|
||||
.get("title")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
}
|
||||
if cwd.is_none() {
|
||||
cwd = value
|
||||
.get("cwd")
|
||||
.or_else(|| value.get("directory"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
if first_user_msg.is_none() {
|
||||
let role = value
|
||||
.get("role")
|
||||
.or_else(|| value.get("message").and_then(|m| m.get("role")))
|
||||
.and_then(Value::as_str);
|
||||
|
||||
if role == Some("user") {
|
||||
let content = value
|
||||
.get("content")
|
||||
.or_else(|| value.get("message").and_then(|m| m.get("content")));
|
||||
if let Some(c) = content {
|
||||
let text = extract_text(c);
|
||||
if !text.trim().is_empty() {
|
||||
first_user_msg = Some(truncate_summary(&text, TITLE_MAX_CHARS).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process tail lines for the most recent timestamp
|
||||
for line in tail.iter().rev() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value: Value = match serde_json::from_str(line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let ts = value
|
||||
.get("timestamp")
|
||||
.or_else(|| value.get("ts"))
|
||||
.and_then(parse_timestamp_to_ms);
|
||||
if let Some(t) = ts {
|
||||
last_ts = Some(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to filename as session ID
|
||||
let session_id = session_id.unwrap_or_else(|| {
|
||||
path.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("unknown")
|
||||
.to_string()
|
||||
});
|
||||
|
||||
let source_path = path.to_string_lossy().to_string();
|
||||
|
||||
Some(SessionMeta {
|
||||
provider_id: PROVIDER_ID.to_string(),
|
||||
session_id,
|
||||
title: title.or_else(|| first_user_msg.clone()),
|
||||
summary: first_user_msg,
|
||||
project_dir: cwd,
|
||||
created_at: first_ts,
|
||||
last_active_at: last_ts.or(first_ts),
|
||||
source_path: Some(source_path),
|
||||
resume_command: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Load messages from a Hermes JSONL transcript file.
|
||||
pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
let file = File::open(path).map_err(|e| format!("Failed to open session file: {e}"))?;
|
||||
let reader = BufReader::new(file);
|
||||
let mut messages = Vec::new();
|
||||
|
||||
for line in reader.lines() {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(_) => continue,
|
||||
};
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let value: Value = match serde_json::from_str(&line) {
|
||||
Ok(v) => v,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
// Support both flat messages and nested {type:"message", message:{...}} format
|
||||
let (role_val, content_val, ts_val) =
|
||||
if value.get("type").and_then(Value::as_str) == Some("message") {
|
||||
let msg = match value.get("message") {
|
||||
Some(m) => m,
|
||||
None => continue,
|
||||
};
|
||||
(
|
||||
msg.get("role"),
|
||||
msg.get("content"),
|
||||
value.get("timestamp").or_else(|| msg.get("ts")),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
value.get("role"),
|
||||
value.get("content"),
|
||||
value.get("timestamp").or_else(|| value.get("ts")),
|
||||
)
|
||||
};
|
||||
|
||||
let role = match role_val.and_then(Value::as_str) {
|
||||
Some(r) => r.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let content = content_val.map(extract_text).unwrap_or_default();
|
||||
if content.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let ts = ts_val.and_then(parse_timestamp_to_ms);
|
||||
messages.push(SessionMessage { role, content, ts });
|
||||
}
|
||||
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Delete a Hermes JSONL session file.
|
||||
pub fn delete_session(_root: &Path, path: &Path, _session_id: &str) -> Result<bool, String> {
|
||||
std::fs::remove_file(path).map_err(|e| {
|
||||
format!(
|
||||
"Failed to delete Hermes session file {}: {e}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn parse_sqlite_source_valid() {
|
||||
let (path, id) = parse_sqlite_source("sqlite:/home/user/.hermes/state.db#session-123")
|
||||
.expect("should parse");
|
||||
assert_eq!(path, PathBuf::from("/home/user/.hermes/state.db"));
|
||||
assert_eq!(id, "session-123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_sqlite_source_invalid() {
|
||||
assert!(parse_sqlite_source("not-sqlite").is_none());
|
||||
assert!(parse_sqlite_source("sqlite:").is_none());
|
||||
assert!(parse_sqlite_source("sqlite:/path#").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_jsonl_session_extracts_metadata() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let path = dir.path().join("test-session.jsonl");
|
||||
let mut f = File::create(&path).expect("create");
|
||||
writeln!(
|
||||
f,
|
||||
r#"{{"type":"session","id":"s1","title":"My Session","cwd":"/home/user/project"}}"#
|
||||
)
|
||||
.unwrap();
|
||||
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello world"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
|
||||
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi there"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
|
||||
f.flush().unwrap();
|
||||
|
||||
let meta = parse_jsonl_session(&path).expect("should parse");
|
||||
assert_eq!(meta.session_id, "s1");
|
||||
assert_eq!(meta.title.as_deref(), Some("My Session"));
|
||||
assert_eq!(meta.project_dir.as_deref(), Some("/home/user/project"));
|
||||
assert!(meta.created_at.is_some());
|
||||
assert!(meta.last_active_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_jsonl_session_fallback_to_filename() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let path = dir.path().join("my-session.jsonl");
|
||||
let mut f = File::create(&path).expect("create");
|
||||
writeln!(f, r#"{{"role":"user","content":"Hello","ts":1700000000}}"#).unwrap();
|
||||
f.flush().unwrap();
|
||||
|
||||
let meta = parse_jsonl_session(&path).expect("should parse");
|
||||
assert_eq!(meta.session_id, "my-session");
|
||||
assert!(meta.title.is_some()); // Falls back to first user message
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_flat_format() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let path = dir.path().join("session.jsonl");
|
||||
let mut f = File::create(&path).expect("create");
|
||||
writeln!(
|
||||
f,
|
||||
r#"{{"role":"user","content":"What is Rust?","ts":1700000000}}"#
|
||||
)
|
||||
.unwrap();
|
||||
writeln!(
|
||||
f,
|
||||
r#"{{"role":"assistant","content":"A systems programming language.","ts":1700000001}}"#
|
||||
)
|
||||
.unwrap();
|
||||
f.flush().unwrap();
|
||||
|
||||
let msgs = load_messages(&path).expect("should load");
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert_eq!(msgs[1].role, "assistant");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_messages_nested_format() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let path = dir.path().join("session.jsonl");
|
||||
let mut f = File::create(&path).expect("create");
|
||||
writeln!(f, r#"{{"type":"session","id":"s1"}}"#).unwrap();
|
||||
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
|
||||
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
|
||||
f.flush().unwrap();
|
||||
|
||||
let msgs = load_messages(&path).expect("should load");
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert!(msgs[0].ts.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_session_removes_file() {
|
||||
let dir = tempdir().expect("tempdir");
|
||||
let path = dir.path().join("session.jsonl");
|
||||
File::create(&path).expect("create");
|
||||
assert!(path.exists());
|
||||
|
||||
delete_session(dir.path(), &path, "session").expect("should delete");
|
||||
assert!(!path.exists());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod claude;
|
||||
pub mod codex;
|
||||
pub mod gemini;
|
||||
pub mod hermes;
|
||||
pub mod openclaw;
|
||||
pub mod opencode;
|
||||
mod utils;
|
||||
|
||||
@@ -78,22 +78,7 @@ end tell"#
|
||||
}
|
||||
|
||||
fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
|
||||
let args = build_ghostty_args(command, cwd);
|
||||
|
||||
let status = Command::new("open")
|
||||
.args(args.iter().map(String::as_str))
|
||||
.status()
|
||||
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
|
||||
let input = ghostty_raw_input(command);
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".to_string());
|
||||
|
||||
let mut args = vec![
|
||||
"-na".to_string(),
|
||||
@@ -108,22 +93,22 @@ fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
args.push(format!("--input={input}"));
|
||||
args
|
||||
}
|
||||
args.push("-e".to_string());
|
||||
args.push(shell);
|
||||
args.push("-l".to_string());
|
||||
args.push("-c".to_string());
|
||||
args.push(command.to_string());
|
||||
|
||||
fn ghostty_raw_input(command: &str) -> String {
|
||||
let mut escaped = String::from("raw:");
|
||||
for ch in command.chars() {
|
||||
match ch {
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
'\n' => escaped.push_str("\\n"),
|
||||
'\r' => escaped.push_str("\\r"),
|
||||
_ => escaped.push(ch),
|
||||
}
|
||||
let status = Command::new("open")
|
||||
.args(&args)
|
||||
.status()
|
||||
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
|
||||
}
|
||||
escaped.push_str("\\n");
|
||||
escaped
|
||||
}
|
||||
|
||||
fn launch_kitty(command: &str, cwd: Option<&str>) -> Result<(), String> {
|
||||
@@ -300,43 +285,10 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ghostty_uses_shell_mode_for_resume_commands() {
|
||||
let args = build_ghostty_args("claude --resume abc-123", Some("/tmp/project dir"));
|
||||
|
||||
fn build_shell_command_keeps_command_without_cwd_prefix_when_not_provided() {
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"-na",
|
||||
"Ghostty",
|
||||
"--args",
|
||||
"--quit-after-last-window-closed=true",
|
||||
"--working-directory=/tmp/project dir",
|
||||
"--input=raw:claude --resume abc-123\\n",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ghostty_keeps_command_without_cwd_prefix_when_not_provided() {
|
||||
let args = build_ghostty_args("claude --resume abc-123", None);
|
||||
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"-na",
|
||||
"Ghostty",
|
||||
"--args",
|
||||
"--quit-after-last-window-closed=true",
|
||||
"--input=raw:claude --resume abc-123\\n",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ghostty_escapes_newlines_and_backslashes_in_input() {
|
||||
assert_eq!(
|
||||
ghostty_raw_input("echo foo\\\\bar\npwd"),
|
||||
"raw:echo foo\\\\\\\\bar\\npwd\\n"
|
||||
build_shell_command("claude --resume abc-123", None),
|
||||
"claude --resume abc-123"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -365,4 +317,22 @@ mod tests {
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ghostty_uses_working_directory_arg_for_cwd() {
|
||||
// cwd should be passed as --working-directory, not embedded in the shell command string
|
||||
// This avoids shell expansion of special characters in directory paths
|
||||
let cwd = "/tmp/project dir";
|
||||
let command = "claude --resume abc-123";
|
||||
|
||||
// Verify build_shell_command does NOT include cwd when used in ghostty context
|
||||
// (ghostty passes cwd via --working-directory flag instead)
|
||||
assert_eq!(
|
||||
build_shell_command(command, None),
|
||||
"claude --resume abc-123"
|
||||
);
|
||||
|
||||
// Verify shell_escape works correctly for paths with spaces
|
||||
assert_eq!(shell_escape(cwd), "\"/tmp/project dir\"");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ pub struct VisibleApps {
|
||||
pub opencode: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub openclaw: bool,
|
||||
#[serde(default)]
|
||||
pub hermes: bool,
|
||||
}
|
||||
|
||||
impl Default for VisibleApps {
|
||||
@@ -46,6 +48,7 @@ impl Default for VisibleApps {
|
||||
gemini: true,
|
||||
opencode: true,
|
||||
openclaw: true,
|
||||
hermes: false, // 默认不显示,需用户手动启用
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,6 +62,7 @@ impl VisibleApps {
|
||||
AppType::Gemini => self.gemini,
|
||||
AppType::OpenCode => self.opencode,
|
||||
AppType::OpenClaw => self.openclaw,
|
||||
AppType::Hermes => self.hermes,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,6 +235,8 @@ pub struct AppSettings {
|
||||
pub opencode_config_dir: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub openclaw_config_dir: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hermes_config_dir: Option<String>,
|
||||
|
||||
// ===== 当前供应商 ID(设备级)=====
|
||||
/// 当前 Claude 供应商 ID(本地存储,优先于数据库 is_current)
|
||||
@@ -248,6 +254,9 @@ pub struct AppSettings {
|
||||
/// 当前 OpenClaw 供应商 ID(本地存储,对 OpenClaw 可能无意义,但保持结构一致)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub current_provider_openclaw: Option<String>,
|
||||
/// 当前 Hermes 供应商 ID(本地存储,保持结构一致)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub current_provider_hermes: Option<String>,
|
||||
|
||||
// ===== Skill 同步设置 =====
|
||||
/// Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
|
||||
@@ -315,11 +324,13 @@ impl Default for AppSettings {
|
||||
gemini_config_dir: None,
|
||||
opencode_config_dir: None,
|
||||
openclaw_config_dir: None,
|
||||
hermes_config_dir: None,
|
||||
current_provider_claude: None,
|
||||
current_provider_codex: None,
|
||||
current_provider_gemini: None,
|
||||
current_provider_opencode: None,
|
||||
current_provider_openclaw: None,
|
||||
current_provider_hermes: None,
|
||||
skill_sync_method: SyncMethod::default(),
|
||||
skill_storage_location: SkillStorageLocation::default(),
|
||||
webdav_sync: None,
|
||||
@@ -377,6 +388,13 @@ impl AppSettings {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
self.hermes_config_dir = self
|
||||
.hermes_config_dir
|
||||
.as_ref()
|
||||
.map(|s| s.trim())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
self.language = self
|
||||
.language
|
||||
.as_ref()
|
||||
@@ -577,6 +595,14 @@ pub fn get_openclaw_override_dir() -> Option<PathBuf> {
|
||||
.map(|p| resolve_override_path(p))
|
||||
}
|
||||
|
||||
pub fn get_hermes_override_dir() -> Option<PathBuf> {
|
||||
let settings = settings_store().read().ok()?;
|
||||
settings
|
||||
.hermes_config_dir
|
||||
.as_ref()
|
||||
.map(|p| resolve_override_path(p))
|
||||
}
|
||||
|
||||
// ===== 当前供应商管理函数 =====
|
||||
|
||||
/// 获取指定应用类型的当前供应商 ID(从本地 settings 读取)
|
||||
@@ -591,6 +617,7 @@ pub fn get_current_provider(app_type: &AppType) -> Option<String> {
|
||||
AppType::Gemini => settings.current_provider_gemini.clone(),
|
||||
AppType::OpenCode => settings.current_provider_opencode.clone(),
|
||||
AppType::OpenClaw => settings.current_provider_openclaw.clone(),
|
||||
AppType::Hermes => settings.current_provider_hermes.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,6 +633,7 @@ pub fn set_current_provider(app_type: &AppType, id: Option<&str>) -> Result<(),
|
||||
AppType::Gemini => settings.current_provider_gemini = id_owned.clone(),
|
||||
AppType::OpenCode => settings.current_provider_opencode = id_owned.clone(),
|
||||
AppType::OpenClaw => settings.current_provider_openclaw = id_owned.clone(),
|
||||
AppType::Hermes => settings.current_provider_hermes = id_owned.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+15
-3
@@ -58,6 +58,7 @@ pub struct TrayAppSection {
|
||||
|
||||
/// Auto 菜单项后缀
|
||||
pub const AUTO_SUFFIX: &str = "auto";
|
||||
pub const TRAY_ID: &str = "cc-switch";
|
||||
|
||||
pub const TRAY_SECTIONS: [TrayAppSection; 3] = [
|
||||
TrayAppSection {
|
||||
@@ -207,7 +208,7 @@ fn handle_auto_click(app: &tauri::AppHandle, app_type: &AppType) -> Result<(), A
|
||||
|
||||
// 4) 更新托盘菜单
|
||||
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(TRAY_ID) {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
@@ -255,7 +256,7 @@ fn handle_provider_click(
|
||||
|
||||
// 更新托盘菜单
|
||||
if let Ok(new_menu) = create_tray_menu(app, app_state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(TRAY_ID) {
|
||||
let _ = tray.set_menu(Some(new_menu));
|
||||
}
|
||||
}
|
||||
@@ -402,7 +403,7 @@ pub fn refresh_tray_menu(app: &tauri::AppHandle) {
|
||||
|
||||
if let Some(state) = app.try_state::<AppState>() {
|
||||
if let Ok(new_menu) = create_tray_menu(app, state.inner()) {
|
||||
if let Some(tray) = app.tray_by_id("main") {
|
||||
if let Some(tray) = app.tray_by_id(TRAY_ID) {
|
||||
if let Err(e) = tray.set_menu(Some(new_menu)) {
|
||||
log::error!("刷新托盘菜单失败: {e}");
|
||||
}
|
||||
@@ -411,6 +412,17 @@ pub fn refresh_tray_menu(app: &tauri::AppHandle) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::TRAY_ID;
|
||||
|
||||
#[test]
|
||||
fn tray_id_is_unique_to_app() {
|
||||
assert_eq!(TRAY_ID, "cc-switch");
|
||||
assert_ne!(TRAY_ID, "main");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn apply_tray_policy(app: &tauri::AppHandle, dock_visible: bool) {
|
||||
use tauri::ActivationPolicy;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.13.0",
|
||||
"version": "3.14.0",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
mod support;
|
||||
|
||||
use cc_switch_lib::{hermes_config, update_settings, AppSettings};
|
||||
|
||||
/// 读取并回写 Hermes provider 时,Hermes v12+ 新增或未来才会出现的字段
|
||||
/// (例如 `rate_limit_delay`、`key_env`)必须透传,不能因为 UI 不感知就静默丢弃。
|
||||
/// 否则用户在 Hermes Web UI 配置的高级字段会在 CC Switch 编辑后消失。
|
||||
fn with_temp_hermes_dir<F: FnOnce(&std::path::Path)>(f: F) {
|
||||
let guard = support::test_mutex().lock().expect("test mutex poisoned");
|
||||
let home = support::ensure_test_home();
|
||||
support::reset_test_fs();
|
||||
|
||||
let hermes_dir = home.join(".hermes-roundtrip");
|
||||
let _ = std::fs::remove_dir_all(&hermes_dir);
|
||||
std::fs::create_dir_all(&hermes_dir).expect("create temp hermes dir");
|
||||
|
||||
update_settings(AppSettings {
|
||||
hermes_config_dir: Some(hermes_dir.to_string_lossy().into_owned()),
|
||||
..AppSettings::default()
|
||||
})
|
||||
.expect("set hermes_config_dir override");
|
||||
|
||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&hermes_dir)));
|
||||
|
||||
// Always restore settings and drop fixture dir, even on test failure.
|
||||
let _ = update_settings(AppSettings::default());
|
||||
let _ = std::fs::remove_dir_all(&hermes_dir);
|
||||
drop(guard);
|
||||
|
||||
if let Err(err) = result {
|
||||
std::panic::resume_unwind(err);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_provider_preserves_unknown_and_future_fields() {
|
||||
with_temp_hermes_dir(|dir| {
|
||||
let yaml = r#"custom_providers:
|
||||
- name: myhost
|
||||
base_url: https://api.example.com/v1
|
||||
api_key: sk-old
|
||||
api_mode: chat_completions
|
||||
rate_limit_delay: 0.5
|
||||
key_env: MY_API_KEY
|
||||
foo_bar: keep-me-around
|
||||
models:
|
||||
gpt-4:
|
||||
context_length: 8192
|
||||
"#;
|
||||
let config_path = dir.join("config.yaml");
|
||||
std::fs::write(&config_path, yaml).expect("seed config.yaml");
|
||||
|
||||
// Simulate the UI sending back only the fields it knows about.
|
||||
let patch = serde_json::json!({
|
||||
"name": "myhost",
|
||||
"base_url": "https://api.example.com/v1",
|
||||
"api_key": "sk-new",
|
||||
"api_mode": "chat_completions",
|
||||
"models": [
|
||||
{ "id": "gpt-4", "context_length": 8192 }
|
||||
]
|
||||
});
|
||||
|
||||
hermes_config::set_provider("myhost", patch).expect("set_provider");
|
||||
|
||||
let written = std::fs::read_to_string(&config_path).expect("read written config");
|
||||
|
||||
assert!(
|
||||
written.contains("rate_limit_delay"),
|
||||
"rate_limit_delay stripped:\n{written}"
|
||||
);
|
||||
assert!(
|
||||
written.contains("key_env"),
|
||||
"key_env key stripped:\n{written}"
|
||||
);
|
||||
assert!(
|
||||
written.contains("MY_API_KEY"),
|
||||
"key_env value stripped:\n{written}"
|
||||
);
|
||||
assert!(
|
||||
written.contains("foo_bar"),
|
||||
"unknown forward-compat field stripped:\n{written}"
|
||||
);
|
||||
assert!(
|
||||
written.contains("sk-new"),
|
||||
"api_key was not updated to sk-new:\n{written}"
|
||||
);
|
||||
assert!(
|
||||
!written.contains("sk-old"),
|
||||
"old api_key still present:\n{written}"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_providers_surfaces_rate_limit_delay_and_key_env() {
|
||||
with_temp_hermes_dir(|dir| {
|
||||
let yaml = r#"custom_providers:
|
||||
- name: myhost
|
||||
base_url: https://api.example.com/v1
|
||||
api_key: sk-xxx
|
||||
api_mode: chat_completions
|
||||
rate_limit_delay: 2.5
|
||||
key_env: FOO_KEY
|
||||
models:
|
||||
m1: {}
|
||||
"#;
|
||||
std::fs::write(dir.join("config.yaml"), yaml).expect("seed config.yaml");
|
||||
|
||||
let providers = hermes_config::get_providers().expect("get_providers");
|
||||
let entry = providers.get("myhost").expect("myhost missing");
|
||||
|
||||
assert_eq!(
|
||||
entry.get("rate_limit_delay").and_then(|v| v.as_f64()),
|
||||
Some(2.5),
|
||||
"rate_limit_delay not surfaced to DAO payload"
|
||||
);
|
||||
assert_eq!(
|
||||
entry.get("key_env").and_then(|v| v.as_str()),
|
||||
Some("FOO_KEY"),
|
||||
"key_env not surfaced to DAO payload"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -554,6 +554,7 @@ command = "echo"
|
||||
codex: false, // 初始未启用
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -682,6 +683,7 @@ fn import_from_claude_merges_into_config() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -217,6 +217,7 @@ fn set_mcp_enabled_for_codex_writes_live_config() {
|
||||
codex: false, // 初始未启用
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -281,6 +282,7 @@ fn enabling_codex_mcp_skips_when_codex_dir_missing() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -325,6 +327,7 @@ fn upsert_mcp_server_disabling_app_removes_from_claude_live_config() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -358,6 +361,7 @@ fn upsert_mcp_server_disabling_app_removes_from_claude_live_config() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -490,6 +494,7 @@ fn enabling_gemini_mcp_skips_when_gemini_dir_missing() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -544,6 +549,7 @@ fn enabling_claude_mcp_skips_when_claude_config_absent() {
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -604,6 +610,7 @@ fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries()
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
@@ -625,6 +632,7 @@ fn sync_all_enabled_removes_known_disabled_but_preserves_unknown_live_entries()
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -75,6 +75,7 @@ command = "say"
|
||||
codex: true, // 启用 Codex
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -163,6 +163,7 @@ command = "say"
|
||||
codex: true,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
hermes: false,
|
||||
},
|
||||
description: None,
|
||||
homepage: None,
|
||||
|
||||
@@ -53,10 +53,8 @@ fn import_from_apps_respects_explicit_app_selection() {
|
||||
vec![ImportSkillSelection {
|
||||
directory: "shared-skill".to_string(),
|
||||
apps: SkillApps {
|
||||
claude: false,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: true,
|
||||
..Default::default()
|
||||
},
|
||||
}],
|
||||
)
|
||||
@@ -103,12 +101,7 @@ fn sync_to_app_removes_disabled_and_orphaned_ssot_symlinks() {
|
||||
repo_name: None,
|
||||
repo_branch: None,
|
||||
readme_url: None,
|
||||
apps: SkillApps {
|
||||
claude: false,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
},
|
||||
apps: SkillApps::default(),
|
||||
installed_at: 0,
|
||||
content_hash: None,
|
||||
updated_at: 0,
|
||||
@@ -151,9 +144,7 @@ fn uninstall_skill_creates_backup_before_removing_ssot() {
|
||||
readme_url: None,
|
||||
apps: SkillApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
..Default::default()
|
||||
},
|
||||
installed_at: 123,
|
||||
content_hash: None,
|
||||
@@ -221,9 +212,7 @@ fn restore_skill_backup_restores_files_to_ssot_and_current_app() {
|
||||
readme_url: None,
|
||||
apps: SkillApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
..Default::default()
|
||||
},
|
||||
installed_at: 456,
|
||||
content_hash: None,
|
||||
@@ -304,9 +293,7 @@ fn delete_skill_backup_removes_backup_directory() {
|
||||
readme_url: None,
|
||||
apps: SkillApps {
|
||||
claude: true,
|
||||
codex: false,
|
||||
gemini: false,
|
||||
opencode: false,
|
||||
..Default::default()
|
||||
},
|
||||
installed_at: 789,
|
||||
content_hash: None,
|
||||
|
||||
+138
-20
@@ -14,6 +14,7 @@ import {
|
||||
Minimize2,
|
||||
X,
|
||||
Book,
|
||||
Brain,
|
||||
Wrench,
|
||||
RefreshCw,
|
||||
History,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
KeyRound,
|
||||
Shield,
|
||||
Cpu,
|
||||
LayoutDashboard,
|
||||
} from "lucide-react";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import type { Provider, VisibleApps } from "@/types";
|
||||
@@ -39,6 +41,12 @@ import {
|
||||
import { checkAllEnvConflicts, checkEnvConflicts } from "@/lib/api/env";
|
||||
import { useProviderActions } from "@/hooks/useProviderActions";
|
||||
import { openclawKeys, useOpenClawHealth } from "@/hooks/useOpenClaw";
|
||||
import {
|
||||
hermesKeys,
|
||||
useHermesHealth,
|
||||
useOpenHermesWebUI,
|
||||
} from "@/hooks/useHermes";
|
||||
import { hermesApi } from "@/lib/api/hermes";
|
||||
import { useProxyStatus } from "@/hooks/useProxyStatus";
|
||||
import { useAutoCompact } from "@/hooks/useAutoCompact";
|
||||
import { useLastValidValue } from "@/hooks/useLastValidValue";
|
||||
@@ -82,6 +90,8 @@ import EnvPanel from "@/components/openclaw/EnvPanel";
|
||||
import ToolsPanel from "@/components/openclaw/ToolsPanel";
|
||||
import AgentsDefaultsPanel from "@/components/openclaw/AgentsDefaultsPanel";
|
||||
import OpenClawHealthBanner from "@/components/openclaw/OpenClawHealthBanner";
|
||||
import HermesHealthBanner from "@/components/hermes/HermesHealthBanner";
|
||||
import HermesMemoryPanel from "@/components/hermes/HermesMemoryPanel";
|
||||
|
||||
type View =
|
||||
| "providers"
|
||||
@@ -96,7 +106,8 @@ type View =
|
||||
| "workspace"
|
||||
| "openclawEnv"
|
||||
| "openclawTools"
|
||||
| "openclawAgents";
|
||||
| "openclawAgents"
|
||||
| "hermesMemory";
|
||||
|
||||
interface WebDavSyncStatusUpdatedPayload {
|
||||
source?: string;
|
||||
@@ -114,6 +125,7 @@ const VALID_APPS: AppId[] = [
|
||||
"gemini",
|
||||
"opencode",
|
||||
"openclaw",
|
||||
"hermes",
|
||||
];
|
||||
|
||||
const getInitialApp = (): AppId => {
|
||||
@@ -139,6 +151,7 @@ const VALID_VIEWS: View[] = [
|
||||
"openclawEnv",
|
||||
"openclawTools",
|
||||
"openclawAgents",
|
||||
"hermesMemory",
|
||||
];
|
||||
|
||||
const getInitialView = (): View => {
|
||||
@@ -174,6 +187,7 @@ function App() {
|
||||
gemini: true,
|
||||
opencode: true,
|
||||
openclaw: true,
|
||||
hermes: true,
|
||||
};
|
||||
|
||||
const getFirstVisibleApp = (): AppId => {
|
||||
@@ -182,6 +196,7 @@ function App() {
|
||||
if (visibleApps.gemini) return "gemini";
|
||||
if (visibleApps.opencode) return "opencode";
|
||||
if (visibleApps.openclaw) return "openclaw";
|
||||
if (visibleApps.hermes) return "hermes";
|
||||
return "claude"; // fallback
|
||||
};
|
||||
|
||||
@@ -199,7 +214,8 @@ function App() {
|
||||
activeApp !== "codex" &&
|
||||
activeApp !== "opencode" &&
|
||||
activeApp !== "openclaw" &&
|
||||
activeApp !== "gemini"
|
||||
activeApp !== "gemini" &&
|
||||
activeApp !== "hermes"
|
||||
) {
|
||||
setCurrentView("providers");
|
||||
}
|
||||
@@ -255,13 +271,16 @@ function App() {
|
||||
currentView === "openclawAgents");
|
||||
const { data: openclawHealthWarnings = [] } =
|
||||
useOpenClawHealth(isOpenClawView);
|
||||
const isHermesView = activeApp === "hermes" && currentView === "providers";
|
||||
const { data: hermesHealthWarnings = [] } = useHermesHealth(isHermesView);
|
||||
const hasSkillsSupport = true;
|
||||
const hasSessionSupport =
|
||||
activeApp === "claude" ||
|
||||
activeApp === "codex" ||
|
||||
activeApp === "opencode" ||
|
||||
activeApp === "openclaw" ||
|
||||
activeApp === "gemini";
|
||||
activeApp === "gemini" ||
|
||||
activeApp === "hermes";
|
||||
|
||||
const {
|
||||
addProvider,
|
||||
@@ -610,6 +629,11 @@ function App() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
const [launchDashboardOpen, setLaunchDashboardOpen] = useState(false);
|
||||
const openHermesWebUI = useOpenHermesWebUI(() =>
|
||||
setLaunchDashboardOpen(true),
|
||||
);
|
||||
|
||||
const handleOpenWebsite = async (url: string) => {
|
||||
try {
|
||||
await settingsApi.openExternal(url);
|
||||
@@ -654,6 +678,13 @@ function App() {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: openclawKeys.health,
|
||||
});
|
||||
} else if (activeApp === "hermes") {
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: hermesKeys.liveProviderIds,
|
||||
});
|
||||
await queryClient.invalidateQueries({
|
||||
queryKey: hermesKeys.health,
|
||||
});
|
||||
}
|
||||
toast.success(
|
||||
t("notifications.removeFromConfigSuccess", {
|
||||
@@ -704,7 +735,11 @@ function App() {
|
||||
iconColor: provider.iconColor,
|
||||
};
|
||||
|
||||
if (activeApp === "opencode" || activeApp === "openclaw") {
|
||||
if (
|
||||
activeApp === "opencode" ||
|
||||
activeApp === "openclaw" ||
|
||||
activeApp === "hermes"
|
||||
) {
|
||||
let liveProviderIds: string[] = [];
|
||||
try {
|
||||
liveProviderIds =
|
||||
@@ -713,10 +748,15 @@ function App() {
|
||||
queryKey: ["opencodeLiveProviderIds"],
|
||||
queryFn: () => providersApi.getOpenCodeLiveProviderIds(),
|
||||
})
|
||||
: await queryClient.ensureQueryData({
|
||||
queryKey: openclawKeys.liveProviderIds,
|
||||
queryFn: () => providersApi.getOpenClawLiveProviderIds(),
|
||||
});
|
||||
: activeApp === "openclaw"
|
||||
? await queryClient.ensureQueryData({
|
||||
queryKey: openclawKeys.liveProviderIds,
|
||||
queryFn: () => providersApi.getOpenClawLiveProviderIds(),
|
||||
})
|
||||
: await queryClient.ensureQueryData({
|
||||
queryKey: hermesKeys.liveProviderIds,
|
||||
queryFn: () => providersApi.getHermesLiveProviderIds(),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"[App] Failed to load live provider IDs for duplication",
|
||||
@@ -877,6 +917,8 @@ function App() {
|
||||
appId={activeApp}
|
||||
/>
|
||||
);
|
||||
case "hermesMemory":
|
||||
return <HermesMemoryPanel />;
|
||||
case "skills":
|
||||
return (
|
||||
<UnifiedSkillsPanel
|
||||
@@ -951,7 +993,9 @@ function App() {
|
||||
setConfirmAction({ provider, action: "delete" })
|
||||
}
|
||||
onRemoveFromConfig={
|
||||
activeApp === "opencode" || activeApp === "openclaw"
|
||||
activeApp === "opencode" ||
|
||||
activeApp === "openclaw" ||
|
||||
activeApp === "hermes"
|
||||
? (provider) =>
|
||||
setConfirmAction({ provider, action: "remove" })
|
||||
: undefined
|
||||
@@ -972,7 +1016,11 @@ function App() {
|
||||
}
|
||||
onCreate={() => setIsAddOpen(true)}
|
||||
onSetAsDefault={
|
||||
activeApp === "openclaw" ? setAsDefaultModel : undefined
|
||||
activeApp === "openclaw"
|
||||
? setAsDefaultModel
|
||||
: activeApp === "hermes"
|
||||
? switchProvider
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</motion.div>
|
||||
@@ -1133,6 +1181,7 @@ function App() {
|
||||
{currentView === "openclawTools" && t("openclaw.tools.title")}
|
||||
{currentView === "openclawAgents" &&
|
||||
t("openclaw.agents.title")}
|
||||
{currentView === "hermesMemory" && t("hermes.memory.title")}
|
||||
</h1>
|
||||
</div>
|
||||
) : (
|
||||
@@ -1193,7 +1242,8 @@ function App() {
|
||||
<div className="flex flex-1 min-w-0 items-center justify-end gap-1.5">
|
||||
{currentView === "providers" &&
|
||||
activeApp !== "opencode" &&
|
||||
activeApp !== "openclaw" && (
|
||||
activeApp !== "openclaw" &&
|
||||
activeApp !== "hermes" && (
|
||||
<div
|
||||
className="flex shrink-0 items-center gap-1.5"
|
||||
style={{ WebkitAppRegion: "no-drag" } as any}
|
||||
@@ -1328,7 +1378,11 @@ function App() {
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={
|
||||
activeApp === "openclaw" ? "openclaw" : "default"
|
||||
activeApp === "openclaw"
|
||||
? "openclaw"
|
||||
: activeApp === "hermes"
|
||||
? "hermes"
|
||||
: "default"
|
||||
}
|
||||
className="flex items-center gap-1"
|
||||
initial={{ opacity: 0 }}
|
||||
@@ -1336,13 +1390,52 @@ function App() {
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
{activeApp === "openclaw" ? (
|
||||
{activeApp === "hermes" ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("skills")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("skills.manage")}
|
||||
>
|
||||
<Wrench className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("hermesMemory")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("hermes.memory.title")}
|
||||
>
|
||||
<Brain className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => void openHermesWebUI()}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("hermes.webui.open")}
|
||||
>
|
||||
<LayoutDashboard className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("mcp")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("mcp.title")}
|
||||
>
|
||||
<McpIcon size={16} />
|
||||
</Button>
|
||||
</>
|
||||
) : activeApp === "openclaw" ? (
|
||||
<>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("workspace")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("workspace.manage")}
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
@@ -1351,7 +1444,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("openclawEnv")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("openclaw.env.title")}
|
||||
>
|
||||
<KeyRound className="w-4 h-4" />
|
||||
@@ -1360,7 +1453,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("openclawTools")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("openclaw.tools.title")}
|
||||
>
|
||||
<Shield className="w-4 h-4" />
|
||||
@@ -1369,7 +1462,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("openclawAgents")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("openclaw.agents.title")}
|
||||
>
|
||||
<Cpu className="w-4 h-4" />
|
||||
@@ -1378,7 +1471,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("sessions")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("sessionManager.title")}
|
||||
>
|
||||
<History className="w-4 h-4" />
|
||||
@@ -1405,7 +1498,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("prompts")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("prompts.manage")}
|
||||
>
|
||||
<Book className="w-4 h-4" />
|
||||
@@ -1429,7 +1522,7 @@ function App() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setCurrentView("mcp")}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5"
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-black/5 dark:hover:bg-white/5 w-8 px-2"
|
||||
title={t("mcp.title")}
|
||||
>
|
||||
<McpIcon size={16} />
|
||||
@@ -1459,6 +1552,9 @@ function App() {
|
||||
{isOpenClawView && openclawHealthWarnings.length > 0 && (
|
||||
<OpenClawHealthBanner warnings={openclawHealthWarnings} />
|
||||
)}
|
||||
{isHermesView && hermesHealthWarnings.length > 0 && (
|
||||
<HermesHealthBanner warnings={hermesHealthWarnings} />
|
||||
)}
|
||||
{renderContent()}
|
||||
</main>
|
||||
|
||||
@@ -1519,6 +1615,28 @@ function App() {
|
||||
onCancel={() => setConfirmAction(null)}
|
||||
/>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={launchDashboardOpen}
|
||||
title={t("hermes.webui.launchConfirmTitle")}
|
||||
message={t("hermes.webui.launchConfirmMessage")}
|
||||
confirmText={t("hermes.webui.launchConfirmAction")}
|
||||
variant="info"
|
||||
onConfirm={() => {
|
||||
setLaunchDashboardOpen(false);
|
||||
void (async () => {
|
||||
try {
|
||||
await hermesApi.launchDashboard();
|
||||
toast.success(t("hermes.webui.launching"));
|
||||
} catch (error) {
|
||||
toast.error(t("hermes.webui.launchFailed"), {
|
||||
description: extractErrorMessage(error) || undefined,
|
||||
});
|
||||
}
|
||||
})();
|
||||
}}
|
||||
onCancel={() => setLaunchDashboardOpen(false)}
|
||||
/>
|
||||
|
||||
<DeepLinkImportDialog />
|
||||
<FirstRunNoticeDialog />
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,14 @@ interface AppSwitcherProps {
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
const ALL_APPS: AppId[] = ["claude", "codex", "gemini", "opencode", "openclaw"];
|
||||
const ALL_APPS: AppId[] = [
|
||||
"claude",
|
||||
"codex",
|
||||
"gemini",
|
||||
"opencode",
|
||||
"openclaw",
|
||||
"hermes",
|
||||
];
|
||||
const STORAGE_KEY = "cc-switch-last-app";
|
||||
|
||||
export function AppSwitcher({
|
||||
@@ -31,6 +38,7 @@ export function AppSwitcher({
|
||||
gemini: "gemini",
|
||||
opencode: "opencode",
|
||||
openclaw: "openclaw",
|
||||
hermes: "hermes",
|
||||
};
|
||||
const appDisplayName: Record<AppId, string> = {
|
||||
claude: "Claude",
|
||||
@@ -38,6 +46,7 @@ export function AppSwitcher({
|
||||
gemini: "Gemini",
|
||||
opencode: "OpenCode",
|
||||
openclaw: "OpenClaw",
|
||||
hermes: "Hermes",
|
||||
};
|
||||
|
||||
// Filter apps based on visibility settings (default all visible)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user