mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 12:44:18 +08:00
Compare commits
70 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 955ea26da9 | |||
| 5beb63e67d | |||
| fa17194d84 | |||
| f1118d370f | |||
| 4f5250fc4d | |||
| 5c36ae066b | |||
| f59fab6c24 | |||
| 6940a4b208 | |||
| ea6123adf7 | |||
| e96eab5278 | |||
| 2985ad2c14 | |||
| aa09c9cb62 | |||
| 27c41f7416 | |||
| 6716a4c408 | |||
| 2626eeebe6 | |||
| ab6266f745 | |||
| 1392ef6238 | |||
| 3cd9a0dec5 | |||
| 8e0e9ac319 | |||
| bda625a4f1 | |||
| 473f21971d | |||
| 03a9296c1f | |||
| 8e7d167ace | |||
| dadefdee77 | |||
| ad030da3b1 | |||
| 8047f95416 | |||
| 0527002cca | |||
| 2a24da517f | |||
| ea95f39adf | |||
| f5acef32fd | |||
| 084857ce25 | |||
| 6692343d1e | |||
| 33eafbad51 | |||
| c2337d6857 | |||
| ce538265cb | |||
| e458e77e30 | |||
| ae90b53454 | |||
| e891f5c876 | |||
| 73073454cd | |||
| 7811383b59 | |||
| c1dff06625 | |||
| 43ae1e5f2c | |||
| b4f262c7bd | |||
| 693c3872f0 | |||
| c67494bafc | |||
| 256b04999c | |||
| 25951d8132 | |||
| d66030bee6 | |||
| 5968336364 | |||
| b7499fc871 | |||
| aeaa016cae | |||
| 2a131a5572 | |||
| a04e72a267 | |||
| ce993baefa | |||
| d5328e5290 | |||
| 0fbba4267c | |||
| 8bf1660237 | |||
| afa09e127e | |||
| 0960fd7179 | |||
| 5ef72a2030 | |||
| e02a2763c2 | |||
| c9cadd6e09 | |||
| 60a9b330e5 | |||
| f4e2c28a2b | |||
| 0e6f2b395f | |||
| 41433cfab2 | |||
| 3f59ab3746 | |||
| ee69c83687 | |||
| 2683af57cb | |||
| 8f83fa2063 |
+91
-1
@@ -5,7 +5,97 @@ 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).
|
||||
|
||||
## [Unreleased]
|
||||
## [3.16.2] - 2026-06-07
|
||||
|
||||
Development since v3.16.1 focuses on broadening data portability and usage observability — S3-compatible cloud sync, OpenCode session usage import, and an opt-in official-subscription quota template — while hardening Codex Chat Completions routing (stream truncation, `tool_choice` / custom-tool / reasoning-token edge cases, file and audio attachments, and a Codex CLI models endpoint), strengthening proxy robustness (ephemeral ports, takeover/placeholder restore, system-message normalization, clearer upstream errors, and a text-only image fallback), fixing coding-plan quota lookups (Zhipu, MiniMax) and several Windows/macOS issues, adding the CherryIN and ZenMux providers, and refreshing the user manual.
|
||||
|
||||
**Stats**: 41 commits | 132 files changed | +11,116 insertions | -1,636 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **S3-Compatible Cloud Sync**: Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, using hand-rolled AWS Signature V4 signing for broad compatibility. The settings panel offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, and Huawei OBS plus a custom endpoint, with connection testing, manual upload/download, and auto-sync on configuration changes (provider, endpoint, MCP, prompt, skill, settings, and proxy tables — not high-frequency data like usage logs); enabling S3 sync disables active WebDAV sync and vice versa (#1351).
|
||||
- **OpenCode Session Usage Sync**: Added OpenCode as a usage-statistics source that imports per-message token, cost, and model data from OpenCode's local SQLite database, with a new "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check accounts for the WAL file so newly written sessions are not skipped (#3215).
|
||||
- **Official Subscription Quota Template**: Added an explicit, opt-in "official subscription" usage template for Claude, Codex, and Gemini official providers that queries plan quota via CLI/OAuth credentials, replacing the previous implicit auto-query. It is disabled by default and enabled from the usage-script modal with a configurable refresh interval.
|
||||
- **Unsupported Image Fallback Rectifier**: Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` marker when the routed model is text-only (declared, or detected via a built-in model-name heuristic) or when the upstream rejects image input, so conversations are not interrupted. A new Settings toggle controls the fallback, with a separate toggle for the heuristic detection.
|
||||
- **ZenMux Token Plan Provider**: Added ZenMux as a Token Plan coding-plan provider that accepts a manually entered API key and base URL in the usage-script modal and renders its quota with USD-denominated used / limit values (#2709).
|
||||
- **CherryIN Preset**: Added the CherryIN aggregator gateway as a quick-config preset across all seven supported apps — Anthropic-format endpoint for Claude Code / Claude Desktop / OpenClaw / Hermes, `@ai-sdk/anthropic` for OpenCode, the OpenAI-compatible endpoint for Codex, and the Gemini-compatible endpoint for Gemini CLI — with the official brand icon, placed next to AiHubMix (#3643).
|
||||
- **CCSub Preset**: Added CCSub, a multi-model aggregator partner, as a quick-config preset across six apps — Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes — with the official brand icon and the partner referral link prefilled as the API-key signup URL (`gpt-5.5` for the OpenAI-compatible Codex and OpenCode endpoints).
|
||||
- **Codex CLI Models Endpoint**: The local proxy now answers `GET /v1/models`, which Codex CLI probes at startup, returning the cc-switch-managed Codex model catalog. A stale-catalog guard parses the live `config.toml` and only serves the catalog when `model_catalog_json` still references the cc-switch-owned file, so a leftover catalog from a previous provider is not advertised (#3818).
|
||||
- **Codex Chat File and Audio Attachments**: The Codex Responses-to-Chat converter now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Usage Dashboard Hero Redesign**: Restructured the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
|
||||
- **SSSAiCode Endpoint Refresh**: Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain and refreshed its endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all seven app presets.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Codex Chat Truncated Stream Detection**: When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer reports it as a normal completion — it finalizes normally only when the stream truly finished, emits an incomplete (`max_output_tokens`) response when partial output was produced, and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also attached to still-active streamed tool calls.
|
||||
- **Codex Chat `tool_choice` Without Tools**: The Responses-to-Chat converter now drops `tool_choice` and `parallel_tool_calls` whenever the resulting tools array is absent or empty, so strict OpenAI-compatible upstreams (vLLM, enterprise gateways) no longer reject the request with "When using `tool_choice`, `tools` must be set." (#3640).
|
||||
- **Codex Custom Tool Metadata Over Chat Routing**: Custom Codex tools (such as the freeform `apply_patch` tool) now preserve their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description instead of a generic placeholder, keeping them usable on Chat Completions upstreams (#3644).
|
||||
- **Codex Chat `reasoning_tokens` in Usage**: The Chat-to-Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns it as a non-object, satisfying the Codex CLI's strict requirement and avoiding repeated parse failures and retries (#3514).
|
||||
- **Codex Cross-Turn Reasoning for Custom and Search Tools**: The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, so `apply_patch` and tool-search calls keep their `reasoning_content` when restored via `previous_response_id`.
|
||||
- **Ephemeral Proxy Port Resolution**: When the proxy listens on port 0 (OS-assigned), takeover now starts the proxy first to learn the real port and writes it into the Live configs and database, so client URLs no longer point at a broken `:0` address; the Claude Desktop gateway URL is rejected if no concrete port has been resolved.
|
||||
- **Proxy Placeholder Backup/Restore Loop**: If a previous proxy stop left the proxy placeholders in Live, taking over again no longer overwrites a good backup with the proxy config, and restore no longer writes the placeholder back to Live — both paths detect the placeholder state and rebuild Live from the current provider, fixing cases where the proxy toggle became a no-op and clients stayed pinned to the local proxy (#3689).
|
||||
- **Official Provider Block Under Proxy Takeover**: While Local Routing takeover is active, only providers explicitly categorized as official are blocked from switching, instead of also disabling custom providers whose endpoint lives in metadata or whose fields are unfilled. The disabled Enable button now shows a lighter hint tooltip in place of the red "Blocked" badge.
|
||||
- **Localhost Listen Address Normalization**: Saving the proxy with a listen address of `localhost` now normalizes it to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
|
||||
- **Anthropic System Message Normalization**: For Anthropic-format providers, system-role entries inside the `messages` array are collapsed and merged into the top-level `system` field (preserving order and any existing top-level system), preventing strict upstreams from rejecting non-leading system messages; OpenAI Chat routing is untouched (#3775).
|
||||
- **Claude Desktop 1M-Context Model Routing**: Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route lookup so exact, alias, legacy, and role-keyword matching resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M-capable model mid-conversation.
|
||||
- **Codex 413 Error Clarity**: When a Codex upstream gateway rejects an oversized request with HTTP 413, the proxy now returns a dedicated message identifying it as the provider's server-side body-size limit (not a CC Switch limit) with recovery steps (run `/compact`, drop large logs or inline images, or ask the provider to raise its limit), instead of echoing the raw upstream HTML page.
|
||||
- **Proxy Panel Error Detail**: When toggling proxy takeover fails, the proxy panel toast now includes the underlying backend error detail instead of only a generic failure message (#3656).
|
||||
- **Copilot Infinite-Whitespace Threshold**: Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, so legitimate tool calls with deeply indented code arguments are no longer falsely aborted while still catching the real Copilot infinite-whitespace bug (#2647).
|
||||
- **Subscription Tier Tray Rendering**: Fixed tray and quota rendering for official subscription tiers via a unified tier-to-label mapping: Claude/Codex no longer drop the seven-day window, Gemini Pro/Flash/Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now display the worst utilization instead of the first match.
|
||||
- **Inflated Claude Stream Input Tokens**: Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion and artificially lowering the displayed cache hit rate. The parser now prefers a smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
|
||||
- **Zhipu Quota Query Endpoint Routing**: The Zhipu coding-plan quota lookup was hard-coded to `api.z.ai`, so users on the mainland China preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
|
||||
- **MiniMax Balance API and Pricing**: Adapted MiniMax coding-plan quota to its new balance API (which returns remaining-percent fields instead of usage counts that broke the old parser and left the tray blank), filtered out non-coding models (e.g. video), handled plans without a weekly limit, and seeded default pricing for MiniMax M3 (#3518).
|
||||
- **GLM Coding Plan Endpoints and Model Fetch**: Corrected the ZhiPu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints across Codex, OpenCode, OpenClaw, and Hermes, and taught the model-list probe to query `{base}/models` for base URLs that already end in a `/v{N}` segment (keeping `/v1/models` as a fallback), so the Fetch Models button no longer 404s on versioned endpoints (#3524).
|
||||
- **Codex Model Catalog Path Portability**: Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
|
||||
- **APINebula OpenCode SDK**: The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects rather than the Responses API.
|
||||
- **Windows Tray Icon Residue on Exit**: Quitting CC Switch on Windows could leave a dead tray icon until hovered; the app now removes the tray icon before exiting so it disappears cleanly (#3797).
|
||||
- **Windows Taskbar Icon**: Set an explicit Windows AppUserModelID at runtime and stamped the installer's desktop and start-menu shortcuts with the same ID and product icon, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
|
||||
- **Windows Subdirectory Skill Updates**: Normalized backslash path separators to forward slashes when scanning installed skills on Windows, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
|
||||
- **macOS Input Auto-Capitalization**: Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
|
||||
- **Codex VS Code Session Previews**: Codex session previews for requests sent from VS Code could show selection or open-file content instead of the prompt when a markdown heading preceded the injected request. Both the backend title and frontend preview now match the last "## My request for Codex:" heading (the IDE injects the real request as the final section) (#3593).
|
||||
- **VS Code Wording in Chinese UI**: Corrected the "Apply to Claude Code plugin" description in the Simplified and Traditional Chinese locales to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
|
||||
|
||||
### Docs
|
||||
|
||||
- **User Manual Refresh**: Refreshed the README locales and the en / zh / ja user manuals to reflect all seven supported apps (adding Claude Desktop and Hermes), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes configuration files, updated the language docs to four languages, revised per-app MCP / Prompts / Skills availability, noted that export produces a timestamped SQL backup including usage logs, and documented the pricing model-ID matching rules (#3411).
|
||||
- **Codex Official Auth Preservation Guide**: Added a trilingual (en / zh / ja) guide explaining how to keep Codex official remote control and plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
|
||||
- **README Release-Note Links and Sponsor Markup**: Updated the Release Notes links in all README locales to point at v3.16.1 and fixed broken smart-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
|
||||
|
||||
## [3.16.1] - 2026-06-01
|
||||
|
||||
Development since v3.16.0 focuses on hardening Codex provider switching and Local Routing takeover: preserving official OAuth auth and model catalogs across normal switches, hot-switches, backup restore, and edit flows; restoring Codex Chat tool/plugin compatibility over Chat Completions upstreams; improving Codex proxy diagnostics and CLI discovery; and documenting DeepSeek routing.
|
||||
|
||||
**Stats**: 23 commits | 62 files changed | +5,603 insertions | -1,113 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **Codex Official Auth Preservation Setting**: Added an opt-in setting that keeps the official ChatGPT / Codex OAuth login in `auth.json` when switching third-party Codex providers, while moving third-party provider tokens into `config.toml` when enabled.
|
||||
- **Codex DeepSeek Routing Guides**: Added localized DeepSeek routing guides for Codex in English, Chinese, and Japanese, with screenshots covering provider routing requirements, Codex provider setup, and Local Routing takeover.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Codex Auth Preservation Is Opt-In**: The new official-auth preservation setting now defaults to off, so third-party Codex switches keep the legacy behavior of writing the active provider auth unless users explicitly enable preservation.
|
||||
- **Codex Provider Switch Restart Hint**: Successful Codex provider switches now tell users to restart the Codex client so catalog and config changes take effect.
|
||||
- **Codex Proxy Takeover Switching Is Serialized**: Provider switches and takeover toggles now share a per-app lock and use backup / live placeholder ownership signals instead of lagging `enabled` or server-running flags, preventing normal live writes from racing a just-activated or temporarily stopped takeover.
|
||||
- **Codex Takeover Hot-Switch Display Refresh**: Hot-switching a Codex provider while Local Routing owns Live now refreshes the proxy-safe live provider id, model, and display name while keeping endpoints pointed at the local proxy.
|
||||
- **Sponsor Ordering**: Swapped the Shengsuanyun and AICodeMirror sponsor blocks across README locales.
|
||||
- **Docs Organization**: Moved the Chinese proxy guide under `docs/guides/` and removed the obsolete working-directory plan document.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Codex Provider Edit Dialog Under Takeover**: The Codex provider edit form now shows an explicit notice and storage-aware auth / config hints clarifying that it displays the stored provider config (not the proxy-managed live `auth.json` / `config.toml`), so the official OAuth token is no longer mistaken as lost while takeover is active. The dialog also treats takeover as active regardless of whether the proxy server is currently running.
|
||||
- **Codex OAuth Auth During Proxy Takeover**: Fixed multiple preserve-mode takeover paths that could clear or overwrite the official ChatGPT / Codex OAuth `auth.json`. Takeover detection now recognizes `PROXY_MANAGED` in `config.toml`, cleanup only removes placeholder bearer tokens, config-only takeover writes are used consistently, and mis-categorized third-party providers no longer trigger the official-provider auth overwrite path. Provider sync and switching now treat the restore backup and live placeholders as the takeover-ownership signal (instead of the lagging `enabled` / proxy-running flags) and serialize switch/takeover per app, so a just-activated or proxy-stopped takeover can no longer be overwritten by a normal live write.
|
||||
- **Codex Model Catalog Data Loss**: Fixed cases where Codex `modelCatalog` could be wiped by live-config backfill, active-provider edit dialogs, provider switches, or proxy takeover-off restore. Snapshot backups now keep existing `model_catalog_json` pointers, provider-rebuilt backups regenerate the catalog projection from the database source of truth, active edit dialogs prefer the DB catalog over lossy Live reconstruction, and provider switches always refresh the generated catalog JSON.
|
||||
- **Codex Chat Tools Over Chat Completions Routing**: Restored Codex `tool_search`, loaded namespace tools, custom tools, and tool outputs when third-party Codex providers are routed through Chat Completions. Non-streaming and streaming Chat responses now map back to the right Responses item types, including native `response.custom_tool_call_input.*` events for custom-tool streaming.
|
||||
- **Codex Proxy Error Diagnostics**: Codex forwarding failures now return richer JSON errors with provider, model, endpoint, upstream status, stable `cc_switch_*` codes, and HTTP statuses aligned with the canonical `ProxyError` response mapping.
|
||||
- **Codex Native Balance / Coding-Plan Queries**: Fixed native usage and plan lookups so each app resolves the correct provider credentials instead of leaking assumptions from another app surface.
|
||||
- **Codex CLI Discovery and Catalog Projection**: Fixed third-party Codex catalog projection that could fail when the Codex CLI was not reachable through one narrow PATH lookup, by adding multi-platform CLI discovery plus a bundled GPT-5.5 model-catalog template fallback.
|
||||
- **Claude Desktop Official Provider Creation**: Fixed adding the Claude Desktop Official provider when the official category/config path was selected.
|
||||
- **Anthropic Tool Thinking History for Kimi / Moonshot**: Added Kimi and Moonshot to the Anthropic-compatible tool-thinking history normalizer so later turns can replay reasoning and tool-call context correctly.
|
||||
- **Windows Tool Version Probing**: Fixed Windows version checks that could misquote `.cmd` / `.bat` commands and decode localized command output as mojibake, causing working tools to appear as "installed but not runnable".
|
||||
|
||||
## [3.16.0] - 2026-05-29
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
# CC Switch
|
||||
|
||||
### The All-in-One Manager for Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
|
||||
### The All-in-One Manager for Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
@@ -43,17 +43,17 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
|
||||
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for CC Switch users: if you register via <a href="https://aigocode.com/invite/CC-SWITCH">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>Thanks to Shengsuanyun for sponsoring this project! Shengsuanyun is a super factory serving AI Native Teams — an industrial-grade AI task parallel execution platform. Its model marketplace aggregates Claude, ChatGPT, Gemini, and other domestic and international LLM and multimedia model capabilities with direct supply. Absolutely no reverse engineering or dilution — platform-wide model SLA availability reaches 99.7%, with <a href="https://watch.shengsuanyun.com/status/shengsuanyun">monitoring dashboards</a> showing green across the board. It also offers enterprise-grade custom gateways for fine-grained team cost and permission management, smart routing, security protection, and BYOK (Bring Your Own Key) hosting. The platform charges on a pay-per-use and tokens plan (coming soon) basis, with invoicing available. Register via <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">this link</a> as a new user to receive ¥10 in credits plus a 10% bonus on your first top-up.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
|
||||
<td>Thanks to AICodeMirror for sponsoring this project! AICodeMirror provides official high-stability relay services for Claude Code / Codex / Gemini CLI, with enterprise-grade concurrency, fast invoicing, and 24/7 dedicated technical support.
|
||||
Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original price, with extra discounts on top-ups! AICodeMirror offers special benefits for CC Switch users: register via <a href="https://www.aicodemirror.com/register?invitecode=9915W3">this link</a> to enjoy 20% off your first top-up, and enterprise customers can get up to 25% off!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>Thanks to Shengsuanyun for sponsoring this project! Shengsuanyun is a super factory serving AI Native Teams — an industrial-grade AI task parallel execution platform. Its model marketplace aggregates Claude, ChatGPT, Gemini, and other domestic and international LLM and multimedia model capabilities with direct supply. Absolutely no reverse engineering or dilution — platform-wide model SLA availability reaches 99.7%, with <a href="https://watch.shengsuanyun.com/status/shengsuanyun">monitoring dashboards</a> showing green across the board. It also offers enterprise-grade custom gateways for fine-grained team cost and permission management, smart routing, security protection, and BYOK (Bring Your Own Key) hosting. The platform charges on a pay-per-use and tokens plan (coming soon) basis, with invoicing available. Register via <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">this link</a> as a new user to receive ¥10 in credits plus a 10% bonus on your first top-up.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
|
||||
<td>Thanks to PatewayAI for sponsoring this project! PatewayAI is an API relay service provider built for heavy AI developers, focused on directly relaying official high-quality model APIs. It offers the full Claude lineup and the Codex series, 100% sourced from official channels — no dilution, no fakes, verification welcome. Billing is transparent and every token-level invoice can be audited line by line.
|
||||
@@ -146,19 +146,24 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
|
||||
<td>Atlas Cloud is a full-modal AI inference platform that gives developers a single AI API to access video generation, image generation, and LLM APIs. Instead of managing multiple vendor integrations, you connect once and get unified access to 300+ curated models across all modalities. Check out Atlas Cloud's new <a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">coding plan</a> promotion for more budget-friendly API access!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td>Thanks to CCSub for sponsoring this project! CCSub is a stable, affordable AI API relay platform — your drop-in replacement for a Claude.ai subscription. One API key gives you access to Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini, and DeepSeek at roughly 30% of direct API cost, with no VPN required from anywhere in the world. Compatible with Claude Code, Codex, Cursor, Cline, Continue, Windsurf, and all major AI coding tools. Register via <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">this link</a> and get $5 free credit on sign-up.</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## Why CC Switch?
|
||||
|
||||
Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI, OpenCode, and OpenClaw — but each has its own configuration format. Switching API providers means manually editing JSON, TOML, or `.env` files, and there is no unified way to manage MCP and Skills across multiple tools.
|
||||
Modern AI-powered coding relies on tools like Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, and Hermes — but each has its own configuration format. Switching API providers means manually editing JSON, TOML, or `.env` files, and there is no unified way to manage MCP and Skills across multiple tools.
|
||||
|
||||
**CC Switch** gives you a single desktop app to manage all five CLI tools. Instead of editing config files by hand, you get a visual interface to import providers with one click, switch between them instantly, with 50+ built-in provider presets, unified MCP and Skills management, and system tray quick switching — all backed by a reliable SQLite database with atomic writes that protect your configs from corruption.
|
||||
**CC Switch** gives you a single desktop app to manage all supported AI tools. Instead of editing config files by hand, you get a visual interface to import providers with one click, switch between them instantly, with 50+ built-in provider presets, unified MCP and Skills management, and system tray quick switching — all backed by a reliable SQLite database with atomic writes that protect your configs from corruption.
|
||||
|
||||
- **One App, Five CLI Tools** — Manage Claude Code, Codex, Gemini CLI, OpenCode, and OpenClaw from a single interface
|
||||
- **One App, Seven Tools** — Manage Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, and Hermes from a single interface
|
||||
- **No More Manual Editing** — 50+ provider presets including AWS Bedrock, NVIDIA NIM, and community relays; just pick and switch
|
||||
- **Unified MCP & Skills Management** — One panel to manage MCP servers and Skills across four apps with bidirectional sync
|
||||
- **Unified MCP & Skills Management** — One panel to manage MCP servers and Skills across Claude, Codex, Gemini, OpenCode, and Hermes with bidirectional sync
|
||||
- **System Tray Quick Switch** — Switch providers instantly from the tray menu, no need to open the full app
|
||||
- **Cloud Sync** — Sync provider data across devices via Dropbox, OneDrive, iCloud, or WebDAV servers
|
||||
- **Cross-Platform** — Native desktop app for Windows, macOS, and Linux, built with Tauri 2
|
||||
@@ -172,12 +177,12 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
|
||||
|
||||
## Features
|
||||
|
||||
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.15.0-en.md)
|
||||
[Full Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
|
||||
|
||||
### Provider Management
|
||||
|
||||
- **5 CLI tools, 50+ presets** — Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw; copy your key and import with one click
|
||||
- **Universal providers** — One config syncs to multiple apps (OpenCode, OpenClaw)
|
||||
- **7 supported tools, 50+ presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, Hermes; copy your key and import with one click
|
||||
- **Universal providers** — One config syncs to Claude Code, Codex, and Gemini CLI
|
||||
- One-click switching, system tray quick access, drag-and-drop sorting, import/export
|
||||
|
||||
### Proxy & Failover
|
||||
@@ -187,7 +192,7 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
|
||||
|
||||
### MCP, Prompts & Skills
|
||||
|
||||
- **Unified MCP panel** — Manage MCP servers across 4 apps with bidirectional sync and Deep Link import
|
||||
- **Unified MCP panel** — Manage MCP servers across Claude, Codex, Gemini, OpenCode, and Hermes with bidirectional sync and Deep Link import
|
||||
- **Prompts** — Markdown editor with cross-app sync (CLAUDE.md / AGENTS.md / GEMINI.md) and backfill protection
|
||||
- **Skills** — One-click install from GitHub repos or ZIP files, custom repository management, with symlink and file copy support
|
||||
|
||||
@@ -197,21 +202,21 @@ Modern AI-powered coding relies on CLI tools like Claude Code, Codex, Gemini CLI
|
||||
|
||||
### Session Manager & Workspace
|
||||
|
||||
- Browse, search, and restore conversation history across all apps
|
||||
- Browse, search, and restore conversation history across supported session sources
|
||||
- **Workspace editor** (OpenClaw) — Edit agent files (AGENTS.md, SOUL.md, etc.) with Markdown preview
|
||||
|
||||
### System & Platform
|
||||
|
||||
- **Cloud sync** — Custom config directory (Dropbox, OneDrive, iCloud, NAS) and WebDAV server sync
|
||||
- **Deep Link** (`ccswitch://`) — Import providers, MCP servers, prompts, and skills via URL
|
||||
- Dark / Light / System theme, auto-launch, auto-updater, atomic writes, auto-backups, i18n (zh/en/ja)
|
||||
- Dark / Light / System theme, auto-launch, auto-updater, atomic writes, auto-backups, i18n (zh/zh-TW/en/ja)
|
||||
|
||||
## FAQ
|
||||
|
||||
<details>
|
||||
<summary><strong>Which AI CLI tools does CC Switch support?</strong></summary>
|
||||
<summary><strong>Which AI tools does CC Switch support?</strong></summary>
|
||||
|
||||
CC Switch supports five tools: **Claude Code**, **Codex**, **Gemini CLI**, **OpenCode**, and **OpenClaw**. Each tool has dedicated provider presets and configuration management.
|
||||
CC Switch supports seven tools: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**. Each tool has dedicated provider presets and configuration management.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -280,8 +285,8 @@ For detailed guides on every feature, check out the **[User Manual](docs/user-ma
|
||||
|
||||
- **MCP**: Click the "MCP" button → Add servers via templates or custom config → Toggle per-app sync
|
||||
- **Prompts**: Click "Prompts" → Create presets with Markdown editor → Activate to sync to live files
|
||||
- **Skills**: Click "Skills" → Browse GitHub repos → One-click install to all apps
|
||||
- **Sessions**: Click "Sessions" → Browse, search, and restore conversation history across all apps
|
||||
- **Skills**: Click "Skills" → Browse GitHub repos → One-click install to supported apps
|
||||
- **Sessions**: Click "Sessions" → Browse, search, and restore conversation history across supported session sources
|
||||
|
||||
> **Note**: On first launch, you can manually import existing CLI tool configs as the default provider.
|
||||
|
||||
@@ -372,7 +377,7 @@ Download the latest Linux build from the [Releases](../../releases) page:
|
||||
- **ProviderService**: Provider CRUD, switching, backfill, sorting
|
||||
- **McpService**: MCP server management, import/export, live file sync
|
||||
- **ProxyService**: Local proxy mode with hot-switching and format conversion
|
||||
- **SessionManager**: Conversation history browsing across all supported apps
|
||||
- **SessionManager**: Conversation history browsing across supported session sources
|
||||
- **ConfigService**: Config import/export, backup rotation
|
||||
- **SpeedtestService**: API endpoint latency measurement
|
||||
|
||||
@@ -494,7 +499,7 @@ pnpm test:unit --coverage
|
||||
│ ├── lib/
|
||||
│ │ ├── api/ # Tauri API wrapper (type-safe)
|
||||
│ │ └── query/ # TanStack Query config
|
||||
│ ├── locales/ # Translations (zh/en/ja)
|
||||
│ ├── locales/ # Translations (zh/zh-TW/en/ja)
|
||||
│ ├── config/ # Presets (providers/mcp)
|
||||
│ └── types/ # TypeScript definitions
|
||||
├── src-tauri/ # Backend (Rust)
|
||||
|
||||
+26
-21
@@ -2,7 +2,7 @@
|
||||
|
||||
# CC Switch
|
||||
|
||||
### Der All-in-One-Manager für Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
|
||||
### Der All-in-One-Manager für Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw & Hermes Agent
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
@@ -43,17 +43,17 @@ MiniMax-M2.7 ist ein großes Sprachmodell der nächsten Generation, das auf auto
|
||||
<td>Danke an AIGoCode für die Unterstützung dieses Projekts! AIGoCode ist eine All-in-One-Plattform, die Claude Code, Codex und die neuesten Gemini-Modelle integriert und Ihnen stabile, effiziente und äußerst kostengünstige KI-Coding-Dienste bietet. Die Plattform stellt flexible Abonnementpläne bereit, birgt kein Risiko einer Kontosperrung, ermöglicht Direktzugriff ohne VPN und reagiert blitzschnell. AIGoCode hat ein besonderes Angebot für CC-Switch-Nutzer vorbereitet: Wenn Sie sich über <a href="https://aigocode.com/invite/CC-SWITCH">diesen Link</a> registrieren, erhalten Sie bei Ihrer ersten Aufladung zusätzliche 10 % Bonusguthaben!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>Danke an Shengsuanyun für die Unterstützung dieses Projekts! Shengsuanyun ist eine Superfabrik für KI-native Teams — eine Plattform zur parallelen Ausführung von KI-Aufgaben in industrieller Qualität. Ihr Modellmarktplatz bündelt die Fähigkeiten von Claude, ChatGPT, Gemini und weiteren in- und ausländischen LLM- und Multimedia-Modellen mit Direktbezug. Absolut kein Reverse Engineering und keine Verwässerung — die plattformweite Modell-SLA-Verfügbarkeit erreicht 99,7 %, und die <a href="https://watch.shengsuanyun.com/status/shengsuanyun">Monitoring-Dashboards</a> zeigen durchgehend grün an. Es bietet außerdem unternehmensgerechte, anpassbare Gateways für fein abgestufte Kosten- und Berechtigungsverwaltung im Team, intelligentes Routing, Sicherheitsschutz und BYOK-Hosting (Bring Your Own Key). Die Plattform rechnet nach Nutzung sowie über einen Token-Plan (in Kürze verfügbar) ab, und Rechnungsstellung ist möglich. Registrieren Sie sich über <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">diesen Link</a> als Neukunde und erhalten Sie ein Guthaben von ¥10 sowie 10 % Bonus auf Ihre erste Aufladung.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
|
||||
<td>Danke an AICodeMirror für die Unterstützung dieses Projekts! AICodeMirror stellt offizielle, hochstabile Relay-Dienste für Claude Code / Codex / Gemini CLI bereit, mit unternehmensgerechter Nebenläufigkeit, schneller Rechnungsstellung und rund um die Uhr verfügbarem dediziertem technischem Support.
|
||||
Offizielle Kanäle von Claude Code / Codex / Gemini zu 38 % / 2 % / 9 % des Originalpreises, mit zusätzlichen Rabatten beim Aufladen! AICodeMirror bietet besondere Vorteile für CC-Switch-Nutzer: Registrieren Sie sich über <a href="https://www.aicodemirror.com/register?invitecode=9915W3">diesen Link</a> und erhalten Sie 20 % Rabatt auf Ihre erste Aufladung; Unternehmenskunden erhalten bis zu 25 % Rabatt!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>Danke an Shengsuanyun für die Unterstützung dieses Projekts! Shengsuanyun ist eine Superfabrik für KI-native Teams — eine Plattform zur parallelen Ausführung von KI-Aufgaben in industrieller Qualität. Ihr Modellmarktplatz bündelt die Fähigkeiten von Claude, ChatGPT, Gemini und weiteren in- und ausländischen LLM- und Multimedia-Modellen mit Direktbezug. Absolut kein Reverse Engineering und keine Verwässerung — die plattformweite Modell-SLA-Verfügbarkeit erreicht 99,7 %, und die <a href="https://watch.shengsuanyun.com/status/shengsuanyun">Monitoring-Dashboards</a> zeigen durchgehend grün an. Es bietet außerdem unternehmensgerechte, anpassbare Gateways für fein abgestufte Kosten- und Berechtigungsverwaltung im Team, intelligentes Routing, Sicherheitsschutz und BYOK-Hosting (Bring Your Own Key). Die Plattform rechnet nach Nutzung sowie über einen Token-Plan (in Kürze verfügbar) ab, und Rechnungsstellung ist möglich. Registrieren Sie sich über <a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">diesen Link</a> als Neukunde und erhalten Sie ein Guthaben von ¥10 sowie 10 % Bonus auf Ihre erste Aufladung.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
|
||||
<td>Danke an PatewayAI für die Unterstützung dieses Projekts! PatewayAI ist ein API-Relay-Anbieter für anspruchsvolle KI-Entwickler, der sich auf das direkte Relayen offizieller hochwertiger Modell-APIs konzentriert. Er bietet die komplette Claude-Reihe und die Codex-Serie, zu 100 % aus offiziellen Kanälen bezogen — keine Verwässerung, keine Fälschungen, Überprüfung ausdrücklich erwünscht. Die Abrechnung ist transparent, und jede Rechnung auf Token-Ebene lässt sich Zeile für Zeile prüfen.
|
||||
@@ -146,19 +146,24 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
|
||||
<td>Atlas Cloud ist eine vollmodale KI-Inferenzplattform, die Entwicklern über eine einzige KI-API Zugriff auf Videogenerierung, Bildgenerierung und LLM-APIs bietet. Statt mehrere Anbieterintegrationen zu verwalten, verbinden Sie sich einmal und erhalten einheitlichen Zugriff auf mehr als 300 kuratierte Modelle über alle Modalitäten hinweg. Sehen Sie sich die neue <a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">Coding-Plan</a>-Aktion von Atlas Cloud für kostengünstigeren API-Zugang an!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td>Danke an CCSub für die Unterstützung dieses Projekts! CCSub ist eine zuverlässige und kostengünstige AI-API-Relay-Plattform — Ihr direkter Ersatz für ein Claude.ai-Abonnement. Mit einem einzigen API-Schlüssel erhalten Sie Zugriff auf Claude Opus 4.8, Sonnet, Haiku, GPT-5, Gemini und DeepSeek zu etwa 30 % der Kosten der direkten API-Nutzung — ohne VPN, weltweit nutzbar. Kompatibel mit Claude Code, Codex, Cursor, Cline, Continue, Windsurf und allen gängigen AI-Coding-Tools. Registrieren Sie sich über <a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">diesen Link</a> und erhalten Sie $5 Startguthaben bei der Anmeldung.</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## Warum CC Switch?
|
||||
|
||||
Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude Code, Codex, Gemini CLI, OpenCode und OpenClaw — doch jedes hat sein eigenes Konfigurationsformat. Der Wechsel des API-Anbieters bedeutet, JSON-, TOML- oder `.env`-Dateien von Hand zu bearbeiten, und es gibt keine einheitliche Möglichkeit, MCP und Skills über mehrere Werkzeuge hinweg zu verwalten.
|
||||
Modernes KI-gestütztes Programmieren stützt sich auf Werkzeuge wie Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw und Hermes — doch jedes hat sein eigenes Konfigurationsformat. Der Wechsel des API-Anbieters bedeutet, JSON-, TOML- oder `.env`-Dateien von Hand zu bearbeiten, und es gibt keine einheitliche Möglichkeit, MCP und Skills über mehrere Werkzeuge hinweg zu verwalten.
|
||||
|
||||
**CC Switch** gibt Ihnen eine einzige Desktop-App, um alle fünf CLI-Werkzeuge zu verwalten. Statt Konfigurationsdateien von Hand zu bearbeiten, erhalten Sie eine visuelle Oberfläche, um Anbieter mit einem Klick zu importieren und sofort zwischen ihnen zu wechseln — mit 50+ integrierten Anbieter-Presets, einheitlicher MCP- und Skills-Verwaltung und schnellem Umschalten über das System-Tray. Das Ganze gestützt auf eine zuverlässige SQLite-Datenbank mit atomaren Schreibvorgängen, die Ihre Konfigurationen vor Beschädigung schützen.
|
||||
**CC Switch** gibt Ihnen eine einzige Desktop-App, um alle unterstützten KI-Werkzeuge zu verwalten. Statt Konfigurationsdateien von Hand zu bearbeiten, erhalten Sie eine visuelle Oberfläche, um Anbieter mit einem Klick zu importieren und sofort zwischen ihnen zu wechseln — mit 50+ integrierten Anbieter-Presets, einheitlicher MCP- und Skills-Verwaltung und schnellem Umschalten über das System-Tray. Das Ganze gestützt auf eine zuverlässige SQLite-Datenbank mit atomaren Schreibvorgängen, die Ihre Konfigurationen vor Beschädigung schützen.
|
||||
|
||||
- **Eine App, fünf CLI-Werkzeuge** — Verwalten Sie Claude Code, Codex, Gemini CLI, OpenCode und OpenClaw über eine einzige Oberfläche
|
||||
- **Eine App, sieben Werkzeuge** — Verwalten Sie Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw und Hermes über eine einzige Oberfläche
|
||||
- **Kein manuelles Bearbeiten mehr** — 50+ Anbieter-Presets einschließlich AWS Bedrock, NVIDIA NIM und Community-Relays; einfach auswählen und umschalten
|
||||
- **Einheitliche MCP- & Skills-Verwaltung** — Ein Panel zur Verwaltung von MCP-Servern und Skills über vier Apps hinweg mit bidirektionaler Synchronisierung
|
||||
- **Einheitliche MCP- & Skills-Verwaltung** — Ein Panel zur Verwaltung von MCP-Servern und Skills für Claude, Codex, Gemini, OpenCode und Hermes mit bidirektionaler Synchronisierung
|
||||
- **Schnellumschaltung über System-Tray** — Wechseln Sie Anbieter sofort über das Tray-Menü, ohne die vollständige App öffnen zu müssen
|
||||
- **Cloud-Synchronisierung** — Synchronisieren Sie Anbieterdaten geräteübergreifend über Dropbox, OneDrive, iCloud oder WebDAV-Server
|
||||
- **Plattformübergreifend** — Native Desktop-App für Windows, macOS und Linux, gebaut mit Tauri 2
|
||||
@@ -172,12 +177,12 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
|
||||
|
||||
## Funktionen
|
||||
|
||||
[Vollständiges Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.15.0-en.md)
|
||||
[Vollständiges Changelog](CHANGELOG.md) | [Release Notes](docs/release-notes/v3.16.1-en.md)
|
||||
|
||||
### Anbieterverwaltung
|
||||
|
||||
- **5 CLI-Werkzeuge, 50+ Presets** — Claude Code, Codex, Gemini CLI, OpenCode, OpenClaw; Schlüssel kopieren und mit einem Klick importieren
|
||||
- **Universelle Anbieter** — Eine Konfiguration synchronisiert sich mit mehreren Apps (OpenCode, OpenClaw)
|
||||
- **7 unterstützte Werkzeuge, 50+ Presets** — Claude Code, Claude Desktop, Codex, Gemini CLI, OpenCode, OpenClaw, Hermes; Schlüssel kopieren und mit einem Klick importieren
|
||||
- **Universelle Anbieter** — Eine Konfiguration synchronisiert sich mit Claude Code, Codex und Gemini CLI
|
||||
- Umschaltung mit einem Klick, Schnellzugriff über System-Tray, Sortierung per Drag-and-drop, Import/Export
|
||||
|
||||
### Proxy & Failover
|
||||
@@ -187,7 +192,7 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
|
||||
|
||||
### MCP, Prompts & Skills
|
||||
|
||||
- **Einheitliches MCP-Panel** — Verwalten Sie MCP-Server über 4 Apps hinweg mit bidirektionaler Synchronisierung und Deep-Link-Import
|
||||
- **Einheitliches MCP-Panel** — Verwalten Sie MCP-Server für Claude, Codex, Gemini, OpenCode und Hermes mit bidirektionaler Synchronisierung und Deep-Link-Import
|
||||
- **Prompts** — Markdown-Editor mit App-übergreifender Synchronisierung (CLAUDE.md / AGENTS.md / GEMINI.md) und Backfill-Schutz
|
||||
- **Skills** — Installation mit einem Klick aus GitHub-Repositorys oder ZIP-Dateien, Verwaltung eigener Repositorys, mit Unterstützung für Symlinks und Dateikopien
|
||||
|
||||
@@ -197,21 +202,21 @@ Modernes KI-gestütztes Programmieren stützt sich auf CLI-Werkzeuge wie Claude
|
||||
|
||||
### Session Manager & Workspace
|
||||
|
||||
- Durchsuchen, suchen und stellen Sie den Gesprächsverlauf über alle Apps hinweg wieder her
|
||||
- Gesprächsverlauf aus unterstützten Sitzungsquellen durchsuchen, suchen und wiederherstellen
|
||||
- **Workspace-Editor** (OpenClaw) — Bearbeiten Sie Agent-Dateien (AGENTS.md, SOUL.md usw.) mit Markdown-Vorschau
|
||||
|
||||
### System & Plattform
|
||||
|
||||
- **Cloud-Synchronisierung** — Eigenes Konfigurationsverzeichnis (Dropbox, OneDrive, iCloud, NAS) und WebDAV-Server-Synchronisierung
|
||||
- **Deep Link** (`ccswitch://`) — Importieren Sie Anbieter, MCP-Server, Prompts und Skills per URL
|
||||
- Dunkles / Helles / System-Theme, automatischer Start, automatischer Updater, atomare Schreibvorgänge, automatische Backups, i18n (zh/en/ja)
|
||||
- Dunkles / Helles / System-Theme, automatischer Start, automatischer Updater, atomare Schreibvorgänge, automatische Backups, i18n (zh/zh-TW/en/ja)
|
||||
|
||||
## FAQ
|
||||
|
||||
<details>
|
||||
<summary><strong>Welche KI-CLI-Werkzeuge unterstützt CC Switch?</strong></summary>
|
||||
<summary><strong>Welche KI-Werkzeuge unterstützt CC Switch?</strong></summary>
|
||||
|
||||
CC Switch unterstützt fünf Werkzeuge: **Claude Code**, **Codex**, **Gemini CLI**, **OpenCode** und **OpenClaw**. Jedes Werkzeug verfügt über dedizierte Anbieter-Presets und Konfigurationsverwaltung.
|
||||
CC Switch unterstützt sieben Werkzeuge: **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw** und **Hermes**. Jedes Werkzeug verfügt über dedizierte Anbieter-Presets und Konfigurationsverwaltung.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -280,8 +285,8 @@ Ausführliche Anleitungen zu jeder Funktion finden Sie im **[Benutzerhandbuch](d
|
||||
|
||||
- **MCP**: Klicken Sie auf die Schaltfläche „MCP" → Server über Vorlagen oder eigene Konfiguration hinzufügen → Synchronisierung pro App umschalten
|
||||
- **Prompts**: Klicken Sie auf „Prompts" → Presets mit dem Markdown-Editor erstellen → Aktivieren, um mit den Live-Dateien zu synchronisieren
|
||||
- **Skills**: Klicken Sie auf „Skills" → GitHub-Repositorys durchsuchen → mit einem Klick in allen Apps installieren
|
||||
- **Sessions**: Klicken Sie auf „Sessions" → Gesprächsverlauf über alle Apps hinweg durchsuchen, suchen und wiederherstellen
|
||||
- **Skills**: Klicken Sie auf „Skills" → GitHub-Repositorys durchsuchen → mit einem Klick in unterstützte Apps installieren
|
||||
- **Sessions**: Klicken Sie auf „Sessions" → Gesprächsverlauf aus unterstützten Sitzungsquellen durchsuchen, suchen und wiederherstellen
|
||||
|
||||
> **Hinweis**: Beim Erststart können Sie bestehende CLI-Werkzeug-Konfigurationen manuell als Standardanbieter importieren.
|
||||
|
||||
@@ -494,7 +499,7 @@ pnpm test:unit --coverage
|
||||
│ ├── lib/
|
||||
│ │ ├── api/ # Tauri-API-Wrapper (typsicher)
|
||||
│ │ └── query/ # TanStack-Query-Konfiguration
|
||||
│ ├── locales/ # Übersetzungen (zh/en/ja)
|
||||
│ ├── locales/ # Übersetzungen (zh/zh-TW/en/ja)
|
||||
│ ├── config/ # Presets (providers/mcp)
|
||||
│ └── types/ # TypeScript-Definitionen
|
||||
├── src-tauri/ # Backend (Rust)
|
||||
|
||||
+26
-21
@@ -2,7 +2,7 @@
|
||||
|
||||
# CC Switch
|
||||
|
||||
### Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes Agent のオールインワン管理ツール
|
||||
### Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes Agent のオールインワン管理ツール
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
@@ -43,17 +43,17 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
|
||||
<td>本プロジェクトは AIGoCode のスポンサー提供でお届けしています。AIGoCode は、Claude Code・Codex・最新の Gemini モデルを統合したオールインワンのAIコーディングプラットフォームで、安定性・高速性・コストパフォーマンスに優れた開発サービスを提供します。柔軟なサブスクリプションプランを備え、レスポンスも非常に高速です。さらに、CC Switch ユーザー向けの特典として、<a href="https://aigocode.com/invite/CC-SWITCH">このリンク</a>から登録すると、初回チャージ時に10%分のボーナスクレジットが付与されます!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>胜算雲(Shengsuanyun)のご支援に感謝します!胜算雲は AI ネイティブチーム向けのスーパーファクトリーであり、産業グレードの AI タスク並列実行プラットフォームです。モデルマーケットプレイスでは Claude、ChatGPT、Gemini をはじめとする国内外の LLM およびマルチメディアモデルの計算リソースを集約・直接提供。リバースエンジニアリングや品質低下は一切なく、プラットフォーム全体のモデル SLA 可用性は 99.7% に達し、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">監視ダッシュボード</a>は常時グリーン表示です。さらにエンタープライズ向けカスタムゲートウェイを提供し、チームのきめ細かなコスト・権限管理、スマートルーティング、セキュリティ保護、BYOK(自社キー持ち込み)ホスティングを実現します。従量課金およびトークンプラン(近日公開)対応で、請求書発行にも対応。<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">このリンク</a>から新規登録すると 10 元分のクレジットと初回チャージ 10% ボーナスが付与されます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
|
||||
<td>AICodeMirror のご支援に感謝します!AICodeMirror は Claude Code / Codex / Gemini CLI の公式高安定リレーサービスを提供しており、エンタープライズ級の同時接続、迅速な請求書発行、24時間年中無休の専用テクニカルサポートを備えています。
|
||||
Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% / 2% / 9%、チャージ時にはさらに割引!AICodeMirror は CC Switch ユーザー向けに特別特典を用意:<a href="https://www.aicodemirror.com/register?invitecode=9915W3">このリンク</a>から登録すると初回チャージ 20% オフ、法人のお客様は最大 25% オフ!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>胜算雲(Shengsuanyun)のご支援に感謝します!胜算雲は AI ネイティブチーム向けのスーパーファクトリーであり、産業グレードの AI タスク並列実行プラットフォームです。モデルマーケットプレイスでは Claude、ChatGPT、Gemini をはじめとする国内外の LLM およびマルチメディアモデルの計算リソースを集約・直接提供。リバースエンジニアリングや品質低下は一切なく、プラットフォーム全体のモデル SLA 可用性は 99.7% に達し、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">監視ダッシュボード</a>は常時グリーン表示です。さらにエンタープライズ向けカスタムゲートウェイを提供し、チームのきめ細かなコスト・権限管理、スマートルーティング、セキュリティ保護、BYOK(自社キー持ち込み)ホスティングを実現します。従量課金およびトークンプラン(近日公開)対応で、請求書発行にも対応。<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">このリンク</a>から新規登録すると 10 元分のクレジットと初回チャージ 10% ボーナスが付与されます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
|
||||
<td>PatewayAI のご支援に感謝します!PatewayAI はヘビーな AI 開発者向けに、公式直結の高品質モデル API 中継サービスを専門に提供するプロバイダーです。Claude シリーズ全モデルおよび Codex シリーズに対応し、100% 公式ソースから直接提供。混ぜ物・水増しは一切なく、検証も歓迎します。課金は透明で、トークン単位の請求書を 1 件ずつ照合可能です。
|
||||
@@ -145,19 +145,24 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
<td>Atlas Cloud は、1 つの API で動画・画像生成や LLM(大規模言語モデル)を利用できる全モーダル対応の AI 推論プラットフォームです。複数のベンダーを個別に管理する手間を省き、一度の接続で 300 以上の厳選されたマルチモーダルモデルにアクセスできます。より低コストで API を利用できる、開発者向けの新しい<a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">「コーディングプラン」</a>プロモーションをぜひチェックしてください!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td>CCSub のご支援に感謝します!CCSub は安定した低価格の AI API リレープラットフォームで、Claude Code 公式サブスクリプションの強力な代替です。1 つの API キーで Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek の全モデルを公式直接利用の約 1/3 のコストでご利用いただけます。VPN 不要で世界中から直接接続可能。Claude Code、Codex、Cursor、Cline、Continue、Windsurf など主要な AI コーディングツールすべてに対応しています。<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">こちらのリンク</a>から登録すると $5 の無料クレジットがもらえます。</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## CC Switch を選ぶ理由
|
||||
|
||||
最新の AI コーディングは Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw などの CLI ツールに依存していますが、各ツールの設定形式はバラバラです。API プロバイダを切り替えるたびに JSON、TOML、`.env` ファイルを手動で編集する必要があり、複数ツール間で MCP や Skills を統一的に管理する手段もありません。
|
||||
最新の AI コーディングは Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes などのツールに依存していますが、各ツールの設定形式はバラバラです。API プロバイダを切り替えるたびに JSON、TOML、`.env` ファイルを手動で編集する必要があり、複数ツール間で MCP や Skills を統一的に管理する手段もありません。
|
||||
|
||||
**CC Switch** は、5 つの CLI ツールを 1 つのデスクトップアプリで一元管理できます。設定ファイルを手作業で編集する代わりに、ワンクリックでプロバイダをインポートし、瞬時に切り替えられるビジュアルインターフェースを提供します。50 以上の組み込みプリセット、統一 MCP・Skills 管理、システムトレイからの即時切り替え機能を搭載。すべてはアトミック書き込みによる信頼性の高い SQLite データベースに支えられており、設定の破損を防ぎます。
|
||||
**CC Switch** は、対応する AI ツールを 1 つのデスクトップアプリで一元管理できます。設定ファイルを手作業で編集する代わりに、ワンクリックでプロバイダをインポートし、瞬時に切り替えられるビジュアルインターフェースを提供します。50 以上の組み込みプリセット、統一 MCP・Skills 管理、システムトレイからの即時切り替え機能を搭載。すべてはアトミック書き込みによる信頼性の高い SQLite データベースに支えられており、設定の破損を防ぎます。
|
||||
|
||||
- **1 つのアプリで 5 つの CLI ツール** -- Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw を単一インターフェースで管理
|
||||
- **1 つのアプリで 7 つのツール** -- Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes を単一インターフェースで管理
|
||||
- **手動編集は不要** -- AWS Bedrock、NVIDIA NIM、コミュニティリレーなど 50 以上のプロバイダプリセットを内蔵。選んで切り替えるだけ
|
||||
- **統一 MCP・Skills 管理** -- 1 つのパネルで 4 つのアプリの MCP サーバーと Skills を双方向同期で管理
|
||||
- **統一 MCP・Skills 管理** -- 1 つのパネルで Claude、Codex、Gemini、OpenCode、Hermes の MCP サーバーと Skills を双方向同期で管理
|
||||
- **システムトレイでクイック切り替え** -- トレイメニューから即座にプロバイダを切り替え。アプリを開く必要なし
|
||||
- **クラウド同期** -- Dropbox、OneDrive、iCloud、または WebDAV サーバー経由でデバイス間のプロバイダデータを同期
|
||||
- **クロスプラットフォーム** -- Tauri 2 で構築された Windows、macOS、Linux 対応のネイティブデスクトップアプリ
|
||||
@@ -171,12 +176,12 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
## 特長
|
||||
|
||||
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.15.0-ja.md)
|
||||
[完全な更新履歴](CHANGELOG.md) | [リリースノート](docs/release-notes/v3.16.1-ja.md)
|
||||
|
||||
### プロバイダ管理
|
||||
|
||||
- **5 つの CLI ツール、50 以上のプリセット** -- Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw。キーをコピーしてワンクリックでインポート
|
||||
- **ユニバーサルプロバイダ** -- 1 つの設定を複数アプリに同期(OpenCode、OpenClaw)
|
||||
- **7 つの対応ツール、50 以上のプリセット** -- Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes。キーをコピーしてワンクリックでインポート
|
||||
- **ユニバーサルプロバイダ** -- 1 つの設定を Claude Code、Codex、Gemini CLI に同期
|
||||
- ワンクリック切り替え、システムトレイクイックアクセス、ドラッグ&ドロップ並び替え、インポート/エクスポート
|
||||
|
||||
### プロキシ & フェイルオーバー
|
||||
@@ -186,7 +191,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
### MCP、Prompts & Skills
|
||||
|
||||
- **統一 MCP パネル** -- 4 つのアプリの MCP サーバーを管理、双方向同期、Deep Link インポート対応
|
||||
- **統一 MCP パネル** -- Claude、Codex、Gemini、OpenCode、Hermes の MCP サーバーを管理、双方向同期、Deep Link インポート対応
|
||||
- **Prompts** -- Markdown エディタ、クロスアプリ同期(CLAUDE.md / AGENTS.md / GEMINI.md)、バックフィル保護
|
||||
- **Skills** -- GitHub リポジトリまたは ZIP ファイルからワンクリックインストール、カスタムリポジトリ管理、シンボリックリンクとファイルコピーに対応
|
||||
|
||||
@@ -196,21 +201,21 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
|
||||
|
||||
### Session Manager & ワークスペース
|
||||
|
||||
- すべてのアプリの会話履歴を閲覧・検索・復元
|
||||
- 対応するセッションソースの会話履歴を閲覧・検索・復元
|
||||
- **ワークスペースエディタ**(OpenClaw)-- エージェントファイル(AGENTS.md、SOUL.md など)を Markdown プレビュー付きで編集
|
||||
|
||||
### システム & プラットフォーム
|
||||
|
||||
- **クラウド同期** -- カスタム設定ディレクトリ(Dropbox、OneDrive、iCloud、NAS)および WebDAV サーバー同期
|
||||
- **Deep Link** (`ccswitch://`) -- URL 経由でプロバイダ、MCP サーバー、Prompts、Skills をワンクリックインポート
|
||||
- ダーク / ライト / システムテーマ、自動起動、自動アップデーター、アトミック書き込み、自動バックアップ、多言語対応(中/英/日)
|
||||
- ダーク / ライト / システムテーマ、自動起動、自動アップデーター、アトミック書き込み、自動バックアップ、多言語対応(簡体中文/繁體中文/英/日)
|
||||
|
||||
## よくある質問
|
||||
|
||||
<details>
|
||||
<summary><strong>CC Switch はどの AI CLI ツールに対応していますか?</strong></summary>
|
||||
<summary><strong>CC Switch はどの AI ツールに対応していますか?</strong></summary>
|
||||
|
||||
CC Switch は **Claude Code**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** の 5 つのツールに対応しています。各ツールに専用のプロバイダプリセットと設定管理が用意されています。
|
||||
CC Switch は **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes** の 7 つのツールに対応しています。各ツールに専用のプロバイダプリセットと設定管理が用意されています。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -279,8 +284,8 @@ CC Switch は「最小限の介入」という設計原則に従っています
|
||||
|
||||
- **MCP**: 「MCP」ボタンをクリック → テンプレートまたはカスタム設定でサーバーを追加 → アプリごとの同期をトグルで切り替え
|
||||
- **Prompts**: 「Prompts」をクリック → Markdown エディタでプリセットを作成 → 有効化してライブファイルに同期
|
||||
- **Skills**: 「Skills」をクリック → GitHub リポジトリを閲覧 → ワンクリックですべてのアプリにインストール
|
||||
- **Sessions**: 「Sessions」をクリック → すべてのアプリの会話履歴を閲覧・検索・復元
|
||||
- **Skills**: 「Skills」をクリック → GitHub リポジトリを閲覧 → 対応アプリへワンクリックでインストール
|
||||
- **Sessions**: 「Sessions」をクリック → 対応するセッションソースの会話履歴を閲覧・検索・復元
|
||||
|
||||
> **補足**: 初回起動時に、既存の CLI ツール設定を手動でインポートしてデフォルトプロバイダとして使用できます。
|
||||
|
||||
@@ -493,7 +498,7 @@ pnpm test:unit --coverage
|
||||
│ ├── lib/
|
||||
│ │ ├── api/ # Tauri API ラッパー(型安全)
|
||||
│ │ └── query/ # TanStack Query 設定
|
||||
│ ├── locales/ # 翻訳 (zh/en/ja)
|
||||
│ ├── locales/ # 翻訳 (zh/zh-TW/en/ja)
|
||||
│ ├── config/ # プリセット (providers/mcp)
|
||||
│ └── types/ # TypeScript 型定義
|
||||
├── src-tauri/ # バックエンド (Rust)
|
||||
|
||||
+30
-25
@@ -2,7 +2,7 @@
|
||||
|
||||
# CC Switch
|
||||
|
||||
### Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes Agent 的全方位管理工具
|
||||
### Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes Agent 的全方位管理工具
|
||||
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
[](https://github.com/farion1231/cc-switch/releases)
|
||||
@@ -43,17 +43,17 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一个集成了 Claude Code、Codex 以及 Gemini 最新模型的一站式平台,为你提供稳定、高效且高性价比的AI编程服务。本站提供灵活的订阅计划,零封号风险,国内直连,无需魔法,极速响应。AIGoCode 为 CC Switch 的用户提供了特别福利,通过<a href="https://aigocode.com/invite/CC-SWITCH">此链接</a>注册的用户首次充值可以获得额外10%奖励额度!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>感谢胜算云赞助了本项目!胜算云是专为AI Native Teams服务的超级工厂,工业级AI任务并行执行平台,模型商城集采直供聚合接入了Claude、Chatgpt、Gemini等海内外LLM及图片视频多媒体模型算力,绝无逆向掺水、全站模型SLA可用性高达99.7%、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">监测接口</a>日常全绿。更有企业级专属定制网关,实现团队精细化成本与权限管控,智能路由+安全防护+BYOK企业自带密钥托管。平台按量及tokens plan(即将上线)计费,可开票,使用<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">此链接</a>注册新用户可获10元模力及首充10%赠送。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.aicodemirror.com/register?invitecode=9915W3"><img src="assets/partners/logos/aicodemirror.jpg" alt="AICodeMirror" width="150"></a></td>
|
||||
<td>感谢 AICodeMirror 赞助了本项目!AICodeMirror 提供 Claude Code / Codex / Gemini CLI 官方高稳定中转服务,支持企业级高并发、极速开票、7×24 专属技术支持。
|
||||
Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更有折上折!AICodeMirror 为 CCSwitch 的用户提供了特别福利,通过<a href="https://www.aicodemirror.com/register?invitecode=9915W3">此链接</a>注册的用户,可享受首充8折,企业客户最高可享 7.5 折!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF"><img src="assets/partners/logos/shengsuanyun.png" alt="Shengsuanyun" width="150"></a></td>
|
||||
<td>感谢胜算云赞助了本项目!胜算云是专为AI Native Teams服务的超级工厂,工业级AI任务并行执行平台,模型商城集采直供聚合接入了Claude、Chatgpt、Gemini等海内外LLM及图片视频多媒体模型算力,绝无逆向掺水、全站模型SLA可用性高达99.7%、<a href="https://watch.shengsuanyun.com/status/shengsuanyun">监测接口</a>日常全绿。更有企业级专属定制网关,实现团队精细化成本与权限管控,智能路由+安全防护+BYOK企业自带密钥托管。平台按量及tokens plan(即将上线)计费,可开票,使用<a href="https://www.shengsuanyun.com/?from=CH_4HHXMRYF">此链接</a>注册新用户可获10元模力及首充10%赠送。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/"><img src="assets/partners/logos/pateway.png" alt="PatewayAI" width="150"></a></td>
|
||||
<td>感谢 PatewayAI 赞助了本项目!PatewayAI 是一家面向重度 AI 开发者、专注官方直连高品质模型 API 中转服务商。提供 Claude 全系列与 Codex 系列模型,100% 官方源直供,不掺假不注水,欢迎检验。计费透明,Token 级账单可逐笔核验。
|
||||
@@ -112,13 +112,13 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
</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>
|
||||
<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>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width=”180”><a href=”https://console.claudeapi.com/register?aff=pCLD”><img src=”assets/partners/logos/claudeapi.png” alt=”ClaudeAPI” width=”150”></a></td>
|
||||
<td>本项目由 <a href=”https://console.claudeapi.com/register?aff=pCLD”>Claude API</a> 赞助。Claude API 直连,三分钟接入 Claude Code 与 Agent 应用 新用户可领取测试额度。基于 Anthropic 官方 Key + AWS Bedrock 官方渠道,非逆向、非降智,支持 Opus / Sonnet / Haiku 全系列模型,保留 Tool Use、1M 上下文等官方能力。适合 Claude Code 深度用户、Agent 工程师与企业技术团队,支持开票和团队对接。点击<a href=”https://console.claudeapi.com/register?aff=pCLD”>这里</a>注册!</td>
|
||||
<td width="180"><a href="https://console.claudeapi.com/register?aff=pCLD"><img src="assets/partners/logos/claudeapi.png" alt="ClaudeAPI" width="150"></a></td>
|
||||
<td>本项目由 <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> 赞助。Claude API 直连,三分钟接入 Claude Code 与 Agent 应用 新用户可领取测试额度。基于 Anthropic 官方 Key + AWS Bedrock 官方渠道,非逆向、非降智,支持 Opus / Sonnet / Haiku 全系列模型,保留 Tool Use、1M 上下文等官方能力。适合 Claude Code 深度用户、Agent 工程师与企业技术团队,支持开票和团队对接。点击<a href="https://console.claudeapi.com/register?aff=pCLD">这里</a>注册!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -146,19 +146,24 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
<td>Atlas Cloud 是一个全模态 AI 推理平台,通过单一 API 为开发者提供视频生成、图像生成及 LLM 接入。免去繁琐的多供应商对接,一次连接即可调用 300+ 款全模态精选模型。立即查看 Atlas Cloud 全新<a href="https://www.atlascloud.ai/coding-plan?utm_source=github&utm_campaign=cc-switch">“编程计划”</a>优惠,获取更具性价比的 API 接入!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.ccsub.net/register?ref=Y6Z8DXEA"><img src="assets/partners/logos/ccsub.jpg" alt="CCSub" width="150"></a></td>
|
||||
<td>感谢 CCSub 赞助本项目!CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini、DeepSeek 全系列模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。通过<a href="https://www.ccsub.net/register?ref=Y6Z8DXEA">此链接</a>注册即送 $5 体验额度!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## 为什么选择 CC Switch?
|
||||
|
||||
现代 AI 编程依赖于 Claude Code、Codex、Gemini CLI、OpenCode 和 OpenClaw 等 CLI 工具——但每个工具都有自己的配置格式。切换 API 供应商意味着手动编辑 JSON、TOML 或 `.env` 文件,而在多个工具之间缺乏一个统一管理 MCP, SKILLS 的方式。
|
||||
现代 AI 编程依赖于 Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes 等工具——但每个工具都有自己的配置格式。切换 API 供应商意味着手动编辑 JSON、TOML 或 `.env` 文件,而在多个工具之间缺乏一个统一管理 MCP, SKILLS 的方式。
|
||||
|
||||
**CC Switch** 为你提供一个桌面应用来管理所有五个 CLI 工具。无需手动编辑配置文件,你将获得一个可视化界面,一键将供应商导入应用,一键在不同的供应商之间进行切换,内置 50+ 供应商预设、统一的 MCP, SKILLS 管理以及系统托盘即时切换功能——所有操作都基于可靠的 SQLite 数据库和原子写入机制,保护你的配置不被损坏。
|
||||
**CC Switch** 为你提供一个桌面应用来管理所有支持的 AI 工具。无需手动编辑配置文件,你将获得一个可视化界面,一键将供应商导入应用,一键在不同的供应商之间进行切换,内置 50+ 供应商预设、统一的 MCP, SKILLS 管理以及系统托盘即时切换功能——所有操作都基于可靠的 SQLite 数据库和原子写入机制,保护你的配置不被损坏。
|
||||
|
||||
- **一个应用,五个 CLI 工具** — 在单一界面中管理 Claude Code、Codex、Gemini CLI、OpenCode 和 OpenClaw
|
||||
- **一个应用,七个工具** — 在单一界面中管理 Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw 和 Hermes
|
||||
- **告别手动编辑** — 50+ 供应商预设,包括 AWS Bedrock、NVIDIA NIM 和社区中转服务;一键即可切换
|
||||
- **统一 MCP, SKILLS 管理** — 一个面板管理四个应用的 MCP, SKILLS, 支持双向同步
|
||||
- **统一 MCP, SKILLS 管理** — 一个面板管理 Claude、Codex、Gemini、OpenCode 和 Hermes 的 MCP, SKILLS, 支持双向同步
|
||||
- **系统托盘快速切换** — 从托盘菜单即时切换供应商,无需打开完整应用
|
||||
- **云同步** — 通过 Dropbox、OneDrive、iCloud 或 WebDAV 服务器在不同设备之间同步供应商数据
|
||||
- **跨平台** — 基于 Tauri 2 构建的原生桌面应用,支持 Windows、macOS 和 Linux
|
||||
@@ -172,12 +177,12 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
|
||||
## 功能特性
|
||||
|
||||
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.15.0-zh.md)
|
||||
[完整更新日志](CHANGELOG.md) | [发布说明](docs/release-notes/v3.16.1-zh.md)
|
||||
|
||||
### 供应商管理
|
||||
|
||||
- **5 个 CLI 工具,50+ 预设** — Claude Code、Codex、Gemini CLI、OpenCode、OpenClaw;复制 key 即可一键导入
|
||||
- **通用供应商** — 一份配置同步到多个应用(OpenCode、OpenClaw)
|
||||
- **7 个支持工具,50+ 预设** — Claude Code、Claude Desktop、Codex、Gemini CLI、OpenCode、OpenClaw、Hermes;复制 key 即可一键导入
|
||||
- **通用供应商** — 一份配置同步到 Claude Code、Codex 和 Gemini CLI
|
||||
- 一键切换、系统托盘快速访问、拖拽排序、导入导出
|
||||
|
||||
### 代理与故障转移
|
||||
@@ -187,7 +192,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
|
||||
### MCP、Prompts 与 Skills
|
||||
|
||||
- **统一 MCP 面板** — 管理 4 个应用的 MCP 服务器,双向同步,支持 Deep Link 导入
|
||||
- **统一 MCP 面板** — 管理 Claude、Codex、Gemini、OpenCode 和 Hermes 的 MCP 服务器,双向同步,支持 Deep Link 导入
|
||||
- **Prompts** — Markdown 编辑器,跨应用同步(CLAUDE.md / AGENTS.md / GEMINI.md),回填保护
|
||||
- **Skills** — 从 GitHub 仓库或 ZIP 文件一键安装,自定义仓库管理,支持软连接和文件复制
|
||||
|
||||
@@ -197,21 +202,21 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
|
||||
|
||||
### 会话管理器与工作区
|
||||
|
||||
- 浏览、搜索和恢复全部应用对话历史
|
||||
- 浏览、搜索和恢复支持的会话来源
|
||||
- **工作区编辑器**(OpenClaw)— 编辑 Agent 文件(AGENTS.md、SOUL.md 等),支持 Markdown 预览
|
||||
|
||||
### 系统与平台
|
||||
|
||||
- **云同步** — 自定义配置目录(Dropbox、OneDrive、iCloud、坚果云、NAS)及 WebDAV 服务器同步
|
||||
- **Deep Link** (`ccswitch://`) — 通过 URL 一键导入供应商、MCP 服务器、提示词和技能
|
||||
- 深色 / 浅色 / 跟随系统主题、开机自启、自动更新、原子写入、自动备份、国际化(中/英/日)
|
||||
- 深色 / 浅色 / 跟随系统主题、开机自启、自动更新、原子写入、自动备份、国际化(简中/繁中/英/日)
|
||||
|
||||
## 常见问题
|
||||
|
||||
<details>
|
||||
<summary><strong>CC Switch 支持哪些 AI CLI 工具?</strong></summary>
|
||||
<summary><strong>CC Switch 支持哪些 AI 工具?</strong></summary>
|
||||
|
||||
CC Switch 支持五个工具:**Claude Code**、**Codex**、**Gemini CLI**、**OpenCode** 和 **OpenClaw**。每个工具都有专属的供应商预设和配置管理。
|
||||
CC Switch 支持七个工具:**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** 和 **Hermes**。每个工具都有专属的供应商预设和配置管理。
|
||||
|
||||
</details>
|
||||
|
||||
@@ -282,8 +287,8 @@ CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安
|
||||
|
||||
- **MCP**:点击"MCP"按钮 → 通过模板或自定义配置添加服务器 → 切换各应用同步开关
|
||||
- **Prompts**:点击"Prompts" → 使用 Markdown 编辑器创建预设 → 激活后同步到 live 文件
|
||||
- **Skills**:点击"Skills" → 浏览 GitHub 仓库 → 一键安装到全部应用
|
||||
- **会话**:点击"Sessions" → 浏览和搜索和恢复全部应用对话历史
|
||||
- **Skills**:点击"Skills" → 浏览 GitHub 仓库 → 一键安装到支持的应用
|
||||
- **会话**:点击"Sessions" → 浏览、搜索和恢复支持的会话来源
|
||||
|
||||
> **注意**:首次启动可以手动导入现有 CLI 工具配置作为默认供应商。
|
||||
|
||||
@@ -496,7 +501,7 @@ pnpm test:unit --coverage
|
||||
│ ├── lib/
|
||||
│ │ ├── api/ # Tauri API 封装(类型安全)
|
||||
│ │ └── query/ # TanStack Query 配置
|
||||
│ ├── locales/ # 翻译 (zh/en/ja)
|
||||
│ ├── locales/ # 翻译 (zh/zh-TW/en/ja)
|
||||
│ ├── config/ # 预设 (providers/mcp)
|
||||
│ └── types/ # TypeScript 类型定义
|
||||
├── src-tauri/ # 后端 (Rust)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.4 KiB |
@@ -0,0 +1,101 @@
|
||||
# Using DeepSeek-Style Chat APIs in Codex: CC Switch Local Routing Guide
|
||||
|
||||
> Applies to CC Switch 3.16.0 and nearby versions. This guide is based on the repository documentation and code, and uses DeepSeek as an example of an OpenAI Chat Completions-compatible API. Screenshots are generated from the current frontend UI with de-identified sample data to avoid exposing a real API key or account balance.
|
||||
|
||||
## Why local routing is needed
|
||||
|
||||
The newer Codex CLI targets the OpenAI Responses API, while DeepSeek, Kimi, MiniMax, SiliconFlow, and many other providers expose the OpenAI Chat Completions shape, usually `/chat/completions`. These two protocols use different request bodies, streaming events, and response structures. If you put a Chat endpoint directly into Codex configuration, common results include an incorrect model list, 404/400 requests, or streaming responses that Codex cannot parse correctly.
|
||||
|
||||
CC Switch solves this by making Codex always talk to a local route and continue sending Responses API requests. The route detects whether the active provider is Chat-format, rewrites the request into Chat Completions for the upstream provider, and finally converts the Chat response back into the Responses shape that Codex understands.
|
||||
|
||||

|
||||
|
||||
The chain has four main steps:
|
||||
|
||||
1. When Codex routing is enabled, the local configuration is written as `http://127.0.0.1:15721/v1`, while `wire_api = "responses"` is kept in place.
|
||||
2. The provider's `meta.apiFormat = "openai_chat"` tells the route that the real upstream is Chat Completions.
|
||||
3. The route rewrites `/responses` or `/v1/responses` to `/chat/completions`, and converts the Responses request body into a Chat request body.
|
||||
4. After the upstream responds, the route converts the Chat JSON or SSE stream back into Responses JSON/SSE.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Prepare these three things first:
|
||||
|
||||
- CC Switch installed and able to start.
|
||||
- Codex CLI installed and run at least once, so the `~/.codex/config.toml` directory structure exists.
|
||||
- An API key from DeepSeek or another Chat Completions provider.
|
||||
|
||||
DeepSeek's official documentation currently lists the OpenAI-compatible base URL as `https://api.deepseek.com` (other providers often use a base URL with a `/v1` suffix), and the Chat API path as `/chat/completions`. CC Switch's DeepSeek preset already contains these details, so prefer the preset and do not manually assemble the endpoint path.
|
||||
|
||||
## Step 1: Add a Codex provider
|
||||
|
||||
Open CC Switch, switch to the top-level `Codex` tab, and click the plus button in the upper-right corner to add a provider.
|
||||
|
||||
Choose the built-in `DeepSeek` preset. You only need to do two things:
|
||||
|
||||
- Enter your DeepSeek API key.
|
||||
- Save the provider.
|
||||
|
||||

|
||||
|
||||
The preset already includes DeepSeek's request base URL, default model, model menu, thinking/reasoning parameters, and automatically enables `Needs Local Routing`. You can adjust the default model or model display names if needed; the protocol conversion is handled by the routing layer.
|
||||
|
||||
## Step 2: Enable local routing and route Codex
|
||||
|
||||
Go to the `Routing` page in Settings, expand `Local Routing`, and complete two toggles:
|
||||
|
||||
1. Turn on the main routing switch to start the local service. The default address is `127.0.0.1:15721`.
|
||||
2. Turn on `Codex` under `Routing Enabled`. If you only want Codex to use local routing, you can leave Claude and Gemini off.
|
||||
|
||||

|
||||
|
||||
After routing is enabled, CC Switch points Codex's live configuration to the local route and manages authentication with a placeholder. The real DeepSeek key stays in the CC Switch provider configuration and is injected by the local route while forwarding requests, so you do not need to expose the key in Codex's live configuration.
|
||||
|
||||
## Step 3: Switch providers and restart Codex
|
||||
|
||||
Return to the Codex provider list and click `Enable` on the DeepSeek provider. If you see the `Needs Routing` marker, that provider must be used while routing is running; when the route is not started, CC Switch shows a prompt saying the routing service is required.
|
||||
|
||||
After switching, restart the current Codex terminal session. This is recommended because:
|
||||
|
||||
- The Codex process may already have read the old `config.toml`.
|
||||
- After `model_catalog_json` is generated, the `/model` menu usually needs a fresh process before it refreshes.
|
||||
|
||||
Inside Codex, use `/model` to check whether the current model comes from the DeepSeek preset, such as `DeepSeek V4 Flash`. The Codex app currently does not support multi-model selection, so it defaults to the first configured model. Then send a small test prompt and confirm that the request count increases in the routing panel, or that a Codex request appears in usage/request logs.
|
||||
|
||||
## How to handle other Chat providers
|
||||
|
||||
DeepSeek, Kimi, MiniMax, SiliconFlow, and other common Chat-format providers already have presets in CC Switch, so use presets first. Only choose custom configuration for providers that are not covered by presets; in that case, fill in the API key, base URL, and models according to the provider's documentation, and set `API Format` to `OpenAI Chat Completions (requires routing)`.
|
||||
|
||||
If the upstream provider directly supports the OpenAI Responses API, you do not need to enable `Needs Local Routing`; CC Switch can connect through Responses directly without Chat conversion.
|
||||
|
||||
## FAQ
|
||||
|
||||
**Codex reports 404 or cannot find `/responses`**
|
||||
|
||||
Usually Codex routing is not enabled, or the upstream Chat base URL was written directly into Codex manually. Check whether `~/.codex/config.toml` points to `http://127.0.0.1:15721/v1`.
|
||||
|
||||
**DeepSeek upstream reports 404**
|
||||
|
||||
If you are using the built-in DeepSeek preset, first confirm that the active provider really comes from the preset and that Codex routing is enabled. Only custom providers require extra base URL checks: the base URL should be the service root, not the full endpoint path with `/chat/completions`.
|
||||
|
||||
**`/model` does not show DeepSeek models**
|
||||
|
||||
Restart Codex after saving the provider. CC Switch generates `cc-switch-model-catalog.json` and writes its path to `model_catalog_json`, but a running Codex process may not hot-load the model catalog.
|
||||
The Codex app currently does not support multi-model selection, so it uses the first configured model by default.
|
||||
|
||||
**Routing is enabled, but requests still go to the wrong provider**
|
||||
|
||||
Confirm that all three states match: the current provider under the Codex tab is DeepSeek; the local routing service is running; and the Codex toggle is enabled under `Routing Enabled`.
|
||||
|
||||
**Can I use an official OpenAI Codex account through local routing?**
|
||||
|
||||
Not recommended. CC Switch blocks switching to official providers while local routing takeover is enabled, because accessing official APIs through a proxy may create account risk. Routing is mainly intended for third-party, aggregator, or protocol-conversion scenarios.
|
||||
|
||||
## References
|
||||
|
||||
- [CC Switch User Manual: Add Provider](../user-manual/en/2-providers/2.1-add.md)
|
||||
- [CC Switch User Manual: Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
|
||||
- [CC Switch User Manual: App Routing](../user-manual/en/4-proxy/4.2-routing.md)
|
||||
- [DeepSeek API Docs: Your First API Call](https://api-docs.deepseek.com/)
|
||||
- [DeepSeek API Docs: Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
|
||||
- [DeepSeek API Docs: Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
|
||||
@@ -0,0 +1,101 @@
|
||||
# Codex で DeepSeek などの Chat 形式 API を使う: CC Switch ローカルルーティングガイド
|
||||
|
||||
> 対象バージョン: CC Switch 3.16.0 およびその前後のバージョン。本記事はリポジトリ内のドキュメントとコードをもとに整理し、OpenAI Chat Completions 互換 API の例として DeepSeek を使用します。スクリーンショットは現在のフロントエンド UI から、実際の API Key やアカウント残高が漏れないよう匿名化したサンプルデータで生成しています。
|
||||
|
||||
## ローカルルーティングが必要な理由
|
||||
|
||||
新しい Codex CLI は OpenAI Responses API を前提にしています。一方で DeepSeek、Kimi、MiniMax、SiliconFlow など多くのプロバイダーが実際に公開しているのは OpenAI Chat Completions 形式、つまり `/chat/completions` です。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造が異なります。Chat エンドポイントをそのまま Codex 設定に入れると、モデル一覧が合わない、リクエストが 404/400 になる、ストリーミングレスポンスを Codex が正しく解析できない、といった問題が起きがちです。
|
||||
|
||||
CC Switch では、Codex が常にローカルルートへ接続し、Responses API のままリクエストを送るようにします。ルート内部で現在のプロバイダーが Chat 形式かどうかを判定し、必要ならリクエストを Chat Completions に書き換えて上流へ送り、最後に Chat レスポンスを Codex が理解できる Responses 形式へ戻します。
|
||||
|
||||

|
||||
|
||||
この経路は主に 4 つのステップに分かれます:
|
||||
|
||||
1. Codex ルーティングを有効にすると、ローカル設定は `http://127.0.0.1:15721/v1` に書き換えられ、`wire_api = "responses"` は維持されます。
|
||||
2. Provider の `meta.apiFormat = "openai_chat"` が、実際の上流は Chat Completions だとルートに伝えます。
|
||||
3. ルートは `/responses` または `/v1/responses` を `/chat/completions` に書き換え、Responses のリクエストボディを Chat のリクエストボディへ変換します。
|
||||
4. 上流から返ってきた後、ルートは Chat の JSON または SSE ストリームを Responses JSON/SSE へ変換して返します。
|
||||
|
||||
## 事前準備
|
||||
|
||||
先に次の 3 つを用意してください:
|
||||
|
||||
- インストール済みで起動できる CC Switch。
|
||||
- インストール済みの Codex CLI。少なくとも 1 回は実行し、`~/.codex/config.toml` のディレクトリ構造が存在していること。
|
||||
- DeepSeek または同種の Chat Completions プロバイダーの API Key。
|
||||
|
||||
DeepSeek 公式ドキュメントでは、OpenAI 互換 base URL は現在 `https://api.deepseek.com`(他のプロバイダーでは `/v1` 付きの base URL もよくあります)、Chat API のパスは `/chat/completions` と記載されています。CC Switch の DeepSeek プリセットにはこれらの情報がすでに入っているため、まずはプリセットを使い、エンドポイントパスを手で組み立てる必要はありません。
|
||||
|
||||
## Step 1: Codex プロバイダーを追加する
|
||||
|
||||
CC Switch を開き、上部の `Codex` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。
|
||||
|
||||
内蔵プリセットの `DeepSeek` を選びます。必要なのは次の 2 つだけです:
|
||||
|
||||
- DeepSeek API Key を入力する。
|
||||
- プロバイダーを保存する。
|
||||
|
||||

|
||||
|
||||
プリセットには DeepSeek のリクエスト先、デフォルトモデル、モデルメニュー、thinking/reasoning パラメータがすでに含まれており、`ローカルルーティングが必要` も自動的に有効になります。必要に応じてデフォルトモデルやモデル表示名を調整できますが、プロトコル変換はルーティング層に任せれば十分です。
|
||||
|
||||
## Step 2: ローカルルーティングを有効にして Codex をルーティングする
|
||||
|
||||
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、次の 2 つのスイッチを設定します:
|
||||
|
||||
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します。デフォルトアドレスは `127.0.0.1:15721` です。
|
||||
2. `ルーティング有効` で `Codex` をオンにします。Codex だけをルーティングしたい場合は、Claude と Gemini はオフのままで構いません。
|
||||
|
||||

|
||||
|
||||
ルーティングを有効にすると、CC Switch は Codex の live 設定をローカルルートへ向け、認証はプレースホルダーで管理します。実際の DeepSeek Key は CC Switch の Provider 設定内に残り、ローカルルートが転送時に注入します。そのため、Codex の live 設定に Key を露出させる必要はありません。
|
||||
|
||||
## Step 3: プロバイダーを切り替えて Codex を再起動する
|
||||
|
||||
Codex プロバイダー一覧に戻り、DeepSeek プロバイダーの `有効化` をクリックします。`ルーティングが必要` の表示が見える場合、そのプロバイダーはルーティング実行中に使う必要があります。ルーティングが起動していない場合、CC Switch は「ルーティングサービスが必要」という趣旨のメッセージを表示します。
|
||||
|
||||
切り替え後は、現在の Codex ターミナルセッションを再起動することをおすすめします。理由は次のとおりです:
|
||||
|
||||
- Codex プロセスがすでに古い `config.toml` を読み込んでいる可能性があります。
|
||||
- `model_catalog_json` の生成後、`/model` メニューの更新には通常、新しいプロセスが必要です。
|
||||
|
||||
Codex に入ったら、`/model` で現在のモデルが DeepSeek プリセット由来かどうかを確認します。たとえば `DeepSeek V4 Flash` などです。現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。その後、小さな質問を 1 つ送って、ルーティングパネルのリクエスト数が増えるか、usage / リクエストログに Codex リクエストが出るかを確認します。
|
||||
|
||||
## 他の Chat プロバイダーの場合
|
||||
|
||||
DeepSeek、Kimi、MiniMax、SiliconFlow など一般的な Chat 形式プロバイダーは CC Switch にプリセットがあるため、まずはプリセットを使ってください。プリセットにないプロバイダーだけ、カスタム設定を選びます。その場合は相手側のドキュメントに従って API Key、base URL、モデルを入力し、`API 形式` を `OpenAI Chat Completions (ルーティングが必要)` に設定します。
|
||||
|
||||
上流が OpenAI Responses API を直接サポートしている場合は、`ローカルルーティングが必要` を有効にする必要はありません。その場合、CC Switch は Responses のまま直結でき、Chat 変換は行いません。
|
||||
|
||||
## よくある質問
|
||||
|
||||
**Codex が 404 を返す、または `/responses` が見つからない**
|
||||
|
||||
多くの場合、Codex ルーティングが有効になっていないか、上流 Chat base URL を手動で Codex に直接書いています。`~/.codex/config.toml` が `http://127.0.0.1:15721/v1` を指しているか確認してください。
|
||||
|
||||
**DeepSeek 上流が 404 を返す**
|
||||
|
||||
内蔵 DeepSeek プリセットを使っている場合は、まず現在のプロバイダーが本当にプリセット由来であること、そして Codex ルーティングが有効であることを確認してください。カスタムプロバイダーを使っている場合だけ、base URL を追加で確認します。base URL はサービスのルートであり、`/chat/completions` 付きの完全なエンドポイントパスではありません。
|
||||
|
||||
**`/model` に DeepSeek モデルが表示されない**
|
||||
|
||||
プロバイダーを保存した後、Codex を再起動してください。CC Switch は `cc-switch-model-catalog.json` を生成し、そのパスを `model_catalog_json` に書き込みますが、実行中の Codex プロセスがモデルカタログをホットロードするとは限りません。
|
||||
現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。
|
||||
|
||||
**ルーティングを有効にしたのに、リクエストが別のプロバイダーへ行く**
|
||||
|
||||
次の 3 つの状態が一致しているか確認してください:Codex タブの現在のプロバイダーが DeepSeek であること、ローカルルーティングサービスが実行中であること、`ルーティング有効` で Codex スイッチがオンであること。
|
||||
|
||||
**公式 OpenAI Codex アカウントをローカルルーティング経由で使えますか**
|
||||
|
||||
おすすめしません。CC Switch はローカルルーティング有効中、公式プロバイダーへの切り替えをブロックします。プロキシ経由で公式 API にアクセスすると、アカウントリスクが発生する可能性があるためです。ルーティングは主にサードパーティ、集約サービス、またはプロトコル変換のための機能です。
|
||||
|
||||
## 参考リンク
|
||||
|
||||
- [CC Switch ユーザーマニュアル: プロバイダーの追加](../user-manual/ja/2-providers/2.1-add.md)
|
||||
- [CC Switch ユーザーマニュアル: プロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
|
||||
- [CC Switch ユーザーマニュアル: アプリケーションルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
|
||||
- [DeepSeek API Docs: Your First API Call](https://api-docs.deepseek.com/)
|
||||
- [DeepSeek API Docs: Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
|
||||
- [DeepSeek API Docs: Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
|
||||
@@ -0,0 +1,101 @@
|
||||
# 在 Codex 中用 DeepSeek 这类 Chat 格式 API:CC Switch 本地路由攻略
|
||||
|
||||
> 适用版本:CC Switch 3.16.0 及附近版本。本文根据仓库内文档与代码整理,并用 DeepSeek 作为 OpenAI Chat Completions 兼容接口的示例。截图来自当前前端界面,使用去敏示例数据生成,避免泄露真实 API Key 或账户余额。
|
||||
|
||||
## 为什么需要本地路由
|
||||
|
||||
新版 Codex CLI 面向的是 OpenAI Responses API,而 DeepSeek、Kimi、MiniMax、SiliconFlow 等很多供应商实际暴露的是 OpenAI Chat Completions 形态,也就是 `/chat/completions`。这两种协议的请求体、流式事件和返回结构不同,直接把 Chat 接口填进 Codex 配置里,常见结果就是模型列表不对、请求 404/400,或者流式响应无法被 Codex 正确解析。
|
||||
|
||||
CC Switch 的做法是让 Codex 始终连本机路由,仍以 Responses API 发送请求;路由在内部识别当前供应商是否是 Chat 格式,再把请求改写成 Chat Completions 发给上游,最后把 Chat 响应转换回 Responses 形态返回给 Codex。
|
||||
|
||||

|
||||
|
||||
这条链路主要分成四步:
|
||||
|
||||
1. Codex 接管时,本地配置会被写成 `http://127.0.0.1:15721/v1`,并强制保持 `wire_api = "responses"`。
|
||||
2. Provider 的 `meta.apiFormat = "openai_chat"` 会告诉路由:真实上游是 Chat Completions。
|
||||
3. 路由把 `/responses` 或 `/v1/responses` 改写到 `/chat/completions`,并把 Responses 请求体转换成 Chat 请求体。
|
||||
4. 上游返回后,路由再把 Chat 的 JSON 或 SSE 转回 Codex 能理解的 Responses JSON/SSE。
|
||||
|
||||
## 准备工作
|
||||
|
||||
你需要先准备好三样东西:
|
||||
|
||||
- 已安装并能启动的 CC Switch。
|
||||
- 已安装 Codex CLI,并至少运行过一次,让 `~/.codex/config.toml` 目录结构存在。
|
||||
- DeepSeek 或同类 Chat Completions 供应商的 API Key。
|
||||
|
||||
DeepSeek 官方文档目前写明 OpenAI 兼容 base URL 是 `https://api.deepseek.com`(其他供应商常见的是带 `/v1` 后缀的 base URL),Chat API 路径是 `/chat/completions`;CC Switch 的 DeepSeek 预设已经按这些信息配好,请优先使用预设,不需要手动拼接口路径。
|
||||
|
||||
## 第一步:添加 Codex 供应商
|
||||
|
||||
打开 CC Switch,切到顶部的 `Codex` 标签,点击右上角的加号添加供应商。
|
||||
|
||||
选择内置预设里的 `DeepSeek`,只需要做两件事:
|
||||
|
||||
- 填入 DeepSeek API Key。
|
||||
- 保存供应商。
|
||||
|
||||

|
||||
|
||||
预设已经内置 DeepSeek 的请求地址、默认模型、模型菜单、thinking/reasoning 参数,并会自动打开 `需要本地路由映射`。你可以按需调整默认模型或模型显示名;协议转换交给路由层完成即可。
|
||||
|
||||
## 第二步:开启本地路由并接管 Codex
|
||||
|
||||
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
|
||||
|
||||
1. 打开 `路由总开关`,启动本地服务。默认地址是 `127.0.0.1:15721`。
|
||||
2. 在 `路由启用` 中打开 `Codex`。如果只想让 Codex 走路由,可以保持 Claude、Gemini 关闭。
|
||||
|
||||

|
||||
|
||||
接管后,CC Switch 会把 Codex 的 live 配置指向本机路由,并用占位符管理认证。真实 DeepSeek Key 仍保存在 CC Switch 的 Provider 配置里,由本地路由在转发时注入,不需要你把 Key 暴露给 Codex live 配置。
|
||||
|
||||
## 第三步:切换供应商并重启 Codex
|
||||
|
||||
回到 Codex 供应商列表,点击 DeepSeek 供应商的 `启用`。如果看到 `需要路由` 标记,说明这个供应商必须在路由运行时使用;没有启动路由时,CC Switch 会弹出“需要路由服务才能正常使用”的提示。
|
||||
|
||||
切换后建议重启当前 Codex 终端会话。原因是:
|
||||
|
||||
- Codex 进程可能已经读取过旧的 `config.toml`。
|
||||
- `model_catalog_json` 生成后,`/model` 菜单通常需要新进程才能刷新。
|
||||
|
||||
进入 Codex 后,可以用 `/model` 查看当前模型是否来自 DeepSeek 预设,例如 `DeepSeek V4 Flash`。目前 Codex app 不支持多模型选择时,会默认使用配置里的第一个模型。随后发一个小问题,确认路由面板的请求数增长,或者在用量/请求日志里看到 Codex 请求即可。
|
||||
|
||||
## 其它 Chat 供应商怎么处理
|
||||
|
||||
DeepSeek、Kimi、MiniMax、SiliconFlow 等常见 Chat 格式供应商在 CC Switch 里已有预设,优先用预设即可。只有预设里没有的供应商,才需要选择自定义配置;这时按对方文档填 API Key、base URL 和模型,并把 `API 格式` 选为 `OpenAI Chat Completions (需开启路由)`。
|
||||
|
||||
如果上游直接支持 OpenAI Responses API,就不需要打开 `需要本地路由映射`;这时 CC Switch 可以按 Responses 直连,不做 Chat 转换。
|
||||
|
||||
## 常见问题
|
||||
|
||||
**Codex 报 404 或找不到 `/responses`**
|
||||
|
||||
通常是没有开启 Codex 接管,或者你手动把上游 Chat base URL 直接写给了 Codex。检查 `~/.codex/config.toml` 是否指向 `http://127.0.0.1:15721/v1`。
|
||||
|
||||
**DeepSeek 上游报 404**
|
||||
|
||||
如果用的是内置 DeepSeek 预设,先确认当前供应商确实来自预设,并且 Codex 路由已启用。只有在使用自定义供应商时,才需要额外检查 base URL:它应该是服务根地址,而不是带 `/chat/completions` 的完整接口路径。
|
||||
|
||||
**`/model` 看不到 DeepSeek 模型**
|
||||
|
||||
保存供应商后重启 Codex。CC Switch 会生成 `cc-switch-model-catalog.json` 并把路径写入 `model_catalog_json`,但正在运行的 Codex 进程不一定会热加载模型目录。
|
||||
目前 Codex app 不支持多模型选择,默认使用配置的第一个模型。
|
||||
|
||||
**开了路由但请求仍走错供应商**
|
||||
|
||||
确认三处状态一致:Codex 标签下当前供应商是 DeepSeek;本地路由服务正在运行;`路由启用` 里 Codex 开关已打开。
|
||||
|
||||
**可以用官方 OpenAI Codex 账号走本地路由吗**
|
||||
|
||||
不建议。CC Switch 会在本地路由接管模式下阻止切到官方供应商,因为用代理访问官方 API 可能带来账号风险。路由主要用于第三方、聚合或协议转换场景。
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [CC Switch 用户手册:添加供应商](../user-manual/zh/2-providers/2.1-add.md)
|
||||
- [CC Switch 用户手册:代理服务](../user-manual/zh/4-proxy/4.1-service.md)
|
||||
- [CC Switch 用户手册:应用路由](../user-manual/zh/4-proxy/4.2-routing.md)
|
||||
- [DeepSeek API 文档:Your First API Call](https://api-docs.deepseek.com/)
|
||||
- [DeepSeek API 文档:Create Chat Completion](https://api-docs.deepseek.com/api/create-chat-completion)
|
||||
- [DeepSeek API 文档:Multi-round Conversation](https://api-docs.deepseek.com/guides/multi_round_chat)
|
||||
@@ -0,0 +1,209 @@
|
||||
# Keep Codex Remote Control and Official Plugins While Using Third-Party APIs: CC Switch Setup Guide
|
||||
|
||||
> Applies to CC Switch v3.16.1 and later. This guide is based on the current code, user manual, and v3.16.1 release notes. Screenshots use de-identified sample data and do not include real Access Tokens or API keys.
|
||||
|
||||
## What this guide solves
|
||||
|
||||
Many Codex users want both of these at the same time:
|
||||
|
||||
1. Use models from DeepSeek, Kimi, GLM, MiniMax, SiliconFlow, or other third-party APIs, or use GPT models through an aggregator.
|
||||
2. Keep Codex official-app capabilities such as mobile remote control and official plugins.
|
||||
|
||||
Previously, when switching to a third-party provider, the old behavior wrote the third-party API key into Codex `auth.json`, which could overwrite the original official ChatGPT / Codex login cache. The third-party model worked, but features that depend on the official login state disappeared.
|
||||
|
||||
The **Codex App Enhancements** switch added in v3.16.1 solves this conflict: the official Access Token stays in `auth.json`, while third-party provider information is written to `config.toml`. Codex App can still see an official account, but actual model requests follow the third-party provider currently selected in CC Switch.
|
||||
|
||||
This behavior already existed in v3.16.0 and was enabled by default. After some users reported that they did not want this behavior, v3.16.1 turned it into an explicit switch.
|
||||
|
||||
## Quick answer
|
||||
|
||||
Recommended order:
|
||||
|
||||
1. In the CC Switch Codex panel, switch to `OpenAI Official`.
|
||||
2. Start Codex and log in once with an official ChatGPT / Codex account. A Free subscription is enough.
|
||||
3. Return to CC Switch and enable `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers`.
|
||||
4. Add or switch to a third-party Codex provider.
|
||||
5. If the provider uses the Chat Completions protocol, such as DeepSeek / Kimi / MiniMax, also enable local routing and route Codex through it.
|
||||
6. Restart Codex so `config.toml` and the model catalog are reloaded.
|
||||
|
||||

|
||||
|
||||
## Prerequisites
|
||||
|
||||
Prepare the following:
|
||||
|
||||
- CC Switch v3.16.1 or later.
|
||||
- Codex installed and able to start. Installing both the app and CLI is recommended.
|
||||
- An official ChatGPT / Codex account that can log in to Codex. A Free subscription is enough.
|
||||
- A third-party API key, such as DeepSeek, Kimi, GLM, MiniMax, OpenRouter, SiliconFlow, or similar.
|
||||
|
||||
Do not manually copy or share the contents of `~/.codex/auth.json`. It stores official login cache and Access Tokens, so it is sensitive.
|
||||
|
||||
## Step 1: Switch back to OpenAI Official and complete official login
|
||||
|
||||
Open CC Switch and switch to the top-level `Codex` tab. First select the `OpenAI Official` provider, or add it from the preset providers if it is missing, and make it the current provider.
|
||||
|
||||

|
||||
|
||||
Then start Codex, preferably the CLI, and follow the official login flow to sign in with your ChatGPT / Codex account. This account can be on the Free plan. In this setup, it mainly preserves the official identity required by Codex App, and does not pay for third-party model usage.
|
||||
|
||||
After login, Codex stores the official login cache in `~/.codex/auth.json`. The key point for the following steps is: do not let third-party provider switching overwrite this file again.
|
||||
|
||||
## Step 2: Enable Codex App Enhancements
|
||||
|
||||
Return to CC Switch and open:
|
||||
|
||||
```text
|
||||
Settings -> General -> Codex App Enhancements
|
||||
```
|
||||
|
||||
Enable:
|
||||
|
||||
```text
|
||||
Keep official login when switching third-party providers
|
||||
```
|
||||
|
||||
This switch is off by default because some users do not want this behavior. Enable it only when you explicitly want "third-party API + official remote control / official plugins" at the same time.
|
||||
|
||||
After it is enabled, backend switching for third-party Codex providers uses a config-only write path:
|
||||
|
||||
- `auth.json`: keeps the official ChatGPT / Codex login cache.
|
||||
- `config.toml`: stores the active third-party provider's model, endpoint, `model_provider`, and provider-scoped `experimental_bearer_token`.
|
||||
|
||||
## Step 3: Add a third-party Codex provider
|
||||
|
||||
Return to the Codex panel and click the plus button in the upper-right corner to add a provider. Prefer built-in presets such as DeepSeek, Kimi, MiniMax, GLM, or SiliconFlow.
|
||||
|
||||
Using DeepSeek as an example, after selecting the preset, you only need to enter the API key. The preset automatically configures the base URL, default model, model mapping table, and "Needs Local Routing" flag.
|
||||
|
||||

|
||||
|
||||
If your third-party provider natively supports the OpenAI Responses API, such as an aggregator that offers GPT models, local routing may not be needed.
|
||||
If it only supports OpenAI Chat Completions, which is common for DeepSeek / Kimi / MiniMax paths, local routing must be enabled so CC Switch can convert Codex Responses requests into Chat Completions requests.
|
||||
|
||||
## Step 4: Enable local routing and route Codex when needed
|
||||
|
||||
Open:
|
||||
|
||||
```text
|
||||
Settings -> Routing -> Local Routing
|
||||
```
|
||||
|
||||
Complete two actions:
|
||||
|
||||
1. Turn on the main routing switch to start the local service. The default address is usually `127.0.0.1:15721`.
|
||||
2. Under `Routing Enabled`, turn on `Codex`.
|
||||
|
||||

|
||||
|
||||
After takeover, Codex's live `config.toml` temporarily points to the CC Switch local route. The real third-party API key remains in the CC Switch provider configuration, and is projected into the `experimental_bearer_token` in `config.toml` when providers are switched.
|
||||
|
||||
## Step 5: Switch to the third-party provider and restart Codex
|
||||
|
||||
Return to the Codex provider list and enable the third-party provider you just added. After switching, restarting Codex is recommended for two reasons:
|
||||
|
||||
- Codex reads `config.toml` at startup.
|
||||
- The Codex `/model` menu usually needs a restart before it reloads `model_catalog_json`.
|
||||
|
||||
After restart, you can run a quick verification:
|
||||
|
||||
- In Codex App, the account information still shows the official account. This is expected.
|
||||
- In CC Switch, the current Codex provider is the third-party provider.
|
||||
- If local routing is enabled, request logs or routing stats show Codex requests going through the local route.
|
||||
- The third-party provider dashboard or balance records show actual model requests.
|
||||
|
||||
## How it works
|
||||
|
||||
Codex mainly uses two configuration files:
|
||||
|
||||
```text
|
||||
~/.codex/auth.json
|
||||
~/.codex/config.toml
|
||||
```
|
||||
|
||||
They have different responsibilities:
|
||||
|
||||
- `auth.json` stores the official ChatGPT / Codex login cache, which Codex App needs to identify the official account and enable remote control and official plugins.
|
||||
- `config.toml` stores runtime configuration such as the current model provider, base URL, model, model catalog, and provider-scoped token.
|
||||
|
||||
After `Keep official login when switching third-party providers` is enabled, CC Switch takes the third-party provider API key from the provider configuration and writes it under the current provider in `config.toml`:
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "DeepSeek"
|
||||
base_url = "https://api.deepseek.com"
|
||||
wire_api = "responses"
|
||||
experimental_bearer_token = "sk-..."
|
||||
```
|
||||
|
||||
At the same time, `auth.json` keeps the official login cache unchanged. Codex App can still identify the official account, while model requests follow the current provider and base URL in `config.toml`.
|
||||
|
||||
If the provider uses the Chat Completions protocol, CC Switch local routing adds another conversion layer:
|
||||
|
||||
```text
|
||||
Codex Responses request
|
||||
|
|
||||
CC Switch local route
|
||||
|
|
||||
Third-party Chat Completions API
|
||||
|
|
||||
Converted back to Codex Responses response
|
||||
```
|
||||
|
||||
This is why you can keep using official plugins / mobile remote control while moving model traffic to a third-party API.
|
||||
|
||||
## Side effects to understand
|
||||
|
||||
### Codex still shows the official account
|
||||
|
||||
This is the easiest part to misunderstand. After this capability is enabled, Codex App reads the official login state from `auth.json`, so it continues to display the official account.
|
||||
|
||||
That does not mean model requests are still going to official OpenAI. Actual traffic is determined by the current Codex provider in CC Switch, `config.toml`, and local routing logs.
|
||||
|
||||
### Do not use the Codex account display to judge billing
|
||||
|
||||
If you switch to DeepSeek, Codex can still display the official account, while model requests go to the DeepSeek API. Billing, quota, error codes, and data policy should all be understood according to the third-party provider. You can inspect specific request details in the usage panel.
|
||||
|
||||
### Restart Codex after changing model mappings
|
||||
|
||||
Codex reads the model catalog at startup. Even if CC Switch has generated a new model catalog, a running Codex process may not hot-load it, so restart Codex after editing model mappings.
|
||||
|
||||
### Turning the switch off returns to the old behavior
|
||||
|
||||
If `Keep official login when switching third-party providers` is turned off, third-party provider switching uses the compatibility behavior from older versions and may write `auth.json` again. If your goal is to keep official remote control and official plugins long term, keep this switch enabled.
|
||||
|
||||
## FAQ
|
||||
|
||||
**I switched to a third-party API. Why does Codex still show the official account?**
|
||||
|
||||
This is expected. Official account information comes from `auth.json`; the actual model provider comes from `config.toml` and the current provider in CC Switch.
|
||||
|
||||
**Is a Free subscription really enough?**
|
||||
|
||||
Yes. The official account is mainly used to obtain and preserve the official login state required by Codex App. Third-party model requests use the third-party API key configured in CC Switch.
|
||||
|
||||
**What should I do if official plugins or mobile remote control still do not work?**
|
||||
|
||||
Switch back to `OpenAI Official`, restart Codex, and complete official login once. Then confirm `Settings -> General -> Codex App Enhancements -> Keep official login when switching third-party providers` is enabled in CC Switch before switching back to the third-party provider.
|
||||
|
||||
**What if third-party requests return 404, the model list is wrong, or streaming responses are broken?**
|
||||
|
||||
If the provider uses Chat Completions, confirm that the provider form has `Needs Local Routing` enabled, and that `Settings -> Routing` has both the main routing switch and Codex takeover enabled.
|
||||
|
||||
**Can I switch back to OpenAI Official while local routing is enabled?**
|
||||
|
||||
Not recommended. CC Switch tries to prevent switching to official providers while local routing takeover is active, because accessing official APIs through a proxy may create account risk. Use official login only to preserve `auth.json`, and route model traffic to third-party providers.
|
||||
|
||||
**Why is this flow so complex? Can it be simplified?**
|
||||
|
||||
Because Codex App Enhancements and routing takeover can create unnecessary trouble for users who do not need them, these features are explicit switches instead of always-on behavior.
|
||||
|
||||
## References
|
||||
|
||||
- [Codex DeepSeek local routing hands-on guide](./codex-deepseek-routing-guide-en.md)
|
||||
- [Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)
|
||||
- [Local Proxy Service](../user-manual/en/4-proxy/4.1-service.md)
|
||||
- [Local Routing](../user-manual/en/4-proxy/4.2-routing.md)
|
||||
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-en.md)
|
||||
@@ -0,0 +1,209 @@
|
||||
# サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する: CC Switch 設定ガイド
|
||||
|
||||
> 対象バージョン: CC Switch v3.16.1 以降。本記事は現在のコード、ユーザーマニュアル、v3.16.1 Release Note をもとに整理しています。スクリーンショットは匿名化したサンプルデータを使用しており、実際の Access Token や API Key は含まれていません。
|
||||
|
||||
## このガイドで解決すること
|
||||
|
||||
Codex を使うとき、多くのユーザーには次の 2 つの要望があります。
|
||||
|
||||
1. DeepSeek、Kimi、GLM、MiniMax、SiliconFlow などのサードパーティ API、または中継サービス上の GPT モデルを使いたい。
|
||||
2. Codex 公式アプリのモバイルリモート操作、公式プラグインなどの機能は残したい。
|
||||
|
||||
以前は、サードパーティプロバイダーへ切り替えると、旧動作ではサードパーティ API Key が Codex の `auth.json` に書き込まれ、元の公式 ChatGPT / Codex ログインキャッシュを上書きする可能性がありました。これによりサードパーティモデルは使えるものの、公式ログイン状態に依存する機能が消えてしまうことがありました。
|
||||
|
||||
v3.16.1 で追加された **Codex アプリ拡張** スイッチは、この矛盾を解決するためのものです。公式 Access Token は `auth.json` に残し、サードパーティプロバイダー情報は `config.toml` に書き込みます。これにより Codex App は引き続き公式アカウントでログインしていると認識しつつ、実際のモデルリクエストは CC Switch で現在選択されているサードパーティプロバイダーへ流れます。
|
||||
|
||||
この機能自体は v3.16.0 から存在し、当時はデフォルトで有効でした。ただし一部のユーザーから不要というフィードバックがあったため、v3.16.1 で明示的なスイッチになりました。
|
||||
|
||||
## まず結論
|
||||
|
||||
おすすめの手順は次のとおりです。
|
||||
|
||||
1. CC Switch の Codex パネルで `OpenAI Official` に切り替える。
|
||||
2. Codex を起動し、公式 ChatGPT / Codex アカウントで一度ログインする。Free サブスクリプションでも構いません。
|
||||
3. CC Switch に戻り、`設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` をオンにする。
|
||||
4. サードパーティ Codex プロバイダーを追加、または切り替える。
|
||||
5. そのプロバイダーが DeepSeek / Kimi / MiniMax などの Chat Completions プロトコルの場合は、ローカルルーティングも有効化し、Codex のルーティングをオンにする。
|
||||
6. Codex を再起動し、`config.toml` とモデルカタログを再読み込みさせる。
|
||||
|
||||

|
||||
|
||||
## 事前準備
|
||||
|
||||
次のものを用意してください。
|
||||
|
||||
- CC Switch v3.16.1 以降。
|
||||
- インストール済みで起動できる Codex。app と CLI の両方を入れておくことをおすすめします。
|
||||
- Codex にログインできる公式 ChatGPT / Codex アカウント。Free サブスクリプションで構いません。
|
||||
- DeepSeek、Kimi、GLM、MiniMax、OpenRouter、SiliconFlow などのサードパーティ API Key。
|
||||
|
||||
`~/.codex/auth.json` の内容を手動でコピーしたり共有したりしないでください。このファイルには公式ログインキャッシュと Access Token が保存されており、機密情報です。
|
||||
|
||||
## Step 1: OpenAI Official に戻して公式ログインを完了する
|
||||
|
||||
CC Switch を開き、上部の `Codex` タブへ切り替えます。まず `OpenAI Official` プロバイダーを選択します。存在しない場合は、プリセットプロバイダーから追加して現在のプロバイダーにしてください。
|
||||
|
||||

|
||||
|
||||
次に Codex を起動します。CLI の起動がおすすめです。Codex の公式ログインフローに従い、ChatGPT / Codex アカウントでログインします。このアカウントは Free プランでも問題ありません。この構成では、主に Codex App が必要とする公式ログイン ID を保持する役割であり、サードパーティモデルの課金には使いません。
|
||||
|
||||
ログイン後、Codex は `~/.codex/auth.json` に公式ログインキャッシュを保存します。以降の重要なポイントは、サードパーティプロバイダー切り替えでこのファイルを上書きさせないことです。
|
||||
|
||||
## Step 2: Codex アプリ拡張を有効化する
|
||||
|
||||
CC Switch に戻り、次を開きます。
|
||||
|
||||
```text
|
||||
設定 → 一般 → Codex アプリ拡張
|
||||
```
|
||||
|
||||
次のスイッチをオンにします。
|
||||
|
||||
```text
|
||||
サードパーティ切替時に公式ログインを保持
|
||||
```
|
||||
|
||||
このスイッチはデフォルトでオフです。一部のユーザーはこの機能を必要としていないためです。「サードパーティ API + 公式リモート操作 / 公式プラグイン」を同時に使いたい場合だけ有効化してください。
|
||||
|
||||
有効化すると、バックエンドで Codex サードパーティプロバイダーを切り替えるときに config-only の書き込み経路が使われます。
|
||||
|
||||
- `auth.json`: 公式 ChatGPT / Codex ログインキャッシュを保持します。
|
||||
- `config.toml`: 現在のサードパーティプロバイダーのモデル、endpoint、`model_provider`、provider-scoped `experimental_bearer_token` を書き込みます。
|
||||
|
||||
## Step 3: サードパーティ Codex プロバイダーを追加する
|
||||
|
||||
Codex パネルに戻り、右上のプラスボタンからプロバイダーを追加します。DeepSeek、Kimi、MiniMax、GLM、SiliconFlow などの内蔵プリセットを優先して使うのがおすすめです。
|
||||
|
||||
DeepSeek を例にすると、プリセットを選んだ後は API Key を入力するだけです。プリセットは base URL、デフォルトモデル、モデルマッピングテーブル、「ローカルルーティングが必要」設定を自動で構成します。
|
||||
|
||||

|
||||
|
||||
サードパーティプロバイダーが OpenAI Responses API をネイティブにサポートしている場合、たとえば GPT モデルを提供する中継サービスであれば、ローカルルーティングは不要なことがあります。
|
||||
一方で DeepSeek / Kimi / MiniMax のように OpenAI Chat Completions だけをサポートする場合は、CC Switch が Codex の Responses リクエストを Chat Completions リクエストへ変換する必要があるため、ローカルルーティングを有効化してください。
|
||||
|
||||
## Step 4: 必要に応じてローカルルーティングと Codex ルーティングを有効化する
|
||||
|
||||
次を開きます。
|
||||
|
||||
```text
|
||||
設定 → ルーティング → ローカルルーティング
|
||||
```
|
||||
|
||||
次の 2 つを行います。
|
||||
|
||||
1. `ルーティング総スイッチ` をオンにし、ローカルサービスを起動する。デフォルトアドレスは通常 `127.0.0.1:15721` です。
|
||||
2. `ルーティング有効` で `Codex` をオンにする。
|
||||
|
||||

|
||||
|
||||
ルーティング有効化後、Codex の live `config.toml` は一時的に CC Switch のローカルルートを指します。実際のサードパーティ API Key は CC Switch のプロバイダー設定内に残り、プロバイダー切り替え時に `config.toml` の `experimental_bearer_token` へ投影されます。
|
||||
|
||||
## Step 5: サードパーティプロバイダーへ切り替えて Codex を再起動する
|
||||
|
||||
Codex プロバイダー一覧に戻り、先ほど追加したサードパーティプロバイダーを有効化します。切り替え後は Codex の再起動をおすすめします。理由は 2 つあります。
|
||||
|
||||
- Codex は起動時に `config.toml` を読み込みます。
|
||||
- Codex の `/model` メニューは通常、再起動後に `model_catalog_json` を再読み込みします。
|
||||
|
||||
再起動後、簡単に確認できます。
|
||||
|
||||
- Codex App ではアカウント情報が引き続き公式アカウントとして表示される。これは期待される動作です。
|
||||
- CC Switch では現在の Codex プロバイダーがサードパーティプロバイダーになっている。
|
||||
- ローカルルーティングを有効化している場合、リクエストログまたはルーティング統計で Codex リクエストがローカルルートを通っていることを確認できる。
|
||||
- サードパーティプロバイダー側のダッシュボードや残高記録に実際のモデルリクエストが表示される。
|
||||
|
||||
## 仕組み
|
||||
|
||||
Codex の設定は主に 2 つのファイルに分かれています。
|
||||
|
||||
```text
|
||||
~/.codex/auth.json
|
||||
~/.codex/config.toml
|
||||
```
|
||||
|
||||
この 2 つは役割が異なります。
|
||||
|
||||
- `auth.json` は公式 ChatGPT / Codex ログインキャッシュを保存します。Codex App が公式アカウント、リモート操作、公式プラグインを認識するために必要なログイン材料です。
|
||||
- `config.toml` は現在のモデルプロバイダー、base URL、モデル、モデルカタログ、provider-scoped token などの実行時設定を保存します。
|
||||
|
||||
`サードパーティ切替時に公式ログインを保持` を有効化すると、CC Switch はサードパーティプロバイダー API Key をプロバイダー設定から取り出し、`config.toml` の現在の provider 配下へ書き込みます。
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "DeepSeek"
|
||||
base_url = "https://api.deepseek.com"
|
||||
wire_api = "responses"
|
||||
experimental_bearer_token = "sk-..."
|
||||
```
|
||||
|
||||
同時に、`auth.json` は公式ログインキャッシュを保持したままです。そのため Codex App 側では公式アカウントを認識でき、モデルリクエストは `config.toml` の現在の provider と base URL に従ってサードパーティ API へ向かいます。
|
||||
|
||||
プロバイダーが Chat Completions プロトコルの場合、CC Switch のローカルルーティングがさらに変換層になります。
|
||||
|
||||
```text
|
||||
Codex Responses リクエスト
|
||||
|
|
||||
CC Switch ローカルルート
|
||||
|
|
||||
サードパーティ Chat Completions API
|
||||
|
|
||||
Codex Responses レスポンスへ変換
|
||||
```
|
||||
|
||||
これにより、公式プラグイン / モバイルリモート操作を使い続けながら、モデル通信だけをサードパーティ API に切り替えられます。
|
||||
|
||||
## 理解しておくべき副作用
|
||||
|
||||
### Codex 内の表示アカウントは公式アカウントのまま
|
||||
|
||||
ここが最も誤解されやすい点です。この機能を有効化すると、Codex App は `auth.json` 内の公式ログイン状態を見るため、公式アカウント情報を表示し続けます。
|
||||
|
||||
ただし、これはモデルリクエストが公式 OpenAI に流れているという意味ではありません。実際の通信先は、CC Switch の現在の Codex プロバイダー、`config.toml`、ローカルルーティングログで判断してください。
|
||||
|
||||
### Codex のアカウント表示で課金先を判断しない
|
||||
|
||||
DeepSeek に切り替えた場合でも、Codex には公式アカウントが表示されます。しかしモデルリクエストは DeepSeek API へ送られます。課金、上限、エラーコード、データポリシーはサードパーティプロバイダー側の仕様として理解してください。具体的なリクエスト情報は使用量パネルで確認できます。
|
||||
|
||||
### モデルマッピングを変更したら Codex を再起動する
|
||||
|
||||
Codex のモデルカタログは起動時に読み込まれます。CC Switch が新しいモデルカタログを生成していても、実行中の Codex がホットロードするとは限りません。モデルマッピングを変更した後は Codex を再起動してください。
|
||||
|
||||
### スイッチをオフにすると旧動作に戻る
|
||||
|
||||
`サードパーティ切替時に公式ログインを保持` をオフにすると、サードパーティプロバイダー切り替えは旧バージョン互換の動作になり、`auth.json` が再度書き込まれる可能性があります。公式リモート操作と公式プラグインを長期的に保持したい場合は、このスイッチをオンのままにすることをおすすめします。
|
||||
|
||||
## よくある質問
|
||||
|
||||
**サードパーティ API に切り替えたのに、なぜ Codex はまだ公式アカウントを表示しますか?**
|
||||
|
||||
これは期待される動作です。公式アカウント情報は `auth.json` から取得され、実際のモデルプロバイダーは `config.toml` と CC Switch の現在のプロバイダーで決まります。
|
||||
|
||||
**Free サブスクリプションで本当に大丈夫ですか?**
|
||||
|
||||
大丈夫です。ここでの公式アカウントは、Codex App が必要とする公式ログイン状態を取得・保持するために使います。サードパーティモデルリクエストは、CC Switch に設定したサードパーティ API Key を使います。
|
||||
|
||||
**有効化しても公式プラグインやモバイルリモート操作が使えない場合は?**
|
||||
|
||||
まず `OpenAI Official` に戻し、Codex を再起動して一度公式ログインを完了してください。その後、CC Switch の `設定 → 一般 → Codex アプリ拡張 → サードパーティ切替時に公式ログインを保持` がオンになっていることを確認し、再度サードパーティプロバイダーへ切り替えてください。
|
||||
|
||||
**サードパーティリクエストが 404 になる、モデル一覧が違う、ストリーミング応答がおかしい場合は?**
|
||||
|
||||
そのプロバイダーが Chat Completions プロトコルの場合、プロバイダーフォームで `ローカルルーティングが必要` が有効になっていること、さらに `設定 → ルーティング` でルーティング総スイッチと Codex ルーティングがオンになっていることを確認してください。
|
||||
|
||||
**ローカルルーティング中に OpenAI Official へ戻せますか?**
|
||||
|
||||
おすすめしません。CC Switch は、ローカルルーティングで Codex を管理している間に公式プロバイダーへ切り替えることをできるだけ防ぎます。プロキシ経由で公式 API にアクセスすると、アカウントリスクが発生する可能性があるためです。公式ログインは `auth.json` を保持するために使い、モデル通信はサードパーティプロバイダーへ切り替えるのがおすすめです。
|
||||
|
||||
**なぜ手順がこんなに複雑なのですか?もっと簡単にできますか?**
|
||||
|
||||
Codex アプリ拡張やルーティング管理は、必要ないユーザーにとっては余計なトラブルになり得るため、常時有効ではなく明示的なスイッチになっています。
|
||||
|
||||
## 参考リンク
|
||||
|
||||
- [Codex DeepSeek ローカルルーティング実践ガイド](./codex-deepseek-routing-guide-ja.md)
|
||||
- [Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)
|
||||
- [ローカルプロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)
|
||||
- [ローカルルーティング](../user-manual/ja/4-proxy/4.2-routing.md)
|
||||
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-ja.md)
|
||||
@@ -0,0 +1,209 @@
|
||||
# 使用第三方 API 时保留 Codex 远程操作和官方插件:CC Switch 配置攻略
|
||||
|
||||
> 适用版本:CC Switch v3.16.1 及以上。本文根据当前代码、用户手册和 v3.16.1 Release Note 整理,截图使用去敏示例数据,不包含真实 Access Token 或 API Key。
|
||||
|
||||
## 这篇攻略解决什么问题
|
||||
|
||||
很多人使用 Codex 时有两个需求:
|
||||
|
||||
1. 模型使用 DeepSeek、Kimi、GLM、MiniMax、硅基流动等第三方 API,或者在中转站使用 gpt 模型。
|
||||
2. 保留 Codex 官方 App 的手机远程操作、官方插件等能力。
|
||||
|
||||
之前切换第三方供应商时,旧行为会把第三方 API Key 写进 Codex 的 `auth.json`,从而覆盖原来的官方 ChatGPT / Codex 登录缓存。这样第三方模型能用了,但依赖官方登录态的功能会消失。
|
||||
|
||||
v3.16.1 新增的 **Codex 应用增强**开关就是为了解决这个矛盾:让官方 Access Token 继续留在 `auth.json`,而第三方供应商信息写入 `config.toml`。这样 Codex App 仍然认为你登录的是官方账号,但实际模型请求会走 CC Switch 当前选中的第三方供应商。
|
||||
|
||||
v3.16.0 就有这个功能,并且默认开启,但是部分用户反映并不想要这个功能,所以在 v3.16.1 中把这个功能做成了开关。
|
||||
|
||||
## 先看结论
|
||||
|
||||
推荐顺序是:
|
||||
|
||||
1. 在 CC Switch 的 Codex 面板切换到 `OpenAI Official`。
|
||||
2. 启动 Codex,并用官方 ChatGPT / Codex 账号登录一次,Free 订阅也可以。
|
||||
3. 回到 CC Switch,打开 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录`。
|
||||
4. 添加或切换到第三方 Codex 供应商。
|
||||
5. 如果该供应商是 Chat Completions 协议,例如 DeepSeek / Kimi / MiniMax,需要同时开启本地路由并启用 Codex 接管。
|
||||
6. 重启 Codex,让 `config.toml` 和模型目录重新加载。
|
||||
|
||||

|
||||
|
||||
## 准备工作
|
||||
|
||||
你需要准备:
|
||||
|
||||
- CC Switch v3.16.1 或更新版本。
|
||||
- 已安装并能启动的 Codex(建议 app 和 cli 都安装)。
|
||||
- 一个可以登录 Codex 的官方 ChatGPT / Codex 账号,Free 订阅即可。
|
||||
- 一个第三方 API Key,例如 DeepSeek、Kimi、GLM、MiniMax、OpenRouter、硅基流动等。
|
||||
|
||||
请不要手动复制或分享 `~/.codex/auth.json` 的内容。里面保存的是官方登录缓存和 Access Token,属于敏感信息。
|
||||
|
||||
## 第一步:先切回 OpenAI Official 并完成官方登录
|
||||
|
||||
打开 CC Switch,切到顶部的 `Codex` 标签页。先选择 `OpenAI Official` 供应商(如果没有的话,就在预设供应商当中添加一个),并把它设为当前供应商。
|
||||
|
||||

|
||||
|
||||
接着启动 Codex(建议启动 cli),按 Codex 的官方登录流程登录你的 ChatGPT / Codex 账号。这个账号可以是 Free 订阅;在这个方案里,它主要负责保留 Codex 官方 App 需要识别的登录身份,不负责第三方模型的计费。
|
||||
|
||||
登录完成后,Codex 会在 `~/.codex/auth.json` 中保存官方登录缓存。后面的关键点就是:不要再让第三方供应商切换覆盖这个文件。
|
||||
|
||||
## 第二步:开启 Codex 应用增强
|
||||
|
||||
回到 CC Switch,进入:
|
||||
|
||||
```text
|
||||
设置 → 通用 → Codex 应用增强
|
||||
```
|
||||
|
||||
打开:
|
||||
|
||||
```text
|
||||
切换第三方时保留官方登录
|
||||
```
|
||||
|
||||
这个开关默认关闭,是因为部分用户并不想要这个功能。只有在你明确需要“第三方 API + 官方远程操作 / 官方插件”同时存在时,才需要开启它。
|
||||
|
||||
开启后,后端切换 Codex 第三方供应商时会走 config-only 写入路径:
|
||||
|
||||
- `auth.json`:继续保留官方 ChatGPT / Codex 登录缓存。
|
||||
- `config.toml`:写入当前第三方供应商的模型、endpoint、`model_provider` 和 provider-scoped `experimental_bearer_token`。
|
||||
|
||||
## 第三步:添加第三方 Codex 供应商
|
||||
|
||||
回到 Codex 面板,点击右上角的加号添加供应商。推荐优先使用内置预设,例如 DeepSeek、Kimi、MiniMax、GLM、SiliconFlow 等。
|
||||
|
||||
以 DeepSeek 为例,选择预设后只需要填 API Key。预设会自动配置 base URL、默认模型、模型映射表和“需要本地路由映射”。
|
||||
|
||||

|
||||
|
||||
如果你的第三方供应商原生支持 OpenAI Responses API(比如提供 gpt 模型的中转站),可以不启用本地路由。
|
||||
如果它只支持 OpenAI Chat Completions,例如常见的 DeepSeek / Kimi / MiniMax 路径,就必须启用本地路由,让 CC Switch 把 Codex 的 Responses 请求转换成 Chat Completions 请求。
|
||||
|
||||
## 第四步:需要时开启本地路由并接管 Codex
|
||||
|
||||
进入:
|
||||
|
||||
```text
|
||||
设置 → 路由 → 本地路由
|
||||
```
|
||||
|
||||
完成两件事:
|
||||
|
||||
1. 打开 `路由总开关`,启动本地服务。默认地址通常是 `127.0.0.1:15721`。
|
||||
2. 在 `路由启用` 中打开 `Codex`。
|
||||
|
||||

|
||||
|
||||
接管后,Codex 的 live `config.toml` 会临时指向 CC Switch 本地路由。真实第三方 API Key 仍然存储在 CC Switch 的供应商配置中,切换供应商时再投影到 `config.toml` 的 `experimental_bearer_token`。
|
||||
|
||||
## 第五步:切换第三方供应商并重启 Codex
|
||||
|
||||
回到 Codex 供应商列表,启用你刚添加的第三方供应商。切换完成后建议重启 Codex,原因有两个:
|
||||
|
||||
- Codex 在启动时读取 `config.toml`。
|
||||
- Codex 的 `/model` 菜单通常需要重启后才会重新加载 `model_catalog_json`。
|
||||
|
||||
重启后,你可以做一个简单验证:
|
||||
|
||||
- 在 Codex App 里,账号信息仍然显示官方账号,这是预期行为。
|
||||
- 在 CC Switch 里,当前 Codex 供应商显示为第三方供应商。
|
||||
- 如果开启了本地路由,请求日志或路由统计会看到 Codex 请求经过本地路由。
|
||||
- 第三方供应商后台或余额记录会出现实际模型请求。
|
||||
|
||||
## 背后的原理
|
||||
|
||||
Codex 的配置主要分成两个文件:
|
||||
|
||||
```text
|
||||
~/.codex/auth.json
|
||||
~/.codex/config.toml
|
||||
```
|
||||
|
||||
这两个文件承担的职责不同:
|
||||
|
||||
- `auth.json` 保存官方 ChatGPT / Codex 登录缓存,也就是 Codex App 识别官方账号、远程操作和官方插件所需的登录材料。
|
||||
- `config.toml` 保存当前模型供应商、base URL、模型、模型目录和 provider-scoped token 等运行配置。
|
||||
|
||||
开启 `切换第三方时保留官方登录` 后,CC Switch 的切换逻辑会把第三方供应商 API Key 从供应商配置中取出,写到 `config.toml` 的当前 provider 下:
|
||||
|
||||
```toml
|
||||
model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "DeepSeek"
|
||||
base_url = "https://api.deepseek.com"
|
||||
wire_api = "responses"
|
||||
experimental_bearer_token = "sk-..."
|
||||
```
|
||||
|
||||
同时,`auth.json` 保持官方登录缓存不变。于是 Codex App 侧依然能识别官方账号;而模型请求会根据 `config.toml` 的当前 provider 和 base URL 走第三方 API。
|
||||
|
||||
如果供应商是 Chat Completions 协议,CC Switch 本地路由会再做一层转换:
|
||||
|
||||
```text
|
||||
Codex Responses 请求
|
||||
↓
|
||||
CC Switch 本地路由
|
||||
↓
|
||||
第三方 Chat Completions API
|
||||
↓
|
||||
转换回 Codex Responses 响应
|
||||
```
|
||||
|
||||
这就是为什么你既能继续使用官方插件 / 手机远程操作,又能把模型流量切到第三方 API。
|
||||
|
||||
## 需要理解的副作用
|
||||
|
||||
### Codex 里显示的账号始终是官方账号
|
||||
|
||||
这是最容易误解的一点。开启该能力后,Codex App 看到的是 `auth.json` 里的官方登录态,所以它会继续显示官方账号信息。
|
||||
|
||||
但这不代表模型请求还在走官方 OpenAI。实际流量以 CC Switch 当前 Codex 供应商、`config.toml` 和本地路由日志为准。
|
||||
|
||||
### 不要用 Codex 账号信息判断计费方
|
||||
|
||||
如果你切到 DeepSeek,Codex 里仍然显示官方账号,但模型请求会走 DeepSeek API。计费、限额、错误码和数据策略都应按第三方供应商理解。可以查看设置用量面板里的具体请求信息。
|
||||
|
||||
### 修改模型映射后要重启 Codex
|
||||
|
||||
Codex 的模型目录是启动时读取的。即使 CC Switch 已经生成了新的模型目录,正在运行的 Codex 也不一定会热加载,所以修改模型映射后请重启 Codex。
|
||||
|
||||
### 关闭开关会回到旧行为
|
||||
|
||||
如果关闭 `切换第三方时保留官方登录`,第三方供应商切换会沿用兼容旧版本的行为,可能重新写入 `auth.json`。如果你的目标是长期保留官方远程操作和官方插件,建议保持该开关开启。
|
||||
|
||||
## 常见问题
|
||||
|
||||
**我已经切到第三方 API,为什么 Codex 还显示官方账号?**
|
||||
|
||||
这是预期行为。官方账号信息来自 `auth.json`,模型请求的实际供应商来自 `config.toml` 和 CC Switch 当前供应商。
|
||||
|
||||
**Free 订阅真的可以吗?**
|
||||
|
||||
可以。这里的官方账号主要用于获取并保留 Codex App 需要的官方登录态。第三方模型请求使用的是你在 CC Switch 里配置的第三方 API Key。
|
||||
|
||||
**开启后官方插件或手机远程操作还是不可用怎么办?**
|
||||
|
||||
先切回 `OpenAI Official`,重新启动 Codex 并完成一次官方登录;然后确认 CC Switch 的 `设置 → 通用 → Codex 应用增强 → 切换第三方时保留官方登录` 已开启,再切回第三方供应商。
|
||||
|
||||
**第三方请求 404、模型列表不对或流式响应异常怎么办?**
|
||||
|
||||
如果该供应商是 Chat Completions 协议,请确认供应商表单里开启了 `需要本地路由映射`,并且 `设置 → 路由` 里已经启动路由总开关、启用 Codex 接管。
|
||||
|
||||
**可以在本地路由模式下切回 OpenAI Official 吗?**
|
||||
|
||||
不建议。CC Switch 会尽量阻止在本地路由接管模式下切到官方供应商,因为用代理访问官方 API 可能带来账号风险。建议官方登录只用于保留 `auth.json`,模型流量则切到第三方供应商。
|
||||
|
||||
**为什么流程做的这么复杂?可以简化吗?**
|
||||
|
||||
因为 Codex 增强开关和路由接管等一系列功能,如果用户并不需要的话,默认打开会带来不必要的麻烦,所以都做成了开关形式。
|
||||
|
||||
## 参考链接
|
||||
|
||||
- [Codex DeepSeek 本地路由实战攻略](./codex-deepseek-routing-guide-zh.md)
|
||||
- [添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)
|
||||
- [本地代理服务](../user-manual/zh/4-proxy/4.1-service.md)
|
||||
- [本地路由](../user-manual/zh/4-proxy/4.2-routing.md)
|
||||
- [CC Switch v3.16.1 Release Note](../release-notes/v3.16.1-zh.md)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 87 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 159 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 116 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 185 KiB |
@@ -6,6 +6,16 @@
|
||||
|
||||
---
|
||||
|
||||
## Usage Guide
|
||||
|
||||
The two headline capabilities in this release are **Codex third-party provider Chat Completions routing** and **in-app managed CLI tool management**. If you want providers that only speak the OpenAI Chat protocol (DeepSeek, Kimi, MiniMax, etc.) to work directly in Codex, or want to install / upgrade CLI tools from one place inside the app, start with these guides:
|
||||
|
||||
- **[Using DeepSeek in Codex: local routing hands-on guide](../guides/codex-deepseek-routing-guide-en.md)** — uses the built-in DeepSeek preset to walk through adding a Codex provider, enabling local routing, and verifying request forwarding.
|
||||
- **[Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)** — covers the "Needs Local Routing" toggle, the model mapping table, and reasoning (thinking) auto-detection.
|
||||
- **[Settings → About: managed CLI tool management](../user-manual/en/1-getting-started/1.5-settings.md)** — covers version detection, per-tool / update-all upgrades, conflict diagnostics, and source-anchored upgrade commands.
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## Only Official Channels (Please Read)
|
||||
@@ -24,15 +34,6 @@
|
||||
|
||||
---
|
||||
|
||||
## Usage Guide
|
||||
|
||||
The two headline capabilities in this release are **Codex third-party provider Chat Completions routing** and **in-app managed CLI tool management**. If you want providers that only speak the OpenAI Chat protocol (DeepSeek, Kimi, MiniMax, etc.) to work directly in Codex, or want to install / upgrade CLI tools from one place inside the app, start with these two:
|
||||
|
||||
- **[Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)** — covers the "Needs Local Routing" toggle, the model mapping table, and reasoning (thinking) auto-detection.
|
||||
- **[Settings → About: managed CLI tool management](../user-manual/en/1-getting-started/1.5-settings.md)** — covers version detection, per-tool / update-all upgrades, conflict diagnostics, and source-anchored upgrade commands.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.16.0's development since v3.15.0 centers on **promoting third-party Codex providers to first-class citizens through Chat Completions routing**. Codex natively only speaks the OpenAI Responses API and GPT-family models; this release lets CC Switch's local proxy convert Codex's outgoing Responses requests into Chat Completions and rebuild the JSON and SSE streaming responses back into Responses shape, preserving `reasoning_content` / inline `<think>` blocks / streamed reasoning summaries / tool calls / `previous_response_id` follow-ups along the way, normalizing error envelopes, and probing Chat-format providers correctly in Stream Check. It ships 22 Chat-routing presets with explicit model catalogs (DeepSeek, Zhipu GLM, Kimi, MiniMax, StepFun, Baidu Qianfan, Bailian, ModelScope, Longcat, BaiLing, Xiaomi MiMo, Volcengine Agentplan, BytePlus, DouBao Seed, SiliconFlow, Novita AI, Nvidia, and more).
|
||||
|
||||
@@ -6,6 +6,16 @@
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースの主役となる 2 つの機能は、**Codex サードパーティプロバイダーの Chat Completions ルーティング**と**アプリ内の管理対象 CLI ツール管理**です。OpenAI Chat プロトコルにしか対応していないプロバイダー(DeepSeek、Kimi、MiniMax など)を Codex で直接使いたい場合、またはアプリ内で CLI ツールの一括インストール / アップグレードをしたい場合は、まずこちらをご覧ください:
|
||||
|
||||
- **[Codex で DeepSeek を使う: ローカルルーティング実践ガイド](../guides/codex-deepseek-routing-guide-ja.md)** —— DeepSeek 内蔵プリセットを例に、Codex プロバイダーの追加、ローカルルーティングの有効化、リクエスト転送の確認までを説明します。
|
||||
- **[Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)** —— 「ローカルルーティングが必要」トグル、モデルマッピングテーブル、思考能力(reasoning)の自動判別までの一連の流れを説明しています。
|
||||
- **[設定 → バージョン情報: 管理対象 CLI ツール管理](../user-manual/ja/1-getting-started/1.5-settings.md)** —— バージョン検出、個別アップグレード / 全体アップグレード、競合診断、インストール元にアンカーされたアップグレードコマンドを説明しています。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一の公式チャネル(必ずお読みください)
|
||||
@@ -24,15 +34,6 @@
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースの主役となる 2 つの機能は、**Codex サードパーティプロバイダーの Chat Completions ルーティング**と**アプリ内蔵の受託 CLI ツール管理**です。OpenAI Chat プロトコルにしか対応していないプロバイダー(DeepSeek、Kimi、MiniMax など)を Codex で直接使いたい場合、またはアプリ内で CLI ツールの一括インストール / アップグレードをしたい場合は、まずこの 2 つをご覧ください:
|
||||
|
||||
- **[Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)** —— 「ローカルルーティングが必要」トグル、モデルマッピングテーブル、思考能力(reasoning)の自動判別までの一連の流れを説明しています。
|
||||
- **[設定 → バージョン情報: 受託 CLI ツール管理](../user-manual/ja/1-getting-started/1.5-settings.md)** —— バージョン検出、個別アップグレード / 全体アップグレード、競合診断、インストール元にアンカーされたアップグレードコマンドを説明しています。
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.16.0 の v3.15.0 以降の開発のコアは、**サードパーティ Codex プロバイダーを Chat Completions ルーティングによって一等市民へ昇格させること**です。Codex はネイティブには OpenAI Responses API と GPT 系モデルしか認識しませんが、本リリースでは CC Switch のローカルプロキシが Codex の送出する Responses リクエストを Chat Completions に変換し、JSON と SSE のストリーミングレスポンスを Responses 形態へ再構築します。その道中で `reasoning_content` / インライン `<think>` ブロック / ストリーミング推論サマリー / ツール呼び出し / `previous_response_id` の継続を保持し、エラーエンベロープを正規化し、Stream Check で Chat 形式プロバイダーを正しくプローブします。あわせて明示的なモデルカタログ付きの 22 個の Chat ルーティングプリセット(DeepSeek、Zhipu GLM、Kimi、MiniMax、StepFun、Baidu Qianfan、Bailian、ModelScope、Longcat、BaiLing、Xiaomi MiMo、Volcengine Agentplan、BytePlus、DouBao Seed、SiliconFlow、Novita AI、Nvidia など)を出荷します。
|
||||
|
||||
@@ -6,6 +6,16 @@
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
本版本最主打的两块能力是 **Codex 第三方供应商 Chat Completions 路由**与**应用内受管 CLI 工具管理**。如果你想让 DeepSeek、Kimi、MiniMax 这类只支持 OpenAI Chat 协议的供应商在 Codex 里直接可用,或者想在应用内一站式安装 / 升级 CLI 工具,建议先读这几篇:
|
||||
|
||||
- **[在 Codex 中使用 DeepSeek:本地路由实战攻略](../guides/codex-deepseek-routing-guide-zh.md)** —— 以 DeepSeek 内置预设为例,演示从添加 Codex 供应商、开启本地路由到验证请求转发的完整路径。
|
||||
- **[添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)** —— 覆盖「需要本地路由映射」开关、模型映射表、思考能力(reasoning)自适应识别的完整流程。
|
||||
- **[设置 → 关于:受管 CLI 工具管理](../user-manual/zh/1-getting-started/1.5-settings.md)** —— 覆盖版本检测、单独升级 / 全部升级、冲突诊断、按安装来源锚定的升级命令。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一官方渠道声明(请务必阅读)
|
||||
@@ -24,15 +34,6 @@
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
本版本最主打的两块能力是 **Codex 第三方供应商 Chat Completions 路由**与**应用内受管 CLI 工具管理**。如果你想让 DeepSeek、Kimi、MiniMax 这类只支持 OpenAI Chat 协议的供应商在 Codex 里直接可用,或者想在应用内一站式安装 / 升级 CLI 工具,建议先读这两篇:
|
||||
|
||||
- **[添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)** —— 覆盖「需要本地路由映射」开关、模型映射表、思考能力(reasoning)自适应识别的完整流程。
|
||||
- **[设置 → 关于:受管 CLI 工具管理](../user-manual/zh/1-getting-started/1.5-settings.md)** —— 覆盖版本检测、单独升级 / 全部升级、冲突诊断、按安装来源锚定的升级命令。
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.16.0 自 v3.15.0 以来的开发核心,是把**第三方 Codex 供应商通过 Chat Completions 路由升级为一等公民**。Codex 原生只认 OpenAI Responses API 与 GPT 系列模型,本版本让 CC Switch 的本地代理把 Codex 发出的 Responses 请求转换为上游的 Chat Completions,再把 JSON 与 SSE 流式响应重建回 Responses 形态,沿途保留 `reasoning_content` / 内联 `<think>` 块 / 流式推理摘要 / 工具调用 / `previous_response_id` 续接状态,并把错误信封规范化、在 Stream Check 中正确探测 Chat 格式供应商。配套上货 22 个带显式模型目录的 Chat 路由预设(DeepSeek、智谱 GLM、Kimi、MiniMax、StepFun、百度千帆、百炼、ModelScope、Longcat、百灵、小米 MiMo、火山 Agentplan、BytePlus、豆包 Seed、SiliconFlow、Novita AI、Nvidia 等)。
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
# CC Switch v3.16.1
|
||||
|
||||
> Codex stability patch: because some users did not want CC Switch to change how Codex config files are written, Codex App Enhancements now has a switch and is off by default. After enabling it, you can keep using Codex mobile remote control, official plugins, and other official-app features while using third-party APIs; this release also includes a series of stability fixes.
|
||||
|
||||
**[中文版 →](v3.16.1-zh.md) | [日本語版 →](v3.16.1-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Usage Guides
|
||||
|
||||
If you want to unlock official-subscription-only Codex remote control and official plugins while using third-party APIs, or want to use DeepSeek / Kimi / GLM / MiniMax and other Chat Completions upstreams in Codex, start with these docs:
|
||||
|
||||
- **[Keep Codex remote control and official plugins while using third-party APIs](../guides/codex-official-auth-preservation-guide-en.md)**: explains how to complete official login first, enable Codex App Enhancements, keep official login state in `auth.json`, and route model traffic to third-party APIs.
|
||||
- **[Using DeepSeek in Codex: local routing hands-on guide](../guides/codex-deepseek-routing-guide-en.md)**: walks through adding a Codex provider, enabling local routing, and verifying request forwarding.
|
||||
- **[Add a Codex provider: Chat Completions routing and model mapping](../user-manual/en/2-providers/2.1-add.md)**: covers the "Needs Local Routing" option, model mapping table, and reasoning capability configuration.
|
||||
- **[Local Proxy Service](../user-manual/en/4-proxy/4.1-service.md)** and **[Local Routing](../user-manual/en/4-proxy/4.2-routing.md)**: explain the proxy service, live-config takeover, and related risk notes.
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## Only Official Channels (Please Read)
|
||||
>
|
||||
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
|
||||
>
|
||||
> | Channel | Only Official |
|
||||
> | ------------------ | ------------------------------------------------------------------------------ |
|
||||
> | Website | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | Author | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.16.1 is a Codex stability patch following v3.16.0. v3.16.0 promoted third-party Codex providers to first-class citizens through Chat Completions routing; this release focuses on several high-risk edges discovered in real use: official ChatGPT / Codex OAuth login state could be overwritten while switching third-party providers or during local routing takeover, the Codex model catalog could be cleared during live backfill, hot switching, takeover shutdown restore, or editing the active provider, and Codex `tool_search`, plugin / connector namespace tools, and custom tools were not fully restored back into Responses events on the Chat Completions upstream path.
|
||||
|
||||
This release also hardens local routing takeover ownership checks. Provider switching and takeover toggles now run serially per app. When deciding whether the live files are proxy-managed, CC Switch no longer relies only on stale `enabled` state or whether the proxy service is currently running; it also checks backups and proxy placeholders in the live files. This prevents ordinary live writes from overwriting proxy-managed config immediately after takeover is enabled, while the proxy is temporarily stopped, or during hot switching.
|
||||
|
||||
**Release date**: 2026-06-01
|
||||
|
||||
**Stats**: 23 commits | 62 files changed | +5,603 insertions | -1,113 deletions
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **Safer Codex OAuth and third-party provider switching**: added an optional official-auth preservation setting. When enabled, third-party provider tokens are written to `config.toml`, while official ChatGPT / Codex OAuth login stays in `auth.json`.
|
||||
- **Codex model catalogs are no longer silently wiped**: `modelCatalog` now treats the database as the source of truth, avoiding overwrites from live configs with missing catalog projections during live backfill, provider switching, takeover shutdown restore, and provider editing.
|
||||
- **Codex Chat tools / plugin routing restored**: `tool_search`, loaded namespace tools, and custom tools from Chat Completions upstreams are remapped back to Codex Responses shape; streaming custom tools now emit native `response.custom_tool_call_input.*` events.
|
||||
- **More stable local routing takeover and hot switching**: provider switching and takeover toggles are serialized per app. Hot switching refreshes provider display information in Codex live config while keeping the endpoint pointed at the local proxy.
|
||||
- **Diagnostics and platform compatibility fixes**: Codex proxy errors now include richer context; Codex CLI model-template discovery supports more platforms and falls back to a static GPT-5.5 template; Windows tool version detection fixes localized output and command quoting issues.
|
||||
|
||||
---
|
||||
|
||||
## Added
|
||||
|
||||
### Codex Official Auth Preservation Setting
|
||||
|
||||
Added an optional setting for preserving official ChatGPT / Codex OAuth login state when switching to third-party Codex providers. When enabled, CC Switch stores third-party provider API keys in the provider-scoped `experimental_bearer_token` inside Codex `config.toml` instead of overwriting the official login cache in `auth.json`.
|
||||
|
||||
Because some users do not want this feature to change how config files are written, the setting is off by default and keeps the compatibility behavior from before v3.16.0. Users who need both official Codex login and third-party providers can manually enable it under Settings -> Codex App Enhancements.
|
||||
|
||||
### Codex DeepSeek Routing Guide
|
||||
|
||||
Added Codex DeepSeek routing guides in Chinese, English, and Japanese, covering provider routing requirements, the DeepSeek Codex provider form, and screenshot-based local routing takeover instructions.
|
||||
|
||||
---
|
||||
|
||||
## Changed
|
||||
|
||||
### Codex Auth Preservation Is Now Opt-In
|
||||
|
||||
Official auth preservation is off by default. Third-party Codex provider switching therefore keeps the old behavior unless the user opts in, avoiding surprise changes to how `auth.json` / `config.toml` are written.
|
||||
|
||||
### Codex Restart Prompt After Provider Switching
|
||||
|
||||
Codex loads the model catalog and part of its config at startup. After successfully switching a Codex provider, the UI now reminds the user to restart Codex so model catalog and config changes actually take effect.
|
||||
|
||||
### Provider Switching and Takeover Toggles Are Serialized
|
||||
|
||||
Codex / Claude / Gemini provider switching and local routing takeover toggles now share a per-app lock, avoiding concurrent writes to live config and backups. Ownership checks also prioritize live backups and the `PROXY_MANAGED` placeholder instead of relying only on whether the proxy service is running.
|
||||
|
||||
### Codex Hot Switching Refreshes Display Info
|
||||
|
||||
When hot switching Codex providers during local routing takeover, CC Switch refreshes the provider id, model, and display name in the live config so the Codex client menu follows the active provider. The base URL still stays pointed at the local proxy, preventing the real upstream endpoint from leaking back into the live file.
|
||||
|
||||
---
|
||||
|
||||
## Fixed
|
||||
|
||||
### Codex Provider Editor Showing Live OAuth During Takeover
|
||||
|
||||
When Codex is under local routing takeover, live `auth.json` / `config.toml` are temporarily rewritten by the proxy. Editing the active provider from those live files could incorrectly show proxy placeholders or official OAuth login as provider config. The editor now explicitly explains that it is showing the provider config stored in the database, not the proxy-managed live files; even if the proxy service is temporarily stopped, CC Switch still treats the app as under takeover when the takeover state indicates so.
|
||||
|
||||
### Codex OAuth Cleared or Overwritten During Takeover
|
||||
|
||||
Fixed multiple preserve-mode takeover paths that could clear or overwrite official ChatGPT / Codex OAuth `auth.json`. Takeover detection now recognizes `PROXY_MANAGED` in `config.toml`, cleanup only removes proxy placeholder tokens, and third-party providers misclassified as official no longer enter the official-auth overwrite path. Provider sync and switching also treat live backups and placeholders as takeover ownership signals, preventing normal live writes from overwriting proxy config right after takeover or while the proxy is paused.
|
||||
|
||||
### Codex Model Catalog Data Loss
|
||||
|
||||
Fixed cases where `modelCatalog` could be cleared during live backfill, active-provider editing, provider switching, and takeover shutdown restore. Snapshot backups preserve existing `model_catalog_json` pointers; backups rebuilt from providers regenerate catalog projections from the database source of truth; editing the active provider now prefers the database model catalog instead of trusting a live reverse-parse result that may have lost its projection.
|
||||
|
||||
Provider switching also now always refreshes the generated Codex model catalog JSON ([#3360](https://github.com/farion1231/cc-switch/pull/3360), thanks [@Postroggy](https://github.com/Postroggy)).
|
||||
|
||||
### Codex Chat Tools, Plugins, and Custom Tools Restored
|
||||
|
||||
Fixed Chat Completions routing for third-party Codex providers so `tool_search`, loaded MCP / connector namespace tools, and custom tools are fully restored back into Codex Responses shape. Non-streaming and streaming Chat responses now recover the correct tool type, namespace, call id, and arguments from the original Responses request; custom-tool streaming now emits native `response.custom_tool_call_input.delta` and `response.custom_tool_call_input.done` events.
|
||||
|
||||
### Fuller Codex Proxy Error Diagnostics
|
||||
|
||||
When Codex forwarding fails, CC Switch now returns JSON errors that include provider, model, endpoint, upstream HTTP status, stable `cc_switch_*` error codes, and normalized HTTP status. This makes it much clearer which provider, endpoint, and upstream error caused the failure.
|
||||
|
||||
### Codex Native Balance / Coding Plan Credential Lookup
|
||||
|
||||
Fixed native balance and Coding Plan queries using credentials from the wrong app. Each app now resolves its own provider credentials instead of carrying authentication assumptions from another app surface into the query flow ([#3355](https://github.com/farion1231/cc-switch/pull/3355), thanks [@SiskonEmilia](https://github.com/SiskonEmilia)).
|
||||
|
||||
### Codex CLI Discovery and Model Catalog Template Fallback
|
||||
|
||||
Fixed a too-narrow Codex CLI discovery path for third-party Codex model catalog projection. The backend now searches common Codex CLI install locations across platforms, and falls back to a built-in GPT-5.5 model catalog template if no template can be found ([#3382](https://github.com/farion1231/cc-switch/pull/3382), thanks [@chofuhoyu](https://github.com/chofuhoyu)).
|
||||
|
||||
### Claude Desktop Official Provider Add Failure
|
||||
|
||||
Fixed an error when adding the Claude Desktop Official provider ([#3405](https://github.com/farion1231/cc-switch/pull/3405), thanks [@Eunknight](https://github.com/Eunknight)).
|
||||
|
||||
### Kimi / Moonshot Tool-Thinking History Normalization
|
||||
|
||||
Added Kimi / Moonshot to the Anthropic-compatible tool-thinking history normalizer. Later turns can now correctly replay reasoning and tool-call context, avoiding failures caused by history messages that do not match upstream requirements ([#3377](https://github.com/farion1231/cc-switch/pull/3377), thanks [@Neon-Wang](https://github.com/Neon-Wang)).
|
||||
|
||||
### Windows Tool Version Detection
|
||||
|
||||
Fixed incorrect quoting for `.cmd` / `.bat` version commands on Windows, and fixed localized command output being decoded as mojibake. Previously, these issues could make runnable tools appear as "installed but not runnable."
|
||||
|
||||
---
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
### Official OAuth Preservation Must Be Enabled Manually
|
||||
|
||||
If you want official ChatGPT / Codex OAuth login to stay in `auth.json` while you frequently switch third-party Codex providers, enable Codex official auth preservation in Settings. It is off by default to keep compatibility for existing users.
|
||||
|
||||
### Restart Codex After Editing Model Mappings
|
||||
|
||||
Codex reads `model_catalog_json` at startup. Even though v3.16.1 fixes model catalog wiping, Codex still needs to be restarted after you edit the model mapping table so the `/model` menu refreshes.
|
||||
|
||||
### During Takeover, the Editor Shows Stored Config, Not Live Files
|
||||
|
||||
When local routing takeover is enabled, live `auth.json` / `config.toml` temporarily point to the CC Switch proxy. The provider editor therefore shows the provider config saved in the database. This is expected; after takeover is disabled, CC Switch restores live config from backups or the database source of truth.
|
||||
|
||||
---
|
||||
|
||||
## Risk Notice
|
||||
|
||||
This release continues the risk notices from previous versions for reverse-proxy-style features.
|
||||
|
||||
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice) for details.
|
||||
|
||||
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
|
||||
|
||||
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
|
||||
|
||||
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
|
||||
|
||||
---
|
||||
|
||||
## Thanks
|
||||
|
||||
Thanks to the following contributors for fixes in v3.16.1:
|
||||
|
||||
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): always update Codex model catalog JSON when switching providers, thanks [@Postroggy](https://github.com/Postroggy).
|
||||
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): resolve native balance / Coding Plan credentials per app, thanks [@SiskonEmilia](https://github.com/SiskonEmilia).
|
||||
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): fix Claude Desktop Official provider add failure, thanks [@Eunknight](https://github.com/Eunknight).
|
||||
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI multi-platform discovery and GPT-5.5 model template fallback, thanks [@chofuhoyu](https://github.com/chofuhoyu).
|
||||
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot tool-thinking history normalization, thanks [@Neon-Wang](https://github.com/Neon-Wang).
|
||||
|
||||
Thanks also to everyone who reported Codex OAuth, model catalog, local routing takeover, and Chat Completions tool-call issues after v3.16.0. Many of these fixes came directly from real-world reproduction details.
|
||||
|
||||
---
|
||||
|
||||
## Download & Install
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 and later | x64 |
|
||||
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ----------------------------------------------- |
|
||||
| `CC-Switch-v3.16.1-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.16.1-Windows-Portable.zip` | Portable build, unzip and run |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ----------------------------------------------------- |
|
||||
| `CC-Switch-v3.16.1-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
|
||||
| `CC-Switch-v3.16.1-macOS.zip` | Unzip and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.16.1-macOS.tar.gz` | For Homebrew install and auto-update |
|
||||
|
||||
Homebrew install:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
|
||||
|
||||
- `CC-Switch-v3.16.1-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.1-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| Distribution | Recommended Format | Install Command |
|
||||
| ---------------------------------------- | ------------------ | ---------------------------------------------------------------------- |
|
||||
| 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` | Make executable and run directly, or use AUR |
|
||||
| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,236 @@
|
||||
# CC Switch v3.16.1
|
||||
|
||||
> Codex 安定性パッチ: 一部のユーザーから「設定ファイルの書き込み方式を変えたくない」というフィードバックがあったため、Codex アプリ拡張にスイッチを追加し、デフォルトではオフにしました。有効化すると、サードパーティ API を使いながら Codex のモバイルリモート操作、公式プラグインなどの公式アプリ機能を引き続き利用できます。本リリースには一連の安定性修正も含まれます。
|
||||
|
||||
**[English →](v3.16.1-en.md) | [中文 →](v3.16.1-zh.md)**
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
サードパーティ API 利用中に、公式サブスクリプションでのみ使える Codex のリモート操作や公式プラグインを有効化したい場合、または DeepSeek / Kimi / GLM / MiniMax などの Chat Completions 上流を Codex で使いたい場合は、まず以下のドキュメントをご覧ください:
|
||||
|
||||
- **[サードパーティ API 利用時に Codex のリモート操作と公式プラグインを保持する](../guides/codex-official-auth-preservation-guide-ja.md)**: 先に公式ログインを完了し、Codex アプリ拡張を有効化して、公式ログイン状態を `auth.json` に残したままモデル通信をサードパーティ API へ切り替える手順を説明します。
|
||||
- **[Codex で DeepSeek を使う: ローカルルーティング実践ガイド](../guides/codex-deepseek-routing-guide-ja.md)**: Codex プロバイダーの追加、ローカルルーティングの有効化、リクエスト転送の確認までを説明します。
|
||||
- **[Codex プロバイダーの追加: Chat Completions ルーティングとモデルマッピング](../user-manual/ja/2-providers/2.1-add.md)**: 「ローカルルーティングが必要」設定、モデルマッピングテーブル、思考能力の設定を説明します。
|
||||
- **[ローカルプロキシサービス](../user-manual/ja/4-proxy/4.1-service.md)** と **[ローカルルーティング](../user-manual/ja/4-proxy/4.2-routing.md)**: プロキシサービス、live 設定のテイクオーバー、関連するリスク注意事項を説明します。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一の公式チャネル(必ずお読みください)
|
||||
>
|
||||
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
|
||||
>
|
||||
> | チャネル | 唯一の公式 |
|
||||
> | ------------ | ------------------------------------------------------------------------------ |
|
||||
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.16.1 は v3.16.0 に続く Codex 安定性パッチです。v3.16.0 では Chat Completions ルーティングによってサードパーティ Codex プロバイダーを一等市民にしました。本リリースでは、実際の利用で見つかったいくつかの高リスクなエッジケースを中心に修正しています。具体的には、サードパーティプロバイダーの切り替えやローカルルーティングのテイクオーバー中に公式 ChatGPT / Codex OAuth ログイン状態が上書きされる問題、live バックフィル・ホットスイッチ・テイクオーバー解除時の復元・現在のプロバイダー編集で Codex モデルカタログが空になる問題、そして Chat Completions 上流パスで Codex の `tool_search`、プラグイン / コネクタの namespace ツール、カスタムツールが Responses イベントへ完全には復元されない問題です。
|
||||
|
||||
本リリースではローカルルーティングのテイクオーバー所有権判定も強化しました。プロバイダー切り替えとテイクオーバートグルはアプリごとに直列実行されます。live ファイルがプロキシ管理下にあるかを判定するとき、遅延しがちな `enabled` 状態やプロキシサービスの起動状態だけに頼らず、バックアップと live 内のプロキシプレースホルダーも確認します。これにより、テイクオーバー直後、プロキシの一時停止中、ホットスイッチ中に、通常の live 書き込みがプロキシ管理設定を上書きしてしまうことを防ぎます。
|
||||
|
||||
**リリース日**: 2026-06-01
|
||||
|
||||
**Stats**: 23 commits | 62 files changed | +5,603 insertions | -1,113 deletions
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **Codex OAuth とサードパーティプロバイダー切り替えをより安全に**: 公式認証を保持する任意設定を追加しました。有効化すると、サードパーティプロバイダーの token は `config.toml` に書き込まれ、公式 ChatGPT / Codex OAuth ログインは `auth.json` に残ります。
|
||||
- **Codex モデルカタログが静かに消えないように**: `modelCatalog` はデータベースを信頼できる情報源として扱い、live バックフィル、プロバイダー切り替え、テイクオーバー解除時の復元、プロバイダー編集で、カタログ投影を失った live 設定によりデータベースが上書きされることを避けます。
|
||||
- **Codex Chat ツール / プラグインルーティングを復元**: Chat Completions 上流から返る `tool_search`、読み込み済み namespace ツール、カスタムツールを Codex Responses 形態へ再マッピングします。ストリーミングのカスタムツールはネイティブの `response.custom_tool_call_input.*` イベントを出力します。
|
||||
- **ローカルルーティングのテイクオーバーとホットスイッチがより安定**: プロバイダー切り替えとテイクオーバートグルはアプリごとに直列化されます。ホットスイッチ時は Codex live 内のプロバイダー表示情報を更新しつつ、endpoint は引き続きローカルプロキシを指します。
|
||||
- **診断とプラットフォーム互換性の修正**: Codex プロキシエラーがより豊富な文脈を返すようになりました。Codex CLI のモデルテンプレート探索はより多くのプラットフォームに対応し、静的な GPT-5.5 テンプレートのフォールバックを備えます。Windows のツールバージョン検出では、ローカライズ出力とコマンド引用符の問題を修正しました。
|
||||
|
||||
---
|
||||
|
||||
## 追加機能
|
||||
|
||||
### Codex 公式認証保持設定
|
||||
|
||||
サードパーティ Codex プロバイダーへ切り替えるときに、公式 ChatGPT / Codex OAuth ログイン状態を保持する任意設定を追加しました。有効化すると、CC Switch はサードパーティプロバイダーの API key を Codex `config.toml` の provider-scoped `experimental_bearer_token` に保存し、`auth.json` 内の公式ログインキャッシュを上書きしません。
|
||||
|
||||
一部のユーザーはこの機能によって設定ファイルの書き込み方式が変わることを望んでいないため、この設定はデフォルトでオフです。v3.16.0 以前の互換動作を維持します。公式 Codex ログインとサードパーティプロバイダーを同時に使いたい場合は、「設定 → Codex アプリ拡張」で手動で有効化できます。
|
||||
|
||||
### Codex DeepSeek ルーティングガイド
|
||||
|
||||
Codex DeepSeek ルーティングガイドを中国語 / 英語 / 日本語で追加しました。プロバイダーのルーティング要件、DeepSeek Codex プロバイダーフォームの設定、ローカルルーティングのテイクオーバー手順をスクリーンショット付きで説明します。
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### Codex 認証保持は opt-in に変更
|
||||
|
||||
公式認証保持設定はデフォルトでオフです。これにより、サードパーティ Codex プロバイダーの切り替えは従来の動作を維持し、ユーザーが気づかないうちに `auth.json` / `config.toml` の書き込み方式が変わることを避けます。
|
||||
|
||||
### Codex プロバイダー切り替え後に再起動を案内
|
||||
|
||||
Codex はモデルカタログと一部の設定をクライアント起動時に読み込みます。Codex プロバイダーの切り替えに成功した後、UI は Codex の再起動を案内し、モデルカタログと設定変更が実際に反映されるようにします。
|
||||
|
||||
### プロバイダー切り替えとテイクオーバートグルを直列化
|
||||
|
||||
Codex / Claude / Gemini のプロバイダー切り替えとローカルルーティングのテイクオーバートグルは、アプリごとのロックを共有するようになりました。これにより、2 つの処理が同時に live 設定とバックアップを書き換えることを避けます。live がプロキシ管理下にあるかの判定も、プロキシサービスが起動しているかだけでなく、live バックアップと `PROXY_MANAGED` プレースホルダーを優先して確認します。
|
||||
|
||||
### Codex ホットスイッチで表示情報を更新
|
||||
|
||||
ローカルルーティングのテイクオーバー中に Codex プロバイダーをホットスイッチすると、CC Switch は live 設定内の provider id、モデル、表示名を更新し、Codex クライアントのメニューが現在のプロバイダーに追従するようにします。同時に base URL はローカルプロキシアドレスのまま維持し、実際の上流 endpoint が live ファイルへ戻ってしまうことを防ぎます。
|
||||
|
||||
---
|
||||
|
||||
## 修正
|
||||
|
||||
### Codex テイクオーバー中の編集ダイアログが live OAuth を表示する問題
|
||||
|
||||
Codex がローカルルーティングのテイクオーバー状態にあるとき、live の `auth.json` / `config.toml` はプロキシによって一時的に書き換えられています。この live を読み続けると、現在のプロバイダー編集時にプロキシプレースホルダーや公式 OAuth ログインをプロバイダー設定として誤表示してしまいます。現在の編集ダイアログは、ここに表示されるのがプロキシ管理下の live ファイルではなく、データベースに保存されたプロバイダー設定であることを明示します。プロキシサービスが一時停止していても、そのアプリがテイクオーバー状態であればテイクオーバーとして扱います。
|
||||
|
||||
### Codex OAuth がテイクオーバー中に消去または上書きされる問題
|
||||
|
||||
公式 ChatGPT / Codex OAuth `auth.json` を消去または上書きする可能性があった複数の preserve-mode テイクオーバーパスを修正しました。テイクオーバー判定は `config.toml` 内の `PROXY_MANAGED` を認識し、クリーンアップはプロキシプレースホルダー token だけを削除します。サードパーティプロバイダーが official と誤分類されても、公式 auth の上書きパスには入りません。プロバイダー同期と切り替えでは、live バックアップとプレースホルダーをテイクオーバー所有権のシグナルとして扱い、テイクオーバー直後やプロキシ一時停止中に通常の live 書き込みがプロキシ設定を上書きすることを防ぎます。
|
||||
|
||||
### Codex モデルカタログのデータ消失
|
||||
|
||||
live バックフィル、現在のプロバイダー編集、プロバイダー切り替え、テイクオーバー解除時の復元などで `modelCatalog` が空になる問題を修正しました。スナップショットバックアップは既存の `model_catalog_json` ポインターを保持します。プロバイダーから再構築されるバックアップは、データベースの信頼できる情報源からカタログ投影を再生成します。現在のプロバイダー編集時は、投影を失っている可能性のある live の逆解析結果ではなく、データベース内のモデルカタログを優先します。
|
||||
|
||||
また、プロバイダー切り替え時には生成済みの Codex モデルカタログ JSON を常に更新するようになりました([#3360](https://github.com/farion1231/cc-switch/pull/3360)、[@Postroggy](https://github.com/Postroggy) に感謝)。
|
||||
|
||||
### Codex Chat ツール、プラグイン、カスタムツールの復元
|
||||
|
||||
サードパーティ Codex プロバイダーが Chat Completions ルーティングを通るとき、`tool_search`、読み込み済みの MCP / connector namespace ツール、カスタムツールを Codex Responses 形態へ完全に復元できない問題を修正しました。非ストリーミングとストリーミングの Chat レスポンスは、元の Responses リクエストに基づいて正しいツール種別、namespace、call id、引数を復元します。カスタムツールのストリーミング出力は、ネイティブの `response.custom_tool_call_input.delta` と `response.custom_tool_call_input.done` イベントを発行します。
|
||||
|
||||
### Codex プロキシエラー診断の拡充
|
||||
|
||||
Codex の転送に失敗したとき、provider、model、endpoint、上流 HTTP ステータス、安定した `cc_switch_*` エラーコード、正規化された HTTP ステータスを含む JSON エラーを返すようになりました。これにより、どのプロバイダー、どの endpoint、どの上流エラーが原因なのかを追いやすくなります。
|
||||
|
||||
### Codex ネイティブ残高 / Coding Plan の認証情報検索
|
||||
|
||||
ネイティブ残高と Coding Plan の照会時に、別アプリの認証情報を誤って使う問題を修正しました。各 app は自分自身のプロバイダー認証情報を解析し、別のアプリ面の認証前提を照会フローへ持ち込まなくなりました([#3355](https://github.com/farion1231/cc-switch/pull/3355)、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝)。
|
||||
|
||||
### Codex CLI 探索とモデルカタログテンプレートのフォールバック
|
||||
|
||||
サードパーティ Codex モデルカタログ投影における Codex CLI の探索パスが狭すぎる問題を修正しました。バックエンドは複数プラットフォームの一般的な Codex CLI インストール場所を探し、それでもテンプレートが見つからない場合は内蔵の GPT-5.5 モデルカタログテンプレートへフォールバックします([#3382](https://github.com/farion1231/cc-switch/pull/3382)、[@chofuhoyu](https://github.com/chofuhoyu) に感謝)。
|
||||
|
||||
### Claude Desktop Official プロバイダー追加失敗
|
||||
|
||||
Claude Desktop Official プロバイダー追加時のエラーを修正しました([#3405](https://github.com/farion1231/cc-switch/pull/3405)、[@Eunknight](https://github.com/Eunknight) に感謝)。
|
||||
|
||||
### Kimi / Moonshot ツール思考履歴の正規化
|
||||
|
||||
Kimi / Moonshot を Anthropic 互換ツール思考履歴 normalizer に追加しました。後続ターンで reasoning と tool-call コンテキストを正しく再生できるようになり、履歴メッセージの形が上流要件に合わず失敗する問題を避けます([#3377](https://github.com/farion1231/cc-switch/pull/3377)、[@Neon-Wang](https://github.com/Neon-Wang) に感謝)。
|
||||
|
||||
### Windows ツールバージョン検出
|
||||
|
||||
Windows で `.cmd` / `.bat` のバージョンコマンドに誤って引用符が付く問題と、ローカライズされたコマンド出力が文字化けしてデコードされる問題を修正しました。以前は、実行可能なツールが「インストール済みだが実行できない」と表示されることがありました。
|
||||
|
||||
---
|
||||
|
||||
## アップグレード時の注意
|
||||
|
||||
### 公式 OAuth 保持は手動で有効化が必要
|
||||
|
||||
公式 ChatGPT / Codex OAuth ログインを `auth.json` に長期保持しつつ、サードパーティ Codex プロバイダーを頻繁に切り替える場合は、設定で Codex 公式認証保持を有効化してください。既存ユーザーの互換動作を維持するため、デフォルトではオフです。
|
||||
|
||||
### モデルマッピング変更後は Codex の再起動が必要
|
||||
|
||||
Codex は起動時に `model_catalog_json` を読み込みます。v3.16.1 でモデルカタログが空になる問題は修正されていますが、モデルマッピングテーブルを変更した後は、`/model` メニューを更新するために Codex の再起動が必要です。
|
||||
|
||||
### テイクオーバー中に編集するのは保存済み設定であり live ファイルではありません
|
||||
|
||||
ローカルルーティングのテイクオーバーを有効化すると、live の `auth.json` / `config.toml` は一時的に CC Switch プロキシを指します。このときプロバイダー編集で表示されるのは、データベースに保存されたプロバイダー設定です。これは期待される動作です。テイクオーバーを無効化すると、CC Switch はバックアップまたはデータベースの信頼できる情報源から live 設定を復元します。
|
||||
|
||||
---
|
||||
|
||||
## リスク通知
|
||||
|
||||
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
|
||||
|
||||
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
|
||||
|
||||
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金、コンプライアンス、データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
|
||||
|
||||
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金、コンプライアンス、データ保持に関する規約に従う必要があります。
|
||||
|
||||
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## 謝辞
|
||||
|
||||
v3.16.1 で修正を届けてくださった以下のコントリビューターに感謝します:
|
||||
|
||||
- [#3360](https://github.com/farion1231/cc-switch/pull/3360): Codex プロバイダー切り替え時にモデルカタログ JSON を常に更新、[@Postroggy](https://github.com/Postroggy) に感謝。
|
||||
- [#3355](https://github.com/farion1231/cc-switch/pull/3355): ネイティブ残高 / Coding Plan 照会の認証情報を app ごとに解析、[@SiskonEmilia](https://github.com/SiskonEmilia) に感謝。
|
||||
- [#3405](https://github.com/farion1231/cc-switch/pull/3405): Claude Desktop Official プロバイダー追加エラーを修正、[@Eunknight](https://github.com/Eunknight) に感謝。
|
||||
- [#3382](https://github.com/farion1231/cc-switch/pull/3382): Codex CLI の複数プラットフォーム探索と GPT-5.5 モデルテンプレートフォールバック、[@chofuhoyu](https://github.com/chofuhoyu) に感謝。
|
||||
- [#3377](https://github.com/farion1231/cc-switch/pull/3377): Kimi / Moonshot ツール思考履歴の正規化、[@Neon-Wang](https://github.com/Neon-Wang) に感謝。
|
||||
|
||||
v3.16.0 リリース後に Codex OAuth、モデルカタログ、ローカルルーティングのテイクオーバー、Chat Completions ツール呼び出しの問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最低バージョン | アーキテクチャ |
|
||||
| -------- | ------------------------ | --------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表を参照 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | --------------------------------------------------- |
|
||||
| `CC-Switch-v3.16.1-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
|
||||
| `CC-Switch-v3.16.1-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ------------------------------------------------------- |
|
||||
| `CC-Switch-v3.16.1-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
|
||||
| `CC-Switch-v3.16.1-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.16.1-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
Homebrew インストール:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux アセットは **x86_64** と **ARM64**(`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
|
||||
|
||||
- `CC-Switch-v3.16.1-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.1-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| 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,236 @@
|
||||
# CC Switch v3.16.1
|
||||
|
||||
> Codex 稳定性补丁:由于部分用户反映不希望改变配置文件的写入方式,因此为 Codex 增强模式添加开关并默认关闭。开启此开关后,你可以在使用第三方 API 的情况下继续使用 Codex 的手机远程操作、官方插件等功能;本版本也包含一系列稳定性修复。
|
||||
|
||||
**[English →](v3.16.1-en.md) | [日本語版 →](v3.16.1-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
如果你希望在使用第三方 API 的时候解锁官方订阅才可以使用的远程操作 Codex、解锁官方插件,或希望在 Codex 中使用 DeepSeek / Kimi / GLM / MiniMax 等 Chat Completions 上游,建议先看这些文档:
|
||||
|
||||
- **[使用第三方 API 时保留 Codex 远程操作和官方插件](../guides/codex-official-auth-preservation-guide-zh.md)**:说明如何先完成官方登录,再开启 Codex 应用增强,让官方登录态留在 `auth.json`,同时把模型流量切到第三方 API。
|
||||
- **[在 Codex 中使用 DeepSeek:本地路由实战攻略](../guides/codex-deepseek-routing-guide-zh.md)**:从添加 Codex 供应商、开启本地路由,到验证请求转发的完整路径。
|
||||
- **[添加 Codex 供应商:Chat Completions 路由与模型映射](../user-manual/zh/2-providers/2.1-add.md)**:覆盖「需要本地路由映射」、模型映射表与思考能力配置。
|
||||
- **[本地代理服务](../user-manual/zh/4-proxy/4.1-service.md)** 与 **[本地路由](../user-manual/zh/4-proxy/4.2-routing.md)**:了解代理服务、接管 live 配置、以及相关风险提示。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一官方渠道声明(请务必阅读)
|
||||
>
|
||||
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
|
||||
>
|
||||
> | 类别 | 唯一官方 |
|
||||
> | -------- | ------------------------------------------------------------------------------ |
|
||||
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.16.1 是 v3.16.0 之后的一版 Codex 稳定性补丁。v3.16.0 让第三方 Codex 供应商通过 Chat Completions 路由成为一等公民;这一版则主要处理真实使用中暴露出的几个高风险边角:官方 ChatGPT / Codex OAuth 登录态在第三方供应商切换或本地路由接管期间被覆盖,Codex 模型目录在 live 回填、热切换、关闭接管恢复或编辑当前供应商时被清空,以及 Codex 的 `tool_search`、插件 / 连接器命名空间、自定义工具在 Chat Completions 上游路径中没有完整恢复为 Responses 事件。
|
||||
|
||||
这版也加固了本地路由接管的所有权判断:切换供应商和开启 / 关闭接管现在按应用串行执行,判断 live 文件是否由代理接管时不再只看滞后的 `enabled` 或代理服务是否正在运行,而是结合备份和 live 中的代理占位符。这样可以避免刚开启接管、代理临时停止,或热切换时的普通 live 写入把代理托管配置覆盖掉。
|
||||
|
||||
**发布日期**:2026-06-01
|
||||
|
||||
**更新规模**:23 commits | 62 files changed | +5,603 / -1,113 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **Codex OAuth 与第三方供应商切换更安全**:新增可选的官方认证保留设置;开启后,第三方供应商 token 写入 `config.toml`,官方 ChatGPT / Codex OAuth 登录继续留在 `auth.json`。
|
||||
- **Codex 模型目录不再被静默清空**:`modelCatalog` 以数据库为真相来源,live 回填、供应商切换、接管关闭恢复、编辑弹窗都会避免用丢失投影的 live 配置覆盖数据库。
|
||||
- **Codex Chat 工具 / 插件路由恢复**:Chat Completions 上游返回的 `tool_search`、已加载命名空间工具、自定义工具会重新映射回 Codex Responses 形态;流式自定义工具现在发出原生 `response.custom_tool_call_input.*` 事件。
|
||||
- **本地路由接管与热切换更稳**:供应商切换和接管开关按 app 串行,热切换会刷新 Codex live 中的供应商显示信息,但 endpoint 仍保持指向本地代理。
|
||||
- **诊断与平台兼容性修复**:Codex 代理错误返回更丰富上下文;Codex CLI 模型模板发现支持更多平台并提供 GPT-5.5 静态兜底;Windows 工具版本探测修复乱码与误判。
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### Codex 官方认证保留设置
|
||||
|
||||
新增一个可选设置,用于在切换第三方 Codex 供应商时保留官方 ChatGPT / Codex OAuth 登录态。开启后,CC Switch 会把第三方供应商的 API key 放进 Codex `config.toml` 的 provider-scoped `experimental_bearer_token`,而不是覆盖 `auth.json` 里的官方登录缓存。
|
||||
|
||||
由于部分用户不希望此功能改变配置文件的写入方式,因此该设置默认关闭,保持 v3.16.0 之前的兼容行为。需要同时使用官方 Codex 登录和第三方供应商的用户,可以在“设置 → Codex 应用增强”里手动开启。
|
||||
|
||||
### Codex DeepSeek 路由指南
|
||||
|
||||
新增中 / 英 / 日三语的 Codex DeepSeek 路由指南,包含供应商路由要求、DeepSeek Codex 供应商表单配置,以及本地路由接管的截图说明。
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### Codex 认证保留默认改为 opt-in
|
||||
|
||||
官方认证保留设置默认关闭。这样第三方 Codex 供应商切换继续沿用旧行为,避免已有用户在不知情的情况下改变 `auth.json` / `config.toml` 的写入方式。
|
||||
|
||||
### Codex 切换供应商后提示重启
|
||||
|
||||
Codex 的模型目录与部分配置在客户端启动时加载。现在成功切换 Codex 供应商后,界面会提示用户重启 Codex,让模型目录和配置变化真正生效。
|
||||
|
||||
### 供应商切换与接管开关串行化
|
||||
|
||||
Codex / Claude / Gemini 的供应商切换与本地路由接管开关现在共享 per-app 锁,避免两个流程同时修改 live 配置和备份。判断 live 是否由代理接管时,也会优先看 live 备份与 `PROXY_MANAGED` 占位符,而不是只看代理服务是否正在运行。
|
||||
|
||||
### Codex 热切换刷新显示信息
|
||||
|
||||
在本地路由接管期间热切换 Codex 供应商时,CC Switch 会刷新 live 配置中的 provider id、模型和显示名称,让 Codex 客户端菜单能跟随当前供应商;同时 base URL 仍保持本地代理地址,避免真实上游 endpoint 泄回 live 文件。
|
||||
|
||||
---
|
||||
|
||||
## 修复
|
||||
|
||||
### Codex 接管期间编辑弹窗误显示 live OAuth
|
||||
|
||||
当 Codex 处于本地路由接管状态时,live `auth.json` / `config.toml` 已被代理临时改写。编辑当前供应商如果继续读取 live,就会把代理占位符或官方 OAuth 登录误显示成供应商配置。现在编辑弹窗会明确提示:此处显示的是数据库中存储的供应商配置,而不是代理托管的 live 文件;即使代理服务暂时停止,只要该 app 仍处于接管状态,也会按接管逻辑处理。
|
||||
|
||||
### Codex OAuth 在接管期间被清空或覆盖
|
||||
|
||||
修复多条 preserve-mode 接管路径,它们此前可能清空或覆盖官方 ChatGPT / Codex OAuth `auth.json`。现在接管检测会识别 `config.toml` 里的 `PROXY_MANAGED`,清理流程只移除代理占位符 token,第三方供应商错误归类为 official 时也不会再走官方 auth 覆盖路径。供应商同步与切换会把 live 备份和占位符视为接管所有权信号,避免正常 live 写入覆盖刚接管或代理暂停时的代理配置。
|
||||
|
||||
### Codex 模型目录数据丢失
|
||||
|
||||
修复 `modelCatalog` 在 live 回填、当前供应商编辑弹窗、供应商切换、关闭接管恢复等场景被清空的问题。快照备份会保留已有 `model_catalog_json` 指针;由供应商重建的备份会从数据库真相来源重新生成目录投影;编辑当前供应商时会优先使用数据库里的模型目录,而不是信任可能已经丢失投影的 live 反解结果。
|
||||
|
||||
同时,供应商切换现在会始终刷新生成的 Codex 模型目录 JSON([#3360](https://github.com/farion1231/cc-switch/pull/3360),感谢 [@Postroggy](https://github.com/Postroggy))。
|
||||
|
||||
### Codex Chat 工具、插件和自定义工具恢复
|
||||
|
||||
修复第三方 Codex 供应商走 Chat Completions 路由时,`tool_search`、已加载的 MCP / connector 命名空间工具、自定义工具无法完整恢复为 Codex Responses 形态的问题。非流式与流式 Chat 响应现在都会根据原始 Responses 请求恢复正确的工具类型、namespace、call id 与参数;自定义工具流式输出会发出原生的 `response.custom_tool_call_input.delta` 和 `response.custom_tool_call_input.done` 事件。
|
||||
|
||||
### Codex 代理错误诊断更完整
|
||||
|
||||
Codex 转发失败时,现在返回包含 provider、model、endpoint、上游 HTTP 状态、稳定 `cc_switch_*` 错误码和规范 HTTP 状态的 JSON 错误。这样排查「到底是哪个供应商、哪个 endpoint、哪种上游错误」会清楚很多。
|
||||
|
||||
### Codex 原生余额 / Coding Plan 查询凭据
|
||||
|
||||
修复原生余额与 Coding Plan 查询时跨 app 错用凭据的问题。现在每个 app 会解析自己的供应商凭据,不再把其他应用面的认证假设带进查询流程([#3355](https://github.com/farion1231/cc-switch/pull/3355),感谢 [@SiskonEmilia](https://github.com/SiskonEmilia))。
|
||||
|
||||
### Codex CLI 发现与模型目录模板兜底
|
||||
|
||||
修复第三方 Codex 模型目录投影对 Codex CLI 发现路径过窄的问题。现在后端会在多平台常见安装位置寻找 Codex CLI,并在仍找不到模板时使用内置 GPT-5.5 模型目录模板兜底([#3382](https://github.com/farion1231/cc-switch/pull/3382),感谢 [@chofuhoyu](https://github.com/chofuhoyu))。
|
||||
|
||||
### Claude Desktop 官方供应商添加失败
|
||||
|
||||
修复添加 Claude Desktop 官方供应商时报错的问题([#3405](https://github.com/farion1231/cc-switch/pull/3405),感谢 [@Eunknight](https://github.com/Eunknight))。
|
||||
|
||||
### Kimi / Moonshot 工具思考历史规范化
|
||||
|
||||
把 Kimi / Moonshot 加入 Anthropic 兼容工具思考历史 normalizer。后续轮次现在能正确重放 reasoning 与 tool-call 上下文,避免因为历史消息形态不符合上游要求而失败([#3377](https://github.com/farion1231/cc-switch/pull/3377),感谢 [@Neon-Wang](https://github.com/Neon-Wang))。
|
||||
|
||||
### Windows 工具版本探测
|
||||
|
||||
修复 Windows 上 `.cmd` / `.bat` 版本命令被错误加引号,以及本地化命令输出被解码成乱码的问题。此前这些问题会让可运行的工具显示为「已安装但无法运行」。
|
||||
|
||||
---
|
||||
|
||||
## 升级提醒
|
||||
|
||||
### 官方 OAuth 保留需要手动开启
|
||||
|
||||
如果你希望官方 ChatGPT / Codex OAuth 登录长期保留在 `auth.json`,同时又频繁切换第三方 Codex 供应商,请在设置中开启 Codex 官方认证保留。默认关闭是为了保持老用户的兼容行为。
|
||||
|
||||
### 修改模型映射后仍需重启 Codex
|
||||
|
||||
Codex 在启动时读取 `model_catalog_json`。因此即使 v3.16.1 已修复模型目录被清空的问题,只要你修改了模型映射表,仍然需要重启 Codex 才能让 `/model` 菜单刷新。
|
||||
|
||||
### 接管期间编辑的是存储配置,不是 live 文件
|
||||
|
||||
本地路由接管开启后,live `auth.json` / `config.toml` 会临时指向 CC Switch 代理。此时编辑供应商时看到的是数据库里保存的供应商配置,属于预期行为;关闭接管后,CC Switch 会按备份或数据库真相来源恢复 live 配置。
|
||||
|
||||
---
|
||||
|
||||
## 风险提示
|
||||
|
||||
本版本继续沿用此前版本对反向代理类功能的风险提示。
|
||||
|
||||
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
|
||||
|
||||
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
|
||||
|
||||
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
|
||||
|
||||
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢以下贡献者在 v3.16.1 中提交修复:
|
||||
|
||||
- [#3360](https://github.com/farion1231/cc-switch/pull/3360):Codex 供应商切换时始终更新模型目录 JSON,感谢 [@Postroggy](https://github.com/Postroggy)。
|
||||
- [#3355](https://github.com/farion1231/cc-switch/pull/3355):原生余额 / Coding Plan 查询按 app 解析凭据,感谢 [@SiskonEmilia](https://github.com/SiskonEmilia)。
|
||||
- [#3405](https://github.com/farion1231/cc-switch/pull/3405):修复 Claude Desktop 官方供应商添加报错,感谢 [@Eunknight](https://github.com/Eunknight)。
|
||||
- [#3382](https://github.com/farion1231/cc-switch/pull/3382):Codex CLI 多平台发现与 GPT-5.5 模型模板兜底,感谢 [@chofuhoyu](https://github.com/chofuhoyu)。
|
||||
- [#3377](https://github.com/farion1231/cc-switch/pull/3377):Kimi / Moonshot 工具思考历史规范化,感谢 [@Neon-Wang](https://github.com/Neon-Wang)。
|
||||
|
||||
也感谢所有在 v3.16.0 发布后反馈 Codex OAuth、模型目录、本地路由接管和 Chat Completions 工具调用问题的用户。很多补丁都来自这些真实使用场景里的复现线索。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | -------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.16.1-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.16.1-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------- |
|
||||
| `CC-Switch-v3.16.1-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.16.1-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.16.1-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux 资产同时提供 **x86_64** 和 **ARM64**(`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
|
||||
|
||||
- `CC-Switch-v3.16.1-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.1-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| 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,347 @@
|
||||
# CC Switch v3.16.2
|
||||
|
||||
> Following the v3.16.1 Codex stability patch, this release mainly broadens data portability and usage observability — adding S3-compatible cloud sync, OpenCode session usage sync, and an official-subscription quota template — while continuing to harden Codex's Chat Completions routing for third-party providers, fixing a batch of Windows / macOS platform issues, adding the CherryIN and ZenMux providers, and fully refreshing the trilingual user manual.
|
||||
|
||||
**[中文版 →](v3.16.2-zh.md) | [日本語版 →](v3.16.2-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Usage Guides
|
||||
|
||||
This release adds an S3 backend for cloud sync and more usage data sources. If you want to use them, start with these docs:
|
||||
|
||||
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: configure cloud sync (WebDAV / S3-compatible storage) on the settings page to back up and restore providers, MCP, prompts, skills, and other config across multiple devices.
|
||||
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources (proxy logs, Codex / Gemini / OpenCode session sync) and how the statistics are counted.
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## Only Official Channels (Please Read)
|
||||
>
|
||||
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
|
||||
>
|
||||
> | Channel | Only Official |
|
||||
> | ------------------ | ------------------------------------------------------------------------------ |
|
||||
> | Website | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | Author | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
CC Switch v3.16.2 is a maintenance update following v3.16.1. After the previous release focused on the security of Codex official authentication and local routing takeover, this release concentrates on two things. First, broadening data portability and usage observability — adding S3-compatible cloud sync (a second cloud-backup backend alongside WebDAV), OpenCode session usage sync, and a quota-statistics template for official subscriptions. Second, continuing to polish the edges exposed when Codex routes third-party providers through Chat Completions — stream-truncation detection, `tool_choice` when tools is empty, custom-tool metadata, reasoning-token statistics, file / audio attachment conversion, and more.
|
||||
|
||||
This release also fixes a batch of local proxy robustness issues (ephemeral port resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop's `[1m]` model routing), addresses several Windows / macOS platform experience issues, adds the CherryIN and ZenMux providers, and fully refreshes the trilingual user manual.
|
||||
|
||||
**Release date**: 2026-06-07
|
||||
|
||||
**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **S3-compatible cloud sync**: adds S3-compatible object storage as a second cloud-backup backend alongside WebDAV, with one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and more.
|
||||
- **More usage data sources**: added OpenCode session usage sync, plus an official-subscription quota template for Claude / Codex / Gemini official providers (explicit toggle, off by default).
|
||||
- **Continued Codex Chat Completions routing hardening**: fixed stream-truncation misdetection, `tool_choice` rejection when tools is empty, custom-tool metadata loss, and missing reasoning-token stats, and added file / audio attachment conversion plus a `/v1/models` reachability endpoint.
|
||||
- **A more robust local proxy**: fixed ephemeral port (port 0) resolution, the takeover placeholder restore loop, Anthropic `system` message normalization, the upstream 413 message, and Claude Desktop 1M-context model routing.
|
||||
- **Platform and providers**: fixed Windows tray / taskbar icons, subdirectory skill updates, and macOS input auto-capitalization, and added the CherryIN and ZenMux providers.
|
||||
|
||||
---
|
||||
|
||||
## Added
|
||||
|
||||
### S3-Compatible Cloud Sync
|
||||
|
||||
Cloud Sync now supports S3-compatible object storage as a second backend alongside WebDAV, signing requests with a self-implemented AWS Signature V4 for the broadest possible compatibility. The settings page offers one-click presets for AWS S3, MinIO, Cloudflare R2, Alibaba Cloud OSS, Tencent Cloud COS, Huawei OBS, and a custom endpoint, with connection testing, manual upload / download, and auto-sync on configuration changes (the providers, endpoint, MCP, prompt, skill, settings, and proxy tables — **not** high-frequency data like usage logs). Enabling S3 sync disables a running WebDAV sync and vice versa (#1351).
|
||||
|
||||
### OpenCode Session Usage Sync
|
||||
|
||||
Added OpenCode as a usage-statistics source that reads per-message token, cost, and model data from OpenCode's local SQLite database and imports it into the usage records, with a dedicated "OpenCode" app filter tab and an "OpenCode Session" data-source label. The database path respects `OPENCODE_DB` and `XDG_DATA_HOME` (defaulting to `~/.local/share/opencode` on all platforms), only finalized messages are imported, and the freshness check includes the WAL file so just-written sessions are not skipped (#3215).
|
||||
|
||||
### Official Subscription Quota Template
|
||||
|
||||
Because some users were concerned that the IP issuing the usage query could differ from the IP issuing in-app requests, risking an account ban, the official-subscription usage template for Claude / Codex / Gemini official providers is now an explicit, opt-in template that queries plan quota via CLI / OAuth credentials, replacing the previous implicit auto-query for official providers. The template is off by default, is enabled from the usage-script modal, and supports a configurable refresh interval. When using this feature, enabling the proxy's TUN mode is recommended.
|
||||
|
||||
### Text-Only Model Image Fallback Rectifier
|
||||
|
||||
Added a proxy rectifier that replaces Anthropic image blocks with an `[Unsupported Image]` placeholder when the routed model is text-only (declared, or detected by a built-in model-name heuristic) or the upstream rejects image input, so conversations are not interrupted. The settings page provides a toggle for this fallback, plus a separate toggle for the heuristic detection (which can be turned off to avoid misjudging multimodal models).
|
||||
|
||||
### ZenMux Token Plan Provider
|
||||
|
||||
Added ZenMux as a Token Plan Coding Plan provider. You can manually enter its API key and base URL in the usage-script modal, and it renders used / quota in USD (#2709).
|
||||
|
||||
### CherryIN Preset
|
||||
|
||||
Added the CherryIN aggregator gateway as a quick-config preset across all 7 managed apps — Claude Code / Claude Desktop / OpenClaw / Hermes use the Anthropic-format endpoint (open.cherryin.net), OpenCode uses `@ai-sdk/anthropic` (`/v1`), Codex uses the OpenAI-compatible endpoint, and Gemini CLI uses the Gemini-compatible endpoint — with the official brand icon, placed next to AiHubMix (#3643).
|
||||
|
||||
### Codex CLI Reachability Endpoint `/v1/models`
|
||||
|
||||
The local proxy now responds to `GET /v1/models`, which Codex CLI probes at startup, returning the CC Switch-managed Codex model catalog. A stale-catalog guard was added: it parses the live `config.toml` and only serves the catalog when `model_catalog_json` still points at the CC Switch-owned catalog file, avoiding exposing a previous provider's leftover catalog to Codex (#3818).
|
||||
|
||||
### Codex Chat File and Audio Attachments
|
||||
|
||||
Codex's Responses→Chat conversion now maps `input_file` parts (carrying `file_id` or inline `file_data`) and `input_audio` parts into their Chat Completions equivalents, and emits top-level `input_*` items that were previously dropped, so file and audio attachments reach Chat-only Codex upstreams.
|
||||
|
||||
---
|
||||
|
||||
## Changed
|
||||
|
||||
### Usage Dashboard Hero Redesign
|
||||
|
||||
Rearranged the Usage Dashboard hero and summary cards into a more compact layout, consolidating the real-token total, request count, and cost into a single top row (#3426).
|
||||
|
||||
### SSSAiCode Endpoint Refresh
|
||||
|
||||
Updated the SSSAiCode preset's website, signup, and API base URLs to the `sssaicodeapi.com` domain, and refreshed its candidate endpoint nodes (default `node-hk.sssaicodeapi.com`, plus `node-hk.sssaiapi.com` and `node-cf.sssaicodeapi.com`) across all 7 app presets.
|
||||
|
||||
---
|
||||
|
||||
## Fixed
|
||||
|
||||
### Codex Chat Stream Truncation Detection
|
||||
|
||||
When a Chat Completions upstream ends a stream without a `finish_reason` or `[DONE]`, CC Switch no longer treats it as a normal completion: it finalizes normally only when the stream truly ended; emits an incomplete (`max_output_tokens`) response when partial output was produced; and emits a failed `stream_truncated` event when nothing was produced. Late-arriving reasoning is also backfilled onto still-active streaming tool calls.
|
||||
|
||||
### Codex Chat `tool_choice` Without Tools
|
||||
|
||||
The Responses→Chat conversion now drops `tool_choice` and `parallel_tool_calls` when the final tools array is missing or empty (including when all tools are filtered out), avoiding 503/400 errors from strict OpenAI-compatible upstreams (vLLM, enterprise gateways) with "When using `tool_choice`, `tools` must be set." (#3640).
|
||||
|
||||
### Codex Custom Tool Metadata Preserved
|
||||
|
||||
Custom Codex tools (such as the freeform `apply_patch` tool) now embed their full original definition — including format and grammar metadata — as a compact, order-stable JSON block in the generated Chat function description, instead of being replaced with a generic placeholder, so they remain usable on Chat Completions upstreams (#3644).
|
||||
|
||||
### Codex Chat Usage Missing `reasoning_tokens`
|
||||
|
||||
The Chat→Responses usage conversion now always includes `output_tokens_details.reasoning_tokens` (defaulting to 0), even when a provider omits `completion_tokens_details` or returns a non-object, satisfying Codex CLI's strict requirement and avoiding repeated response-parse failures and retries (#3514).
|
||||
|
||||
### Cross-Turn Reasoning for Codex Custom / Search Tools
|
||||
|
||||
The cross-turn reasoning cache in Codex Chat history now covers the full tool-call set (`function_call`, `custom_tool_call`, `tool_search_call`) and their outputs, not just plain function calls, so `apply_patch` and tool-search calls keep their own `reasoning_content` when restored via `previous_response_id`.
|
||||
|
||||
### Ephemeral Port (port 0) Resolution
|
||||
|
||||
When the proxy is configured to listen on port 0 (OS-assigned), takeover now starts the proxy first to obtain the real port before writing live configs and the database, avoiding client URLs pointing at an invalid `:0` address; if no concrete port has been resolved yet, the Claude Desktop gateway URL is rejected outright.
|
||||
|
||||
### Proxy Placeholder Backup / Restore Loop
|
||||
|
||||
If a previous proxy stop failed to restore the original live config and left proxy placeholders in live, taking over again no longer overwrites the good backup with the proxy config, and restore no longer writes the placeholder back to live: both paths detect the placeholder state and rebuild live from the current provider as the source of truth, fixing cases where the proxy toggle became a no-op and the client was pinned to the local proxy address (#3689).
|
||||
|
||||
### Provider Switching Wrongly Blocked During Proxy Takeover
|
||||
|
||||
During local routing takeover, only providers explicitly classified as official are now blocked from switching, instead of also disabling custom providers whose endpoint lives in meta or whose fields are simply unfilled. The disabled "Enable" button now shows a lighter hint tooltip instead of the previous red "Blocked" badge.
|
||||
|
||||
### localhost Listen Address Normalization
|
||||
|
||||
When saving the proxy with a listen address of `localhost`, it is now normalized to `127.0.0.1` before persisting, avoiding binding inconsistencies (#3016).
|
||||
|
||||
### Anthropic `system` Message Normalization
|
||||
|
||||
For Anthropic-format providers, system-role entries inside the `messages` array are now collapsed and merged into the top-level `system` field (preserving original order and any existing top-level system), avoiding strict upstreams rejecting non-leading system messages; OpenAI Chat routing is unaffected (#3775).
|
||||
|
||||
### Claude Desktop 1M-Context Model Routing
|
||||
|
||||
Claude Desktop appends a `[1m]` marker to the model name when the 1M-context beta is active (e.g. `claude-opus-4-8[1m]`). The proxy now strips that suffix before route matching so exact, alias, legacy, and role-keyword matching all resolve correctly, fixing `route_unknown` (HTTP 400) failures when switching to a 1M model mid-conversation; the original model name is still kept in the `route_unknown` error for diagnostics.
|
||||
|
||||
### Codex 413 Error Message
|
||||
|
||||
When a Codex upstream gateway rejects an oversized request body with HTTP 413, the proxy now returns a dedicated message explaining that this is the provider's server-side body-size limit (not a CC Switch local limit), with actionable recovery steps (run `/compact`, remove large logs or inline images, or ask the provider to raise the limit), instead of echoing the upstream's raw HTML error page.
|
||||
|
||||
### Proxy Panel Error Detail
|
||||
|
||||
When toggling proxy takeover fails, the proxy panel toast now includes the specific error detail returned by the backend, instead of only a generic failure message (#3656).
|
||||
|
||||
### Copilot Infinite-Whitespace Threshold
|
||||
|
||||
Raised the streaming infinite-whitespace abort threshold from 20 to 500 consecutive whitespace characters, avoiding false aborts of legitimate tool calls whose arguments contain deeply indented code (Python, YAML, Rust, Markdown), while still catching the real Copilot infinite-whitespace bug (#2647).
|
||||
|
||||
### Subscription Tier Tray Rendering
|
||||
|
||||
Via a unified tier-to-label mapping, fixed rendering of official subscription tiers in the tray and quota display: Claude / Codex no longer drop the 7-day window, Gemini Pro / Flash / Flash-Lite tiers no longer leak raw machine names, and multi-window plans (e.g. Opus + Sonnet) now show the worst utilization instead of the first match.
|
||||
|
||||
### Inflated Claude Stream input_tokens
|
||||
|
||||
Some Anthropic-compatible streaming providers (e.g. Qwen, MiniMax) report the full context as `input_tokens` in `message_start`, double-counting the cached portion already reported separately and artificially lowering the displayed cache hit rate. The parser now prefers the smaller positive `input_tokens` from `message_delta` and adopts the paired cache counts from the same usage block; native Claude and OpenRouter-converted paths are unchanged.
|
||||
|
||||
### Zhipu Quota Query Endpoint Routing
|
||||
|
||||
The Zhipu Coding Plan quota query was hard-coded to `api.z.ai`, so users on the mainland preset (`open.bigmodel.cn`) could not retrieve usage when the international endpoint was unreachable. The quota request now routes to the host matching the user's configured base URL (#3702).
|
||||
|
||||
### MiniMax Balance API and Pricing
|
||||
|
||||
Adapted MiniMax Coding Plan quota to its new balance API (which returns remaining-percent fields instead of the usage counts the old parser relied on, which left tiers empty and the tray showing no usage), filtered out non-coding models (such as video), handled plans without a weekly limit, and added default pricing for the MiniMax M3 model (#3518).
|
||||
|
||||
### GLM Coding Plan Endpoints and Model Fetch
|
||||
|
||||
Fixed the Zhipu / Z.AI GLM Coding Plan presets to the `/api/coding/paas/v4` endpoints (covering Codex, OpenCode, OpenClaw, Hermes), and made the model-list probe query `{base}/models` first for base URLs that already end in a `/v{N}` version segment (keeping `/v1/models` as a fallback), so the "Fetch models" button no longer 404s on versioned endpoints (#3524).
|
||||
|
||||
### Codex Model Catalog Path Portability
|
||||
|
||||
Codex now writes only the relative filename `cc-switch-model-catalog.json` to `config.toml` instead of an absolute path (Codex CLI resolves it from the config directory), fixing the model catalog breaking on WSL and symlinked setups where the absolute path could not be translated (#3614).
|
||||
|
||||
### APINebula's OpenCode SDK
|
||||
|
||||
The APINebula OpenCode preset now loads `@ai-sdk/openai-compatible` instead of `@ai-sdk/openai`, so requests use the OpenAI Chat Completions format the relay expects, rather than the Responses API that fails against chat-completions-only upstreams.
|
||||
|
||||
### Windows Tray Icon Residue After Exit
|
||||
|
||||
On Windows, quitting CC Switch could leave a dead tray icon behind until the mouse passed over it. The app now explicitly removes the tray icon before exiting, so it disappears cleanly when the process ends (#3797).
|
||||
|
||||
### Windows Taskbar Icon
|
||||
|
||||
Sets an explicit Windows AppUserModelID at runtime and writes the same ID and product icon onto the installer's desktop and start-menu shortcuts, so CC Switch shows the correct icon and groups properly in the taskbar (#3457).
|
||||
|
||||
### Windows Update Check for Subdirectory Skills
|
||||
|
||||
When scanning installed skills on Windows, backslash path separators are now normalized to forward slashes, so skills nested in subdirectories (e.g. `skills/my-skill`) are matched by the update check instead of being silently skipped (#3430).
|
||||
|
||||
### macOS Input Auto-Capitalization
|
||||
|
||||
Disabled autocomplete, autocorrect, autocapitalize, and spellcheck on the shared text Input component, so macOS no longer auto-capitalizes or auto-corrects the first letter typed into configuration fields (#3626).
|
||||
|
||||
### Codex VS Code Session Previews
|
||||
|
||||
For Codex requests sent from VS Code, the session preview could show selection or open-file content instead of the real prompt when a markdown heading preceded the injected request. The backend title and frontend preview now both match the last "## My request for Codex:" heading (the IDE injects the real request as the final section), so the preview reflects the user's prompt (#3593).
|
||||
|
||||
### VS Code Wording in the Chinese UI
|
||||
|
||||
Corrected the "Apply to Claude Code plugin" description in Simplified and Traditional Chinese to write "VS Code" properly instead of "Vscode", aligning with the English and Japanese strings (#3228).
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
### User Manual Refresh
|
||||
|
||||
Refreshed the README localizations and the en / zh / ja user manuals to reflect all 7 managed apps (adding Claude Desktop and Hermes to the intro and overview copy), corrected the OpenCode config path to `~/.config/opencode/` (`opencode.json`), documented Hermes config files, updated the language docs to four languages, corrected per-app MCP / prompt / skill support, noted that export now produces a timestamped SQL backup that includes usage logs, and documented the pricing model-ID matching rules (#3411).
|
||||
|
||||
### Codex Official Auth Preservation Guide
|
||||
|
||||
Added a Chinese / English / Japanese guide explaining how to keep Codex official remote control and official plugins working while routing model traffic to third-party APIs, and linked it from the v3.16.1 release notes.
|
||||
|
||||
### README Links and Sponsor Markup
|
||||
|
||||
Updated the Release Notes links in each language README to v3.16.1, and fixed broken curly-quote characters in the README_ZH sponsor blocks so their HTML attributes render correctly (#3772).
|
||||
|
||||
---
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
### S3 and WebDAV Cloud Sync Are Mutually Exclusive
|
||||
|
||||
Cloud Sync runs only one backend at a time. Enabling S3 auto-sync disables a running WebDAV auto-sync and vice versa. If you previously used WebDAV, make sure both ends are aligned before switching to S3, so you don't assume the old backend is still backing up.
|
||||
|
||||
### Restart Codex After Editing Model Mappings
|
||||
|
||||
Codex reads `model_catalog_json` at startup. Even though this release rewrites the model catalog to a relative path and adds the `/v1/models` reachability endpoint, you still need to restart Codex after editing the model mapping table for the `/model` menu to refresh.
|
||||
|
||||
---
|
||||
|
||||
## Risk Notice
|
||||
|
||||
This release continues the risk notices from previous versions for reverse-proxy-style features.
|
||||
|
||||
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#️-risk-notice) for details.
|
||||
|
||||
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
|
||||
|
||||
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
|
||||
|
||||
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
|
||||
|
||||
---
|
||||
|
||||
## Thanks
|
||||
|
||||
Thanks to the following contributors for the features and fixes in v3.16.2:
|
||||
|
||||
- [#1351](https://github.com/farion1231/cc-switch/pull/1351): add S3-compatible cloud storage sync, thanks [@keithyt06](https://github.com/keithyt06).
|
||||
- [#3215](https://github.com/farion1231/cc-switch/pull/3215): add OpenCode session usage sync, thanks [@nothingness0db](https://github.com/nothingness0db).
|
||||
- [#2709](https://github.com/farion1231/cc-switch/pull/2709): add the ZenMux Token Plan provider, thanks [@Eter365](https://github.com/Eter365).
|
||||
- [#3643](https://github.com/farion1231/cc-switch/pull/3643): add the CherryIN preset provider, thanks [@zhibisora](https://github.com/zhibisora).
|
||||
- [#3818](https://github.com/farion1231/cc-switch/pull/3818): add the Codex CLI reachability `GET /v1/models` endpoint, thanks [@CSberlin](https://github.com/CSberlin).
|
||||
- [#3426](https://github.com/farion1231/cc-switch/pull/3426): Usage Dashboard hero redesign, thanks [@allenxu09](https://github.com/allenxu09).
|
||||
- [#3640](https://github.com/farion1231/cc-switch/pull/3640): drop `tool_choice` when tools is empty, thanks [@Postroggy](https://github.com/Postroggy).
|
||||
- [#3644](https://github.com/farion1231/cc-switch/pull/3644): preserve Codex custom tool metadata in chat routing, thanks [@LanternCX](https://github.com/LanternCX).
|
||||
- [#3514](https://github.com/farion1231/cc-switch/pull/3514): always include `reasoning_tokens` in Chat→Responses, thanks [@yeeyzy](https://github.com/yeeyzy).
|
||||
- [#3689](https://github.com/farion1231/cc-switch/pull/3689): skip backup / restore when live is already a proxy placeholder, thanks [@YongmaoLuo](https://github.com/YongmaoLuo).
|
||||
- [#3016](https://github.com/farion1231/cc-switch/pull/3016): normalize the localhost listen address, thanks [@Alexlangl](https://github.com/Alexlangl).
|
||||
- [#3775](https://github.com/farion1231/cc-switch/pull/3775): normalize Anthropic `system` messages, thanks [@Dearli666](https://github.com/Dearli666).
|
||||
- [#3656](https://github.com/farion1231/cc-switch/pull/3656): improve error message display in the proxy panel, thanks [@lzcndm](https://github.com/lzcndm).
|
||||
- [#2647](https://github.com/farion1231/cc-switch/pull/2647): raise the infinite-whitespace threshold 20 → 500, thanks [@NiuBlibing](https://github.com/NiuBlibing).
|
||||
- [#3702](https://github.com/farion1231/cc-switch/pull/3702): route the Zhipu quota query to the configured base URL, thanks [@YongmaoLuo](https://github.com/YongmaoLuo).
|
||||
- [#3518](https://github.com/farion1231/cc-switch/pull/3518): adapt to the MiniMax new balance API and default pricing, thanks [@LaoYueHanNi](https://github.com/LaoYueHanNi).
|
||||
- [#3524](https://github.com/farion1231/cc-switch/pull/3524): fix the Zhipu Coding Plan presets and model probing for versioned endpoints, thanks [@makoMakoGo](https://github.com/makoMakoGo).
|
||||
- [#3614](https://github.com/farion1231/cc-switch/pull/3614): use a relative filename for the model catalog, thanks [@steponeerror](https://github.com/steponeerror).
|
||||
- [#3797](https://github.com/farion1231/cc-switch/pull/3797): fix the Windows tray icon residue after exit, thanks [@iAJue](https://github.com/iAJue).
|
||||
- [#3457](https://github.com/farion1231/cc-switch/pull/3457): fix the Windows taskbar icon, thanks [@ZhangNanNan1018](https://github.com/ZhangNanNan1018).
|
||||
- [#3430](https://github.com/farion1231/cc-switch/pull/3430): normalize Windows path separators to match subdirectory skill updates, thanks [@Ninthless](https://github.com/Ninthless).
|
||||
- [#3626](https://github.com/farion1231/cc-switch/pull/3626): disable macOS input auto-capitalization, thanks [@ZHLHZHU](https://github.com/ZHLHZHU).
|
||||
- [#3593](https://github.com/farion1231/cc-switch/pull/3593): fix Codex VS Code session previews, thanks [@xwil1](https://github.com/xwil1).
|
||||
- [#3228](https://github.com/farion1231/cc-switch/pull/3228): align the VS Code wording in the Chinese UI, thanks [@Games55k](https://github.com/Games55k).
|
||||
- [#3411](https://github.com/farion1231/cc-switch/pull/3411): refresh the user manual to reflect current app support, thanks [@makoMakoGo](https://github.com/makoMakoGo).
|
||||
- [#3772](https://github.com/farion1231/cc-switch/pull/3772): fix README release-note links and sponsor markup, thanks [@null-easy](https://github.com/null-easy).
|
||||
|
||||
Thanks also to everyone who reported Codex Chat routing, local proxy takeover, usage statistics, and platform compatibility issues after v3.16.1. Many of these fixes came directly from real-world reproduction details.
|
||||
|
||||
---
|
||||
|
||||
## Download & Install
|
||||
|
||||
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) and download the build for your system.
|
||||
|
||||
### System Requirements
|
||||
|
||||
| System | Minimum Version | Architecture |
|
||||
| ------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 and later | x64 |
|
||||
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ------------------------------------------------ |
|
||||
| `CC-Switch-v3.16.2-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.16.2-Windows-Portable.zip` | Portable build, unzip and run |
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ----------------------------------------------------- |
|
||||
| `CC-Switch-v3.16.2-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
|
||||
| `CC-Switch-v3.16.2-macOS.zip` | Unzip and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.16.2-macOS.tar.gz` | For Homebrew install and auto-update |
|
||||
|
||||
Homebrew install:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
Upgrade:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
|
||||
|
||||
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| Distribution | Recommended Format | Install Command |
|
||||
| --------------------------------------- | ------------------ | --------------------------------------------------------------------- |
|
||||
| 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` | Make executable and run directly, or use AUR |
|
||||
| Other distributions / unsure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -0,0 +1,347 @@
|
||||
# CC Switch v3.16.2
|
||||
|
||||
> v3.16.1 の Codex 安定性パッチに続き、本リリースはデータの可搬性と用量の可観測性の拡張を主眼としています。S3 互換クラウド同期、OpenCode セッション用量同期、公式サブスクリプション残量テンプレートを追加し、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際の堅牢性を引き続き強化しました。あわせて Windows / macOS のプラットフォーム問題を一括修正し、CherryIN・ZenMux プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
|
||||
|
||||
**[English →](v3.16.2-en.md) | [中文 →](v3.16.2-zh.md)**
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースではクラウド同期の S3 バックエンドと、より多くの用量統計ソースを追加しました。利用したい場合は、まず以下のドキュメントをご覧ください:
|
||||
|
||||
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: 設定ページでクラウド同期(WebDAV / S3 互換ストレージ)を構成し、プロバイダー、MCP、プロンプト、スキルなどの設定を複数デバイス間でバックアップ・復元します。
|
||||
- **[用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 用量ダッシュボードのデータソース(プロキシログ、Codex / Gemini / OpenCode セッション同期)と統計の数え方を確認できます。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一の公式チャネル(必ずお読みください)
|
||||
>
|
||||
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
|
||||
>
|
||||
> | チャネル | 唯一の公式 |
|
||||
> | ------------ | ------------------------------------------------------------------------------ |
|
||||
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
|
||||
|
||||
---
|
||||
|
||||
## 概要
|
||||
|
||||
CC Switch v3.16.2 は v3.16.1 に続くメンテナンスアップデートです。前リリースでは Codex 公式認証とローカルルーティングのテイクオーバーのセキュリティ問題に集中しましたが、本リリースは 2 点に重きを置いています。1 つ目はデータの可搬性と用量の可観測性の拡張で、S3 互換クラウド同期(WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンド)、OpenCode セッション用量同期、公式サブスクリプション向けの残量統計テンプレートを追加しました。2 つ目は、Codex がサードパーティプロバイダーを Chat Completions ルーティングする際に露呈したエッジケースの継続的な改善で、ストリーム切断の判定、tools が空のときの `tool_choice`、カスタムツールのメタデータ、推論トークン統計、ファイル / 音声添付の変換などです。
|
||||
|
||||
本リリースではローカルプロキシの堅牢性に関する問題(一時ポートの解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の `[1m]` モデルルーティング)を一括修正し、いくつかの Windows / macOS のプラットフォーム体験の問題に対処し、CherryIN・ZenMux の 2 プロバイダーを追加し、3 言語のユーザーマニュアルを全面的に刷新しました。
|
||||
|
||||
**リリース日**: 2026-06-07
|
||||
|
||||
**Stats**: 41 commits | 132 files changed | +11,116 / -1,636 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **S3 互換クラウド同期**: WebDAV に並ぶ 2 つ目のクラウドバックアップバックエンドとして S3 互換オブジェクトストレージを追加。AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS などのワンクリックプリセットを内蔵します。
|
||||
- **より多くの用量データソース**: OpenCode セッション用量同期と、Claude / Codex / Gemini 公式プロバイダー向けの公式サブスクリプション残量テンプレート(明示的なトグル、デフォルトでオフ)を追加しました。
|
||||
- **Codex Chat Completions ルーティングの継続的な強化**: ストリーム切断の誤判定、tools が空のときの `tool_choice` 拒否、カスタムツールメタデータの欠落、推論トークン統計の欠落を修正し、ファイル / 音声添付の変換と `/v1/models` 到達性エンドポイントを追加しました。
|
||||
- **より堅牢なローカルプロキシ**: 一時ポート(port 0)の解決、テイクオーバーのプレースホルダー復元ループ、Anthropic `system` メッセージの正規化、上流 413 の文言、Claude Desktop の 1M コンテキストモデルルーティングを修正しました。
|
||||
- **プラットフォームとプロバイダー**: Windows のトレイ / タスクバーアイコン、サブディレクトリスキルの更新、macOS の入力自動大文字化を修正し、CherryIN・ZenMux プロバイダーを追加しました。
|
||||
|
||||
---
|
||||
|
||||
## 追加機能
|
||||
|
||||
### S3 互換クラウド同期
|
||||
|
||||
クラウド同期は WebDAV に並ぶ 2 つ目のバックエンドとして S3 互換オブジェクトストレージに対応しました。署名は自前実装の AWS Signature V4 を用い、できるだけ多くのサービスと互換性を持たせています。設定ページでは AWS S3、MinIO、Cloudflare R2、Alibaba Cloud OSS、Tencent Cloud COS、Huawei OBS、およびカスタム endpoint のワンクリックプリセットを提供し、接続テスト、手動アップロード / ダウンロード、設定変更時の自動同期(providers、endpoint、MCP、プロンプト、スキル、設定、プロキシなどの設定テーブル。用量ログのような高頻度書き込みデータは**含みません**)に対応します。S3 同期を有効化すると、実行中の WebDAV 同期は停止し、その逆も同様です(#1351)。
|
||||
|
||||
### OpenCode セッション用量同期
|
||||
|
||||
OpenCode を用量統計のソースとして追加しました。OpenCode のローカル SQLite データベースからメッセージごとの token、コスト、モデルのデータを読み取り、用量レコードへインポートします。専用の「OpenCode」アプリフィルタタブと「OpenCode Session」データソースラベルを備えます。データベースパスは `OPENCODE_DB` と `XDG_DATA_HOME` を尊重し(全プラットフォームで既定は `~/.local/share/opencode`)、完了済みのメッセージのみをインポートし、新鮮度判定で WAL ファイルも含めるため、書き込み直後のセッションがスキップされません(#3215)。
|
||||
|
||||
### 公式サブスクリプション残量テンプレート
|
||||
|
||||
用量照会を発行する IP とアプリ内リクエストを発行する IP が異なるとアカウント停止のリスクがある、という一部ユーザーの懸念を受けて、Claude / Codex / Gemini 公式プロバイダー向けに、CLI / OAuth 認証情報でプラン残量を照会する明示的・任意の「公式サブスクリプション」用量テンプレートを追加し、これまでの公式プロバイダーに対する暗黙の自動照会を置き換えました。このテンプレートはデフォルトでオフで、用量スクリプトのモーダルから有効化でき、更新間隔を設定できます。本機能を利用する際は、プロキシの TUN モードを有効化することを推奨します。
|
||||
|
||||
### テキスト専用モデルの画像フォールバック整流器
|
||||
|
||||
ルーティング先のモデルがテキスト専用(明示的な宣言、または内蔵のモデル名ヒューリスティックで判定)の場合、または上流が画像入力を拒否する場合に、Anthropic の画像ブロックを `[Unsupported Image]` プレースホルダーへ置き換えるプロキシ整流器を追加し、会話の中断を防ぎます。設定ページにこのフォールバックのトグルを用意し、さらにヒューリスティック検出を制御する別のトグル(マルチモーダルモデルの誤判定を避けるためオフにできます)を用意しました。
|
||||
|
||||
### ZenMux Token Plan プロバイダー
|
||||
|
||||
ZenMux を Token Plan 系の Coding Plan プロバイダーとして追加しました。用量スクリプトのモーダルで API key と base URL を手動入力でき、使用量 / 残量を米ドル建てでリッチに表示します(#2709)。
|
||||
|
||||
### CherryIN プリセット
|
||||
|
||||
CherryIN アグリゲーターゲートウェイをクイック設定プリセットとして、受管 7 アプリすべてに追加しました。Claude Code / Claude Desktop / OpenClaw / Hermes は Anthropic 形式の endpoint(open.cherryin.net)、OpenCode は `@ai-sdk/anthropic`(`/v1`)、Codex は OpenAI 互換 endpoint、Gemini CLI は Gemini 互換 endpoint を使用します。公式ブランドアイコン付きで、AiHubMix の隣に配置されます(#3643)。
|
||||
|
||||
### Codex CLI 到達性エンドポイント `/v1/models`
|
||||
|
||||
ローカルプロキシは、Codex CLI が起動時にプローブする `GET /v1/models` に応答し、CC Switch が管理する Codex モデルカタログを返すようになりました。あわせて古いカタログのガードを追加: live の `config.toml` を解析し、`model_catalog_json` が CC Switch 所有のカタログファイルを指している場合のみ提供することで、前のプロバイダーが残したカタログを Codex に見せてしまうことを防ぎます(#3818)。
|
||||
|
||||
### Codex Chat のファイル・音声添付
|
||||
|
||||
Codex の Responses→Chat 変換は、`input_file`(`file_id` またはインライン `file_data` を持つ)と `input_audio` のコンテンツ部分を Chat Completions の対応形態へマッピングし、これまで破棄されていたトップレベルの `input_*` 項目も出力するようになりました。これにより、ファイルと音声の添付が Chat のみ対応の Codex 上流へ届きます。
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### 用量ダッシュボードのヒーロー再設計
|
||||
|
||||
用量ダッシュボードのヒーロー領域とサマリーカードをよりコンパクトなレイアウトに再構成し、実トークン総量、リクエスト数、コストを最上部の 1 行にまとめました(#3426)。
|
||||
|
||||
### SSSAiCode エンドポイント刷新
|
||||
|
||||
SSSAiCode プリセットの公式サイト、登録、API base URL を `sssaicodeapi.com` ドメインへ更新し、endpoint 候補ノード(既定 `node-hk.sssaicodeapi.com`、ほかに `node-hk.sssaiapi.com` と `node-cf.sssaicodeapi.com`)を全 7 アプリのプリセットで刷新しました。
|
||||
|
||||
---
|
||||
|
||||
## 修正
|
||||
|
||||
### Codex Chat ストリーム切断の判定
|
||||
|
||||
Chat Completions 上流が `finish_reason` も `[DONE]` もなくストリームを終了した場合、CC Switch はこれを正常完了として扱わなくなりました: 本当に終了したときのみ正常に締め、部分的な出力があった場合は incomplete(`max_output_tokens`)レスポンスを、何も出力されなかった場合は失敗 `stream_truncated` イベントを発行します。遅れて届いた推論も、まだアクティブなストリーミングのツール呼び出しへバックフィルされます。
|
||||
|
||||
### tools が空のときの Codex Chat `tool_choice`
|
||||
|
||||
Responses→Chat 変換は、最終的な tools 配列が欠落または空(すべてのツールがフィルタで除外された場合を含む)のときに `tool_choice` と `parallel_tool_calls` を破棄するようになりました。これにより、厳格な OpenAI 互換上流(vLLM、エンタープライズゲートウェイ)が「When using `tool_choice`, `tools` must be set.」で 503/400 を返すことを避けます(#3640)。
|
||||
|
||||
### Codex カスタムツールメタデータの保持
|
||||
|
||||
カスタム Codex ツール(自由形式の `apply_patch` ツールなど)は、汎用プレースホルダーへ置き換えられる代わりに、format と grammar のメタデータを含む完全な元定義を、生成される Chat 関数の説明にコンパクトで順序の安定した JSON ブロックとして埋め込むようになりました。これにより Chat Completions 上流でも引き続き利用できます(#3644)。
|
||||
|
||||
### Codex Chat 用量の `reasoning_tokens` 欠落
|
||||
|
||||
Chat→Responses の用量変換は、プロバイダーが `completion_tokens_details` を省略したり非オブジェクトを返したりしても、常に `output_tokens_details.reasoning_tokens`(既定 0)を含めるようになりました。これにより Codex CLI の厳格な要件を満たし、レスポンス解析の失敗と再試行の繰り返しを避けます(#3514)。
|
||||
|
||||
### Codex カスタム / 検索ツールのターン跨ぎ推論
|
||||
|
||||
Codex Chat 履歴のターン跨ぎ推論キャッシュが、通常の関数呼び出しだけでなく、ツール呼び出しの全集合(`function_call`、`custom_tool_call`、`tool_search_call`)とその出力をカバーするようになりました。これにより `apply_patch` とツール検索の呼び出しは、`previous_response_id` で復元されるときにそれぞれの `reasoning_content` を保持します。
|
||||
|
||||
### 一時ポート(port 0)の解決
|
||||
|
||||
プロキシが port 0(OS 割り当て)でリッスンするよう構成されている場合、テイクオーバーはまずプロキシを起動して実際のポートを取得してから live 設定とデータベースへ書き込むようになり、クライアント URL が無効な `:0` アドレスを指すことを避けます。具体的なポートがまだ解決されていない場合、Claude Desktop のゲートウェイ URL は拒否されます。
|
||||
|
||||
### プロキシプレースホルダーのバックアップ / 復元ループ
|
||||
|
||||
前回プロキシ停止時に元の live 設定の復元に失敗し、プロキシプレースホルダーが live に残ってしまった場合でも、再度テイクオーバーする際に正常なバックアップをプロキシ設定で上書きすることはなくなり、復元時にプレースホルダーを live へ書き戻すこともなくなりました: いずれの経路もプレースホルダー状態を検知し、現在のプロバイダーを信頼できる情報源として live を再構築します。これにより、プロキシのトグルが何もしない状態になり、クライアントがローカルプロキシアドレスに固定されてしまう問題を修正しました(#3689)。
|
||||
|
||||
### プロキシテイクオーバー中のプロバイダー切り替え誤ブロック
|
||||
|
||||
ローカルルーティングのテイクオーバー中、明示的に official と分類されたプロバイダーのみが切り替えをブロックされるようになり、endpoint が meta に存在する、またはフィールドが未入力なだけのカスタムプロバイダーまで無効化することはなくなりました。無効化された「有効化」ボタンは、以前の赤い「ブロック済み」バッジの代わりに、より軽いヒントのツールチップを表示します。
|
||||
|
||||
### localhost リッスンアドレスの正規化
|
||||
|
||||
プロキシのリッスンアドレスを `localhost` で保存した場合、永続化前に `127.0.0.1` へ正規化されるようになり、バインドの不整合を避けます(#3016)。
|
||||
|
||||
### Anthropic `system` メッセージの正規化
|
||||
|
||||
Anthropic 形式のプロバイダーでは、`messages` 配列内の system ロールのエントリを折りたたんでトップレベルの `system` フィールドへマージするようになり(元の順序と既存のトップレベル system を保持)、厳格な上流が先頭以外の system メッセージを拒否することを避けます。OpenAI Chat ルーティングは影響を受けません(#3775)。
|
||||
|
||||
### Claude Desktop 1M コンテキストモデルルーティング
|
||||
|
||||
Claude Desktop は 1M コンテキスト beta が有効なとき、モデル名に `[1m]` マーカーを付加します(例: `claude-opus-4-8[1m]`)。プロキシはルーティング照合の前にこの接尾辞を除去するようになり、完全一致・エイリアス・旧名・ロールキーワードの照合がすべて正しく解決されます。これにより、会話の途中で 1M モデルへ切り替えたときの `route_unknown`(HTTP 400)の失敗を修正しました。診断用に、`route_unknown` エラーには元のモデル名を引き続き保持します。
|
||||
|
||||
### Codex 413 エラーの文言
|
||||
|
||||
Codex 上流ゲートウェイが過大なリクエストボディを HTTP 413 で拒否したとき、プロキシはこれが CC Switch のローカル制限ではなくプロバイダーのサーバー側ボディサイズ制限であることを説明する専用メッセージを返し、実行可能な回復手順(`/compact` の実行、大きなログやインライン画像の削除、プロバイダーへの上限引き上げ依頼)を提示するようになりました。上流の生の HTML エラーページをそのまま返すことはなくなりました。
|
||||
|
||||
### プロキシパネルのエラー詳細
|
||||
|
||||
プロキシのテイクオーバー切り替えに失敗したとき、プロキシパネルのトーストは、汎用の失敗メッセージだけでなく、バックエンドが返す具体的なエラー詳細を含めるようになりました(#3656)。
|
||||
|
||||
### Copilot 無限空白検出のしきい値
|
||||
|
||||
ストリーミングの無限空白の中断しきい値を、連続する空白文字 20 から 500 へ引き上げました。これにより、引数に深くインデントされたコード(Python、YAML、Rust、Markdown)を含む正当なツール呼び出しが誤って中断されることを避けつつ、本物の Copilot 無限空白バグは引き続き捕捉します(#2647)。
|
||||
|
||||
### サブスクリプション階層のトレイ表示
|
||||
|
||||
統一された階層→ラベルのマッピングにより、トレイと残量表示における公式サブスクリプション階層の表示を修正しました: Claude / Codex は 7 日ウィンドウを取りこぼさなくなり、Gemini Pro / Flash / Flash-Lite の階層は生のマシン名を漏らさなくなり、複数ウィンドウのプラン(Opus + Sonnet など)は最初の一致ではなく最悪の利用率を表示するようになりました。
|
||||
|
||||
### Claude ストリームの input_tokens 過大計上
|
||||
|
||||
一部の Anthropic 互換ストリーミングプロバイダー(Qwen、MiniMax など)は `message_start` で完全なコンテキストを `input_tokens` として報告し、別途報告済みのキャッシュ分を二重計上して、表示上のキャッシュヒット率を不当に低下させていました。パーサーは `message_delta` のより小さい正の `input_tokens` を優先し、同じ usage ブロックのキャッシュカウントを採用するようになりました。ネイティブ Claude と OpenRouter 変換の経路は変更ありません。
|
||||
|
||||
### 智譜(Zhipu)残量照会の endpoint ルーティング
|
||||
|
||||
智譜 Coding Plan の残量照会は `api.z.ai` にハードコードされていたため、本土プリセット(`open.bigmodel.cn`)のユーザーは国際 endpoint が到達不能なときに用量を取得できませんでした。残量リクエストは、ユーザーが構成した base URL に一致するホストへルーティングされるようになりました(#3702)。
|
||||
|
||||
### MiniMax 残量 API と価格
|
||||
|
||||
MiniMax Coding Plan の残量を新しい残量 API に対応させました(新 API は、旧パーサーが依存していた用量カウント(階層が空になりトレイに用量が表示されなくなる)の代わりに、残り割合のフィールドを返します)。非コーディングモデル(動画など)を除外し、週次上限のないプランに対応し、MiniMax M3 モデルの既定価格を追加しました(#3518)。
|
||||
|
||||
### GLM Coding Plan の endpoint とモデル取得
|
||||
|
||||
智譜 / Z.AI の GLM Coding Plan プリセットを `/api/coding/paas/v4` endpoint に修正し(Codex、OpenCode、OpenClaw、Hermes をカバー)、すでに `/v{N}` のバージョンセグメントで終わる base URL については、モデル一覧プローブが `{base}/models` を先に照会するようにしました(`/v1/models` はフォールバックとして保持)。これにより「モデル取得」ボタンがバージョン付き endpoint で 404 にならなくなりました(#3524)。
|
||||
|
||||
### Codex モデルカタログパスの可搬性
|
||||
|
||||
Codex は `config.toml` に絶対パスではなく相対ファイル名 `cc-switch-model-catalog.json` のみを書き込むようになりました(Codex CLI は設定ディレクトリから解決します)。これにより、絶対パスを変換できない WSL やシンボリックリンク環境でモデルカタログが壊れる問題を修正しました(#3614)。
|
||||
|
||||
### APINebula の OpenCode SDK
|
||||
|
||||
APINebula の OpenCode プリセットは `@ai-sdk/openai` ではなく `@ai-sdk/openai-compatible` を読み込むようになり、chat-completions のみ対応の上流で失敗する Responses API ではなく、このリレーが期待する OpenAI Chat Completions 形式でリクエストを行います。
|
||||
|
||||
### Windows 終了後のトレイアイコン残留
|
||||
|
||||
Windows では CC Switch を終了すると、マウスを重ねるまで無効なトレイアイコンが残ることがありました。アプリは終了前にトレイアイコンを明示的に削除するようになり、プロセス終了とともにきれいに消えます(#3797)。
|
||||
|
||||
### Windows タスクバーアイコン
|
||||
|
||||
実行時に Windows AppUserModelID を明示的に設定し、インストーラーが生成するデスクトップとスタートメニューのショートカットに同じ ID と製品アイコンを書き込みます。これにより CC Switch がタスクバーで正しいアイコンを表示し、正しくグループ化されます(#3457)。
|
||||
|
||||
### Windows サブディレクトリスキルの更新チェック
|
||||
|
||||
Windows でインストール済みスキルをスキャンする際、バックスラッシュのパス区切りをスラッシュへ正規化するようになり、サブディレクトリにネストされたスキル(`skills/my-skill` など)が静かにスキップされず、更新チェックで一致するようになりました(#3430)。
|
||||
|
||||
### macOS の入力自動大文字化
|
||||
|
||||
共有のテキスト Input コンポーネントで autocomplete、autocorrect、autocapitalize、spellcheck を無効化し、macOS が設定フィールドに入力された最初の文字を自動で大文字化・自動修正しないようにしました(#3626)。
|
||||
|
||||
### Codex VS Code セッションプレビュー
|
||||
|
||||
VS Code から送信された Codex リクエストでは、注入されたリクエストの前に markdown 見出しがあると、セッションプレビューが本当のプロンプトではなく選択範囲や開いているファイルの内容を表示することがありました。バックエンドのタイトルとフロントエンドのプレビューはいずれも、最後の「## My request for Codex:」見出しに一致するようになり(IDE は本当のリクエストを最後のセクションとして注入します)、プレビューがユーザーのプロンプトを反映します(#3593)。
|
||||
|
||||
### 中国語 UI の VS Code 表記
|
||||
|
||||
簡体字・繁体字中国語の「Claude Code プラグインに適用」の説明を、「Vscode」ではなく正しく「VS Code」と表記するよう修正し、英語・日本語の文言と揃えました(#3228)。
|
||||
|
||||
---
|
||||
|
||||
## ドキュメント
|
||||
|
||||
### ユーザーマニュアル刷新
|
||||
|
||||
README の各言語版と en / zh / ja のユーザーマニュアルを刷新し、受管 7 アプリすべてを反映(紹介と概要の文面に Claude Desktop と Hermes を追加)、OpenCode の設定パスを `~/.config/opencode/`(`opencode.json`)に修正、Hermes の設定ファイルの説明を追加、言語ドキュメントを 4 言語に更新、アプリごとの MCP / プロンプト / スキルの対応状況を訂正、エクスポートがタイムスタンプ付きで用量ログを含む SQL バックアップを生成することを記載、価格モデル ID のマッチングルールを追記しました(#3411)。
|
||||
|
||||
### Codex 公式認証保持ガイド
|
||||
|
||||
モデル通信をサードパーティ API へ切り替えつつ、Codex の公式リモート操作と公式プラグインを動作させ続ける方法を説明する中国語 / 英語 / 日本語のガイドを追加し、v3.16.1 のリリースノートからリンクしました。
|
||||
|
||||
### README リンクとスポンサー表記
|
||||
|
||||
各言語の README のリリースノートリンクを v3.16.1 に更新し、README_ZH のスポンサーブロックで壊れていた曲線引用符文字を修正して、HTML 属性が正しくレンダリングされるようにしました(#3772)。
|
||||
|
||||
---
|
||||
|
||||
## アップグレード時の注意
|
||||
|
||||
### S3 と WebDAV のクラウド同期は排他
|
||||
|
||||
クラウド同期は同時に 1 つのバックエンドのみを実行します。S3 自動同期を有効化すると、実行中の WebDAV 自動同期は停止し、その逆も同様です。以前 WebDAV を使っていた場合は、S3 へ切り替える前に両端のデータが揃っていることを確認し、旧バックエンドがまだバックアップしていると誤解しないようにしてください。
|
||||
|
||||
### モデルマッピング変更後は Codex の再起動が必要
|
||||
|
||||
Codex は起動時に `model_catalog_json` を読み込みます。本リリースでモデルカタログを相対パスへ書き換え、`/v1/models` 到達性エンドポイントを追加しましたが、モデルマッピングテーブルを変更した後は、`/model` メニューを更新するために Codex の再起動が必要です。
|
||||
|
||||
---
|
||||
|
||||
## リスク通知
|
||||
|
||||
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
|
||||
|
||||
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。
|
||||
|
||||
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金、コンプライアンス、データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
|
||||
|
||||
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金、コンプライアンス、データ保持に関する規約に従う必要があります。
|
||||
|
||||
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## 謝辞
|
||||
|
||||
v3.16.2 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
|
||||
|
||||
- [#1351](https://github.com/farion1231/cc-switch/pull/1351): S3 互換クラウドストレージ同期を追加、[@keithyt06](https://github.com/keithyt06) に感謝。
|
||||
- [#3215](https://github.com/farion1231/cc-switch/pull/3215): OpenCode セッション用量同期を追加、[@nothingness0db](https://github.com/nothingness0db) に感謝。
|
||||
- [#2709](https://github.com/farion1231/cc-switch/pull/2709): ZenMux Token Plan プロバイダーを追加、[@Eter365](https://github.com/Eter365) に感謝。
|
||||
- [#3643](https://github.com/farion1231/cc-switch/pull/3643): CherryIN プリセットプロバイダーを追加、[@zhibisora](https://github.com/zhibisora) に感謝。
|
||||
- [#3818](https://github.com/farion1231/cc-switch/pull/3818): Codex CLI 到達性確認用の `GET /v1/models` エンドポイントを追加、[@CSberlin](https://github.com/CSberlin) に感謝。
|
||||
- [#3426](https://github.com/farion1231/cc-switch/pull/3426): 用量ダッシュボードのヒーロー再設計、[@allenxu09](https://github.com/allenxu09) に感謝。
|
||||
- [#3640](https://github.com/farion1231/cc-switch/pull/3640): tools が空のとき `tool_choice` を破棄、[@Postroggy](https://github.com/Postroggy) に感謝。
|
||||
- [#3644](https://github.com/farion1231/cc-switch/pull/3644): Chat ルーティングで Codex カスタムツールメタデータを保持、[@LanternCX](https://github.com/LanternCX) に感謝。
|
||||
- [#3514](https://github.com/farion1231/cc-switch/pull/3514): Chat→Responses で常に `reasoning_tokens` を含める、[@yeeyzy](https://github.com/yeeyzy) に感謝。
|
||||
- [#3689](https://github.com/farion1231/cc-switch/pull/3689): live がすでにプロキシプレースホルダーのときバックアップ / 復元をスキップ、[@YongmaoLuo](https://github.com/YongmaoLuo) に感謝。
|
||||
- [#3016](https://github.com/farion1231/cc-switch/pull/3016): localhost リッスンアドレスを正規化、[@Alexlangl](https://github.com/Alexlangl) に感謝。
|
||||
- [#3775](https://github.com/farion1231/cc-switch/pull/3775): Anthropic `system` メッセージを正規化、[@Dearli666](https://github.com/Dearli666) に感謝。
|
||||
- [#3656](https://github.com/farion1231/cc-switch/pull/3656): プロキシパネルのエラー表示を改善、[@lzcndm](https://github.com/lzcndm) に感謝。
|
||||
- [#2647](https://github.com/farion1231/cc-switch/pull/2647): 無限空白検出のしきい値を 20 → 500 へ引き上げ、[@NiuBlibing](https://github.com/NiuBlibing) に感謝。
|
||||
- [#3702](https://github.com/farion1231/cc-switch/pull/3702): 智譜の残量照会を構成済み base URL へルーティング、[@YongmaoLuo](https://github.com/YongmaoLuo) に感謝。
|
||||
- [#3518](https://github.com/farion1231/cc-switch/pull/3518): MiniMax の新残量 API と既定価格に対応、[@LaoYueHanNi](https://github.com/LaoYueHanNi) に感謝。
|
||||
- [#3524](https://github.com/farion1231/cc-switch/pull/3524): 智譜 Coding Plan プリセットとバージョン付き endpoint のモデル探索を修正、[@makoMakoGo](https://github.com/makoMakoGo) に感謝。
|
||||
- [#3614](https://github.com/farion1231/cc-switch/pull/3614): モデルカタログを相対ファイル名に変更、[@steponeerror](https://github.com/steponeerror) に感謝。
|
||||
- [#3797](https://github.com/farion1231/cc-switch/pull/3797): Windows 終了後のトレイアイコン残留を修正、[@iAJue](https://github.com/iAJue) に感謝。
|
||||
- [#3457](https://github.com/farion1231/cc-switch/pull/3457): Windows タスクバーアイコンを修正、[@ZhangNanNan1018](https://github.com/ZhangNanNan1018) に感謝。
|
||||
- [#3430](https://github.com/farion1231/cc-switch/pull/3430): Windows のパス区切りを正規化してサブディレクトリスキルの更新に対応、[@Ninthless](https://github.com/Ninthless) に感謝。
|
||||
- [#3626](https://github.com/farion1231/cc-switch/pull/3626): macOS の入力自動大文字化を無効化、[@ZHLHZHU](https://github.com/ZHLHZHU) に感謝。
|
||||
- [#3593](https://github.com/farion1231/cc-switch/pull/3593): Codex VS Code セッションプレビューを修正、[@xwil1](https://github.com/xwil1) に感謝。
|
||||
- [#3228](https://github.com/farion1231/cc-switch/pull/3228): 中国語 UI の VS Code 表記を揃える、[@Games55k](https://github.com/Games55k) に感謝。
|
||||
- [#3411](https://github.com/farion1231/cc-switch/pull/3411): 現行のアプリ対応を反映してユーザーマニュアルを刷新、[@makoMakoGo](https://github.com/makoMakoGo) に感謝。
|
||||
- [#3772](https://github.com/farion1231/cc-switch/pull/3772): README のリリースノートリンクとスポンサー表記を修正、[@null-easy](https://github.com/null-easy) に感謝。
|
||||
|
||||
v3.16.1 リリース後に Codex Chat ルーティング、ローカルプロキシのテイクオーバー、用量統計、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くの修正は、実際の利用シーンから得られた再現情報に基づいています。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最低バージョン | アーキテクチャ |
|
||||
| -------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表を参照 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | ------------------------------------------ |
|
||||
| `CC-Switch-v3.16.2-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
|
||||
| `CC-Switch-v3.16.2-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ------------------------------------------------------ |
|
||||
| `CC-Switch-v3.16.2-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
|
||||
| `CC-Switch-v3.16.2-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.16.2-macOS.tar.gz` | Homebrew インストールと自動更新用 |
|
||||
|
||||
Homebrew インストール:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux アセットは **x86_64** と **ARM64**(`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
|
||||
|
||||
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| ディストリビューション | 推奨形式 | インストール方法 |
|
||||
| --------------------------------------- | ----------- | ------------------------------------------------------------------------- |
|
||||
| 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,347 @@
|
||||
# CC Switch v3.16.2
|
||||
|
||||
> 在 v3.16.1 的 Codex 稳定性补丁之后,这一版主要拓宽了数据的可携带性与用量观测能力——新增 S3 兼容云同步、OpenCode 会话用量同步、官方订阅额度模板——并继续加固 Codex 通过 Chat Completions 路由第三方供应商的稳健性,同时修复了一批 Windows / macOS 平台问题,新增 CherryIN、ZenMux 供应商,并全面刷新了三语用户手册。
|
||||
|
||||
**[English →](v3.16.2-en.md) | [日本語版 →](v3.16.2-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
这一版新增了云同步的 S3 后端和更多用量统计来源,如果你想用上,可以先看这些文档:
|
||||
|
||||
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:在设置页配置云同步(WebDAV / S3 兼容存储),用于在多台设备间备份和恢复供应商、MCP、提示词、技能等配置。
|
||||
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源(代理日志、Codex / Gemini / OpenCode 会话同步)与统计口径。
|
||||
|
||||
---
|
||||
|
||||
> [!WARNING]
|
||||
>
|
||||
> ## 唯一官方渠道声明(请务必阅读)
|
||||
>
|
||||
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
|
||||
>
|
||||
> | 类别 | 唯一官方 |
|
||||
> | -------- | ------------------------------------------------------------------------------ |
|
||||
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
|
||||
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
|
||||
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
|
||||
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
|
||||
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
|
||||
>
|
||||
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
|
||||
|
||||
---
|
||||
|
||||
## 概览
|
||||
|
||||
CC Switch v3.16.2 是 v3.16.1 之后的一版维护更新。在上一版集中处理 Codex 官方鉴权与本地路由接管的安全问题之后,这一版把重心放在两件事上:一是拓宽数据的可携带性和用量观测——新增 S3 兼容云同步(WebDAV 之外的第二套云备份后端)、OpenCode 会话用量同步,以及面向官方订阅的额度统计模板;二是继续打磨 Codex 通过 Chat Completions 路由第三方供应商时暴露出来的边角问题——流式截断判定、空 tools 下的 `tool_choice`、自定义工具元数据、推理 token 统计、文件 / 音频附件转换等。
|
||||
|
||||
此外,本版还修复了一批本地代理的稳健性问题(临时端口解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案、Claude Desktop 的 `[1m]` 模型路由),处理了若干 Windows / macOS 平台体验问题,并新增 CherryIN、ZenMux 两个供应商,同时全面刷新了三语用户手册。
|
||||
|
||||
**发布日期**:2026-06-07
|
||||
|
||||
**更新规模**:41 commits | 132 files changed | +11,116 / -1,636 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **S3 兼容云同步**:在 WebDAV 之外新增 S3 兼容对象存储作为第二套云备份后端,内置 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 等一键预设。
|
||||
- **更多用量统计来源**:新增 OpenCode 会话用量同步,以及面向 Claude / Codex / Gemini 官方订阅的额度统计模板(显式开关、默认关闭)。
|
||||
- **Codex Chat Completions 路由继续加固**:修复流式截断误判、空 tools 下 `tool_choice` 被拒、自定义工具元数据丢失、推理 token 统计缺失,并支持文件 / 音频附件转换与 `/v1/models` 探活端点。
|
||||
- **本地代理更稳**:修复临时端口(port 0)解析、接管占位符还原死循环、Anthropic `system` 消息归一化、上游 413 文案,以及 Claude Desktop 1M 上下文模型路由。
|
||||
- **平台与供应商**:修复 Windows 托盘 / 任务栏图标、子目录技能更新、macOS 输入自动大写等问题,并新增 CherryIN、ZenMux 供应商。
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### S3 兼容云同步
|
||||
|
||||
云同步现在支持 S3 兼容对象存储作为 WebDAV 之外的第二套后端,签名采用自实现的 AWS Signature V4,以兼容尽可能多的服务。设置页提供 AWS S3、MinIO、Cloudflare R2、阿里云 OSS、腾讯云 COS、华为 OBS 以及自定义 endpoint 的一键预设,支持连接测试、手动上传 / 下载,以及在配置变更时自动同步(providers、endpoint、MCP、提示词、技能、设置、代理等配置表,**不含**用量日志这类高频写入数据)。开启 S3 同步会停用正在运行的 WebDAV 同步,反之亦然([#1351](https://github.com/farion1231/cc-switch/pull/1351))。
|
||||
|
||||
### OpenCode 会话用量同步
|
||||
|
||||
新增 OpenCode 作为用量统计来源,从 OpenCode 本地 SQLite 数据库读取每条消息的 token、成本和模型数据并导入用量记录,并提供独立的「OpenCode」应用筛选页签和「OpenCode Session」数据来源标签。数据库路径会遵循 `OPENCODE_DB` 和 `XDG_DATA_HOME`(在所有平台默认 `~/.local/share/opencode`),只导入已完成的消息,并在判断新鲜度时把 WAL 文件一并计入,避免刚写入的会话被跳过([#3215](https://github.com/farion1231/cc-switch/pull/3215))。
|
||||
|
||||
### 官方订阅额度模板
|
||||
|
||||
由于部分用户担心发起用量查询的 IP 和发起应用内请求的不一致导致封号风险,因此为 Claude / Codex / Gemini 官方供应商新增一个显式、可选的「官方订阅」用量模板,通过 CLI / OAuth 凭据查询套餐额度,替代此前对官方供应商的隐式自动查询。该模板默认关闭,需要在用量脚本弹窗里开启,并可配置刷新间隔。使用此功能建议开启代理的 TUN 模式。
|
||||
|
||||
### 文本模型图片回退整流器
|
||||
|
||||
新增一个代理整流器:当路由到的模型仅支持文本(显式声明,或由内置的模型名启发式判定),或上游拒绝图片输入时,会把 Anthropic 图片块替换为 `[Unsupported Image]` 占位标记,避免对话被中断。设置页提供该回退功能的开关,并单独提供一个开关控制启发式检测(可关闭以避免误判多模态模型)。
|
||||
|
||||
### ZenMux Token Plan 供应商
|
||||
|
||||
新增 ZenMux 作为 Token Plan 类的 Coding Plan 供应商,可在用量脚本弹窗里手动填写 API key 和 base URL,并以美元口径富展示已用 / 额度([#2709](https://github.com/farion1231/cc-switch/pull/2709))。
|
||||
|
||||
### CherryIN 预设
|
||||
|
||||
新增 CherryIN 聚合网关作为快捷配置预设,覆盖全部 7 个受管应用——Claude Code / Claude Desktop / OpenClaw / Hermes 使用 Anthropic 格式端点(open.cherryin.net),OpenCode 使用 `@ai-sdk/anthropic`(`/v1`),Codex 使用 OpenAI 兼容端点,Gemini CLI 使用 Gemini 兼容端点,附带官方品牌图标,位置紧挨 AiHubMix([#3643](https://github.com/farion1231/cc-switch/pull/3643))。
|
||||
|
||||
### Codex CLI 模型探活端点 `/v1/models`
|
||||
|
||||
本地代理现在会响应 Codex CLI 启动时探测的 `GET /v1/models`,返回 CC Switch 托管的 Codex 模型目录。同时加入了过期目录守卫:解析 live 的 `config.toml`,仅当 `model_catalog_json` 仍指向 CC Switch 持有的目录文件时才提供,避免把上一个供应商遗留的目录暴露给 Codex([#3818](https://github.com/farion1231/cc-switch/pull/3818))。
|
||||
|
||||
### Codex Chat 文件与音频附件
|
||||
|
||||
Codex 的 Responses→Chat 转换现在会把 `input_file`(携带 `file_id` 或内联 `file_data`)和 `input_audio` 内容部分映射为 Chat Completions 的对应形态,并补发此前会被丢弃的顶层 `input_*` 项,让文件和音频附件能够送达只支持 Chat 的 Codex 上游。
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### 用量看板 Hero 重新设计
|
||||
|
||||
把用量看板的 Hero 区与汇总卡片重排为更紧凑的布局,将真实 token 总量、请求数和成本合并到顶部一行展示([#3426](https://github.com/farion1231/cc-switch/pull/3426))。
|
||||
|
||||
### SSSAiCode 端点刷新
|
||||
|
||||
把 SSSAiCode 预设的官网、注册和 API base URL 更新到 `sssaicodeapi.com` 域名,并刷新其端点候选节点(默认 `node-hk.sssaicodeapi.com`,另含 `node-hk.sssaiapi.com` 和 `node-cf.sssaicodeapi.com`),覆盖全部 7 个应用预设。
|
||||
|
||||
---
|
||||
|
||||
## 修复
|
||||
|
||||
### Codex Chat 流式截断判定
|
||||
|
||||
当 Chat Completions 上游在没有 `finish_reason` 或 `[DONE]` 的情况下结束流时,CC Switch 不再把它当作正常完成:只有流真正结束才正常收尾;已产出部分内容时发出 incomplete(`max_output_tokens`)响应;完全没有产出时发出失败的 `stream_truncated` 事件。晚到的推理内容也会回填到仍在进行的流式工具调用上。
|
||||
|
||||
### Codex Chat 空 tools 下的 `tool_choice`
|
||||
|
||||
Responses→Chat 转换现在会在最终 tools 数组缺失或为空(包括所有工具被过滤掉)时一并丢弃 `tool_choice` 和 `parallel_tool_calls`,避免严格的 OpenAI 兼容上游(vLLM、企业网关)以"When using `tool_choice`, `tools` must be set."报 503/400([#3640](https://github.com/farion1231/cc-switch/pull/3640))。
|
||||
|
||||
### Codex 自定义工具元数据保留
|
||||
|
||||
自定义 Codex 工具(如自由格式的 `apply_patch` 工具)现在会把完整的原始定义——包括 format 和 grammar 元数据——以紧凑、顺序稳定的 JSON 块嵌入生成的 Chat 函数描述中,而不是替换成通用占位符,从而在 Chat Completions 上游上仍可正常使用([#3644](https://github.com/farion1231/cc-switch/pull/3644))。
|
||||
|
||||
### Codex Chat 用量缺少 `reasoning_tokens`
|
||||
|
||||
Chat→Responses 的用量转换现在总会包含 `output_tokens_details.reasoning_tokens`(默认 0),即使供应商省略 `completion_tokens_details` 或返回非对象也是如此,满足 Codex CLI 的严格要求,避免反复的响应解析失败和重试([#3514](https://github.com/farion1231/cc-switch/pull/3514))。
|
||||
|
||||
### Codex 自定义工具 / 搜索工具的跨轮推理
|
||||
|
||||
Codex Chat 历史里的跨轮推理缓存现在覆盖完整的工具调用集合(`function_call`、`custom_tool_call`、`tool_search_call`)及其输出,而不再仅限普通函数调用,因此 `apply_patch` 和工具搜索调用在通过 `previous_response_id` 恢复时能保留各自的 `reasoning_content`。
|
||||
|
||||
### 临时端口(port 0)解析
|
||||
|
||||
当代理被配置为监听 0 端口(由系统分配)时,接管流程现在会先启动代理以拿到真实端口,再写入 live 配置和数据库,避免客户端 URL 指向无效的 `:0` 地址;若还没解析出具体端口,Claude Desktop 的网关 URL 会被直接拒绝。
|
||||
|
||||
### 代理占位符备份 / 恢复死循环
|
||||
|
||||
如果上一次停止代理时未能还原原始 live 配置、把代理占位符遗留在了 live 中,再次接管时不会再用代理配置覆盖掉正常备份,恢复时也不会把占位符写回 live:两条路径都会识别占位符状态并以当前供应商为真相来源重建 live,修复了代理开关变成空操作、客户端被钉死在本地代理地址的问题([#3689](https://github.com/farion1231/cc-switch/pull/3689))。
|
||||
|
||||
### 代理接管期间误拦截供应商切换
|
||||
|
||||
在本地路由接管期间,现在只有显式归类为官方的供应商会被禁止切换,而不会再把端点存在 meta 里、或字段尚未填写的自定义供应商一并禁用。被禁用的「启用」按钮现在以更轻量的提示气泡替代原先的红色「已拦截」标记。
|
||||
|
||||
### localhost 监听地址归一化
|
||||
|
||||
保存代理时如果监听地址填的是 `localhost`,现在会先归一化为 `127.0.0.1` 再持久化,避免绑定不一致([#3016](https://github.com/farion1231/cc-switch/pull/3016))。
|
||||
|
||||
### Anthropic `system` 消息归一化
|
||||
|
||||
对 Anthropic 格式的供应商,`messages` 数组里的 system 角色条目现在会被折叠并合并到顶层 `system` 字段(保留原顺序以及已有的顶层 system),避免严格上游拒绝非首位的 system 消息;OpenAI Chat 路由不受影响([#3775](https://github.com/farion1231/cc-switch/pull/3775))。
|
||||
|
||||
### Claude Desktop 1M 上下文模型路由
|
||||
|
||||
Claude Desktop 在 1M 上下文 beta 激活时会给模型名追加 `[1m]` 标记(如 `claude-opus-4-8[1m]`)。代理现在会在路由匹配前先剥掉该后缀,让精确、别名、旧名和角色关键词匹配都能正确命中,修复了对话中途切换到 1M 模型时的 `route_unknown`(HTTP 400)失败;诊断用的 `route_unknown` 错误里仍保留原始模型名。
|
||||
|
||||
### Codex 413 错误文案
|
||||
|
||||
当 Codex 上游网关以 HTTP 413 拒绝过大的请求体时,代理现在返回专门的提示,说明这是供应商服务端的请求体大小限制(而非 CC Switch 本地限制),并给出可操作的恢复步骤(运行 `/compact`、移除大段日志或内联图片,或请供应商调高限制),不再原样回显上游的 HTML 错误页。
|
||||
|
||||
### 代理面板错误详情
|
||||
|
||||
切换代理接管失败时,代理面板的提示现在会带上后端返回的具体错误详情,而不是只显示一句笼统的失败信息([#3656](https://github.com/farion1231/cc-switch/pull/3656))。
|
||||
|
||||
### Copilot 无限空白检测阈值
|
||||
|
||||
把流式无限空白的中断阈值从 20 调高到 500 个连续空白字符,避免参数里含深层缩进代码(Python、YAML、Rust、Markdown)的正常工具调用被误判中断,同时仍能捕获真正的 Copilot 无限空白 bug([#2647](https://github.com/farion1231/cc-switch/pull/2647))。
|
||||
|
||||
### 订阅档位托盘渲染
|
||||
|
||||
通过统一的档位到标签映射,修复官方订阅档位在托盘和额度展示上的渲染问题:Claude / Codex 不再漏掉 7 天窗口,Gemini Pro / Flash / Flash-Lite 档位不再泄露原始机器名,多窗口套餐(如 Opus + Sonnet)现在按最差利用率展示而非取第一个匹配。
|
||||
|
||||
### Claude 流式 input_tokens 虚高
|
||||
|
||||
部分 Anthropic 兼容的流式供应商(如 Qwen、MiniMax)会在 `message_start` 里把完整上下文当作 `input_tokens` 上报,重复计入了已经单独统计的缓存部分,导致显示的缓存命中率被人为拉低。现在解析器会优先采用 `message_delta` 中更小的正 `input_tokens`,并采用同一 usage 块里配套的缓存计数;原生 Claude 和 OpenRouter 转换路径不变。
|
||||
|
||||
### 智谱配额查询端点路由
|
||||
|
||||
智谱 Coding Plan 的配额查询此前被硬编码到 `api.z.ai`,导致使用大陆预设(`open.bigmodel.cn`)的用户在国际端点不可达时查不到用量。现在配额请求会路由到与用户所配 base URL 匹配的主机([#3702](https://github.com/farion1231/cc-switch/pull/3702))。
|
||||
|
||||
### MiniMax 余额接口与定价
|
||||
|
||||
适配 MiniMax Coding Plan 配额的新余额接口(新接口返回剩余百分比字段,而非旧解析器依赖、会导致档位为空、托盘不再显示用量的用量计数),过滤掉非编程模型(如视频),兼容无周限额的套餐,并为 MiniMax M3 模型补充了默认定价([#3518](https://github.com/farion1231/cc-switch/pull/3518))。
|
||||
|
||||
### GLM Coding Plan 端点与模型拉取
|
||||
|
||||
把智谱 / Z.AI 的 GLM Coding Plan 预设修正到 `/api/coding/paas/v4` 端点(覆盖 Codex、OpenCode、OpenClaw、Hermes),并让模型列表探测对已经以 `/v{N}` 版本段结尾的 base URL 改为先查 `{base}/models`(保留 `/v1/models` 作为兜底),让「拉取模型」按钮不再在带版本号的端点上 404([#3524](https://github.com/farion1231/cc-switch/pull/3524))。
|
||||
|
||||
### Codex 模型目录路径可移植性
|
||||
|
||||
Codex 现在只把相对文件名 `cc-switch-model-catalog.json` 写入 `config.toml`,而不是绝对路径(Codex CLI 会从配置目录解析它),修复了在 WSL 和符号链接环境下绝对路径无法转换、导致模型目录失效的问题([#3614](https://github.com/farion1231/cc-switch/pull/3614))。
|
||||
|
||||
### APINebula 的 OpenCode SDK
|
||||
|
||||
APINebula 的 OpenCode 预设现在加载 `@ai-sdk/openai-compatible` 而非 `@ai-sdk/openai`,让请求使用该中转期望的 OpenAI Chat Completions 格式,而不是只支持 chat-completions 的上游会失败的 Responses API。
|
||||
|
||||
### Windows 退出后托盘图标残留
|
||||
|
||||
在 Windows 上退出 CC Switch 可能会留下一个失效的托盘图标,直到鼠标划过才消失。现在应用会在退出前显式移除托盘图标,让它随进程结束干净消失([#3797](https://github.com/farion1231/cc-switch/pull/3797))。
|
||||
|
||||
### Windows 任务栏图标
|
||||
|
||||
在运行时显式设置 Windows AppUserModelID,并给安装器生成的桌面和开始菜单快捷方式写入相同的 ID 和产品图标,让 CC Switch 在任务栏上显示正确图标并正确归组([#3457](https://github.com/farion1231/cc-switch/pull/3457))。
|
||||
|
||||
### Windows 子目录技能的更新检查
|
||||
|
||||
在 Windows 上扫描已安装技能时,把反斜杠路径分隔符归一化为正斜杠,让嵌套在子目录里的技能(如 `skills/my-skill`)能被更新检查匹配到,而不是被静默跳过([#3430](https://github.com/farion1231/cc-switch/pull/3430))。
|
||||
|
||||
### macOS 输入自动大写
|
||||
|
||||
为共享的文本 Input 组件关闭自动完成、自动纠错、自动大写和拼写检查,让 macOS 不再对配置字段里输入的首字母自动大写或自动纠正([#3626](https://github.com/farion1231/cc-switch/pull/3626))。
|
||||
|
||||
### Codex VS Code 会话预览
|
||||
|
||||
从 VS Code 发起的 Codex 请求,其会话预览在注入请求前存在 markdown 标题时,可能显示选区或打开文件的内容而非真实提示。现在后端标题和前端预览都会匹配最后一个「## My request for Codex:」标题(IDE 把真实请求作为最后一节注入),让预览反映用户的提示([#3593](https://github.com/farion1231/cc-switch/pull/3593))。
|
||||
|
||||
### 中文界面 VS Code 文案
|
||||
|
||||
把简体和繁体中文里「应用到 Claude Code 插件」的描述改为正确书写「VS Code」而非「Vscode」,与英文、日文文案对齐([#3228](https://github.com/farion1231/cc-switch/pull/3228))。
|
||||
|
||||
---
|
||||
|
||||
## 文档
|
||||
|
||||
### 用户手册刷新
|
||||
|
||||
刷新了 README 各语言版本以及 en / zh / ja 用户手册,使其反映全部 7 个受管应用(在介绍和总览文案里补上 Claude Desktop 与 Hermes),把 OpenCode 配置路径修正为 `~/.config/opencode/`(`opencode.json`),补充了 Hermes 配置文件说明,把语言文档更新为四种语言,订正各应用 MCP / 提示词 / 技能的支持情况,说明导出现在会生成带时间戳、含用量日志的 SQL 备份,并补充了定价模型 ID 匹配规则([#3411](https://github.com/farion1231/cc-switch/pull/3411))。
|
||||
|
||||
### Codex 官方认证保留指南
|
||||
|
||||
新增中 / 英 / 日三语指南,说明如何在把模型流量切到第三方 API 的同时,保留 Codex 官方远程操作和官方插件的可用性,并从 v3.16.1 release notes 链接到该指南。
|
||||
|
||||
### README 链接与赞助商标记
|
||||
|
||||
把各语言 README 里的 Release Notes 链接更新到 v3.16.1,并修复 README_ZH 赞助商区块里损坏的弯引号字符,让其 HTML 属性能正确渲染([#3772](https://github.com/farion1231/cc-switch/pull/3772))。
|
||||
|
||||
---
|
||||
|
||||
## 升级提醒
|
||||
|
||||
### S3 与 WebDAV 云同步互斥
|
||||
|
||||
云同步同一时间只会运行一套后端。开启 S3 自动同步会停用正在运行的 WebDAV 自动同步,反之亦然。如果你之前用的是 WebDAV,切到 S3 前请确认两端数据已对齐,避免误以为旧后端仍在备份。
|
||||
|
||||
### 修改模型映射后仍需重启 Codex
|
||||
|
||||
Codex 在启动时读取 `model_catalog_json`。即使本版已把模型目录改写为相对路径并新增了 `/v1/models` 探活端点,只要你修改了模型映射表,仍然需要重启 Codex 才能让 `/model` 菜单刷新。
|
||||
|
||||
---
|
||||
|
||||
## 风险提示
|
||||
|
||||
本版本继续沿用此前版本对反向代理类功能的风险提示。
|
||||
|
||||
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。
|
||||
|
||||
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
|
||||
|
||||
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
|
||||
|
||||
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢以下贡献者在 v3.16.2 中提交的功能与修复:
|
||||
|
||||
- [#1351](https://github.com/farion1231/cc-switch/pull/1351):新增 S3 兼容云存储同步,感谢 [@keithyt06](https://github.com/keithyt06)。
|
||||
- [#3215](https://github.com/farion1231/cc-switch/pull/3215):新增 OpenCode 会话用量同步,感谢 [@nothingness0db](https://github.com/nothingness0db)。
|
||||
- [#2709](https://github.com/farion1231/cc-switch/pull/2709):新增 ZenMux Token Plan 供应商,感谢 [@Eter365](https://github.com/Eter365)。
|
||||
- [#3643](https://github.com/farion1231/cc-switch/pull/3643):新增 CherryIN 预设供应商,感谢 [@zhibisora](https://github.com/zhibisora)。
|
||||
- [#3818](https://github.com/farion1231/cc-switch/pull/3818):新增 Codex CLI 探活用的 `GET /v1/models` 端点,感谢 [@CSberlin](https://github.com/CSberlin)。
|
||||
- [#3426](https://github.com/farion1231/cc-switch/pull/3426):用量看板 Hero 重新设计,感谢 [@allenxu09](https://github.com/allenxu09)。
|
||||
- [#3640](https://github.com/farion1231/cc-switch/pull/3640):空 tools 时丢弃 `tool_choice`,感谢 [@Postroggy](https://github.com/Postroggy)。
|
||||
- [#3644](https://github.com/farion1231/cc-switch/pull/3644):Chat 路由保留 Codex 自定义工具元数据,感谢 [@LanternCX](https://github.com/LanternCX)。
|
||||
- [#3514](https://github.com/farion1231/cc-switch/pull/3514):Chat→Responses 始终包含 `reasoning_tokens`,感谢 [@yeeyzy](https://github.com/yeeyzy)。
|
||||
- [#3689](https://github.com/farion1231/cc-switch/pull/3689):live 已是代理占位符时跳过备份 / 恢复,感谢 [@YongmaoLuo](https://github.com/YongmaoLuo)。
|
||||
- [#3016](https://github.com/farion1231/cc-switch/pull/3016):归一化 localhost 监听地址,感谢 [@Alexlangl](https://github.com/Alexlangl)。
|
||||
- [#3775](https://github.com/farion1231/cc-switch/pull/3775):规范化 Anthropic `system` 消息,感谢 [@Dearli666](https://github.com/Dearli666)。
|
||||
- [#3656](https://github.com/farion1231/cc-switch/pull/3656):改进代理面板错误信息展示,感谢 [@lzcndm](https://github.com/lzcndm)。
|
||||
- [#2647](https://github.com/farion1231/cc-switch/pull/2647):调高无限空白检测阈值 20 → 500,感谢 [@NiuBlibing](https://github.com/NiuBlibing)。
|
||||
- [#3702](https://github.com/farion1231/cc-switch/pull/3702):智谱配额查询按所配 base URL 路由,感谢 [@YongmaoLuo](https://github.com/YongmaoLuo)。
|
||||
- [#3518](https://github.com/farion1231/cc-switch/pull/3518):适配 MiniMax 余额查询新接口与默认定价,感谢 [@LaoYueHanNi](https://github.com/LaoYueHanNi)。
|
||||
- [#3524](https://github.com/farion1231/cc-switch/pull/3524):修复智谱 Coding Plan 预设与带版本号端点的模型探测,感谢 [@makoMakoGo](https://github.com/makoMakoGo)。
|
||||
- [#3614](https://github.com/farion1231/cc-switch/pull/3614):模型目录改用相对文件名,感谢 [@steponeerror](https://github.com/steponeerror)。
|
||||
- [#3797](https://github.com/farion1231/cc-switch/pull/3797):修复 Windows 退出后托盘图标残留,感谢 [@iAJue](https://github.com/iAJue)。
|
||||
- [#3457](https://github.com/farion1231/cc-switch/pull/3457):修复 Windows 任务栏图标,感谢 [@ZhangNanNan1018](https://github.com/ZhangNanNan1018)。
|
||||
- [#3430](https://github.com/farion1231/cc-switch/pull/3430):归一化 Windows 路径分隔符以匹配子目录技能更新,感谢 [@Ninthless](https://github.com/Ninthless)。
|
||||
- [#3626](https://github.com/farion1231/cc-switch/pull/3626):关闭 macOS 输入框自动大写,感谢 [@ZHLHZHU](https://github.com/ZHLHZHU)。
|
||||
- [#3593](https://github.com/farion1231/cc-switch/pull/3593):修复 Codex VS Code 会话预览,感谢 [@xwil1](https://github.com/xwil1)。
|
||||
- [#3228](https://github.com/farion1231/cc-switch/pull/3228):对齐中文界面 VS Code 文案,感谢 [@Games55k](https://github.com/Games55k)。
|
||||
- [#3411](https://github.com/farion1231/cc-switch/pull/3411):刷新用户手册以反映当前应用支持,感谢 [@makoMakoGo](https://github.com/makoMakoGo)。
|
||||
- [#3772](https://github.com/farion1231/cc-switch/pull/3772):修复 README release note 链接与赞助商标记,感谢 [@null-easy](https://github.com/null-easy)。
|
||||
|
||||
也感谢所有在 v3.16.1 发布后反馈 Codex Chat 路由、本地代理接管、用量统计和平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | -------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.16.2-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.16.2-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------- |
|
||||
| `CC-Switch-v3.16.2-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.16.2-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.16.2-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
|
||||
|
||||
Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask cc-switch
|
||||
```
|
||||
|
||||
更新:
|
||||
|
||||
```bash
|
||||
brew upgrade --cask cc-switch
|
||||
```
|
||||
|
||||
### Linux
|
||||
|
||||
Linux 资产同时提供 **x86_64** 和 **ARM64**(`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
|
||||
|
||||
- `CC-Switch-v3.16.2-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.16.2-Linux-arm64.AppImage` / `.deb` / `.rpm`
|
||||
|
||||
| 发行版 | 推荐格式 | 安装方式 |
|
||||
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
|
||||
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` 或 `sudo apt install ./CC-Switch-*.deb` |
|
||||
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` 或 `sudo dnf install ./CC-Switch-*.rpm` |
|
||||
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
|
||||
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
|
||||
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
|
||||
@@ -1,6 +1,6 @@
|
||||
# CC Switch User Manual / 用户手册 / ユーザーマニュアル
|
||||
|
||||
> Claude Code / Codex / Gemini CLI / OpenCode / OpenClaw
|
||||
> Claude Code / Claude Desktop / Codex / Gemini CLI / OpenCode / OpenClaw / Hermes
|
||||
|
||||
## Language / 语言 / 言語
|
||||
|
||||
@@ -12,9 +12,9 @@
|
||||
|
||||
## Version / 版本 / バージョン
|
||||
|
||||
- Documentation version: v3.15.0
|
||||
- Last updated: 2026-05-16
|
||||
- Compatible with CC Switch v3.15.0+
|
||||
- Documentation version: v3.16.0
|
||||
- Last updated: 2026-05-29
|
||||
- Compatible with CC Switch v3.16.0+
|
||||
|
||||
## Links
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## What is CC Switch
|
||||
|
||||
CC Switch is a cross-platform desktop application designed for developers who use AI coding tools. It helps you centrally manage configurations for **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**.
|
||||
CC Switch is a cross-platform desktop application designed for developers who use AI tools. It helps you centrally manage configurations for **Claude Code**, **Claude Desktop**, **Codex**, **Gemini CLI**, **OpenCode**, **OpenClaw**, and **Hermes**.
|
||||
|
||||
## What Problems Does It Solve
|
||||
|
||||
@@ -45,7 +45,7 @@ CC Switch solves these problems through a unified interface.
|
||||
| **Codex** | OpenAI's code generation tool |
|
||||
| **Gemini CLI** | Google's AI command-line tool |
|
||||
| **OpenCode** | Open-source AI coding terminal tool |
|
||||
| **OpenClaw** | Open-source AI coding assistant (multi-provider gateway) |
|
||||
| **OpenClaw** | Open-source AI assistant (multi-provider gateway) |
|
||||
| **Hermes** | Hermes Agent provider, MCP, Skills, and Memory management |
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| 2 | Settings Button | Open the settings page (shortcut `Cmd/Ctrl + ,`) |
|
||||
| 3 | Proxy Toggle | Start/stop the local proxy service |
|
||||
| 4 | App Switcher | Switch between Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes |
|
||||
| 5 | Feature Area | Skills / Prompts / MCP entry points |
|
||||
| 5 | Feature Area | App-specific feature entry points |
|
||||
| 6 | Add Button | Add a new provider |
|
||||
|
||||
### App Switcher
|
||||
@@ -33,9 +33,9 @@ After switching, the provider list displays the configurations for the selected
|
||||
|
||||
| Button | Function | Visibility |
|
||||
|--------|----------|------------|
|
||||
| Skills | Skill extension management | Always visible |
|
||||
| Prompts | System prompt management | Always visible |
|
||||
| MCP | MCP server management | Always visible |
|
||||
| Skills | Skill extension management | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
| Prompts | System prompt management | Claude / Codex / Gemini / OpenCode |
|
||||
| MCP | MCP server management | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
|
||||
## Provider Cards
|
||||
|
||||
@@ -113,13 +113,14 @@ CC Switch displays an icon in the system tray, providing quick access to operati
|
||||
|
||||
### Multi-language Support
|
||||
|
||||
The tray menu supports three languages, automatically switching based on settings:
|
||||
The tray menu supports four languages, automatically switching based on settings:
|
||||
|
||||
| Language | Open Main Window | Quit |
|
||||
|----------|-----------------|------|
|
||||
| Chinese | Open Main Window | Quit |
|
||||
| Simplified Chinese | 打开主界面 | 退出 |
|
||||
| Traditional Chinese | 開啟主介面 | 退出 |
|
||||
| English | Open main window | Quit |
|
||||
| Japanese | Open main window | Quit |
|
||||
| Japanese | メインウィンドウを開く | 終了 |
|
||||
|
||||
### Lightweight Mode
|
||||
|
||||
@@ -147,7 +148,7 @@ The settings page is divided into multiple tabs:
|
||||
|
||||
### General Tab
|
||||
|
||||
- Language settings (Chinese/English/Japanese)
|
||||
- Language settings (Simplified Chinese/Traditional Chinese/English/Japanese)
|
||||
- Theme settings (System/Light/Dark)
|
||||
- Window behavior (launch on startup, close behavior)
|
||||
|
||||
|
||||
@@ -9,11 +9,12 @@ This section describes how to configure CC Switch according to your preferences.
|
||||
|
||||
## Language Settings
|
||||
|
||||
CC Switch supports three languages:
|
||||
CC Switch supports four languages:
|
||||
|
||||
| Language | Description |
|
||||
|----------|-------------|
|
||||
| Simplified Chinese | Default language |
|
||||
| Traditional Chinese | Traditional Chinese interface |
|
||||
| English | English interface |
|
||||
| Japanese | Japanese interface |
|
||||
|
||||
@@ -124,8 +125,9 @@ You can customize each CLI tool's configuration directory:
|
||||
| Claude Directory | `~/.claude/` | Claude Code configuration directory |
|
||||
| Codex Directory | `~/.codex/` | Codex configuration directory |
|
||||
| Gemini Directory | `~/.gemini/` | Gemini CLI configuration directory |
|
||||
| OpenCode Directory | `~/.opencode/` | OpenCode configuration directory |
|
||||
| OpenCode Directory | `~/.config/opencode/` | OpenCode configuration directory |
|
||||
| OpenClaw Directory | `~/.openclaw/` | OpenClaw configuration directory |
|
||||
| Hermes Directory | `~/.hermes/` | Hermes configuration directory |
|
||||
|
||||
> **Note**: After changing directories, the app must be restarted, and the corresponding CLI tools must also be configured to use the same directory.
|
||||
|
||||
@@ -133,14 +135,15 @@ You can customize each CLI tool's configuration directory:
|
||||
|
||||
### Export Configuration
|
||||
|
||||
Click the "Export" button to save a backup file containing:
|
||||
Click the "Export" button to save a SQL backup file containing:
|
||||
|
||||
- All provider configurations
|
||||
- MCP server configurations
|
||||
- Prompt presets
|
||||
- Usage logs
|
||||
- App settings
|
||||
|
||||
The backup file is in JSON format and can be viewed with a text editor.
|
||||
The exported file name format is `cc-switch-export-{timestamp}.sql`.
|
||||
|
||||
### Import Configuration
|
||||
|
||||
|
||||
@@ -103,15 +103,16 @@ Each MCP server can independently control which apps it is enabled for.
|
||||
| Claude | Sync to Claude Code | `~/.claude.json`'s `mcpServers` |
|
||||
| Codex | Sync to Codex | `~/.codex/config.toml`'s `[mcp_servers]` |
|
||||
| Gemini | Sync to Gemini CLI | `~/.gemini/settings.json`'s `mcpServers` |
|
||||
| OpenCode | Sync to OpenCode | `~/.opencode/config.json`'s `mcpServers` |
|
||||
| OpenCode | Sync to OpenCode | `~/.config/opencode/opencode.json`'s `mcp` |
|
||||
| Hermes | Sync to Hermes | `~/.hermes/config.yaml`'s `mcp_servers` |
|
||||
|
||||
> **Note**: OpenClaw does not currently support MCP server management. MCP functionality is currently only supported for Claude, Codex, Gemini, and OpenCode.
|
||||
> **Note**: OpenClaw and Claude Desktop do not currently support CC Switch MCP sync. MCP functionality is supported for Claude, Codex, Gemini, OpenCode, and Hermes.
|
||||
|
||||
### Toggle Implementation
|
||||
|
||||
When enabling an app's toggle, CC Switch will:
|
||||
|
||||
1. **Update database**: Set the server's `apps.claude/codex/gemini/opencode` status to `true`
|
||||
1. **Update database**: Set the server's `apps.claude/codex/gemini/opencode/hermes` status to `true`
|
||||
2. **Sync to live configuration**: Write the server configuration to the corresponding app's configuration file
|
||||
3. **Take effect immediately**: The new MCP server is automatically loaded the next time the CLI tool starts
|
||||
|
||||
@@ -128,7 +129,8 @@ MCP server sync only executes when the corresponding app is installed:
|
||||
- **Claude**: Requires `~/.claude/` directory or `~/.claude.json` file to exist
|
||||
- **Codex**: Requires `~/.codex/` directory to exist
|
||||
- **Gemini**: Requires `~/.gemini/` directory to exist
|
||||
- **OpenCode**: Requires `~/.opencode/` directory to exist
|
||||
- **OpenCode**: Requires `~/.config/opencode/` directory to exist
|
||||
- **Hermes**: Requires `~/.hermes/` directory to exist
|
||||
|
||||
> **Tip**: If a CLI tool is not installed, enabling its toggle will not cause an error, but the configuration will not be written.
|
||||
|
||||
@@ -154,7 +156,7 @@ After deletion, the configuration is removed from all app configuration files.
|
||||
If you have already configured MCP servers in CLI tools, you can import them into CC Switch:
|
||||
|
||||
1. Click the "Import" button
|
||||
2. Select the app to import from (Claude/Codex/Gemini/OpenCode)
|
||||
2. Select the app to import from (Claude/Codex/Gemini/OpenCode/Hermes)
|
||||
3. CC Switch reads the existing configuration and imports it
|
||||
|
||||
## Configuration File Formats
|
||||
|
||||
@@ -81,8 +81,7 @@ After activation, the prompt is written to the corresponding app's file:
|
||||
| Claude | `~/.claude/CLAUDE.md` |
|
||||
| Codex | `~/.codex/AGENTS.md` |
|
||||
| Gemini | `~/.gemini/GEMINI.md` |
|
||||
| OpenCode | `~/.opencode/AGENTS.md` |
|
||||
| OpenClaw | `~/.openclaw/AGENTS.md` |
|
||||
| OpenCode | `~/.config/opencode/AGENTS.md` |
|
||||
|
||||
## Edit a Preset
|
||||
|
||||
@@ -141,7 +140,6 @@ Prompts are managed separately per app:
|
||||
- When switched to Codex, Codex's presets are shown
|
||||
- When switched to Gemini, Gemini's presets are shown
|
||||
- When switched to OpenCode, OpenCode's presets are shown
|
||||
- When switched to OpenClaw, OpenClaw's presets are shown
|
||||
|
||||
To use the same prompt across multiple apps, you need to create them separately.
|
||||
|
||||
|
||||
@@ -12,18 +12,17 @@ Skills exist as folders containing:
|
||||
|
||||
## Supported Applications
|
||||
|
||||
Skills are supported across all four applications:
|
||||
Skills are supported across five applications:
|
||||
|
||||
- **Claude Code**
|
||||
- **Codex**
|
||||
- **Gemini CLI**
|
||||
- **OpenCode**
|
||||
- **Hermes**
|
||||
|
||||
## Open the Skills Page
|
||||
|
||||
Click the **Skills** button in the top navigation bar.
|
||||
|
||||
> Note: The Skills button is visible in all app modes.
|
||||
Click the **Skills** button in the top navigation bar when the selected app supports Skills.
|
||||
|
||||
## Page Overview
|
||||
|
||||
@@ -93,7 +92,8 @@ Click the "Refresh" button to re-scan repositories for the latest skills.
|
||||
| Claude | `~/.claude/skills/` |
|
||||
| Codex | `~/.codex/skills/` |
|
||||
| Gemini | `~/.gemini/skills/` |
|
||||
| OpenCode | `~/.opencode/skills/` |
|
||||
| OpenCode | `~/.config/opencode/skills/` |
|
||||
| Hermes | `~/.hermes/skills/` |
|
||||
|
||||
### Installation Contents
|
||||
|
||||
@@ -119,7 +119,7 @@ Installation copies the skill folder to your local machine:
|
||||
### Uninstall Effect
|
||||
|
||||
- **Automatic backup**: Before deletion, the skill is backed up to `~/.cc-switch/skill-backups/`
|
||||
- Removes the skill from all app directories (Claude, Codex, Gemini, OpenCode)
|
||||
- Removes the skill from all app directories (Claude, Codex, Gemini, OpenCode, Hermes)
|
||||
- Removes the skill from the SSOT directory (`~/.cc-switch/skills/`)
|
||||
- Deletes the skill record from the database
|
||||
|
||||
|
||||
@@ -215,9 +215,11 @@ Set prices for each model (per million tokens):
|
||||
|
||||
Before matching pricing, CC Switch normalizes the requested model ID:
|
||||
|
||||
- Remove everything before the last `/`
|
||||
- Remove everything after `:`
|
||||
- Remove everything before the last `/` and convert to lowercase
|
||||
- Remove everything after `:` and trim a trailing `[1m]`
|
||||
- Replace `@` with `-`
|
||||
- Remove common wrapper prefixes, version suffixes, and date suffixes (`-YYYY-MM-DD`, `-YYYYMMDD`)
|
||||
- Some model families can match a short ID to a versioned pricing entry
|
||||
|
||||
When adding pricing entries, enter the normalized Model ID rather than the full raw model name from the request.
|
||||
|
||||
@@ -226,6 +228,10 @@ When adding pricing entries, enter the normalized Model ID rather than the full
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | Removes the provider prefix |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | Removes the prefix and the `:` suffix |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | Replaces `@` with `-` |
|
||||
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | Removes the prefix and date suffix |
|
||||
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | Removes the prefix and matches dotted format |
|
||||
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | Removes wrapper prefix, version suffix, and `:` suffix |
|
||||
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | Matches a short ID to versioned pricing |
|
||||
|
||||
### Operations
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ Customizable location in settings (for cloud sync).
|
||||
├── settings.json # Device-level settings
|
||||
├── skills/ # Skill SSOT directory
|
||||
├── skill-backups/ # Skill backups (created on uninstall)
|
||||
└── db_backup_*.db # Database backups
|
||||
└── backups/ # Database backups
|
||||
```
|
||||
|
||||
### Database Contents
|
||||
@@ -51,7 +51,8 @@ Customizable location in settings (for cloud sync).
|
||||
"codexConfigDir": null,
|
||||
"geminiConfigDir": null,
|
||||
"opencodeConfigDir": null,
|
||||
"openclawConfigDir": null
|
||||
"openclawConfigDir": null,
|
||||
"hermesConfigDir": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
|
||||
|
||||
### Configuration Directory
|
||||
|
||||
Default: `~/.opencode/`
|
||||
Default: `~/.config/opencode/`
|
||||
|
||||
### Key Files
|
||||
|
||||
```
|
||||
~/.opencode/
|
||||
├── config.json # Main configuration file
|
||||
~/.config/opencode/
|
||||
├── opencode.json # Main configuration file
|
||||
├── AGENTS.md # System prompt
|
||||
└── skills/ # Skills directory
|
||||
└── ...
|
||||
```
|
||||
## Hermes Configuration
|
||||
|
||||
### Configuration Directory
|
||||
|
||||
Default: `~/.hermes/`
|
||||
|
||||
### Key Files
|
||||
|
||||
```
|
||||
~/.hermes/
|
||||
├── config.yaml # Main settings, providers, and MCP configuration
|
||||
├── .env # API keys and secrets
|
||||
├── SOUL.md # Profile identity/persona
|
||||
├── memories/
|
||||
│ ├── MEMORY.md # Agent memory
|
||||
│ └── USER.md # User profile memory
|
||||
├── skills/ # Active skills directory
|
||||
├── state.db # SQLite session database
|
||||
└── sessions/ # Gateway transcripts and optional JSON snapshots
|
||||
```
|
||||
|
||||
### config.yaml
|
||||
|
||||
Hermes uses YAML configuration. CC Switch writes MCP servers to `mcp_servers`, writes editable provider entries to `custom_providers`, reads read-only entries from Hermes' `providers` dict, and updates `model.provider` / `model.default` when switching providers.
|
||||
|
||||
## OpenClaw Configuration
|
||||
|
||||
@@ -219,7 +244,6 @@ Default: `~/.openclaw/`
|
||||
```
|
||||
~/.openclaw/
|
||||
├── openclaw.json # Main configuration file (JSON5 format)
|
||||
├── AGENTS.md # System prompt
|
||||
└── skills/ # Skills directory
|
||||
└── ...
|
||||
```
|
||||
@@ -246,18 +270,17 @@ OpenClaw uses a JSON5 format configuration file with the following main sections
|
||||
env: {
|
||||
ANTHROPIC_API_KEY: "sk-..."
|
||||
},
|
||||
// Agent default model configuration
|
||||
// Agent default configuration
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: "provider/model"
|
||||
}
|
||||
},
|
||||
workspace: "~/.openclaw/workspace"
|
||||
}
|
||||
},
|
||||
// Tool configuration
|
||||
tools: {},
|
||||
// Workspace file configuration
|
||||
workspace: {}
|
||||
tools: {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -267,7 +290,7 @@ OpenClaw uses a JSON5 format configuration file with the following main sections
|
||||
| `env` | Environment variable configuration |
|
||||
| `agents.defaults` | Agent default model settings |
|
||||
| `tools` | Tool configuration |
|
||||
| `workspace` | Workspace file management |
|
||||
| `agents.defaults.workspace` | Workspace directory path |
|
||||
|
||||
## Configuration Priority
|
||||
|
||||
|
||||
@@ -106,15 +106,15 @@ CC Switch User Manual
|
||||
|
||||
## Version Information
|
||||
|
||||
- Documentation version: v3.15.0
|
||||
- Last updated: 2026-05-16
|
||||
- Applicable to CC Switch v3.15.0+
|
||||
- Documentation version: v3.16.0
|
||||
- Last updated: 2026-05-29
|
||||
- Applicable to CC Switch v3.16.0+
|
||||
|
||||
### v3.15.0 Highlights
|
||||
### v3.16.0 Highlights
|
||||
|
||||
- **First-class Claude Desktop panel**: supports third-party providers, direct / model mapping modes, Copilot / Codex OAuth reuse, and 3P profile writing. See [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
|
||||
- **Role-based model mapping**: adapts Claude Desktop model validation with Sonnet / Opus / Haiku routes and `supports1m`
|
||||
- **Claude Desktop local routing**: provides a local gateway at `127.0.0.1:15721/claude-desktop` for providers that need conversion
|
||||
- **Codex Chat Completions routing**: route Chat-only providers such as DeepSeek, Kimi, GLM, and MiniMax through Codex. See [2.1 Add Provider](./2-providers/2.1-add.md)
|
||||
- **Managed CLI tool lifecycle**: install, update, update all, and diagnose Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes from Settings / About. See [1.5 Personalization](./1-getting-started/1.5-settings.md)
|
||||
- **Provider and model refresh**: new partner presets, refreshed default models and pricing, Claude Opus 4.8 defaults, and GPT 5.5 defaults where applicable
|
||||
- **Routing support badges**: Claude Code / Codex provider cards indicate whether a provider can be served through Local Routing
|
||||
- **Codex OAuth live model discovery**: ChatGPT Codex providers fetch available models from the ChatGPT backend on demand
|
||||
- **Filter-driven Usage Hero**: shows cache-normalized real total tokens and cache hit rate, updating with date / provider / model filters — see [4.4 Usage Statistics](./4-proxy/4.4-usage.md)
|
||||
@@ -124,7 +124,7 @@ CC Switch User Manual
|
||||
- **Per-App Tray Submenus**: Claude / Codex / Gemini submenus show the current provider and available usage summaries — see [2.2 Switch Provider](./2-providers/2.2-switch.md)
|
||||
- **Skills Discovery & Batch Updates**: SHA-256 update detection, batch updates, skills.sh public registry search — see [3.3 Skills Management](./3-extensions/3.3-skills.md)
|
||||
- **Full URL Endpoint Mode**: Advanced option to treat `base_url` as the full upstream endpoint — see [2.1 Add Provider](./2-providers/2.1-add.md)
|
||||
- **OpenCode / OpenClaw Stream Check Coverage**: Stream Check covers Claude / Codex / Gemini / OpenCode / OpenClaw — see [4.5 Model Test](./4-proxy/4.5-model-test.md)
|
||||
- **OpenCode / OpenClaw / Hermes Stream Check Coverage**: Stream Check covers Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — see [4.5 Model Test](./4-proxy/4.5-model-test.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## CC Switch とは
|
||||
|
||||
CC Switch はクロスプラットフォームのデスクトップアプリケーションで、AI プログラミングツールを使用する開発者向けに設計されています。**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes** などの管理対象アプリの設定を統一的に管理できます。
|
||||
CC Switch はクロスプラットフォームのデスクトップアプリケーションで、AI ツールを使用する開発者向けに設計されています。**Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw**、**Hermes** などの管理対象アプリの設定を統一的に管理できます。
|
||||
|
||||
## どのような問題を解決するか
|
||||
|
||||
@@ -45,7 +45,7 @@ CC Switch は統一されたインターフェースでこれらの問題を解
|
||||
| **Codex** | OpenAI のコード生成ツール |
|
||||
| **Gemini CLI** | Google の AI コマンドラインツール |
|
||||
| **OpenCode** | オープンソース AI プログラミングターミナルツール |
|
||||
| **OpenClaw** | オープンソース AI プログラミングアシスタント(マルチプロバイダーゲートウェイ) |
|
||||
| **OpenClaw** | オープンソース AI アシスタント(マルチプロバイダーゲートウェイ) |
|
||||
| **Hermes** | Hermes Agent のプロバイダー、MCP、Skills、Memory 管理 |
|
||||
|
||||
## 対応プラットフォーム
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| ② | 設定ボタン | 設定ページを開く(ショートカット `Cmd/Ctrl + ,`) |
|
||||
| ③ | プロキシスイッチ | ローカルプロキシサービスの起動/停止 |
|
||||
| ④ | アプリ切り替え | Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes を切り替え |
|
||||
| ⑤ | 機能エリア | Skills / Prompts / MCP の入口 |
|
||||
| ⑤ | 機能エリア | 現在のアプリで利用できる機能入口 |
|
||||
| ⑥ | 追加ボタン | 新しいプロバイダーを追加 |
|
||||
|
||||
### アプリ切り替え
|
||||
@@ -33,9 +33,9 @@
|
||||
|
||||
| ボタン | 機能 | 表示条件 |
|
||||
|------|------|----------|
|
||||
| Skills | スキル拡張管理 | 常に表示 |
|
||||
| Prompts | システムプロンプト管理 | 常に表示 |
|
||||
| MCP | MCP サーバー管理 | 常に表示 |
|
||||
| Skills | スキル拡張管理 | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
| Prompts | システムプロンプト管理 | Claude / Codex / Gemini / OpenCode |
|
||||
| MCP | MCP サーバー管理 | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
|
||||
## プロバイダーカード
|
||||
|
||||
@@ -113,11 +113,12 @@ CC Switch はシステムトレイにアイコンを表示し、クイック操
|
||||
|
||||
### 多言語対応
|
||||
|
||||
トレイメニューは 3 つの言語に対応し、設定に応じて自動的に切り替わります:
|
||||
トレイメニューは 4 つの言語に対応し、設定に応じて自動的に切り替わります:
|
||||
|
||||
| 言語 | メインウィンドウを開く | 終了 |
|
||||
|------|-----------|------|
|
||||
| 中文 | 打开主界面 | 退出 |
|
||||
| 簡体中文 | 打开主界面 | 退出 |
|
||||
| 繁體中文 | 開啟主介面 | 退出 |
|
||||
| English | Open main window | Quit |
|
||||
| 日本語 | メインウィンドウを開く | 終了 |
|
||||
|
||||
@@ -147,7 +148,7 @@ CC Switch はシステムトレイにアイコンを表示し、クイック操
|
||||
|
||||
### 一般タブ
|
||||
|
||||
- 言語設定(中文/English/日本語)
|
||||
- 言語設定(簡体中文/繁體中文/English/日本語)
|
||||
- テーマ設定(システムに合わせる/ライト/ダーク)
|
||||
- ウィンドウ動作(起動時に自動実行、閉じる動作)
|
||||
|
||||
|
||||
@@ -9,11 +9,12 @@
|
||||
|
||||
## 言語設定
|
||||
|
||||
CC Switch は 3 つの言語に対応しています:
|
||||
CC Switch は 4 つの言語に対応しています:
|
||||
|
||||
| 言語 | 説明 |
|
||||
| -------- | -------- |
|
||||
| 簡体中文 | デフォルト言語 |
|
||||
| 繁體中文 | 繁体字中国語インターフェース |
|
||||
| English | 英語インターフェース |
|
||||
| 日本語 | 日本語インターフェース |
|
||||
|
||||
@@ -124,8 +125,9 @@ CC Switch 自体のデータの保存場所で、デフォルトは `~/.cc-switc
|
||||
| Claude ディレクトリ | `~/.claude/` | Claude Code 設定ディレクトリ |
|
||||
| Codex ディレクトリ | `~/.codex/` | Codex 設定ディレクトリ |
|
||||
| Gemini ディレクトリ | `~/.gemini/` | Gemini CLI 設定ディレクトリ |
|
||||
| OpenCode ディレクトリ | `~/.opencode/` | OpenCode 設定ディレクトリ |
|
||||
| OpenCode ディレクトリ | `~/.config/opencode/` | OpenCode 設定ディレクトリ |
|
||||
| OpenClaw ディレクトリ | `~/.openclaw/` | OpenClaw 設定ディレクトリ |
|
||||
| Hermes ディレクトリ | `~/.hermes/` | Hermes 設定ディレクトリ |
|
||||
|
||||
> **注意**:ディレクトリを変更した後はアプリの再起動が必要で、対応する CLI ツールも同じディレクトリを設定する必要があります。
|
||||
|
||||
@@ -133,14 +135,15 @@ CC Switch 自体のデータの保存場所で、デフォルトは `~/.cc-switc
|
||||
|
||||
### 設定のエクスポート
|
||||
|
||||
「エクスポート」ボタンをクリックして、以下の内容を含むバックアップファイルを保存します:
|
||||
「エクスポート」ボタンをクリックして、以下の内容を含む SQL バックアップファイルを保存します:
|
||||
|
||||
- すべてのプロバイダー設定
|
||||
- MCP サーバー設定
|
||||
- Prompts プリセット
|
||||
- 使用量ログ
|
||||
- アプリ設定
|
||||
|
||||
バックアップファイルは JSON 形式で、テキストエディタで確認できます。
|
||||
エクスポートされるファイル名の形式は `cc-switch-export-{timestamp}.sql` です。
|
||||
|
||||
### 設定のインポート
|
||||
|
||||
|
||||
@@ -103,15 +103,16 @@ SSE プロトコルでサーバーと通信し、リアルタイムプッシュ
|
||||
| Claude | Claude Code に同期 | `~/.claude.json` の `mcpServers` |
|
||||
| Codex | Codex に同期 | `~/.codex/config.toml` の `[mcp_servers]` |
|
||||
| Gemini | Gemini CLI に同期 | `~/.gemini/settings.json` の `mcpServers` |
|
||||
| OpenCode | OpenCode に同期 | `~/.opencode/config.json` の `mcpServers` |
|
||||
| OpenCode | OpenCode に同期 | `~/.config/opencode/opencode.json` の `mcp` |
|
||||
| Hermes | Hermes に同期 | `~/.hermes/config.yaml` の `mcp_servers` |
|
||||
|
||||
> **注意**:OpenClaw は現在 MCP サーバー管理に対応していません。MCP 機能は現在 Claude、Codex、Gemini、OpenCode の 4 つのアプリのみサポートしています。
|
||||
> **注意**:OpenClaw と Claude Desktop は現在 CC Switch MCP 同期に対応していません。MCP 機能は Claude、Codex、Gemini、OpenCode、Hermes に対応しています。
|
||||
|
||||
### スイッチの動作
|
||||
|
||||
あるアプリのスイッチをオンにすると、CC Switch は以下を実行します:
|
||||
|
||||
1. **データベースの更新**:サーバーの `apps.claude/codex/gemini/opencode` のステータスを `true` に設定
|
||||
1. **データベースの更新**:サーバーの `apps.claude/codex/gemini/opencode/hermes` のステータスを `true` に設定
|
||||
2. **Live 設定に同期**:サーバー設定を対応アプリの設定ファイルに書き込み
|
||||
3. **即時反映**:次回 CLI ツール起動時に新しい MCP サーバーが自動的にロード
|
||||
|
||||
@@ -128,7 +129,8 @@ MCP サーバーの同期は、対応アプリがインストールされてい
|
||||
- **Claude**:`~/.claude/` ディレクトリまたは `~/.claude.json` ファイルが存在する必要あり
|
||||
- **Codex**:`~/.codex/` ディレクトリが存在する必要あり
|
||||
- **Gemini**:`~/.gemini/` ディレクトリが存在する必要あり
|
||||
- **OpenCode**:`~/.opencode/` ディレクトリが存在する必要あり
|
||||
- **OpenCode**:`~/.config/opencode/` ディレクトリが存在する必要あり
|
||||
- **Hermes**:`~/.hermes/` ディレクトリが存在する必要あり
|
||||
|
||||
> **ヒント**:CLI ツールがインストールされていない場合、対応するスイッチをオンにしてもエラーにはなりませんが、設定は書き込まれません。
|
||||
|
||||
@@ -154,7 +156,7 @@ MCP サーバーの同期は、対応アプリがインストールされてい
|
||||
CLI ツールで既に MCP サーバーを設定している場合、CC Switch にインポートできます:
|
||||
|
||||
1. 「インポート」ボタンをクリック
|
||||
2. インポートするアプリを選択(Claude/Codex/Gemini/OpenCode)
|
||||
2. インポートするアプリを選択(Claude/Codex/Gemini/OpenCode/Hermes)
|
||||
3. CC Switch が既存の設定を読み取ってインポート
|
||||
|
||||
## 設定ファイル形式
|
||||
|
||||
@@ -81,8 +81,7 @@ CC Switch を使用すると:
|
||||
| Claude | `~/.claude/CLAUDE.md` |
|
||||
| Codex | `~/.codex/AGENTS.md` |
|
||||
| Gemini | `~/.gemini/GEMINI.md` |
|
||||
| OpenCode | `~/.opencode/AGENTS.md` |
|
||||
| OpenClaw | `~/.openclaw/AGENTS.md` |
|
||||
| OpenCode | `~/.config/opencode/AGENTS.md` |
|
||||
|
||||
## プリセットの編集
|
||||
|
||||
@@ -141,7 +140,6 @@ Prompts はアプリごとに個別に管理されます:
|
||||
- Codex に切り替えると、Codex のプリセットが表示
|
||||
- Gemini に切り替えると、Gemini のプリセットが表示
|
||||
- OpenCode に切り替えると、OpenCode のプリセットが表示
|
||||
- OpenClaw に切り替えると、OpenClaw のプリセットが表示
|
||||
|
||||
複数のアプリで同じプロンプトを使用する場合は、それぞれで作成する必要があります。
|
||||
|
||||
|
||||
@@ -12,18 +12,17 @@ Skills は再利用可能な機能拡張で、AI ツールに特定分野の専
|
||||
|
||||
## 対応アプリ
|
||||
|
||||
Skills 機能は以下の 4 つのアプリに対応しています:
|
||||
Skills 機能は以下の 5 つのアプリに対応しています:
|
||||
|
||||
- **Claude Code**
|
||||
- **Codex**
|
||||
- **Gemini CLI**
|
||||
- **OpenCode**
|
||||
- **Hermes**
|
||||
|
||||
## Skills ページを開く
|
||||
|
||||
上部ナビゲーションバーの **Skills** ボタンをクリックします。
|
||||
|
||||
> 注意:Skills ボタンはすべてのアプリモードで表示されます。
|
||||
選択中のアプリが Skills に対応している場合、上部ナビゲーションバーの **Skills** ボタンをクリックします。
|
||||
|
||||
## ページ概要
|
||||
|
||||
@@ -93,7 +92,8 @@ CC Switch は強力な検索とフィルタリング機能を提供していま
|
||||
| Claude | `~/.claude/skills/` |
|
||||
| Codex | `~/.codex/skills/` |
|
||||
| Gemini | `~/.gemini/skills/` |
|
||||
| OpenCode | `~/.opencode/skills/` |
|
||||
| OpenCode | `~/.config/opencode/skills/` |
|
||||
| Hermes | `~/.hermes/skills/` |
|
||||
|
||||
### インストール内容
|
||||
|
||||
@@ -119,7 +119,7 @@ CC Switch は強力な検索とフィルタリング機能を提供していま
|
||||
### アンインストールの効果
|
||||
|
||||
- **自動バックアップ**:削除前にスキルが `~/.cc-switch/skill-backups/` にバックアップされる
|
||||
- すべてのアプリディレクトリ(Claude、Codex、Gemini、OpenCode)からスキルを削除
|
||||
- すべてのアプリディレクトリ(Claude、Codex、Gemini、OpenCode、Hermes)からスキルを削除
|
||||
- SSOT ディレクトリ(`~/.cc-switch/skills/`)からスキルを削除
|
||||
- データベースからスキルレコードを削除
|
||||
|
||||
|
||||
@@ -215,9 +215,11 @@ Token 使用量の変化を表示:
|
||||
|
||||
料金を照合する前に、CC Switch はリクエスト内のモデル ID を正規化します:
|
||||
|
||||
- 最後の `/` より前の接頭辞を削除
|
||||
- `:` 以降の接尾辞を削除
|
||||
- 最後の `/` より前の接頭辞を削除し、小文字に変換
|
||||
- `:` 以降の接尾辞を削除し、末尾の `[1m]` を削除
|
||||
- `@` を `-` に置換
|
||||
- 一般的なラッパー接頭辞、バージョン接尾辞、日付接尾辞(`-YYYY-MM-DD`、`-YYYYMMDD`)を削除
|
||||
- 一部のモデルファミリーでは、短い ID からバージョン付き価格エントリに照合できます
|
||||
|
||||
料金設定では、リクエスト内の完全な元のモデル名ではなく、正規化後のモデル ID を入力してください。
|
||||
|
||||
@@ -226,6 +228,10 @@ Token 使用量の変化を表示:
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | プロバイダー接頭辞を削除 |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 接頭辞と `:` 以降を削除 |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | `@` を `-` に置換 |
|
||||
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | 接頭辞と日付接尾辞を削除 |
|
||||
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | 接頭辞を削除し、ドット形式に照合 |
|
||||
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | ラッパー接頭辞、バージョン接尾辞、`:` 以降を削除 |
|
||||
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 短い ID からバージョン付き価格に照合 |
|
||||
|
||||
### 操作
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
├── settings.json # デバイスレベルの設定
|
||||
├── skills/ # スキル SSOT ディレクトリ
|
||||
├── skill-backups/ # スキルバックアップ(アンインストール時に作成)
|
||||
└── db_backup_*.db # データベースバックアップ
|
||||
└── backups/ # データベースバックアップ
|
||||
```
|
||||
|
||||
### データベースの内容
|
||||
@@ -51,7 +51,8 @@
|
||||
"codexConfigDir": null,
|
||||
"geminiConfigDir": null,
|
||||
"opencodeConfigDir": null,
|
||||
"openclawConfigDir": null
|
||||
"openclawConfigDir": null,
|
||||
"hermesConfigDir": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
|
||||
|
||||
### 設定ディレクトリ
|
||||
|
||||
デフォルト:`~/.opencode/`
|
||||
デフォルト:`~/.config/opencode/`
|
||||
|
||||
### 主要ファイル
|
||||
|
||||
```
|
||||
~/.opencode/
|
||||
├── config.json # メイン設定ファイル
|
||||
~/.config/opencode/
|
||||
├── opencode.json # メイン設定ファイル
|
||||
├── AGENTS.md # システムプロンプト
|
||||
└── skills/ # スキルディレクトリ
|
||||
└── ...
|
||||
```
|
||||
## Hermes の設定
|
||||
|
||||
### 設定ディレクトリ
|
||||
|
||||
デフォルト:`~/.hermes/`
|
||||
|
||||
### 主要ファイル
|
||||
|
||||
```
|
||||
~/.hermes/
|
||||
├── config.yaml # メイン設定、プロバイダー、MCP 設定
|
||||
├── .env # API キーとシークレット
|
||||
├── SOUL.md # Profile identity/persona
|
||||
├── memories/
|
||||
│ ├── MEMORY.md # エージェント記憶
|
||||
│ └── USER.md # ユーザープロファイル記憶
|
||||
├── skills/ # 有効なスキルディレクトリ
|
||||
├── state.db # SQLite セッションデータベース
|
||||
└── sessions/ # Gateway transcript と任意の JSON snapshot
|
||||
```
|
||||
|
||||
### config.yaml
|
||||
|
||||
Hermes は YAML 設定を使用します。CC Switch は MCP サーバーを `mcp_servers` に書き込み、編集可能なプロバイダーエントリを `custom_providers` に書き込み、Hermes の `providers` dict にある読み取り専用エントリを読み取り、プロバイダー切り替え時に `model.provider` / `model.default` を更新します。
|
||||
|
||||
## OpenClaw の設定
|
||||
|
||||
@@ -219,7 +244,6 @@ GEMINI_MODEL=gemini-pro
|
||||
```
|
||||
~/.openclaw/
|
||||
├── openclaw.json # メイン設定ファイル(JSON5 形式)
|
||||
├── AGENTS.md # システムプロンプト
|
||||
└── skills/ # スキルディレクトリ
|
||||
└── ...
|
||||
```
|
||||
@@ -246,18 +270,17 @@ OpenClaw は JSON5 形式の設定ファイルを使用し、主に以下のセ
|
||||
env: {
|
||||
ANTHROPIC_API_KEY: "sk-..."
|
||||
},
|
||||
// Agent デフォルトモデル設定
|
||||
// Agent デフォルト設定
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: "provider/model"
|
||||
}
|
||||
},
|
||||
workspace: "~/.openclaw/workspace"
|
||||
}
|
||||
},
|
||||
// ツール設定
|
||||
tools: {},
|
||||
// ワークスペースファイル設定
|
||||
workspace: {}
|
||||
tools: {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -267,7 +290,7 @@ OpenClaw は JSON5 形式の設定ファイルを使用し、主に以下のセ
|
||||
| `env` | 環境変数設定 |
|
||||
| `agents.defaults` | Agent デフォルトモデル設定 |
|
||||
| `tools` | ツール設定 |
|
||||
| `workspace` | ワークスペースファイル管理 |
|
||||
| `agents.defaults.workspace` | ワークスペースディレクトリパス |
|
||||
|
||||
## 設定の優先順位
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ chmod +x CC-Switch-*.AppImage
|
||||
- バージョンの非互換性
|
||||
|
||||
**解決方法**:
|
||||
1. ファイルが CC Switch からエクスポートされた JSON ファイルであることを確認
|
||||
1. ファイルが CC Switch からエクスポートされた SQL バックアップファイルであることを確認
|
||||
2. ファイル内容が完全であるか確認
|
||||
3. テキストエディタで開いてフォーマットを確認
|
||||
|
||||
|
||||
@@ -106,15 +106,15 @@ CC Switch ユーザーマニュアル
|
||||
|
||||
## バージョン情報
|
||||
|
||||
- ドキュメントバージョン:v3.15.0
|
||||
- 最終更新:2026-05-16
|
||||
- CC Switch v3.15.0+ 対応
|
||||
- ドキュメントバージョン:v3.16.0
|
||||
- 最終更新:2026-05-29
|
||||
- CC Switch v3.16.0+ 対応
|
||||
|
||||
### v3.15.0 の注目機能
|
||||
### v3.16.0 の注目機能
|
||||
|
||||
- **Claude Desktop の一等管理パネル**:サードパーティプロバイダー、直結 / モデルマッピングの 2 モード、Copilot / Codex OAuth 再利用、3P profile 書き込みに対応 — 詳細は [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
|
||||
- **役割別モデルマッピング**:Sonnet / Opus / Haiku ルートと `supports1m` フラグで Claude Desktop のモデル検証に対応
|
||||
- **Claude Desktop ローカルルーティング**:変換が必要なプロバイダー向けに `127.0.0.1:15721/claude-desktop` のローカルゲートウェイを提供
|
||||
- **Codex Chat Completions ルーティング**:DeepSeek、Kimi、GLM、MiniMax など Chat 専用プロバイダーを Codex で利用可能 — 詳細は [2.1 プロバイダーの追加](./2-providers/2.1-add.md)
|
||||
- **管理対象 CLI ツールのライフサイクル**:設定 / About で Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes のインストール、更新、一括更新、診断に対応 — 詳細は [1.5 個人設定](./1-getting-started/1.5-settings.md)
|
||||
- **プロバイダーとモデルマトリクス更新**:提携プリセットを追加し、既定モデルと価格表を更新。Claude Opus は 4.8、該当する GPT 既定値は 5.5 に更新
|
||||
- **ルーティング対応バッジ**:Claude Code / Codex のプロバイダーカードで Local Routing 対応可否を確認可能
|
||||
- **Codex OAuth ライブモデル検出**:ChatGPT Codex 系プロバイダーは必要に応じて ChatGPT バックエンドから利用可能モデルを取得
|
||||
- **フィルター連動 Usage Hero**:キャッシュ正規化後の実消費 Token とキャッシュヒット率を表示し、日付 / プロバイダー / モデルフィルターに追従 — 詳細は [4.4 使用量統計](./4-proxy/4.4-usage.md)
|
||||
@@ -124,7 +124,7 @@ CC Switch ユーザーマニュアル
|
||||
- **アプリ別トレイサブメニュー**:Claude / Codex / Gemini のサブメニューで現在のプロバイダーと使用量サマリーを確認可能 — 詳細は [2.2 プロバイダーの切り替え](./2-providers/2.2-switch.md)
|
||||
- **Skills の発見と一括更新**:SHA-256 ハッシュによる更新検出、一括更新、skills.sh 公式レジストリ検索 — 詳細は [3.3 Skills スキル管理](./3-extensions/3.3-skills.md)
|
||||
- **完全URLエンドポイントモード**:高度なオプションで `base_url` を完全なアップストリームエンドポイントとして扱う — 詳細は [2.1 プロバイダーの追加](./2-providers/2.1-add.md)
|
||||
- **OpenCode / OpenClaw ストリームチェック対応**:Stream Check は Claude / Codex / Gemini / OpenCode / OpenClaw をカバー — 詳細は [4.5 モデルテスト](./4-proxy/4.5-model-test.md)
|
||||
- **OpenCode / OpenClaw / Hermes ストリームチェック対応**:Stream Check は Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes をカバー — 詳細は [4.5 モデルテスト](./4-proxy/4.5-model-test.md)
|
||||
|
||||
## コントリビュート
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 什么是 CC Switch
|
||||
|
||||
CC Switch 是一款跨平台桌面应用,专为使用 AI 编程工具的开发者设计。它帮助你统一管理 **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** 和 **Hermes** 等受管应用的配置。
|
||||
CC Switch 是一款跨平台桌面应用,专为使用 AI 工具的开发者设计。它帮助你统一管理 **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**、**OpenCode**、**OpenClaw** 和 **Hermes** 等受管应用的配置。
|
||||
|
||||
## 解决什么问题
|
||||
|
||||
@@ -45,7 +45,7 @@ CC Switch 通过统一的界面解决这些问题。
|
||||
| **Codex** | OpenAI 的代码生成工具 |
|
||||
| **Gemini CLI** | Google 的 AI 命令行工具 |
|
||||
| **OpenCode** | 开源 AI 编程终端工具 |
|
||||
| **OpenClaw** | 开源 AI 编程助手(多供应商网关) |
|
||||
| **OpenClaw** | 开源 AI 助手(多供应商网关) |
|
||||
| **Hermes** | Hermes Agent,支持供应商、MCP、Skills 和 Memory 管理 |
|
||||
|
||||
## 支持的平台
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
| ② | 设置按钮 | 打开设置页面(快捷键 `Cmd/Ctrl + ,`) |
|
||||
| ③ | 代理开关 | 启动/停止本地代理服务 |
|
||||
| ④ | 应用切换器 | 切换 Claude / Claude Desktop / Codex / Gemini / OpenCode / OpenClaw / Hermes |
|
||||
| ⑤ | 功能区 | Skills / Prompts / MCP 入口 |
|
||||
| ⑤ | 功能区 | 当前应用支持的功能入口 |
|
||||
| ⑥ | 添加按钮 | 添加新供应商 |
|
||||
|
||||
### 应用切换器
|
||||
@@ -33,9 +33,9 @@
|
||||
|
||||
| 按钮 | 功能 | 可见条件 |
|
||||
|------|------|----------|
|
||||
| Skills | 技能扩展管理 | 始终可见 |
|
||||
| Prompts | 系统提示词管理 | 始终可见 |
|
||||
| MCP | MCP 服务器管理 | 始终可见 |
|
||||
| Skills | 技能扩展管理 | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
| Prompts | 系统提示词管理 | Claude / Codex / Gemini / OpenCode |
|
||||
| MCP | MCP 服务器管理 | Claude / Codex / Gemini / OpenCode / Hermes |
|
||||
|
||||
## 供应商卡片
|
||||
|
||||
@@ -113,11 +113,12 @@ CC Switch 在系统托盘显示图标,提供快速操作入口。
|
||||
|
||||
### 多语言支持
|
||||
|
||||
托盘菜单支持三种语言,根据设置自动切换:
|
||||
托盘菜单支持四种语言,根据设置自动切换:
|
||||
|
||||
| 语言 | 打开主界面 | 退出 |
|
||||
|------|-----------|------|
|
||||
| 中文 | 打开主界面 | 退出 |
|
||||
| 简体中文 | 打开主界面 | 退出 |
|
||||
| 繁體中文 | 開啟主介面 | 退出 |
|
||||
| English | Open main window | Quit |
|
||||
| 日本語 | メインウィンドウを開く | 終了 |
|
||||
|
||||
@@ -147,7 +148,7 @@ CC Switch 在系统托盘显示图标,提供快速操作入口。
|
||||
|
||||
### 通用 Tab
|
||||
|
||||
- 语言设置(中文/English/日本語)
|
||||
- 语言设置(简体中文/繁體中文/English/日本語)
|
||||
- 主题设置(跟随系统/浅色/深色)
|
||||
- 窗口行为(开机自启、关闭行为)
|
||||
|
||||
|
||||
@@ -9,11 +9,12 @@
|
||||
|
||||
## 语言设置
|
||||
|
||||
CC Switch 支持三种语言:
|
||||
CC Switch 支持四种语言:
|
||||
|
||||
| 语言 | 说明 |
|
||||
| -------- | -------- |
|
||||
| 简体中文 | 默认语言 |
|
||||
| 繁體中文 | 繁体中文界面 |
|
||||
| English | 英文界面 |
|
||||
| 日本語 | 日文界面 |
|
||||
|
||||
@@ -124,8 +125,9 @@ CC Switch 自身数据的存储位置,默认为 `~/.cc-switch/`。
|
||||
| Claude 目录 | `~/.claude/` | Claude Code 配置目录 |
|
||||
| Codex 目录 | `~/.codex/` | Codex 配置目录 |
|
||||
| Gemini 目录 | `~/.gemini/` | Gemini CLI 配置目录 |
|
||||
| OpenCode 目录 | `~/.opencode/` | OpenCode 配置目录 |
|
||||
| OpenCode 目录 | `~/.config/opencode/` | OpenCode 配置目录 |
|
||||
| OpenClaw 目录 | `~/.openclaw/` | OpenClaw 配置目录 |
|
||||
| Hermes 目录 | `~/.hermes/` | Hermes 配置目录 |
|
||||
|
||||
> ⚠️ **注意**:修改目录后需要重启应用,且对应的 CLI 工具也需要配置相同的目录。
|
||||
|
||||
@@ -133,14 +135,15 @@ CC Switch 自身数据的存储位置,默认为 `~/.cc-switch/`。
|
||||
|
||||
### 导出配置
|
||||
|
||||
点击「导出」按钮,保存包含以下内容的备份文件:
|
||||
点击「导出」按钮,保存包含以下内容的 SQL 备份文件:
|
||||
|
||||
- 所有供应商配置
|
||||
- MCP 服务器配置
|
||||
- Prompts 预设
|
||||
- 用量日志
|
||||
- 应用设置
|
||||
|
||||
备份文件格式为 JSON,可以用文本编辑器查看。
|
||||
导出文件名格式为 `cc-switch-export-{timestamp}.sql`。
|
||||
|
||||
### 导入配置
|
||||
|
||||
|
||||
@@ -103,15 +103,16 @@ MCP (Model Context Protocol) 是一种协议,允许 AI 工具访问外部数
|
||||
| Claude | 同步到 Claude Code | `~/.claude.json` 的 `mcpServers` |
|
||||
| Codex | 同步到 Codex | `~/.codex/config.toml` 的 `[mcp_servers]` |
|
||||
| Gemini | 同步到 Gemini CLI | `~/.gemini/settings.json` 的 `mcpServers` |
|
||||
| OpenCode | 同步到 OpenCode | `~/.opencode/config.json` 的 `mcpServers` |
|
||||
| OpenCode | 同步到 OpenCode | `~/.config/opencode/opencode.json` 的 `mcp` |
|
||||
| Hermes | 同步到 Hermes | `~/.hermes/config.yaml` 的 `mcp_servers` |
|
||||
|
||||
> ⚠️ **注意**:OpenClaw 暂不支持 MCP 服务器管理。MCP 功能目前仅支持 Claude、Codex、Gemini 和 OpenCode 四个应用。
|
||||
> ⚠️ **注意**:OpenClaw 和 Claude Desktop 暂不支持 CC Switch MCP 同步。MCP 功能支持 Claude、Codex、Gemini、OpenCode 和 Hermes。
|
||||
|
||||
### 开关实现机制
|
||||
|
||||
当开启某个应用的开关时,CC Switch 会:
|
||||
|
||||
1. **更新数据库**:将服务器的 `apps.claude/codex/gemini/opencode` 状态设为 `true`
|
||||
1. **更新数据库**:将服务器的 `apps.claude/codex/gemini/opencode/hermes` 状态设为 `true`
|
||||
2. **同步到 Live 配置**:将服务器配置写入对应应用的配置文件
|
||||
3. **即时生效**:下次启动 CLI 工具时自动加载新的 MCP 服务器
|
||||
|
||||
@@ -128,7 +129,8 @@ MCP 服务器同步仅在对应应用已安装时执行:
|
||||
- **Claude**:需存在 `~/.claude/` 目录或 `~/.claude.json` 文件
|
||||
- **Codex**:需存在 `~/.codex/` 目录
|
||||
- **Gemini**:需存在 `~/.gemini/` 目录
|
||||
- **OpenCode**:需存在 `~/.opencode/` 目录
|
||||
- **OpenCode**:需存在 `~/.config/opencode/` 目录
|
||||
- **Hermes**:需存在 `~/.hermes/` 目录
|
||||
|
||||
> 💡 **提示**:如果某个 CLI 工具未安装,开启对应开关不会报错,但配置不会写入。
|
||||
|
||||
@@ -154,7 +156,7 @@ MCP 服务器同步仅在对应应用已安装时执行:
|
||||
如果你已经在 CLI 工具中配置了 MCP 服务器,可以导入到 CC Switch:
|
||||
|
||||
1. 点击「导入」按钮
|
||||
2. 选择要导入的应用(Claude/Codex/Gemini/OpenCode)
|
||||
2. 选择要导入的应用(Claude/Codex/Gemini/OpenCode/Hermes)
|
||||
3. CC Switch 会读取现有配置并导入
|
||||
|
||||
## 配置文件格式
|
||||
|
||||
@@ -81,8 +81,7 @@ Prompts 功能用于管理系统提示词预设。系统提示词会影响 AI
|
||||
| Claude | `~/.claude/CLAUDE.md` |
|
||||
| Codex | `~/.codex/AGENTS.md` |
|
||||
| Gemini | `~/.gemini/GEMINI.md` |
|
||||
| OpenCode | `~/.opencode/AGENTS.md` |
|
||||
| OpenClaw | `~/.openclaw/AGENTS.md` |
|
||||
| OpenCode | `~/.config/opencode/AGENTS.md` |
|
||||
|
||||
## 编辑预设
|
||||
|
||||
@@ -141,7 +140,6 @@ Prompts 是按应用分开管理的:
|
||||
- 切换到 Codex 时,显示 Codex 的预设
|
||||
- 切换到 Gemini 时,显示 Gemini 的预设
|
||||
- 切换到 OpenCode 时,显示 OpenCode 的预设
|
||||
- 切换到 OpenClaw 时,显示 OpenClaw 的预设
|
||||
|
||||
如需在多个应用使用相同的提示词,需要分别创建。
|
||||
|
||||
|
||||
@@ -12,18 +12,17 @@ Skills 是可复用的能力扩展,让 AI 工具获得特定领域的专业能
|
||||
|
||||
## 支持的应用
|
||||
|
||||
Skills 功能支持所有四种应用:
|
||||
Skills 功能支持五种应用:
|
||||
|
||||
- **Claude Code**
|
||||
- **Codex**
|
||||
- **Gemini CLI**
|
||||
- **OpenCode**
|
||||
- **Hermes**
|
||||
|
||||
## 打开 Skills 页面
|
||||
|
||||
点击顶部导航栏的 **Skills** 按钮。
|
||||
|
||||
> 注意:Skills 按钮在所有应用模式下均可见。
|
||||
当当前应用支持 Skills 时,点击顶部导航栏的 **Skills** 按钮。
|
||||
|
||||
## 页面概览
|
||||
|
||||
@@ -93,7 +92,8 @@ CC Switch 提供强大的搜索和过滤功能:
|
||||
| Claude | `~/.claude/skills/` |
|
||||
| Codex | `~/.codex/skills/` |
|
||||
| Gemini | `~/.gemini/skills/` |
|
||||
| OpenCode | `~/.opencode/skills/` |
|
||||
| OpenCode | `~/.config/opencode/skills/` |
|
||||
| Hermes | `~/.hermes/skills/` |
|
||||
|
||||
### 安装内容
|
||||
|
||||
@@ -119,7 +119,7 @@ CC Switch 提供强大的搜索和过滤功能:
|
||||
### 卸载效果
|
||||
|
||||
- **自动备份**:删除前,技能会被备份到 `~/.cc-switch/skill-backups/`
|
||||
- 从所有应用目录(Claude、Codex、Gemini、OpenCode)移除技能
|
||||
- 从所有应用目录(Claude、Codex、Gemini、OpenCode、Hermes)移除技能
|
||||
- 从 SSOT 目录(`~/.cc-switch/skills/`)移除技能
|
||||
- 从数据库删除技能记录
|
||||
|
||||
|
||||
@@ -215,9 +215,11 @@ v3.15.0 起,用量页顶部改为筛选驱动的 Hero 卡。切换日期范围
|
||||
|
||||
在匹配定价前,CC Switch 会先对请求中的模型 ID 做标准化处理:
|
||||
|
||||
- 去掉最后一个 `/` 之前的前缀
|
||||
- 去掉 `:` 之后的后缀
|
||||
- 去掉最后一个 `/` 之前的前缀,并转成小写
|
||||
- 去掉 `:` 之后的后缀,去掉末尾的 `[1m]`
|
||||
- 将 `@` 替换为 `-`
|
||||
- 去掉常见包装前缀、版本后缀、日期后缀(`-YYYY-MM-DD`、`-YYYYMMDD`)
|
||||
- 部分模型族支持短 ID 匹配带版本的定价项
|
||||
|
||||
因此,在定价配置中请填写清洗后的模型 ID,而不是请求里的完整原始模型名。
|
||||
|
||||
@@ -226,6 +228,10 @@ v3.15.0 起,用量页顶部改为筛选驱动的 Hero 卡。切换日期范围
|
||||
| `stepfun-ai/step-3.5-flash` | `step-3.5-flash` | 去掉供应商前缀 |
|
||||
| `moonshotai/kimi-k2-0905:exa` | `kimi-k2-0905` | 去掉前缀和 `:` 后缀 |
|
||||
| `gpt-5.2-codex@low` | `gpt-5.2-codex-low` | 将 `@` 替换为 `-` |
|
||||
| `OpenAI/GPT-5.5-2026-05-14` | `gpt-5.5` | 去掉前缀和日期后缀 |
|
||||
| `anthropic/claude-opus-4.8` | `claude-opus-4-8` | 去掉前缀并匹配点号格式 |
|
||||
| `global.anthropic.claude-opus-4-8-v1:0` | `claude-opus-4-8` | 去掉包装前缀、版本后缀和 `:` 后缀 |
|
||||
| `claude-haiku-4-5` | `claude-haiku-4-5-20251001` | 短 ID 匹配带版本定价 |
|
||||
|
||||
### 操作
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
├── settings.json # 设备级设置
|
||||
├── skills/ # 技能 SSOT 目录
|
||||
├── skill-backups/ # 技能备份(卸载时创建)
|
||||
└── db_backup_*.db # 数据库备份
|
||||
└── backups/ # 数据库备份
|
||||
```
|
||||
|
||||
### 数据库内容
|
||||
@@ -51,7 +51,8 @@
|
||||
"codexConfigDir": null,
|
||||
"geminiConfigDir": null,
|
||||
"opencodeConfigDir": null,
|
||||
"openclawConfigDir": null
|
||||
"openclawConfigDir": null,
|
||||
"hermesConfigDir": null
|
||||
}
|
||||
```
|
||||
|
||||
@@ -196,17 +197,41 @@ GEMINI_MODEL=gemini-pro
|
||||
|
||||
### 配置目录
|
||||
|
||||
默认:`~/.opencode/`
|
||||
默认:`~/.config/opencode/`
|
||||
|
||||
### 主要文件
|
||||
|
||||
```
|
||||
~/.opencode/
|
||||
├── config.json # 主配置文件
|
||||
~/.config/opencode/
|
||||
├── opencode.json # 主配置文件
|
||||
├── AGENTS.md # 系统提示词
|
||||
└── skills/ # 技能目录
|
||||
└── ...
|
||||
```
|
||||
## Hermes 配置
|
||||
|
||||
### 配置目录
|
||||
|
||||
默认:`~/.hermes/`
|
||||
|
||||
### 主要文件
|
||||
|
||||
```
|
||||
~/.hermes/
|
||||
├── config.yaml # 主设置、供应商与 MCP 配置
|
||||
├── .env # API keys 与 secrets
|
||||
├── SOUL.md # Profile 身份/人格
|
||||
├── memories/
|
||||
│ ├── MEMORY.md # Agent 记忆
|
||||
│ └── USER.md # 用户画像记忆
|
||||
├── skills/ # 活跃技能目录
|
||||
├── state.db # SQLite 会话数据库
|
||||
└── sessions/ # Gateway 转录与可选 JSON 快照
|
||||
```
|
||||
|
||||
### config.yaml
|
||||
|
||||
Hermes 使用 YAML 配置。CC Switch 将 MCP 服务器写入 `mcp_servers`,将可编辑的供应商条目写入 `custom_providers`,读取 Hermes `providers` 字典中的只读条目,并在切换供应商时更新 `model.provider` / `model.default`。
|
||||
|
||||
## OpenClaw 配置
|
||||
|
||||
@@ -219,7 +244,6 @@ GEMINI_MODEL=gemini-pro
|
||||
```
|
||||
~/.openclaw/
|
||||
├── openclaw.json # 主配置文件(JSON5 格式)
|
||||
├── AGENTS.md # 系统提示词
|
||||
└── skills/ # 技能目录
|
||||
└── ...
|
||||
```
|
||||
@@ -246,18 +270,17 @@ OpenClaw 使用 JSON5 格式配置文件,主要包含以下部分:
|
||||
env: {
|
||||
ANTHROPIC_API_KEY: "sk-..."
|
||||
},
|
||||
// Agent 默认模型配置
|
||||
// Agent 默认配置
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: "provider/model"
|
||||
}
|
||||
},
|
||||
workspace: "~/.openclaw/workspace"
|
||||
}
|
||||
},
|
||||
// 工具配置
|
||||
tools: {},
|
||||
// 工作区文件配置
|
||||
workspace: {}
|
||||
tools: {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -267,7 +290,7 @@ OpenClaw 使用 JSON5 格式配置文件,主要包含以下部分:
|
||||
| `env` | 环境变量配置 |
|
||||
| `agents.defaults` | Agent 默认模型设置 |
|
||||
| `tools` | 工具配置 |
|
||||
| `workspace` | 工作区文件管理 |
|
||||
| `agents.defaults.workspace` | 工作区目录路径 |
|
||||
|
||||
## 配置优先级
|
||||
|
||||
|
||||
@@ -144,7 +144,7 @@ chmod +x CC-Switch-*.AppImage
|
||||
- 版本不兼容
|
||||
|
||||
**解决方法**:
|
||||
1. 确认文件是 CC Switch 导出的 JSON 文件
|
||||
1. 确认文件是 CC Switch 导出的 SQL 备份文件
|
||||
2. 检查文件内容是否完整
|
||||
3. 尝试用文本编辑器打开检查格式
|
||||
|
||||
|
||||
@@ -106,15 +106,15 @@
|
||||
|
||||
## 版本信息
|
||||
|
||||
- 文档版本:v3.15.0
|
||||
- 最后更新:2026-05-16
|
||||
- 适用于 CC Switch v3.15.0+
|
||||
- 文档版本:v3.16.0
|
||||
- 最后更新:2026-05-29
|
||||
- 适用于 CC Switch v3.16.0+
|
||||
|
||||
### v3.15.0 亮点
|
||||
### v3.16.0 亮点
|
||||
|
||||
- **Claude Desktop 一等管理面板**:支持第三方供应商、直连 / 模型映射两种模式、Copilot / Codex OAuth 复用与 3P profile 写入 — 详见 [2.6 Claude Desktop](./2-providers/2.6-claude-desktop.md)
|
||||
- **按角色的模型映射**:用 Sonnet / Opus / Haiku 路由和 `supports1m` 标志适配 Claude Desktop 的模型校验
|
||||
- **Claude Desktop 本地路由**:通过 `127.0.0.1:15721/claude-desktop` 为需要转换的供应商提供本地网关
|
||||
- **Codex Chat Completions 路由**:DeepSeek、Kimi、GLM、MiniMax 等仅支持 Chat 协议的供应商可通过 Codex 使用 — 详见 [2.1 添加供应商](./2-providers/2.1-add.md)
|
||||
- **托管 CLI 工具生命周期**:在设置 / 关于页安装、升级、全部升级并诊断 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — 详见 [1.5 个性化配置](./1-getting-started/1.5-settings.md)
|
||||
- **供应商与模型矩阵刷新**:新增合作方预设,刷新默认模型与计费矩阵,Claude Opus 默认升级到 4.8,适用场景下 GPT 默认升级到 5.5
|
||||
- **路由支持徽章**:Claude Code / Codex 供应商卡片会标明是否支持 Local Routing,便于选择可代理的供应商
|
||||
- **Codex OAuth 实时模型发现**:ChatGPT Codex 类供应商按需从 ChatGPT 后端拉取最新模型列表
|
||||
- **用量看板筛选驱动 Hero**:展示缓存归一化后的真实总 token 与缓存命中率,并跟随日期 / 供应商 / 模型筛选实时更新 — 详见 [4.4 用量统计](./4-proxy/4.4-usage.md)
|
||||
@@ -124,7 +124,7 @@
|
||||
- **托盘按应用分级菜单**:Claude / Codex / Gemini 独立子菜单,标题展示当前供应商与可用用量摘要 — 详见 [2.2 切换供应商](./2-providers/2.2-switch.md)
|
||||
- **Skills 发现与批量更新**:SHA-256 更新检测、批量更新、skills.sh 公共注册表搜索 — 详见 [3.3 Skills 技能管理](./3-extensions/3.3-skills.md)
|
||||
- **完整 URL 端点模式**:高级选项支持将 base_url 视作完整上游端点 — 详见 [2.1 添加供应商](./2-providers/2.1-add.md)
|
||||
- **OpenCode / OpenClaw 流式检测覆盖**:Stream Check 面板覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw — 详见 [4.5 模型检查](./4-proxy/4.5-model-test.md)
|
||||
- **OpenCode / OpenClaw / Hermes 流式检测覆盖**:Stream Check 面板覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes — 详见 [4.5 模型检查](./4-proxy/4.5-model-test.md)
|
||||
|
||||
## 贡献
|
||||
|
||||
|
||||
@@ -1,597 +0,0 @@
|
||||
# CC-Switch "工作目录" 功能 — 实施方案
|
||||
|
||||
## Context
|
||||
|
||||
CC-Switch 管理 5 个 CLI 工具(Claude Code / Codex / Gemini CLI / OpenCode / OpenClaw)的供应商、MCP 服务器、Skills、提示词配置。当前所有启用状态是全局的——用户在不同项目间切换时需要手动 toggle。
|
||||
|
||||
本功能允许用户注册多个工作目录(项目文件夹),切换目录时自动保存/恢复各实体的启用状态。**不做数据隔离**——所有实体共享全局池,仅 "谁是激活的" 按目录区分。
|
||||
|
||||
---
|
||||
|
||||
## 一、需要按目录区分的实体(完整清单)
|
||||
|
||||
| 实体 | 当前状态字段 | 存储方式 | 需要区分? | 理由 |
|
||||
|------|-------------|---------|-----------|------|
|
||||
| **Provider** | `is_current` | per `(id, app_type)` | **YES** | 不同项目用不同供应商 |
|
||||
| **Provider (Failover)** | `in_failover_queue` | per `(id, app_type)` | **YES** | 备用供应商队列跟随主供应商配置 |
|
||||
| **MCP Server** | `enabled_claude/codex/gemini/opencode` | per `id`, 4列 | **YES** | 不同项目需要不同 MCP 工具 |
|
||||
| **Skill** | `enabled_claude/codex/gemini/opencode` | per `id`, 4列 | **YES** | 不同项目需要不同 Skills |
|
||||
| **Prompt** | `enabled` | per `(id, app_type)`, 单选 | **YES** | 不同项目用不同系统提示词 |
|
||||
| Proxy Config | `enabled`, thresholds | per `app_type` | NO | 基础设施级别,非项目相关 |
|
||||
| Settings | key-value | flat table | NO | 全局用户偏好 |
|
||||
| Provider Health | failures, errors | runtime | **CLEAR** | 切换时清除,重新计算 |
|
||||
| Common Config | `common_config_{app}` | settings table | NO | 全局模板,非项目相关 |
|
||||
| Usage/Logs | historical | various tables | NO | 历史数据,不应分区 |
|
||||
|
||||
> 原计划遗漏了 **Failover Queue** 和 **Provider Health 清除**。
|
||||
|
||||
---
|
||||
|
||||
## 二、数据库变更(Schema v8 → v9)
|
||||
|
||||
### 新增 5 张表
|
||||
|
||||
```sql
|
||||
-- 1. 工作目录注册表
|
||||
CREATE TABLE IF NOT EXISTS working_directories (
|
||||
id TEXT PRIMARY KEY,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
name TEXT,
|
||||
is_current BOOLEAN NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
-- 2. Provider 状态快照 (is_current + in_failover_queue)
|
||||
-- 每个目录保存所有 provider 的两个状态标志
|
||||
CREATE TABLE IF NOT EXISTS dir_provider_state (
|
||||
dir_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
provider_id TEXT NOT NULL,
|
||||
is_current BOOLEAN NOT NULL DEFAULT 0,
|
||||
in_failover_queue BOOLEAN NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (dir_id, app_type, provider_id)
|
||||
);
|
||||
|
||||
-- 3. MCP 启用状态快照 (直接镜像 4 列,不做行展开)
|
||||
CREATE TABLE IF NOT EXISTS dir_mcp_state (
|
||||
dir_id TEXT NOT NULL,
|
||||
mcp_id TEXT NOT NULL,
|
||||
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,
|
||||
PRIMARY KEY (dir_id, mcp_id)
|
||||
);
|
||||
|
||||
-- 4. Skill 启用状态快照 (直接镜像 4 列)
|
||||
CREATE TABLE IF NOT EXISTS dir_skill_state (
|
||||
dir_id TEXT NOT NULL,
|
||||
skill_id TEXT NOT NULL,
|
||||
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,
|
||||
PRIMARY KEY (dir_id, skill_id)
|
||||
);
|
||||
|
||||
-- 5. Prompt 启用状态快照 (每个 app_type 只存激活的 prompt_id)
|
||||
CREATE TABLE IF NOT EXISTS dir_prompt_state (
|
||||
dir_id TEXT NOT NULL,
|
||||
app_type TEXT NOT NULL,
|
||||
prompt_id TEXT NOT NULL,
|
||||
PRIMARY KEY (dir_id, app_type)
|
||||
);
|
||||
```
|
||||
|
||||
### 设计决策说明
|
||||
|
||||
**MCP/Skill 用 4 列镜像而非 `(entity_id, app_type, enabled)` 行展开**:
|
||||
- 与主表 `mcp_servers` / `skills` 结构一致,snapshot/apply 代码直接 copy 4 列
|
||||
- 避免 4 倍行膨胀(每个 MCP 服务器 1 行 vs 4 行)
|
||||
- 未来增加新 app 时,两边同步加列即可
|
||||
|
||||
**Prompt 只存 `(dir_id, app_type, prompt_id)`**:
|
||||
- 每个 app_type 最多一个 enabled prompt,不需要存 boolean
|
||||
- 无记录 = 该 app 无激活 prompt
|
||||
|
||||
**Provider 合并 `is_current` + `in_failover_queue`**:
|
||||
- 两个标志都是 per `(app_type, provider_id)` 的状态
|
||||
- 存在同一表中避免多表 JOIN
|
||||
|
||||
### 迁移脚本
|
||||
|
||||
在 `schema.rs` 中:
|
||||
- `create_tables_on_conn()` 添加 5 个 CREATE TABLE
|
||||
- 新增 `migrate_v8_to_v9(conn)`: 创建 5 张表 + 插入 `__default__` 行
|
||||
- `SCHEMA_VERSION` 升至 9
|
||||
- 迁移循环添加 `7 => ...` 后加 `8 => { Self::migrate_v8_to_v9(conn)?; Self::set_user_version(conn, 9)?; }`
|
||||
|
||||
```rust
|
||||
fn migrate_v8_to_v9(conn: &Connection) -> Result<(), AppError> {
|
||||
// 创建 5 张表(使用 IF NOT EXISTS,幂等)
|
||||
// ...
|
||||
// 插入 __default__ 虚拟目录,代表"全局默认"状态
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO working_directories (id, path, name, is_current, created_at) \
|
||||
VALUES ('__default__', '__default__', NULL, 0, ?1)",
|
||||
[crate::database::get_unix_timestamp()?],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、后端实现
|
||||
|
||||
### 3.1 DAO 层 — `src-tauri/src/database/dao/working_dir.rs`
|
||||
|
||||
所有方法都是 `impl Database` 块,遵循现有 DAO 模式。
|
||||
|
||||
**关键方法签名**(需要 `_on_conn` 变体支持事务):
|
||||
|
||||
```rust
|
||||
// ═══ 工作目录 CRUD ═══
|
||||
pub fn list_working_directories(&self) -> Result<Vec<WorkingDirectory>, AppError>
|
||||
pub fn add_working_directory(&self, id: &str, path: &str, name: Option<&str>) -> Result<(), AppError>
|
||||
pub fn delete_working_directory(&self, id: &str) -> Result<(), AppError>
|
||||
pub fn rename_working_directory(&self, id: &str, name: &str) -> Result<(), AppError>
|
||||
pub fn get_current_working_directory(&self) -> Result<Option<WorkingDirectory>, AppError>
|
||||
|
||||
// 使用 _on_conn 变体,在 Service 层的事务中调用
|
||||
fn set_current_working_directory_on_conn(conn: &Connection, id: &str) -> Result<(), AppError>
|
||||
|
||||
// ═══ 快照写入 ═══ (都有 _on_conn 变体)
|
||||
fn snapshot_providers_on_conn(conn: &Connection, dir_id: &str) -> Result<(), AppError>
|
||||
fn snapshot_mcp_on_conn(conn: &Connection, dir_id: &str) -> Result<(), AppError>
|
||||
fn snapshot_skills_on_conn(conn: &Connection, dir_id: &str) -> Result<(), AppError>
|
||||
fn snapshot_prompts_on_conn(conn: &Connection, dir_id: &str) -> Result<(), AppError>
|
||||
|
||||
// ═══ 快照恢复 ═══ (都有 _on_conn 变体, 返回 bool = 是否有快照)
|
||||
fn apply_provider_snapshot_on_conn(conn: &Connection, dir_id: &str) -> Result<bool, AppError>
|
||||
fn apply_mcp_snapshot_on_conn(conn: &Connection, dir_id: &str) -> Result<bool, AppError>
|
||||
fn apply_skill_snapshot_on_conn(conn: &Connection, dir_id: &str) -> Result<bool, AppError>
|
||||
fn apply_prompt_snapshot_on_conn(conn: &Connection, dir_id: &str) -> Result<bool, AppError>
|
||||
```
|
||||
|
||||
**snapshot_providers 实现思路**:
|
||||
```sql
|
||||
-- 先清除旧快照
|
||||
DELETE FROM dir_provider_state WHERE dir_id = ?1;
|
||||
-- 从主表复制当前状态
|
||||
INSERT INTO dir_provider_state (dir_id, app_type, provider_id, is_current, in_failover_queue)
|
||||
SELECT ?1, app_type, id, is_current, in_failover_queue
|
||||
FROM providers
|
||||
WHERE is_current = 1 OR in_failover_queue = 1;
|
||||
```
|
||||
|
||||
**apply_provider_snapshot 实现思路**:
|
||||
```sql
|
||||
-- 检查是否有快照
|
||||
SELECT COUNT(*) FROM dir_provider_state WHERE dir_id = ?1; -- 如果 0,返回 false
|
||||
|
||||
-- 在事务中:先清除主表所有 is_current 和 in_failover_queue
|
||||
UPDATE providers SET is_current = 0;
|
||||
UPDATE providers SET in_failover_queue = 0;
|
||||
|
||||
-- 从快照恢复
|
||||
UPDATE providers SET is_current = 1
|
||||
WHERE (id, app_type) IN (SELECT provider_id, app_type FROM dir_provider_state WHERE dir_id = ?1 AND is_current = 1);
|
||||
|
||||
UPDATE providers SET in_failover_queue = 1
|
||||
WHERE (id, app_type) IN (SELECT provider_id, app_type FROM dir_provider_state WHERE dir_id = ?1 AND in_failover_queue = 1);
|
||||
```
|
||||
|
||||
**snapshot_mcp / snapshot_skills 实现思路**(直接镜像 4 列):
|
||||
```sql
|
||||
DELETE FROM dir_mcp_state WHERE dir_id = ?1;
|
||||
INSERT INTO dir_mcp_state (dir_id, mcp_id, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode)
|
||||
SELECT ?1, id, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
|
||||
FROM mcp_servers;
|
||||
```
|
||||
|
||||
**apply_mcp_snapshot 实现思路**:
|
||||
```sql
|
||||
-- 先全部禁用
|
||||
UPDATE mcp_servers SET enabled_claude = 0, enabled_codex = 0, enabled_gemini = 0, enabled_opencode = 0;
|
||||
|
||||
-- 从快照恢复
|
||||
UPDATE mcp_servers SET
|
||||
enabled_claude = (SELECT enabled_claude FROM dir_mcp_state WHERE dir_id = ?1 AND mcp_id = mcp_servers.id),
|
||||
enabled_codex = (SELECT enabled_codex FROM dir_mcp_state WHERE dir_id = ?1 AND mcp_id = mcp_servers.id),
|
||||
enabled_gemini = (SELECT enabled_gemini FROM dir_mcp_state WHERE dir_id = ?1 AND mcp_id = mcp_servers.id),
|
||||
enabled_opencode = (SELECT enabled_opencode FROM dir_mcp_state WHERE dir_id = ?1 AND mcp_id = mcp_servers.id)
|
||||
WHERE id IN (SELECT mcp_id FROM dir_mcp_state WHERE dir_id = ?1);
|
||||
```
|
||||
|
||||
### 3.2 Service 层 — `src-tauri/src/services/working_dir.rs`
|
||||
|
||||
```rust
|
||||
use crate::store::AppState;
|
||||
use crate::error::AppError;
|
||||
use crate::database::lock_conn;
|
||||
use crate::app_config::AppType;
|
||||
use crate::services::{McpService, ProviderService, SkillService};
|
||||
use crate::config::write_text_file;
|
||||
use crate::prompt_files::prompt_file_path;
|
||||
|
||||
pub struct WorkingDirService;
|
||||
|
||||
impl WorkingDirService {
|
||||
/// 核心切换逻辑
|
||||
pub fn switch(state: &AppState, target_dir_id: &str) -> Result<(), AppError> {
|
||||
// ═══ 前置检查 ═══
|
||||
// 1. 检查代理接管状态,若活跃则拒绝切换
|
||||
// 使用 db.is_live_takeover_active() 或同步检查 proxy_config.live_takeover_active
|
||||
// (因为 ProxyService::is_running() 是 async,而此函数是 sync)
|
||||
Self::check_proxy_not_active(state)?;
|
||||
|
||||
// ═══ Phase 1: 回填 Prompt ═══
|
||||
// 在 snapshot 之前,将 live 文件内容回填到当前 enabled prompt
|
||||
// 这样即使用户手动编辑了 live 文件,内容也不会丢失
|
||||
Self::backfill_prompt_content(state)?;
|
||||
|
||||
// ═══ Phase 2: 数据库操作(事务) ═══
|
||||
{
|
||||
let conn = lock_conn!(state.db.conn);
|
||||
conn.execute("BEGIN IMMEDIATE", [])?;
|
||||
|
||||
let result = (|| -> Result<(), AppError> {
|
||||
// 获取当前工作目录
|
||||
let current = Self::get_current_dir_id_on_conn(&conn)?;
|
||||
|
||||
// 保存当前状态到旧目录
|
||||
if let Some(old_id) = ¤t {
|
||||
Database::snapshot_providers_on_conn(&conn, old_id)?;
|
||||
Database::snapshot_mcp_on_conn(&conn, old_id)?;
|
||||
Database::snapshot_skills_on_conn(&conn, old_id)?;
|
||||
Database::snapshot_prompts_on_conn(&conn, old_id)?;
|
||||
} else {
|
||||
// 无当前目录 = 全局模式,保存到 __default__
|
||||
Database::snapshot_providers_on_conn(&conn, "__default__")?;
|
||||
Database::snapshot_mcp_on_conn(&conn, "__default__")?;
|
||||
Database::snapshot_skills_on_conn(&conn, "__default__")?;
|
||||
Database::snapshot_prompts_on_conn(&conn, "__default__")?;
|
||||
}
|
||||
|
||||
// 加载目标目录快照(如果有的话)
|
||||
// 如果无快照(首次进入),保持主表不变
|
||||
Database::apply_provider_snapshot_on_conn(&conn, target_dir_id)?;
|
||||
Database::apply_mcp_snapshot_on_conn(&conn, target_dir_id)?;
|
||||
Database::apply_skill_snapshot_on_conn(&conn, target_dir_id)?;
|
||||
Database::apply_prompt_snapshot_on_conn(&conn, target_dir_id)?;
|
||||
|
||||
// 更新 is_current 标记
|
||||
Database::set_current_working_directory_on_conn(&conn, target_dir_id)?;
|
||||
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
match result {
|
||||
Ok(()) => conn.execute("COMMIT", [])?,
|
||||
Err(e) => {
|
||||
let _ = conn.execute("ROLLBACK", []);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
// conn 锁在此处释放
|
||||
|
||||
// ═══ Phase 3: 同步 live 配置文件 ═══
|
||||
Self::sync_all_live(state)?;
|
||||
|
||||
// ═══ Phase 4: 清除 Provider Health ═══
|
||||
state.db.clear_all_provider_health()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 回填 live prompt 文件内容到 DB(切换前调用)
|
||||
fn backfill_prompt_content(state: &AppState) -> Result<(), AppError> {
|
||||
for app in AppType::all() {
|
||||
let path = prompt_file_path(&app)?;
|
||||
if !path.exists() { continue; }
|
||||
let live_content = std::fs::read_to_string(&path).unwrap_or_default();
|
||||
if live_content.trim().is_empty() { continue; }
|
||||
|
||||
let mut prompts = state.db.get_prompts(app.as_str())?;
|
||||
if let Some((_, prompt)) = prompts.iter_mut().find(|(_, p)| p.enabled) {
|
||||
prompt.content = live_content;
|
||||
prompt.updated_at = Some(get_unix_timestamp()?);
|
||||
state.db.save_prompt(app.as_str(), prompt)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 将 DB 中的 enabled prompt 内容写入 live 文件(切换后调用)
|
||||
/// 注意:不做回填!只写入。区别于 PromptService::enable_prompt()
|
||||
fn write_prompts_to_live(state: &AppState) -> Result<(), AppError> {
|
||||
for app in AppType::all() {
|
||||
let path = prompt_file_path(&app)?;
|
||||
let prompts = state.db.get_prompts(app.as_str())?;
|
||||
if let Some(prompt) = prompts.values().find(|p| p.enabled) {
|
||||
write_text_file(&path, &prompt.content)?;
|
||||
}
|
||||
// 无 enabled prompt 时不清空文件(保留现状)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 同步所有 live 配置(Provider + MCP + Skill + Prompt)
|
||||
fn sync_all_live(state: &AppState) -> Result<(), AppError> {
|
||||
// 1. Provider → live files
|
||||
ProviderService::sync_current_to_live(state)?;
|
||||
// sync_current_to_live 内部已调用 McpService::sync_all_enabled()
|
||||
|
||||
// 2. Skills → app dirs (循环每个 app)
|
||||
for app in AppType::all() {
|
||||
let _ = SkillService::sync_to_app(&state.db, &app);
|
||||
}
|
||||
|
||||
// 3. Prompts → live files
|
||||
Self::write_prompts_to_live(state)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 检查代理是否活跃(同步检查数据库标志)
|
||||
fn check_proxy_not_active(state: &AppState) -> Result<(), AppError> {
|
||||
// 检查 proxy_config 表中 live_takeover_active 列
|
||||
// 如果有任何 app 的 live_takeover_active = 1,拒绝切换
|
||||
let conn = lock_conn!(state.db.conn);
|
||||
let active: bool = conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM proxy_config WHERE live_takeover_active = 1)",
|
||||
[], |r| r.get(0)
|
||||
).unwrap_or(false);
|
||||
|
||||
if active {
|
||||
return Err(AppError::Message(
|
||||
"代理接管模式运行中,请先停止代理再切换工作目录".into()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 Command 层 — `src-tauri/src/commands/working_dir.rs`
|
||||
|
||||
遵循现有模式:`State<'_, AppState>` + `Result<T, String>` + `.map_err(|e| e.to_string())`。
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
pub fn list_working_directories(state: State<'_, AppState>) -> Result<Vec<WorkingDirectory>, String>
|
||||
|
||||
#[tauri::command]
|
||||
pub fn add_working_directory(state: State<'_, AppState>, path: String, name: Option<String>) -> Result<WorkingDirectory, String>
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_working_directory(state: State<'_, AppState>, id: String) -> Result<(), String>
|
||||
|
||||
#[tauri::command]
|
||||
pub fn rename_working_directory(state: State<'_, AppState>, id: String, name: String) -> Result<(), String>
|
||||
|
||||
#[tauri::command]
|
||||
pub fn switch_working_directory(state: State<'_, AppState>, id: String) -> Result<(), String>
|
||||
// 调用 WorkingDirService::switch()
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_current_working_directory(state: State<'_, AppState>) -> Result<Option<WorkingDirectory>, String>
|
||||
```
|
||||
|
||||
### 3.4 需修改的现有文件
|
||||
|
||||
| 文件 | 修改内容 |
|
||||
|------|---------|
|
||||
| `src-tauri/src/database/schema.rs` | 添加 5 个 CREATE TABLE + `migrate_v8_to_v9()` |
|
||||
| `src-tauri/src/database/mod.rs` | `SCHEMA_VERSION = 9` + 迁移循环加 `8 => ...` + `pub mod working_dir` in dao |
|
||||
| `src-tauri/src/database/dao/mod.rs` | 添加 `pub mod working_dir;` |
|
||||
| `src-tauri/src/services/mod.rs` | 添加 `pub mod working_dir;` + `pub use working_dir::WorkingDirService;` |
|
||||
| `src-tauri/src/commands/mod.rs` | 添加 `mod working_dir;` + `pub use working_dir::*;` |
|
||||
| `src-tauri/src/lib.rs` | invoke_handler 注册 6 个新命令 |
|
||||
|
||||
### 3.5 可能需要新增的 DAO 辅助方法
|
||||
|
||||
`src-tauri/src/database/dao/failover.rs`:
|
||||
```rust
|
||||
/// 清除所有 provider_health 记录(切换目录时调用)
|
||||
pub fn clear_all_provider_health(&self) -> Result<(), AppError>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、前端实现
|
||||
|
||||
### 4.1 API — `src/lib/api/workingDir.ts`
|
||||
|
||||
```typescript
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
|
||||
export interface WorkingDirectory {
|
||||
id: string;
|
||||
path: string;
|
||||
name?: string;
|
||||
isCurrent: boolean;
|
||||
createdAt: number;
|
||||
}
|
||||
|
||||
export const workingDirApi = {
|
||||
list: () => invoke<WorkingDirectory[]>("list_working_directories"),
|
||||
add: (path: string, name?: string) =>
|
||||
invoke<WorkingDirectory>("add_working_directory", { path, name }),
|
||||
delete: (id: string) => invoke<void>("delete_working_directory", { id }),
|
||||
rename: (id: string, name: string) =>
|
||||
invoke<void>("rename_working_directory", { id, name }),
|
||||
switch: (id: string) => invoke<void>("switch_working_directory", { id }),
|
||||
getCurrent: () =>
|
||||
invoke<WorkingDirectory | null>("get_current_working_directory"),
|
||||
};
|
||||
```
|
||||
|
||||
### 4.2 组件 — `src/components/WorkingDirSwitcher.tsx`
|
||||
|
||||
**位置**:Header toolbar,靠近 AppSwitcher。
|
||||
|
||||
**功能**:
|
||||
- 下拉菜单显示已注册目录列表
|
||||
- 当前目录高亮
|
||||
- "浏览…" 按钮调用 Tauri 文件夹选择对话框
|
||||
- 右键菜单:重命名、删除
|
||||
- "__default__(全局)" 选项恢复到全局状态
|
||||
- 切换后 invalidate 所有相关 React Query
|
||||
|
||||
**切换后的 Query Invalidation**:
|
||||
```typescript
|
||||
// 需要验证实际的 queryKey 名称
|
||||
queryClient.invalidateQueries({ queryKey: ["providers"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["mcp-servers"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["installed-skills"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["prompts"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["workingDirectories"] });
|
||||
```
|
||||
|
||||
### 4.3 i18n
|
||||
|
||||
三个文件都需更新:
|
||||
- `src/i18n/locales/zh.json`
|
||||
- `src/i18n/locales/en.json`
|
||||
- `src/i18n/locales/ja.json`
|
||||
|
||||
---
|
||||
|
||||
## 五、切换流程时序
|
||||
|
||||
```
|
||||
用户选择目录 B
|
||||
│
|
||||
├── 1. check_proxy_not_active()
|
||||
│ → 如果代理接管中,返回错误,终止
|
||||
│
|
||||
├── 2. backfill_prompt_content()
|
||||
│ → 读 live prompt 文件 → 更新 DB 中已启用 prompt 的 content
|
||||
│ → 保护用户手动编辑的 prompt 不丢失
|
||||
│
|
||||
├── 3. BEGIN TRANSACTION
|
||||
│ ├── snapshot(old_dir / __default__)
|
||||
│ │ ├── providers → dir_provider_state (is_current + in_failover_queue)
|
||||
│ │ ├── mcp_servers → dir_mcp_state (4 列直接复制)
|
||||
│ │ ├── skills → dir_skill_state (4 列直接复制)
|
||||
│ │ └── prompts → dir_prompt_state (enabled prompt_id)
|
||||
│ │
|
||||
│ ├── apply(target_dir)
|
||||
│ │ ├── dir_provider_state → providers
|
||||
│ │ ├── dir_mcp_state → mcp_servers
|
||||
│ │ ├── dir_skill_state → skills
|
||||
│ │ └── dir_prompt_state → prompts
|
||||
│ │
|
||||
│ └── set_current_working_directory(target_dir)
|
||||
│
|
||||
├── COMMIT
|
||||
│
|
||||
├── 4. sync_all_live()
|
||||
│ ├── ProviderService::sync_current_to_live(state)
|
||||
│ │ └── 内部已调用 McpService::sync_all_enabled()
|
||||
│ ├── for app in AppType::all() { SkillService::sync_to_app(&db, &app) }
|
||||
│ └── write_prompts_to_live() ← 无回填,直接写
|
||||
│
|
||||
└── 5. clear_all_provider_health()
|
||||
→ 清除运行时熔断器状态
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 六、边界情况处理
|
||||
|
||||
| 场景 | 处理方式 |
|
||||
|------|---------|
|
||||
| **首次进入目录(无快照)** | `apply_*_snapshot()` 返回 false,主表保持不变。用户调整后,下次切走时自动保存。 |
|
||||
| **全局模式 → 目录** | 自动将当前状态 snapshot 到 `__default__` 虚拟目录。`__default__` 在 v9 迁移中预创建。 |
|
||||
| **目录 → 全局模式** | 用户选择 `__default__`,恢复全局状态。 |
|
||||
| **新增 MCP/Skill/Provider** | 新实体在 dir_*_state 中无记录。apply 时只更新有记录的实体,新增的保持 DB 默认值。 |
|
||||
| **删除 MCP/Skill/Provider** | dir_*_state 中对应记录在 apply 时找不到主表行,UPDATE 影响 0 行,静默跳过。 |
|
||||
| **删除工作目录** | 级联删除 dir_*_state 中所有 `dir_id` 匹配的行。若为当前目录,回退到 `__default__`。 |
|
||||
| **代理接管中切换** | `check_proxy_not_active()` 检测到 `live_takeover_active = 1`,拒绝切换并提示用户先停止代理。 |
|
||||
| **切换中途崩溃** | 事务保护 DB 操作的原子性。最坏情况:DB 已更新但 live 文件未同步。下次启动可添加恢复检查(Phase 2 优化)。 |
|
||||
| **用户手动编辑了 prompt 文件** | `backfill_prompt_content()` 在切换前读取 live 文件回填到 DB,保护手动修改。 |
|
||||
|
||||
---
|
||||
|
||||
## 七、实施顺序
|
||||
|
||||
### Phase 1: 数据库
|
||||
1. `database/schema.rs` — 5 个 CREATE TABLE + `migrate_v8_to_v9()`
|
||||
2. `database/mod.rs` — `SCHEMA_VERSION = 9` + 迁移分支
|
||||
3. `database/dao/working_dir.rs` — 全部 DAO 方法(`_on_conn` 变体)
|
||||
4. `database/dao/failover.rs` — 新增 `clear_all_provider_health()`
|
||||
5. `database/dao/mod.rs` — 注册模块
|
||||
|
||||
### Phase 2: 服务 + 命令
|
||||
6. `services/working_dir.rs` — `WorkingDirService::switch()` 等
|
||||
7. `commands/working_dir.rs` — 6 个 Tauri 命令
|
||||
8. `services/mod.rs` — 注册模块
|
||||
9. `commands/mod.rs` — 注册模块
|
||||
10. `lib.rs` — invoke_handler 注册
|
||||
|
||||
### Phase 3: 前端
|
||||
11. `src/lib/api/workingDir.ts` — API 封装
|
||||
12. `src/types.ts` — WorkingDirectory 类型
|
||||
13. `src/components/WorkingDirSwitcher.tsx` — UI 组件
|
||||
14. `src/App.tsx` — 集成到 header toolbar
|
||||
15. `src/i18n/locales/{zh,en,ja}.json` — 国际化
|
||||
|
||||
### Phase 4: 优化(可选)
|
||||
16. 启动恢复检查(DB 状态 vs live 文件一致性)
|
||||
17. 托盘菜单显示当前工作目录
|
||||
|
||||
---
|
||||
|
||||
## 八、关键文件索引
|
||||
|
||||
### 新增文件(5 个)
|
||||
- `src-tauri/src/database/dao/working_dir.rs`
|
||||
- `src-tauri/src/services/working_dir.rs`
|
||||
- `src-tauri/src/commands/working_dir.rs`
|
||||
- `src/lib/api/workingDir.ts`
|
||||
- `src/components/WorkingDirSwitcher.tsx`
|
||||
|
||||
### 必须修改的文件(7 个)
|
||||
- `src-tauri/src/database/schema.rs` — CREATE TABLE + 迁移
|
||||
- `src-tauri/src/database/mod.rs` — 版本号 + 迁移循环
|
||||
- `src-tauri/src/database/dao/mod.rs` — 模块注册
|
||||
- `src-tauri/src/database/dao/failover.rs` — clear_all_provider_health
|
||||
- `src-tauri/src/services/mod.rs` — 模块注册
|
||||
- `src-tauri/src/commands/mod.rs` — 模块注册
|
||||
- `src-tauri/src/lib.rs` — invoke_handler
|
||||
|
||||
### 必须修改的前端文件(4 个)
|
||||
- `src/App.tsx` — 集成 WorkingDirSwitcher
|
||||
- `src/types.ts` — WorkingDirectory 接口
|
||||
- `src/i18n/locales/zh.json` — 中文
|
||||
- `src/i18n/locales/en.json` — 英文
|
||||
- `src/i18n/locales/ja.json` — 日文
|
||||
|
||||
### 参考文件(理解现有模式)
|
||||
- `src-tauri/src/services/mcp.rs` — `sync_all_enabled()` (line 165)
|
||||
- `src-tauri/src/services/skill.rs` — `sync_to_app()` (line 1707)
|
||||
- `src-tauri/src/services/provider/mod.rs` — `sync_current_to_live()` (line 1552)
|
||||
- `src-tauri/src/services/prompt.rs` — `enable_prompt()` (line 73) — 理解回填逻辑
|
||||
- `src-tauri/src/prompt_files.rs` — prompt 文件路径
|
||||
- `src-tauri/src/config.rs` — `write_text_file()` (line 176)
|
||||
|
||||
---
|
||||
|
||||
## 九、验证计划
|
||||
|
||||
### 后端验证
|
||||
1. `cargo test` — DAO 层单元测试(使用 `Database::memory()`)
|
||||
- 快照/恢复往返一致性
|
||||
- 新增/删除实体后的 apply 行为
|
||||
- `__default__` 全局状态保护
|
||||
- 事务回滚测试
|
||||
2. 手动测试 — 启动应用,创建两个目录,切换并验证 live 文件变化
|
||||
|
||||
### 前端验证
|
||||
1. `pnpm typecheck` — TypeScript 类型检查
|
||||
2. `pnpm lint` — ESLint 检查
|
||||
3. 手动 UI 测试 — 工作目录切换器交互、query invalidation 后数据刷新
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.16.0",
|
||||
"version": "3.16.2",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
Generated
+3
-1
@@ -735,7 +735,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.16.0"
|
||||
version = "3.16.2"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
@@ -749,6 +749,7 @@ dependencies = [
|
||||
"dirs 5.0.1",
|
||||
"flate2",
|
||||
"futures",
|
||||
"hmac",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
@@ -798,6 +799,7 @@ dependencies = [
|
||||
"uuid",
|
||||
"webkit2gtk",
|
||||
"webpki-roots 0.26.11",
|
||||
"windows-sys 0.61.2",
|
||||
"winreg 0.52.0",
|
||||
"zip 2.4.2",
|
||||
]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.16.0"
|
||||
version = "3.16.2"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
@@ -77,6 +77,7 @@ indexmap = { version = "2", features = ["serde"] }
|
||||
rust_decimal = "1.33"
|
||||
uuid = { version = "1.11", features = ["v4"] }
|
||||
sha2 = "0.10"
|
||||
hmac = "0.12"
|
||||
json5 = "0.4"
|
||||
json-five = "0.3.1"
|
||||
|
||||
@@ -88,6 +89,7 @@ webkit2gtk = { version = "2.0.1", features = ["v2_16"] }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winreg = "0.52"
|
||||
windows-sys = { version = "0.61", features = ["Win32_Globalization", "Win32_UI_Shell"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
objc2 = "0.5"
|
||||
|
||||
@@ -664,7 +664,7 @@ pub fn model_list_response(provider: &Provider) -> Result<Value, AppError> {
|
||||
}
|
||||
|
||||
pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<Value, AppError> {
|
||||
let requested = body
|
||||
let requested_raw = body
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
@@ -677,6 +677,7 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
|
||||
"Claude Desktop request is missing the model field",
|
||||
)
|
||||
})?;
|
||||
let requested = strip_one_m_suffix_for_route_lookup(&requested_raw);
|
||||
|
||||
let routes = proxy_model_routes(provider)?;
|
||||
let upstream_model = routes
|
||||
@@ -685,20 +686,21 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
|
||||
.or_else(|| {
|
||||
routes
|
||||
.iter()
|
||||
.find(|r| is_compatible_opus_route_alias(&r.route_id, &requested))
|
||||
.find(|r| is_compatible_opus_route_alias(&r.route_id, requested))
|
||||
})
|
||||
.map(|route| route.upstream_model.clone())
|
||||
.or_else(|| legacy_raw_route_upstream_model(provider, &requested))
|
||||
.or_else(|| legacy_raw_route_upstream_model(provider, requested))
|
||||
.or_else(|| {
|
||||
// 角色关键词回落:Claude Desktop 的部分调用(如子 agent)会请求带发布
|
||||
// 日期后缀的完整官方名(claude-haiku-4-5-20251001),与 manifest 暴露的
|
||||
// 简短 route_id(claude-haiku-4-5)不精确相等。按 opus/haiku/sonnet 归类
|
||||
// 到同档已配置路由,对齐 Claude Code model_mapper 的宽松匹配。
|
||||
// 仅对 Claude Desktop 认可的安全模型名回落(排除 [1m] 标记等非法形式)。
|
||||
if !is_claude_safe_model_id(&requested) {
|
||||
// 匹配前已剥离本地 [1m] 标记;这里仍只对 Claude Desktop 认可的
|
||||
// 安全模型名回落,避免非 Claude route 被误映射。
|
||||
if !is_claude_safe_model_id(requested) {
|
||||
return None;
|
||||
}
|
||||
let role = claude_role_keyword(&requested)?;
|
||||
let role = claude_role_keyword(requested)?;
|
||||
routes
|
||||
.iter()
|
||||
.find(|route| claude_role_keyword(&route.route_id) == Some(role))
|
||||
@@ -707,8 +709,8 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
|
||||
.ok_or_else(|| {
|
||||
AppError::localized(
|
||||
"claude_desktop.provider.route_unknown",
|
||||
format!("Claude Desktop 模型路由未配置: {requested}"),
|
||||
format!("Claude Desktop model route is not configured: {requested}"),
|
||||
format!("Claude Desktop 模型路由未配置: {requested_raw}"),
|
||||
format!("Claude Desktop model route is not configured: {requested_raw}"),
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -719,6 +721,18 @@ pub fn map_proxy_request_model(mut body: Value, provider: &Provider) -> Result<V
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn strip_one_m_suffix_for_route_lookup(model: &str) -> &str {
|
||||
let trimmed = model.trim();
|
||||
let marker = ONE_M_CONTEXT_MARKER.as_bytes();
|
||||
let bytes = trimmed.as_bytes();
|
||||
if bytes.len() >= marker.len()
|
||||
&& bytes[bytes.len() - marker.len()..].eq_ignore_ascii_case(marker)
|
||||
{
|
||||
return trimmed[..trimmed.len() - marker.len()].trim_end();
|
||||
}
|
||||
trimmed
|
||||
}
|
||||
|
||||
fn legacy_raw_route_upstream_model(provider: &Provider, requested: &str) -> Option<String> {
|
||||
provider
|
||||
.meta
|
||||
@@ -873,6 +887,11 @@ pub fn proxy_gateway_base_url_from_db(db: &Database) -> Result<String, AppError>
|
||||
// get_proxy_config is async-tagged but its body is fully synchronous (rusqlite
|
||||
// under a Mutex), so block_on cannot deadlock the calling thread.
|
||||
let config = futures::executor::block_on(db.get_proxy_config())?;
|
||||
if config.listen_port == 0 {
|
||||
return Err(AppError::Config(
|
||||
"Claude Desktop 代理地址需要真实监听端口;请先启动本地代理或使用固定端口".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(format!(
|
||||
"{}{}",
|
||||
proxy_origin_from_parts(&config.listen_address, config.listen_port),
|
||||
@@ -1290,6 +1309,12 @@ mod tests {
|
||||
Database::memory().expect("memory db")
|
||||
}
|
||||
|
||||
fn set_proxy_port(db: &Database, port: u16) {
|
||||
let mut config = crate::proxy::types::ProxyConfig::default();
|
||||
config.listen_port = port;
|
||||
futures::executor::block_on(db.update_proxy_config(config)).expect("update proxy config");
|
||||
}
|
||||
|
||||
fn direct_provider(id: &str) -> Provider {
|
||||
let mut provider = Provider::with_id(
|
||||
id.to_string(),
|
||||
@@ -1310,6 +1335,19 @@ mod tests {
|
||||
provider
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_gateway_base_url_rejects_unresolved_ephemeral_port() {
|
||||
let db = test_db();
|
||||
set_proxy_port(&db, 0);
|
||||
|
||||
let err = proxy_gateway_base_url_from_db(&db)
|
||||
.expect_err("unresolved ephemeral port should not produce a :0 URL");
|
||||
assert!(
|
||||
err.to_string().contains("真实监听端口"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
fn official_provider() -> Provider {
|
||||
let mut provider = Provider::with_id(
|
||||
CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID.to_string(),
|
||||
@@ -1820,15 +1858,48 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_desktop_proxy_rejects_1m_suffix_route() {
|
||||
let provider = proxy_provider("proxy");
|
||||
fn claude_desktop_proxy_strips_1m_suffix_before_route_lookup() {
|
||||
let mut provider = proxy_provider("proxy");
|
||||
provider
|
||||
.meta
|
||||
.as_mut()
|
||||
.expect("meta")
|
||||
.claude_desktop_model_routes = std::collections::HashMap::from([
|
||||
(
|
||||
"claude-sonnet-4-6".to_string(),
|
||||
ClaudeDesktopModelRoute {
|
||||
model: "upstream-sonnet".to_string(),
|
||||
label_override: None,
|
||||
supports_1m: Some(true),
|
||||
},
|
||||
),
|
||||
(
|
||||
"claude-opus-4-8".to_string(),
|
||||
ClaudeDesktopModelRoute {
|
||||
model: "upstream-opus".to_string(),
|
||||
label_override: None,
|
||||
supports_1m: Some(true),
|
||||
},
|
||||
),
|
||||
]);
|
||||
|
||||
let err = map_proxy_request_model(
|
||||
let mapped = map_proxy_request_model(
|
||||
json!({"model": "claude-opus-4-8[1m]", "messages": []}),
|
||||
&provider,
|
||||
)
|
||||
.expect("compact 1M suffix should map to Opus route");
|
||||
assert_eq!(mapped["model"], json!("upstream-opus"));
|
||||
|
||||
let mapped = map_proxy_request_model(
|
||||
json!({"model": "claude-sonnet-4-6 [1M]", "messages": []}),
|
||||
&provider,
|
||||
)
|
||||
.expect_err("1M suffix route should not be accepted");
|
||||
assert!(err.to_string().contains("claude-sonnet-4-6 [1M]"));
|
||||
.expect("spaced uppercase 1M suffix should map to Sonnet route");
|
||||
assert_eq!(mapped["model"], json!("upstream-sonnet"));
|
||||
|
||||
let err = map_proxy_request_model(json!({"model": "gpt-5[1m]", "messages": []}), &provider)
|
||||
.expect_err("non-Claude route should still fail after stripping 1M suffix");
|
||||
assert!(err.to_string().contains("gpt-5[1m]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1947,12 +2018,13 @@ mod tests {
|
||||
let direct = direct_provider("direct");
|
||||
assert!(is_compatible_direct_provider(&direct));
|
||||
|
||||
let claude_official = Provider::with_id(
|
||||
let mut claude_official = Provider::with_id(
|
||||
"claude-official".to_string(),
|
||||
"Claude Official".to_string(),
|
||||
json!({"env": {}}),
|
||||
Some("https://www.anthropic.com/claude-code".to_string()),
|
||||
);
|
||||
claude_official.category = Some("official".to_string());
|
||||
assert!(!is_compatible_direct_provider(&claude_official));
|
||||
|
||||
let mut openai_format = direct_provider("openai");
|
||||
|
||||
+505
-50
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::{
|
||||
@@ -204,6 +205,29 @@ pub fn extract_codex_api_key(auth: Option<&Value>, config_text: Option<&str>) ->
|
||||
.or_else(|| config_text.and_then(extract_codex_experimental_bearer_token))
|
||||
}
|
||||
|
||||
/// Extract the upstream base URL from a Codex `config.toml` string.
|
||||
///
|
||||
/// Prefers the active `[model_providers.<model_provider>].base_url`, falling
|
||||
/// back to a top-level `base_url` when no model provider is selected.
|
||||
pub fn extract_codex_base_url(config_text: &str) -> Option<String> {
|
||||
let doc = config_text.parse::<toml::Value>().ok()?;
|
||||
|
||||
if let Some(active_provider) = doc.get("model_provider").and_then(|v| v.as_str()) {
|
||||
if let Some(base_url) = doc
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(active_provider))
|
||||
.and_then(|provider| provider.get("base_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return Some(base_url.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
doc.get("base_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
pub fn codex_auth_has_login_material(auth: &Value) -> bool {
|
||||
let Some(obj) = auth.as_object() else {
|
||||
return false;
|
||||
@@ -393,39 +417,227 @@ fn load_codex_model_template_from_cache() -> Result<Option<Value>, AppError> {
|
||||
Ok(find_codex_model_template(&catalog))
|
||||
}
|
||||
|
||||
fn load_codex_model_template_from_bundled() -> Result<Option<Value>, AppError> {
|
||||
let output = match Command::new("codex")
|
||||
.args(["debug", "models", "--bundled"])
|
||||
.output()
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
log::debug!("failed to run `codex debug models --bundled`: {err}");
|
||||
return Ok(None);
|
||||
}
|
||||
/// Fixed candidates for locating the `codex` CLI when it is not on the process
|
||||
/// PATH (common in GUI apps launched outside a terminal).
|
||||
const CODEX_CLI_FIXED_CANDIDATES: &[&str] = &[
|
||||
"codex", // PATH (all platforms)
|
||||
"/opt/homebrew/bin/codex", // macOS Apple Silicon Homebrew
|
||||
"/usr/local/bin/codex", // macOS Intel Homebrew / Linux
|
||||
"/home/linuxbrew/.linuxbrew/bin/codex", // Linux Homebrew
|
||||
];
|
||||
|
||||
fn push_codex_cli_candidate(
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
seen: &mut HashSet<String>,
|
||||
candidate: PathBuf,
|
||||
) {
|
||||
let key = candidate.to_string_lossy().into_owned();
|
||||
if seen.insert(key) {
|
||||
candidates.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_existing_codex_cli_candidate(
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
seen: &mut HashSet<String>,
|
||||
candidate: PathBuf,
|
||||
) {
|
||||
if candidate.exists() {
|
||||
push_codex_cli_candidate(candidates, seen, candidate);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_codex_cli_candidates_from_version_dirs(
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
seen: &mut HashSet<String>,
|
||||
versions_dir: PathBuf,
|
||||
suffix: &[&str],
|
||||
) {
|
||||
let Ok(entries) = fs::read_dir(versions_dir) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log::debug!("`codex debug models --bundled` failed: {stderr}");
|
||||
return Ok(None);
|
||||
let mut discovered = entries
|
||||
.filter_map(Result::ok)
|
||||
.map(|entry| {
|
||||
let mut candidate = entry.path();
|
||||
for component in suffix {
|
||||
candidate.push(component);
|
||||
}
|
||||
candidate
|
||||
})
|
||||
.filter(|candidate| candidate.exists())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Prefer newer-looking version directories before older global installs.
|
||||
discovered.sort_by(|a, b| b.cmp(a));
|
||||
for candidate in discovered {
|
||||
push_codex_cli_candidate(candidates, seen, candidate);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_home_codex_cli_candidates(
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
seen: &mut HashSet<String>,
|
||||
home: &Path,
|
||||
) {
|
||||
for relative in [
|
||||
".nvm/current/bin/codex",
|
||||
".volta/bin/codex",
|
||||
".asdf/shims/codex",
|
||||
".local/share/mise/shims/codex",
|
||||
".config/mise/shims/codex",
|
||||
".local/bin/codex",
|
||||
".npm-global/bin/codex",
|
||||
".npm-packages/bin/codex",
|
||||
".local/share/pnpm/codex",
|
||||
"Library/pnpm/codex",
|
||||
] {
|
||||
push_existing_codex_cli_candidate(candidates, seen, home.join(relative));
|
||||
}
|
||||
|
||||
let catalog: Value = serde_json::from_slice(&output.stdout).map_err(|e| {
|
||||
AppError::Message(format!(
|
||||
"Failed to parse `codex debug models --bundled` output: {e}"
|
||||
))
|
||||
})?;
|
||||
Ok(find_codex_model_template(&catalog))
|
||||
push_codex_cli_candidates_from_version_dirs(
|
||||
candidates,
|
||||
seen,
|
||||
home.join(".nvm/versions/node"),
|
||||
&["bin", "codex"],
|
||||
);
|
||||
push_codex_cli_candidates_from_version_dirs(
|
||||
candidates,
|
||||
seen,
|
||||
home.join(".local/share/fnm/node-versions"),
|
||||
&["installation", "bin", "codex"],
|
||||
);
|
||||
push_codex_cli_candidates_from_version_dirs(
|
||||
candidates,
|
||||
seen,
|
||||
home.join("Library/Application Support/fnm/node-versions"),
|
||||
&["installation", "bin", "codex"],
|
||||
);
|
||||
}
|
||||
|
||||
fn push_env_codex_cli_candidates(candidates: &mut Vec<PathBuf>, seen: &mut HashSet<String>) {
|
||||
for (env_key, suffix) in [
|
||||
("NPM_CONFIG_PREFIX", &["bin", "codex"][..]),
|
||||
("VOLTA_HOME", &["bin", "codex"][..]),
|
||||
("ASDF_DATA_DIR", &["shims", "codex"][..]),
|
||||
("MISE_DATA_DIR", &["shims", "codex"][..]),
|
||||
("PNPM_HOME", &["codex"][..]),
|
||||
] {
|
||||
let Some(prefix) = std::env::var_os(env_key) else {
|
||||
continue;
|
||||
};
|
||||
let mut candidate = PathBuf::from(prefix);
|
||||
for component in suffix {
|
||||
candidate.push(component);
|
||||
}
|
||||
push_existing_codex_cli_candidate(candidates, seen, candidate);
|
||||
}
|
||||
|
||||
if let Some(nvm_dir) = std::env::var_os("NVM_DIR") {
|
||||
push_codex_cli_candidates_from_version_dirs(
|
||||
candidates,
|
||||
seen,
|
||||
PathBuf::from(nvm_dir).join("versions/node"),
|
||||
&["bin", "codex"],
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(fnm_dir) = std::env::var_os("FNM_DIR") {
|
||||
push_codex_cli_candidates_from_version_dirs(
|
||||
candidates,
|
||||
seen,
|
||||
PathBuf::from(fnm_dir).join("node-versions"),
|
||||
&["installation", "bin", "codex"],
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if let Some(appdata) = std::env::var_os("APPDATA") {
|
||||
let npm_dir = PathBuf::from(appdata).join("npm");
|
||||
for name in ["codex.cmd", "codex.exe", "codex"] {
|
||||
push_existing_codex_cli_candidate(candidates, seen, npm_dir.join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_cli_candidates() -> Vec<PathBuf> {
|
||||
let mut candidates = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
for candidate in CODEX_CLI_FIXED_CANDIDATES {
|
||||
push_codex_cli_candidate(&mut candidates, &mut seen, PathBuf::from(candidate));
|
||||
}
|
||||
|
||||
push_env_codex_cli_candidates(&mut candidates, &mut seen);
|
||||
push_home_codex_cli_candidates(&mut candidates, &mut seen, &get_home_dir());
|
||||
|
||||
candidates
|
||||
}
|
||||
|
||||
fn load_codex_model_template_from_bundled() -> Result<Option<Value>, AppError> {
|
||||
for candidate in codex_cli_candidates() {
|
||||
let candidate_label = candidate.to_string_lossy();
|
||||
let output = match Command::new(&candidate)
|
||||
.args(["debug", "models", "--bundled"])
|
||||
.output()
|
||||
{
|
||||
Ok(output) => output,
|
||||
Err(err) => {
|
||||
log::debug!("failed to run `{candidate_label} debug models --bundled`: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
log::debug!("`{candidate_label} debug models --bundled` failed: {stderr}");
|
||||
continue;
|
||||
}
|
||||
|
||||
let catalog: Value = match serde_json::from_slice(&output.stdout) {
|
||||
Ok(catalog) => catalog,
|
||||
Err(e) => {
|
||||
log::debug!(
|
||||
"Failed to parse `{candidate_label} debug models --bundled` output: {e}"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(template) = find_codex_model_template(&catalog) {
|
||||
return Ok(Some(template));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn load_codex_model_template_static() -> Option<Value> {
|
||||
let text = include_str!("resources/gpt5_5_template.json");
|
||||
match serde_json::from_str(text) {
|
||||
Ok(template) => Some(template),
|
||||
Err(e) => {
|
||||
log::warn!("Failed to parse bundled gpt-5.5 template: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_codex_model_catalog_template() -> Result<Value, AppError> {
|
||||
// ① models_cache.json (created by Codex when it connects to OpenAI)
|
||||
if let Some(template) = load_codex_model_template_from_cache()? {
|
||||
return Ok(template);
|
||||
}
|
||||
// ② codex CLI (PATH + platform-specific common paths)
|
||||
if let Some(template) = load_codex_model_template_from_bundled()? {
|
||||
return Ok(template);
|
||||
}
|
||||
// ③ Static fallback bundled at compile time
|
||||
if let Some(template) = load_codex_model_template_static() {
|
||||
return Ok(template);
|
||||
}
|
||||
|
||||
Err(AppError::Message(format!(
|
||||
"Codex model catalog template `{CODEX_MODEL_CATALOG_TEMPLATE_SLUG}` not found. Please start Codex once so models_cache.json is available, or ensure the `codex` CLI is on PATH."
|
||||
@@ -470,20 +682,18 @@ fn set_codex_model_catalog_json_field(
|
||||
let mut doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
|
||||
let generated_path = get_codex_model_catalog_path();
|
||||
|
||||
match catalog_path {
|
||||
Some(path) => {
|
||||
doc["model_catalog_json"] = toml_edit::value(path.to_string_lossy().as_ref());
|
||||
Some(_) => {
|
||||
doc["model_catalog_json"] = toml_edit::value(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
|
||||
}
|
||||
None => {
|
||||
let should_remove = doc
|
||||
.get("model_catalog_json")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(|path| {
|
||||
path == generated_path.to_string_lossy().as_ref()
|
||||
|| Path::new(path).file_name().and_then(|name| name.to_str())
|
||||
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
|
||||
Path::new(path).file_name().and_then(|name| name.to_str())
|
||||
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if should_remove {
|
||||
@@ -556,7 +766,10 @@ pub fn read_codex_model_catalog_simplified_from_live() -> Result<Option<Value>,
|
||||
/// Given `config.toml` text, resolve the on-disk path of the cc-switch–owned
|
||||
/// catalog file (returns `None` if `model_catalog_json` is absent or points at
|
||||
/// a file we don't own). Relative paths fall back to `generated_path`.
|
||||
fn resolve_cc_switch_catalog_path(config_text: &str, generated_path: &Path) -> Option<PathBuf> {
|
||||
pub(crate) fn resolve_cc_switch_catalog_path(
|
||||
config_text: &str,
|
||||
generated_path: &Path,
|
||||
) -> Option<PathBuf> {
|
||||
if config_text.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -568,9 +781,8 @@ fn resolve_cc_switch_catalog_path(config_text: &str, generated_path: &Path) -> O
|
||||
.filter(|s| !s.is_empty())?;
|
||||
|
||||
let referenced_path = Path::new(catalog_path_str);
|
||||
let is_cc_switch_owned = catalog_path_str == generated_path.to_string_lossy().as_ref()
|
||||
|| referenced_path.file_name().and_then(|name| name.to_str())
|
||||
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
|
||||
let is_cc_switch_owned = referenced_path.file_name().and_then(|name| name.to_str())
|
||||
== Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME);
|
||||
if !is_cc_switch_owned {
|
||||
return None;
|
||||
}
|
||||
@@ -634,18 +846,39 @@ fn build_simplified_catalog_from_texts(config_text: &str, catalog_text: &str) ->
|
||||
Some(json!({ "models": entries }))
|
||||
}
|
||||
|
||||
/// Unified helper: write Codex live config with model catalog preparation.
|
||||
/// Replaces scattered `prepare_codex_config_text_with_model_catalog` calls.
|
||||
pub fn write_codex_live_with_catalog(
|
||||
/// Decide the `config.toml` text to write during a takeover-off restore,
|
||||
/// projecting the model catalog **only when `settings` carries an inline
|
||||
/// `modelCatalog`**.
|
||||
///
|
||||
/// Restore feeds back a stored backup, and Codex backups come in two shapes that
|
||||
/// need opposite handling:
|
||||
///
|
||||
/// - **Snapshot backup** (`read_codex_live_settings`): `{ auth, config }` with no
|
||||
/// inline `modelCatalog`. Its `config.toml` text already carries whatever
|
||||
/// `model_catalog_json` pointer existed at backup time, and the generated
|
||||
/// catalog file on disk is untouched. Here we must keep the config **raw** —
|
||||
/// running catalog projection would see "no specs" and strip the live pointer.
|
||||
/// - **Provider-rebuilt backup** (`update_live_backup_from_provider`): the DB
|
||||
/// provider's settings, i.e. `{ auth, config (no pointer), modelCatalog
|
||||
/// (inline DB SSOT) }`. Here the pointer/catalog file must be (re)generated
|
||||
/// from the inline `modelCatalog`, or the mapping is lost on restore.
|
||||
///
|
||||
/// Gating on the presence of the inline `modelCatalog` key routes each shape
|
||||
/// correctly; an empty inline catalog still projects (and so correctly drops a
|
||||
/// now-stale pointer), while an absent key leaves the text untouched. This is
|
||||
/// **orthogonal to auth** — a provider-rebuilt backup can pair an inline
|
||||
/// `modelCatalog` with empty `auth.json` (the API key living in the config's
|
||||
/// `experimental_bearer_token`), so the caller must decide config projection
|
||||
/// independently of whether it writes or deletes `auth.json`.
|
||||
pub fn prepare_codex_live_config_text_with_optional_catalog(
|
||||
settings: &Value,
|
||||
auth: &Value,
|
||||
config_text: Option<&str>,
|
||||
) -> Result<(), AppError> {
|
||||
let prepared_config = config_text
|
||||
.map(|text| prepare_codex_config_text_with_model_catalog(settings, text))
|
||||
.transpose()?;
|
||||
|
||||
write_codex_live_atomic(auth, prepared_config.as_deref())
|
||||
config_text: &str,
|
||||
) -> Result<String, AppError> {
|
||||
if settings.get("modelCatalog").is_some() {
|
||||
prepare_codex_config_text_with_model_catalog(settings, config_text)
|
||||
} else {
|
||||
Ok(config_text.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_codex_provider_live_with_catalog(
|
||||
@@ -739,7 +972,10 @@ fn set_codex_experimental_bearer_token(config_text: &str, token: &str) -> Result
|
||||
Ok(doc.to_string())
|
||||
}
|
||||
|
||||
fn remove_codex_experimental_bearer_token(config_text: &str) -> Result<String, AppError> {
|
||||
pub fn remove_codex_experimental_bearer_token_if(
|
||||
config_text: &str,
|
||||
predicate: impl Fn(&str) -> bool,
|
||||
) -> Result<String, AppError> {
|
||||
if config_text.trim().is_empty() || !config_text.contains("experimental_bearer_token") {
|
||||
return Ok(config_text.to_string());
|
||||
}
|
||||
@@ -755,14 +991,32 @@ fn remove_codex_experimental_bearer_token(config_text: &str) -> Result<String, A
|
||||
.and_then(|table| table.get_mut(provider_id.as_str()))
|
||||
.and_then(|item| item.as_table_mut())
|
||||
{
|
||||
provider_table.remove("experimental_bearer_token");
|
||||
let should_remove = provider_table
|
||||
.get("experimental_bearer_token")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::trim)
|
||||
.is_some_and(&predicate);
|
||||
if should_remove {
|
||||
provider_table.remove("experimental_bearer_token");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
doc.as_table_mut().remove("experimental_bearer_token");
|
||||
let should_remove_top_level = doc
|
||||
.get("experimental_bearer_token")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::trim)
|
||||
.is_some_and(&predicate);
|
||||
if should_remove_top_level {
|
||||
doc.as_table_mut().remove("experimental_bearer_token");
|
||||
}
|
||||
Ok(doc.to_string())
|
||||
}
|
||||
|
||||
fn remove_codex_experimental_bearer_token(config_text: &str) -> Result<String, AppError> {
|
||||
remove_codex_experimental_bearer_token_if(config_text, |_| true)
|
||||
}
|
||||
|
||||
/// Read the current Codex live settings as a `{ auth, config }` object.
|
||||
///
|
||||
/// Missing `auth.json` collapses to `{}` so a config-only third-party install
|
||||
@@ -788,15 +1042,19 @@ pub fn read_codex_live_settings() -> Result<Value, AppError> {
|
||||
|
||||
/// Route a Codex live write between full auth+config or config-only.
|
||||
///
|
||||
/// Official providers with usable login material own `auth.json`; everyone
|
||||
/// else only touches `config.toml` so the user's ChatGPT login cache survives
|
||||
/// third-party switches.
|
||||
/// Official providers with usable login material own `auth.json`. Third-party
|
||||
/// providers only touch `config.toml` when the compatibility setting is enabled
|
||||
/// so the user's ChatGPT login cache survives provider switches.
|
||||
pub fn write_codex_live_for_provider(
|
||||
category: Option<&str>,
|
||||
auth: &Value,
|
||||
config_text: Option<&str>,
|
||||
) -> Result<(), AppError> {
|
||||
if category == Some("official") && codex_auth_has_login_material(auth) {
|
||||
let should_write_auth = (category == Some("official") && codex_auth_has_login_material(auth))
|
||||
|| (category != Some("official")
|
||||
&& !crate::settings::preserve_codex_official_auth_on_switch());
|
||||
|
||||
if should_write_auth {
|
||||
write_codex_live_atomic(auth, config_text)
|
||||
} else {
|
||||
let live_config = prepare_codex_provider_live_config(auth, config_text.unwrap_or(""))?;
|
||||
@@ -1533,7 +1791,7 @@ base_url = "https://production.api/v1"
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_catalog_json_field_operates_on_top_level() {
|
||||
fn model_catalog_json_field_writes_relative_filename() {
|
||||
let input = r#"model_provider = "any"
|
||||
|
||||
[model_providers.any]
|
||||
@@ -1547,7 +1805,7 @@ name = "any"
|
||||
parsed
|
||||
.get("model_catalog_json")
|
||||
.and_then(|value| value.as_str()),
|
||||
Some("/tmp/cc-switch-model-catalog.json")
|
||||
Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME)
|
||||
);
|
||||
assert!(
|
||||
parsed
|
||||
@@ -1677,4 +1935,201 @@ name = "any"
|
||||
"entries lacking slug are skipped; a fully-skipped catalog yields None"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_cli_candidates_are_non_empty() {
|
||||
let candidates = codex_cli_candidates();
|
||||
assert!(
|
||||
candidates
|
||||
.iter()
|
||||
.any(|candidate| candidate == Path::new("codex")),
|
||||
"codex CLI candidates must include the PATH entry"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_cli_candidates_include_user_node_manager_bins() {
|
||||
let temp_home = tempfile::tempdir().expect("create temp home");
|
||||
let home = temp_home.path();
|
||||
let expected = [
|
||||
home.join(".nvm/versions/node/v22.14.0/bin/codex"),
|
||||
home.join(".volta/bin/codex"),
|
||||
home.join(".asdf/shims/codex"),
|
||||
home.join(".local/share/mise/shims/codex"),
|
||||
home.join(".local/share/fnm/node-versions/v22.14.0/installation/bin/codex"),
|
||||
];
|
||||
|
||||
for candidate in &expected {
|
||||
std::fs::create_dir_all(candidate.parent().expect("candidate parent"))
|
||||
.expect("create candidate parent");
|
||||
std::fs::write(candidate, "").expect("create candidate");
|
||||
}
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
push_home_codex_cli_candidates(&mut candidates, &mut seen, home);
|
||||
|
||||
for candidate in expected {
|
||||
assert!(
|
||||
candidates.contains(&candidate),
|
||||
"user-level Codex CLI candidate should be discovered: {}",
|
||||
candidate.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_cli_candidates_deduplicate_entries() {
|
||||
let temp_home = tempfile::tempdir().expect("create temp home");
|
||||
let home = temp_home.path();
|
||||
let candidate = home.join(".volta/bin/codex");
|
||||
std::fs::create_dir_all(candidate.parent().expect("candidate parent"))
|
||||
.expect("create candidate parent");
|
||||
std::fs::write(&candidate, "").expect("create candidate");
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
push_existing_codex_cli_candidate(&mut candidates, &mut seen, candidate.clone());
|
||||
push_home_codex_cli_candidates(&mut candidates, &mut seen, home);
|
||||
|
||||
assert_eq!(
|
||||
candidates.iter().filter(|path| **path == candidate).count(),
|
||||
1,
|
||||
"duplicate candidates should be removed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_template_is_valid_json_with_slug() {
|
||||
let template =
|
||||
load_codex_model_template_static().expect("static template must parse as valid JSON");
|
||||
assert_eq!(
|
||||
template.get("slug").and_then(|v| v.as_str()),
|
||||
Some("gpt-5.5"),
|
||||
"static template slug must be gpt-5.5"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_template_has_required_keys() {
|
||||
let template =
|
||||
load_codex_model_template_static().expect("static template must parse as valid JSON");
|
||||
for key in &[
|
||||
"model_messages",
|
||||
"base_instructions",
|
||||
"context_window",
|
||||
"display_name",
|
||||
] {
|
||||
assert!(
|
||||
template.get(key).is_some(),
|
||||
"static template must contain key '{key}'"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_catalog_json_field_writes_filename_ignoring_unc_path() {
|
||||
let input = r#"model_provider = "custom"
|
||||
model = "glm-5"
|
||||
"#;
|
||||
// Simulate a WSL UNC path as cc-switch would see it on Windows;
|
||||
// the function now writes just the relative filename.
|
||||
let unc_path =
|
||||
Path::new(r"\\wsl.localhost\Ubuntu\home\user\.codex\cc-switch-model-catalog.json");
|
||||
|
||||
let result = set_codex_model_catalog_json_field(input, Some(unc_path)).unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
let written_path = parsed
|
||||
.get("model_catalog_json")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("model_catalog_json should be set");
|
||||
assert_eq!(
|
||||
written_path, CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME,
|
||||
"should write only the relative filename, not the UNC path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_catalog_json_field_writes_filename_for_any_path() {
|
||||
let input = r#"model_provider = "custom"
|
||||
model = "glm-5"
|
||||
"#;
|
||||
let regular_path = Path::new("/home/user/.codex/cc-switch-model-catalog.json");
|
||||
|
||||
let result = set_codex_model_catalog_json_field(input, Some(regular_path)).unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
parsed.get("model_catalog_json").and_then(|v| v.as_str()),
|
||||
Some(CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME),
|
||||
"should write only the relative filename, not the full path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_catalog_json_none_removes_cc_switch_owned_by_filename() {
|
||||
// After the WSL fix, TOML may contain a Linux-style path.
|
||||
// The None arm must still remove it (file_name match catches any format).
|
||||
let input = r#"model_catalog_json = "/home/user/.codex/cc-switch-model-catalog.json"
|
||||
"#;
|
||||
let result = set_codex_model_catalog_json_field(input, None).unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
assert!(
|
||||
parsed.get("model_catalog_json").is_none(),
|
||||
"None arm should remove cc-switch-owned field regardless of path format"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_catalog_json_none_preserves_user_owned_catalog() {
|
||||
let input = r#"model_catalog_json = "/Users/me/.codex/my-custom-catalog.json"
|
||||
"#;
|
||||
let result = set_codex_model_catalog_json_field(input, None).unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
assert_eq!(
|
||||
parsed.get("model_catalog_json").and_then(|v| v.as_str()),
|
||||
Some("/Users/me/.codex/my-custom-catalog.json"),
|
||||
"None arm should NOT remove user-owned catalog"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_catalog_finds_relative_filename() {
|
||||
let config_text = r#"model_provider = "custom"
|
||||
model_catalog_json = "cc-switch-model-catalog.json"
|
||||
"#;
|
||||
let generated_path = PathBuf::from("/home/user/.codex/cc-switch-model-catalog.json");
|
||||
let result = resolve_cc_switch_catalog_path(config_text, &generated_path);
|
||||
assert_eq!(
|
||||
result,
|
||||
Some(generated_path),
|
||||
"relative filename should resolve to generated_path for file I/O"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_catalog_ignores_user_owned_relative() {
|
||||
let config_text = r#"model_catalog_json = "my-custom-catalog.json"
|
||||
"#;
|
||||
let generated_path = PathBuf::from("/home/user/.codex/cc-switch-model-catalog.json");
|
||||
let result = resolve_cc_switch_catalog_path(config_text, &generated_path);
|
||||
assert_eq!(
|
||||
result, None,
|
||||
"user-owned catalog should not be claimed by cc-switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_catalog_json_none_removes_relative_path() {
|
||||
let input = r#"model_catalog_json = "cc-switch-model-catalog.json"
|
||||
"#;
|
||||
let result = set_codex_model_catalog_json_field(input, None).unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&result).unwrap();
|
||||
assert!(
|
||||
parsed.get("model_catalog_json").is_none(),
|
||||
"None arm should remove relative cc-switch-owned field"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+133
-35
@@ -249,8 +249,8 @@ fn finish_lifecycle_output(output: &std::process::Output) -> Result<(), String>
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
let stdout = decode_command_output(&output.stdout);
|
||||
let raw = if stderr.trim().is_empty() {
|
||||
stdout.trim()
|
||||
} else {
|
||||
@@ -271,6 +271,81 @@ fn last_lines(text: &str, n: usize) -> String {
|
||||
lines[start..].join("\n")
|
||||
}
|
||||
|
||||
fn decode_command_output(bytes: &[u8]) -> String {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
decode_windows_command_output(bytes)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn decode_windows_command_output(bytes: &[u8]) -> String {
|
||||
if bytes.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
if let Ok(text) = std::str::from_utf8(bytes) {
|
||||
return text.to_string();
|
||||
}
|
||||
|
||||
use windows_sys::Win32::Globalization::{GetACP, GetOEMCP, MultiByteToWideChar};
|
||||
|
||||
fn decode_codepage(bytes: &[u8], codepage: u32) -> Option<String> {
|
||||
if codepage == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let input_len = i32::try_from(bytes.len()).ok()?;
|
||||
unsafe {
|
||||
let wide_len = MultiByteToWideChar(
|
||||
codepage,
|
||||
0,
|
||||
bytes.as_ptr(),
|
||||
input_len,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
if wide_len <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut wide = vec![0u16; wide_len as usize];
|
||||
let written = MultiByteToWideChar(
|
||||
codepage,
|
||||
0,
|
||||
bytes.as_ptr(),
|
||||
input_len,
|
||||
wide.as_mut_ptr(),
|
||||
wide_len,
|
||||
);
|
||||
if written <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(String::from_utf16_lossy(&wide[..written as usize]))
|
||||
}
|
||||
}
|
||||
|
||||
let oem_cp = unsafe { GetOEMCP() };
|
||||
if let Some(decoded) = decode_codepage(bytes, oem_cp) {
|
||||
return decoded;
|
||||
}
|
||||
|
||||
let ansi_cp = unsafe { GetACP() };
|
||||
if ansi_cp != oem_cp {
|
||||
if let Some(decoded) = decode_codepage(bytes, ansi_cp) {
|
||||
return decoded;
|
||||
}
|
||||
}
|
||||
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
fn normalize_requested_tools(tools: &[String]) -> Vec<&'static str> {
|
||||
let set: std::collections::HashSet<&str> = tools.iter().map(|s| s.as_str()).collect();
|
||||
VALID_TOOLS
|
||||
@@ -936,8 +1011,8 @@ fn try_get_version(tool: &str) -> ShellProbe {
|
||||
|
||||
match output {
|
||||
Ok(out) => {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
let stdout = decode_command_output(&out.stdout).trim().to_string();
|
||||
let stderr = decode_command_output(&out.stderr).trim().to_string();
|
||||
if out.status.success() {
|
||||
let raw = if stdout.is_empty() { &stderr } else { &stdout };
|
||||
if raw.is_empty() {
|
||||
@@ -1051,8 +1126,8 @@ fn try_get_version_wsl(
|
||||
|
||||
match output {
|
||||
Ok(out) => {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
let stdout = decode_command_output(&out.stdout).trim().to_string();
|
||||
let stderr = decode_command_output(&out.stderr).trim().to_string();
|
||||
if out.status.success() {
|
||||
let raw = if stdout.is_empty() { &stderr } else { &stdout };
|
||||
if raw.is_empty() {
|
||||
@@ -1431,8 +1506,43 @@ fn build_tool_search_paths(tool: &str) -> Vec<std::path::PathBuf> {
|
||||
search_paths
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn is_windows_command_script(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.map(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat"))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn run_windows_tool_version_command(
|
||||
tool_path: &Path,
|
||||
new_path: &str,
|
||||
) -> std::io::Result<std::process::Output> {
|
||||
use std::process::Command;
|
||||
|
||||
if is_windows_command_script(tool_path) {
|
||||
let path = tool_path.to_string_lossy();
|
||||
let command = format!("call {} --version", win_quote_path_for_batch(&path));
|
||||
let mut cmd = Command::new("cmd");
|
||||
return cmd
|
||||
.args(["/D", "/S", "/C"])
|
||||
.raw_arg(&command)
|
||||
.env("PATH", new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output();
|
||||
}
|
||||
|
||||
Command::new(tool_path)
|
||||
.arg("--version")
|
||||
.env("PATH", new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
}
|
||||
|
||||
/// 扫描常见路径查找 CLI(PATH 主命令未命中时的兜底单探)。
|
||||
fn scan_cli_version(tool: &str) -> ShellProbe {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use std::process::Command;
|
||||
|
||||
let search_paths = build_tool_search_paths(tool);
|
||||
@@ -1458,13 +1568,7 @@ fn scan_cli_version(tool: &str) -> ShellProbe {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let output = {
|
||||
Command::new("cmd")
|
||||
.args(["/C", &format!("\"{}\" --version", tool_path.display())])
|
||||
.env("PATH", &new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
};
|
||||
let output = run_windows_tool_version_command(&tool_path, &new_path);
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let output = {
|
||||
@@ -1475,8 +1579,8 @@ fn scan_cli_version(tool: &str) -> ShellProbe {
|
||||
};
|
||||
|
||||
if let Ok(out) = output {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
let stdout = decode_command_output(&out.stdout).trim().to_string();
|
||||
let stderr = decode_command_output(&out.stderr).trim().to_string();
|
||||
if out.status.success() {
|
||||
let raw = if stdout.is_empty() { &stderr } else { &stdout };
|
||||
if !raw.is_empty() {
|
||||
@@ -1588,7 +1692,7 @@ fn resolve_path_default(tool: &str) -> Option<std::path::PathBuf> {
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let raw = String::from_utf8_lossy(&out.stdout);
|
||||
let raw = decode_command_output(&out.stdout);
|
||||
// 不能死取第一行:交互式 .zshrc 可能先打印欢迎语(如 "🚀 Welcome back"),
|
||||
// command -v 的真实路径在其后;取第一个 `/` 开头的行才稳。
|
||||
let first = first_abs_path_line(&raw)?;
|
||||
@@ -1607,7 +1711,7 @@ fn resolve_path_default(tool: &str) -> Option<std::path::PathBuf> {
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let raw = String::from_utf8_lossy(&out.stdout);
|
||||
let raw = decode_command_output(&out.stdout);
|
||||
let first = raw.lines().next()?.trim();
|
||||
if first.is_empty() {
|
||||
return None;
|
||||
@@ -1619,6 +1723,7 @@ fn resolve_path_default(tool: &str) -> Option<std::path::PathBuf> {
|
||||
/// `build_tool_search_paths`,但不在首个命中处停止——而是对每个去重后的真实
|
||||
/// 可执行文件都跑一次 `--version`,从而能发现"升级写入 A 处、PATH 实际用 B 处"。
|
||||
fn enumerate_tool_installations(tool: &str) -> Vec<ToolInstallation> {
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use std::process::Command;
|
||||
|
||||
let search_paths = build_tool_search_paths(tool);
|
||||
@@ -1648,14 +1753,7 @@ fn enumerate_tool_installations(tool: &str) -> Vec<ToolInstallation> {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
let output = {
|
||||
use std::os::windows::process::CommandExt;
|
||||
Command::new("cmd")
|
||||
.args(["/C", &format!("\"{}\" --version", tool_path.display())])
|
||||
.env("PATH", &new_path)
|
||||
.creation_flags(CREATE_NO_WINDOW)
|
||||
.output()
|
||||
};
|
||||
let output = run_windows_tool_version_command(&tool_path, &new_path);
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let output = Command::new(&tool_path)
|
||||
.arg("--version")
|
||||
@@ -1664,14 +1762,14 @@ fn enumerate_tool_installations(tool: &str) -> Vec<ToolInstallation> {
|
||||
|
||||
let (version, runnable, error) = match output {
|
||||
Ok(out) if out.status.success() => {
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
let stdout = decode_command_output(&out.stdout).trim().to_string();
|
||||
let stderr = decode_command_output(&out.stderr).trim().to_string();
|
||||
let raw = if stdout.is_empty() { stderr } else { stdout };
|
||||
(Some(extract_version(&raw)), true, None)
|
||||
}
|
||||
Ok(out) => {
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
let stderr = decode_command_output(&out.stderr).trim().to_string();
|
||||
let stdout = decode_command_output(&out.stdout).trim().to_string();
|
||||
let detail = if stderr.is_empty() { stdout } else { stderr };
|
||||
let detail = detail.trim();
|
||||
let error = if detail.is_empty() {
|
||||
@@ -2542,7 +2640,7 @@ end tell"#,
|
||||
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"Terminal.app 执行失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
@@ -2603,7 +2701,7 @@ fn launch_macos_iterm2(script_file: &std::path::Path) -> Result<(), String> {
|
||||
.map_err(|e| format!("执行 osascript 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"iTerm2 执行失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
@@ -2633,7 +2731,7 @@ fn launch_macos_ghostty(script_file: &std::path::Path) -> Result<(), String> {
|
||||
.map_err(|e| format!("启动 Ghostty 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"Ghostty 启动失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
@@ -2666,7 +2764,7 @@ fn launch_macos_open_app(
|
||||
.map_err(|e| format!("启动 {app_name} 失败: {e}"))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"{} 启动失败 (exit code: {:?}): {}",
|
||||
app_name,
|
||||
@@ -2718,7 +2816,7 @@ fn launch_macos_warp(script_file: &std::path::Path) -> Result<(), String> {
|
||||
|
||||
let output = cmd.output().map_err(|e| format!("启动 Warp 失败: {e}"))?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"Warp 启动失败 (exit code: {:?}): {}",
|
||||
output.status.code(),
|
||||
@@ -2961,7 +3059,7 @@ fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), S
|
||||
.map_err(|e| format!("启动 {} 失败: {e}", terminal_name))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let stderr = decode_command_output(&output.stderr);
|
||||
return Err(format!(
|
||||
"{} 启动失败 (exit code: {:?}): {}",
|
||||
terminal_name,
|
||||
|
||||
@@ -29,6 +29,7 @@ mod subscription;
|
||||
mod sync_support;
|
||||
|
||||
mod lightweight;
|
||||
mod s3_sync;
|
||||
mod usage;
|
||||
mod webdav_sync;
|
||||
mod workspace;
|
||||
@@ -61,6 +62,7 @@ pub use stream_check::*;
|
||||
pub use subscription::*;
|
||||
|
||||
pub use lightweight::*;
|
||||
pub use s3_sync::*;
|
||||
pub use usage::*;
|
||||
pub use webdav_sync::*;
|
||||
pub use workspace::*;
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::str::FromStr;
|
||||
const TEMPLATE_TYPE_GITHUB_COPILOT: &str = "github_copilot";
|
||||
const TEMPLATE_TYPE_TOKEN_PLAN: &str = "token_plan";
|
||||
const TEMPLATE_TYPE_BALANCE: &str = "balance";
|
||||
const TEMPLATE_TYPE_OFFICIAL_SUBSCRIPTION: &str = "official_subscription";
|
||||
const COPILOT_UNIT_PREMIUM: &str = "requests";
|
||||
|
||||
/// 获取所有供应商
|
||||
@@ -219,6 +220,17 @@ pub fn import_claude_desktop_providers_from_claude(
|
||||
Ok(imported)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn ensure_claude_desktop_official_provider(state: State<'_, AppState>) -> Result<bool, String> {
|
||||
state
|
||||
.db
|
||||
.ensure_official_seed_by_id(
|
||||
crate::database::CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID,
|
||||
AppType::ClaudeDesktop,
|
||||
)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn claude_provider_models_are_claude_safe(provider: &Provider) -> bool {
|
||||
let Some(env) = provider
|
||||
.settings_config
|
||||
@@ -398,6 +410,50 @@ pub async fn queryProviderUsage(
|
||||
inner
|
||||
}
|
||||
|
||||
/// Resolve `(base_url, api_key)` for native usage queries, delegating to the
|
||||
/// per-app resolver on `Provider`. Missing provider → empty credentials.
|
||||
fn resolve_native_credentials(app_type: &AppType, provider: Option<&Provider>) -> (String, String) {
|
||||
provider
|
||||
.map(|p| p.resolve_usage_credentials(app_type))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn resolve_coding_plan_credentials(
|
||||
app_type: &AppType,
|
||||
provider: Option<&Provider>,
|
||||
usage_script: Option<&crate::provider::UsageScript>,
|
||||
) -> (String, String) {
|
||||
let is_zenmux = usage_script
|
||||
.and_then(|s| s.coding_plan_provider.as_deref())
|
||||
.map(|provider| provider.eq_ignore_ascii_case("zenmux"))
|
||||
.unwrap_or(false);
|
||||
|
||||
if !is_zenmux {
|
||||
return resolve_native_credentials(app_type, provider);
|
||||
}
|
||||
|
||||
let script_base_url = usage_script
|
||||
.and_then(|s| s.base_url.as_deref())
|
||||
.unwrap_or("")
|
||||
.trim_end_matches('/')
|
||||
.to_string();
|
||||
let script_api_key = usage_script
|
||||
.and_then(|s| s.api_key.as_deref())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
|
||||
if !script_base_url.is_empty() && !script_api_key.is_empty() {
|
||||
return (script_base_url, script_api_key);
|
||||
}
|
||||
|
||||
let native = resolve_native_credentials(app_type, provider);
|
||||
if !native.0.is_empty() && !native.1.is_empty() {
|
||||
native
|
||||
} else {
|
||||
(script_base_url, script_api_key)
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_provider_usage_inner(
|
||||
state: &AppState,
|
||||
copilot_state: &CopilotAuthState,
|
||||
@@ -455,25 +511,10 @@ async fn query_provider_usage_inner(
|
||||
|
||||
// ── Coding Plan 专用路径 ──
|
||||
if template_type == TEMPLATE_TYPE_TOKEN_PLAN {
|
||||
// 从供应商配置中提取 API Key 和 Base URL
|
||||
let settings_config = provider
|
||||
.map(|p| &p.settings_config)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let env = settings_config.get("env");
|
||||
let base_url = env
|
||||
.and_then(|e| e.get("ANTHROPIC_BASE_URL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let api_key = env
|
||||
.and_then(|e| {
|
||||
e.get("ANTHROPIC_AUTH_TOKEN")
|
||||
.or_else(|| e.get("ANTHROPIC_API_KEY"))
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let (base_url, api_key) =
|
||||
resolve_coding_plan_credentials(&app_type, provider, usage_script);
|
||||
|
||||
let quota = crate::services::coding_plan::get_coding_plan_quota(base_url, api_key)
|
||||
let quota = crate::services::coding_plan::get_coding_plan_quota(&base_url, &api_key)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query coding plan: {e}"))?;
|
||||
|
||||
@@ -486,6 +527,19 @@ async fn query_provider_usage_inner(
|
||||
});
|
||||
}
|
||||
|
||||
// ZenMux 的 tier 携带 USD 额度信息,需要编码为 JSON extra
|
||||
let has_usd = quota
|
||||
.tiers
|
||||
.first()
|
||||
.map(|t| t.used_value_usd.is_some())
|
||||
.unwrap_or(false);
|
||||
let plan_label = quota
|
||||
.credential_message
|
||||
.as_deref()
|
||||
.and_then(|msg| msg.split(' ').next())
|
||||
.map(|tier| format!("ZenMux·{}", tier.to_uppercase()));
|
||||
let mut first_tier = true;
|
||||
|
||||
let data: Vec<crate::provider::UsageData> = quota
|
||||
.tiers
|
||||
.iter()
|
||||
@@ -493,6 +547,26 @@ async fn query_provider_usage_inner(
|
||||
let total = 100.0;
|
||||
let used = tier.utilization;
|
||||
let remaining = total - used;
|
||||
let extra = if has_usd {
|
||||
let mut extra_json = serde_json::json!({
|
||||
"resetsAt": tier.resets_at,
|
||||
});
|
||||
if let Some(v) = tier.used_value_usd {
|
||||
extra_json["usedValueUsd"] = serde_json::json!(v);
|
||||
}
|
||||
if let Some(v) = tier.max_value_usd {
|
||||
extra_json["maxValueUsd"] = serde_json::json!(v);
|
||||
}
|
||||
if first_tier {
|
||||
if let Some(ref label) = plan_label {
|
||||
extra_json["planLabel"] = serde_json::json!(label);
|
||||
}
|
||||
first_tier = false;
|
||||
}
|
||||
Some(extra_json.to_string())
|
||||
} else {
|
||||
tier.resets_at.clone()
|
||||
};
|
||||
crate::provider::UsageData {
|
||||
plan_name: Some(tier.name.clone()),
|
||||
remaining: Some(remaining),
|
||||
@@ -501,7 +575,7 @@ async fn query_provider_usage_inner(
|
||||
unit: Some("%".to_string()),
|
||||
is_valid: Some(true),
|
||||
invalid_message: None,
|
||||
extra: tier.resets_at.clone(),
|
||||
extra,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -515,28 +589,58 @@ async fn query_provider_usage_inner(
|
||||
|
||||
// ── 官方余额查询路径 ──
|
||||
if template_type == TEMPLATE_TYPE_BALANCE {
|
||||
let settings_config = provider
|
||||
.map(|p| &p.settings_config)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let env = settings_config.get("env");
|
||||
let base_url = env
|
||||
.and_then(|e| e.get("ANTHROPIC_BASE_URL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let api_key = env
|
||||
.and_then(|e| {
|
||||
e.get("ANTHROPIC_AUTH_TOKEN")
|
||||
.or_else(|| e.get("ANTHROPIC_API_KEY"))
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
// 按 app 区分的凭据存储格式提取 Base URL 与 API Key
|
||||
let (base_url, api_key) = resolve_native_credentials(&app_type, provider);
|
||||
|
||||
return crate::services::balance::get_balance(base_url, api_key)
|
||||
return crate::services::balance::get_balance(&base_url, &api_key)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query balance: {e}"));
|
||||
}
|
||||
|
||||
// ── 官方订阅额度查询路径 ──
|
||||
if template_type == TEMPLATE_TYPE_OFFICIAL_SUBSCRIPTION {
|
||||
if !usage_script.map(|s| s.enabled).unwrap_or(false) {
|
||||
return Ok(crate::provider::UsageResult {
|
||||
success: false,
|
||||
data: None,
|
||||
error: Some("Usage query is disabled".to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
let quota = crate::services::subscription::get_subscription_quota(app_type.as_str())
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query subscription quota: {e}"))?;
|
||||
|
||||
if !quota.success {
|
||||
return Ok(crate::provider::UsageResult {
|
||||
success: false,
|
||||
data: None,
|
||||
error: quota.error.or(quota.credential_message),
|
||||
});
|
||||
}
|
||||
|
||||
let data: Vec<crate::provider::UsageData> = quota
|
||||
.tiers
|
||||
.iter()
|
||||
.map(|tier| crate::provider::UsageData {
|
||||
plan_name: Some(tier.name.clone()),
|
||||
remaining: Some(100.0 - tier.utilization),
|
||||
total: Some(100.0),
|
||||
used: Some(tier.utilization),
|
||||
unit: Some("%".to_string()),
|
||||
is_valid: Some(true),
|
||||
invalid_message: None,
|
||||
extra: tier.resets_at.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
return Ok(crate::provider::UsageResult {
|
||||
success: true,
|
||||
data: if data.is_empty() { None } else { Some(data) },
|
||||
error: None,
|
||||
});
|
||||
}
|
||||
|
||||
// ── 通用 JS 脚本路径 ──
|
||||
ProviderService::query_usage(state, app_type, provider_id)
|
||||
.await
|
||||
@@ -957,3 +1061,104 @@ mod import_claude_desktop_tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod native_query_credentials_tests {
|
||||
use super::{resolve_coding_plan_credentials, resolve_native_credentials};
|
||||
use crate::app_config::AppType;
|
||||
use crate::provider::{Provider, UsageScript};
|
||||
use serde_json::json;
|
||||
|
||||
fn usage_script(
|
||||
coding_plan_provider: Option<&str>,
|
||||
base_url: Option<&str>,
|
||||
api_key: Option<&str>,
|
||||
) -> UsageScript {
|
||||
UsageScript {
|
||||
enabled: true,
|
||||
language: "javascript".to_string(),
|
||||
code: String::new(),
|
||||
timeout: Some(10),
|
||||
api_key: api_key.map(str::to_string),
|
||||
base_url: base_url.map(str::to_string),
|
||||
access_token: None,
|
||||
user_id: None,
|
||||
template_type: Some("token_plan".to_string()),
|
||||
auto_query_interval: None,
|
||||
coding_plan_provider: coding_plan_provider.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delegates_to_provider_for_codex() {
|
||||
let provider = Provider::with_id(
|
||||
"test".to_string(),
|
||||
"Test".to_string(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-codex" },
|
||||
"config": "model_provider = \"deepseek\"\n\
|
||||
[model_providers.deepseek]\n\
|
||||
base_url = \"https://api.deepseek.com\"\n",
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let (base_url, api_key) = resolve_native_credentials(&AppType::Codex, Some(&provider));
|
||||
assert_eq!(base_url, "https://api.deepseek.com");
|
||||
assert_eq!(api_key, "sk-codex");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_provider_yields_empty() {
|
||||
let (base_url, api_key) = resolve_native_credentials(&AppType::Codex, None);
|
||||
assert!(base_url.is_empty());
|
||||
assert!(api_key.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zenmux_coding_plan_uses_script_credentials_first() {
|
||||
let provider = Provider::with_id(
|
||||
"test".to_string(),
|
||||
"Test".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://provider.zenmux.example/v1",
|
||||
"ANTHROPIC_AUTH_TOKEN": "sk-provider"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let script = usage_script(
|
||||
Some("zenmux"),
|
||||
Some("https://script.zenmux.example/api/usage/"),
|
||||
Some("sk-script"),
|
||||
);
|
||||
|
||||
let (base_url, api_key) =
|
||||
resolve_coding_plan_credentials(&AppType::Claude, Some(&provider), Some(&script));
|
||||
|
||||
assert_eq!(base_url, "https://script.zenmux.example/api/usage");
|
||||
assert_eq!(api_key, "sk-script");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zenmux_coding_plan_falls_back_to_provider_credentials() {
|
||||
let provider = Provider::with_id(
|
||||
"test".to_string(),
|
||||
"Test".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://provider.zenmux.example/v1",
|
||||
"ANTHROPIC_AUTH_TOKEN": "sk-provider"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
let script = usage_script(Some("zenmux"), Some("https://script.zenmux.example"), None);
|
||||
|
||||
let (base_url, api_key) =
|
||||
resolve_coding_plan_credentials(&AppType::Claude, Some(&provider), Some(&script));
|
||||
|
||||
assert_eq!(base_url, "https://provider.zenmux.example/v1");
|
||||
assert_eq!(api_key, "sk-provider");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use tauri::State;
|
||||
|
||||
use crate::commands::sync_support::{
|
||||
attach_warning, post_sync_warning_from_result, run_post_import_sync,
|
||||
};
|
||||
use crate::error::AppError;
|
||||
use crate::services::s3_sync as s3_sync_service;
|
||||
use crate::settings::{self, S3SyncSettings};
|
||||
use crate::store::AppState;
|
||||
|
||||
fn persist_sync_error(settings: &mut S3SyncSettings, error: &AppError, source: &str) {
|
||||
settings.status.last_error = Some(error.to_string());
|
||||
settings.status.last_error_source = Some(source.to_string());
|
||||
let _ = settings::update_s3_sync_status(settings.status.clone());
|
||||
}
|
||||
|
||||
fn s3_not_configured_error() -> String {
|
||||
AppError::localized(
|
||||
"s3.sync.not_configured",
|
||||
"未配置 S3 同步",
|
||||
"S3 sync is not configured.",
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn s3_sync_disabled_error() -> String {
|
||||
AppError::localized("s3.sync.disabled", "S3 同步未启用", "S3 sync is disabled.").to_string()
|
||||
}
|
||||
|
||||
fn require_enabled_s3_settings() -> Result<S3SyncSettings, String> {
|
||||
let settings = settings::get_s3_sync_settings().ok_or_else(s3_not_configured_error)?;
|
||||
if !settings.enabled {
|
||||
return Err(s3_sync_disabled_error());
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
fn resolve_secret_for_request(
|
||||
mut incoming: S3SyncSettings,
|
||||
existing: Option<S3SyncSettings>,
|
||||
preserve_empty_secret: bool,
|
||||
) -> S3SyncSettings {
|
||||
if let Some(existing_settings) = existing {
|
||||
if preserve_empty_secret && incoming.secret_access_key.is_empty() {
|
||||
incoming.secret_access_key = existing_settings.secret_access_key;
|
||||
}
|
||||
}
|
||||
incoming
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn s3_sync_mutex() -> &'static tokio::sync::Mutex<()> {
|
||||
s3_sync_service::sync_mutex()
|
||||
}
|
||||
|
||||
async fn run_with_s3_lock<T, Fut>(operation: Fut) -> Result<T, AppError>
|
||||
where
|
||||
Fut: std::future::Future<Output = Result<T, AppError>>,
|
||||
{
|
||||
s3_sync_service::run_with_sync_lock(operation).await
|
||||
}
|
||||
|
||||
fn map_sync_result<T, F>(result: Result<T, AppError>, on_error: F) -> Result<T, String>
|
||||
where
|
||||
F: FnOnce(&AppError),
|
||||
{
|
||||
match result {
|
||||
Ok(value) => Ok(value),
|
||||
Err(err) => {
|
||||
on_error(&err);
|
||||
Err(err.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn s3_test_connection(
|
||||
settings: S3SyncSettings,
|
||||
#[allow(non_snake_case)] preserveEmptyPassword: Option<bool>,
|
||||
) -> Result<Value, String> {
|
||||
let preserve_empty = preserveEmptyPassword.unwrap_or(true);
|
||||
let resolved =
|
||||
resolve_secret_for_request(settings, settings::get_s3_sync_settings(), preserve_empty);
|
||||
s3_sync_service::check_connection(&resolved)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({
|
||||
"success": true,
|
||||
"message": "S3 connection ok"
|
||||
}))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn s3_sync_upload(state: State<'_, AppState>) -> Result<Value, String> {
|
||||
let db = state.db.clone();
|
||||
let mut settings = require_enabled_s3_settings()?;
|
||||
|
||||
let result = run_with_s3_lock(s3_sync_service::upload(&db, &mut settings)).await;
|
||||
map_sync_result(result, |error| {
|
||||
persist_sync_error(&mut settings, error, "manual")
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn s3_sync_download(state: State<'_, AppState>) -> Result<Value, String> {
|
||||
let db = state.db.clone();
|
||||
let db_for_sync = db.clone();
|
||||
let mut settings = require_enabled_s3_settings()?;
|
||||
let _auto_sync_suppression = crate::services::s3_auto_sync::AutoSyncSuppressionGuard::new();
|
||||
|
||||
let sync_result = run_with_s3_lock(s3_sync_service::download(&db, &mut settings)).await;
|
||||
let mut result = map_sync_result(sync_result, |error| {
|
||||
persist_sync_error(&mut settings, error, "manual")
|
||||
})?;
|
||||
|
||||
// Post-download sync is best-effort: snapshot restore has already succeeded.
|
||||
let warning = post_sync_warning_from_result(
|
||||
tauri::async_runtime::spawn_blocking(move || run_post_import_sync(db_for_sync))
|
||||
.await
|
||||
.map_err(|e| e.to_string()),
|
||||
);
|
||||
if let Some(msg) = warning.as_ref() {
|
||||
log::warn!("[S3] post-download sync warning: {msg}");
|
||||
}
|
||||
result = attach_warning(result, warning);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn s3_sync_save_settings(
|
||||
settings: S3SyncSettings,
|
||||
#[allow(non_snake_case)] passwordTouched: Option<bool>,
|
||||
) -> Result<Value, String> {
|
||||
let password_touched = passwordTouched.unwrap_or(false);
|
||||
let existing = settings::get_s3_sync_settings();
|
||||
let mut sync_settings =
|
||||
resolve_secret_for_request(settings, existing.clone(), !password_touched);
|
||||
|
||||
// Preserve server-owned fields that the frontend does not manage
|
||||
if let Some(existing_settings) = existing {
|
||||
sync_settings.status = existing_settings.status;
|
||||
}
|
||||
|
||||
sync_settings.normalize();
|
||||
sync_settings.validate().map_err(|e| e.to_string())?;
|
||||
settings::set_s3_sync_settings(Some(sync_settings)).map_err(|e| e.to_string())?;
|
||||
Ok(json!({ "success": true }))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn s3_sync_fetch_remote_info() -> Result<Value, String> {
|
||||
let settings = require_enabled_s3_settings()?;
|
||||
let info = s3_sync_service::fetch_remote_info(&settings)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(info.unwrap_or(json!({ "empty": true })))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
map_sync_result, persist_sync_error, require_enabled_s3_settings,
|
||||
resolve_secret_for_request, run_with_s3_lock, s3_sync_mutex,
|
||||
};
|
||||
use crate::error::AppError;
|
||||
use crate::settings::{AppSettings, S3SyncSettings};
|
||||
use serial_test::serial;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn s3_sync_mutex_is_singleton() {
|
||||
let a = s3_sync_mutex() as *const _;
|
||||
let b = s3_sync_mutex() as *const _;
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn s3_sync_mutex_serializes_concurrent_access() {
|
||||
let guard = s3_sync_mutex().lock().await;
|
||||
let acquired = Arc::new(AtomicBool::new(false));
|
||||
let acquired_bg = Arc::clone(&acquired);
|
||||
|
||||
let waiter = tokio::spawn(async move {
|
||||
let _inner_guard = s3_sync_mutex().lock().await;
|
||||
acquired_bg.store(true, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(40)).await;
|
||||
assert!(!acquired.load(Ordering::SeqCst));
|
||||
|
||||
drop(guard);
|
||||
tokio::time::timeout(Duration::from_secs(1), waiter)
|
||||
.await
|
||||
.expect("background task should complete after lock release")
|
||||
.expect("background task should not panic");
|
||||
|
||||
assert!(acquired.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn map_sync_result_runs_error_handler_after_lock_release() {
|
||||
let result =
|
||||
run_with_s3_lock(async { Err::<(), AppError>(AppError::Config("boom".to_string())) })
|
||||
.await;
|
||||
|
||||
let mut lock_released = false;
|
||||
let mapped = map_sync_result(result, |_| {
|
||||
lock_released = s3_sync_mutex().try_lock().is_ok();
|
||||
});
|
||||
|
||||
assert!(mapped.is_err());
|
||||
assert!(lock_released);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_secret_for_request_preserves_existing_when_requested() {
|
||||
let incoming = S3SyncSettings {
|
||||
region: "us-east-1".to_string(),
|
||||
bucket: "my-bucket".to_string(),
|
||||
access_key_id: "AKID".to_string(),
|
||||
secret_access_key: String::new(),
|
||||
..S3SyncSettings::default()
|
||||
};
|
||||
let existing = Some(S3SyncSettings {
|
||||
secret_access_key: "SECRET".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
});
|
||||
let resolved = resolve_secret_for_request(incoming, existing, true);
|
||||
assert_eq!(resolved.secret_access_key, "SECRET");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_secret_for_request_allows_explicit_empty_secret() {
|
||||
let incoming = S3SyncSettings {
|
||||
region: "us-east-1".to_string(),
|
||||
bucket: "my-bucket".to_string(),
|
||||
access_key_id: "AKID".to_string(),
|
||||
secret_access_key: String::new(),
|
||||
..S3SyncSettings::default()
|
||||
};
|
||||
let existing = Some(S3SyncSettings {
|
||||
secret_access_key: "SECRET".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
});
|
||||
let resolved = resolve_secret_for_request(incoming, existing, false);
|
||||
assert!(resolved.secret_access_key.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn persist_sync_error_updates_status_without_overwriting_credentials() {
|
||||
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-error-status-test");
|
||||
let _ = std::fs::remove_dir_all(&test_home);
|
||||
std::fs::create_dir_all(&test_home).expect("create test home");
|
||||
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
|
||||
|
||||
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
|
||||
let mut current = S3SyncSettings {
|
||||
enabled: true,
|
||||
region: "us-east-1".to_string(),
|
||||
bucket: "my-bucket".to_string(),
|
||||
access_key_id: "AKID".to_string(),
|
||||
secret_access_key: "SECRET".to_string(),
|
||||
remote_root: "cc-switch-sync".to_string(),
|
||||
profile: "default".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
};
|
||||
crate::settings::set_s3_sync_settings(Some(current.clone())).expect("seed s3 settings");
|
||||
|
||||
persist_sync_error(
|
||||
&mut current,
|
||||
&crate::error::AppError::Config("boom".to_string()),
|
||||
"manual",
|
||||
);
|
||||
|
||||
let after = crate::settings::get_s3_sync_settings().expect("read s3 settings");
|
||||
assert_eq!(after.region, "us-east-1");
|
||||
assert_eq!(after.bucket, "my-bucket");
|
||||
assert_eq!(after.access_key_id, "AKID");
|
||||
assert_eq!(after.secret_access_key, "SECRET");
|
||||
assert_eq!(after.remote_root, "cc-switch-sync");
|
||||
assert_eq!(after.profile, "default");
|
||||
assert!(
|
||||
after
|
||||
.status
|
||||
.last_error
|
||||
.as_deref()
|
||||
.unwrap_or_default()
|
||||
.contains("boom"),
|
||||
"status error should be updated"
|
||||
);
|
||||
assert_eq!(after.status.last_error_source.as_deref(), Some("manual"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn require_enabled_s3_settings_rejects_disabled_config() {
|
||||
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-enabled-disabled-test");
|
||||
let _ = std::fs::remove_dir_all(&test_home);
|
||||
std::fs::create_dir_all(&test_home).expect("create test home");
|
||||
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
|
||||
|
||||
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
|
||||
crate::settings::set_s3_sync_settings(Some(S3SyncSettings {
|
||||
enabled: false,
|
||||
region: "us-east-1".to_string(),
|
||||
bucket: "my-bucket".to_string(),
|
||||
access_key_id: "AKID".to_string(),
|
||||
secret_access_key: "SECRET".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
}))
|
||||
.expect("seed disabled s3 settings");
|
||||
|
||||
let err = require_enabled_s3_settings().expect_err("disabled settings should fail");
|
||||
assert!(
|
||||
err.contains("disabled") || err.contains("未启用"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn require_enabled_s3_settings_returns_settings_when_enabled() {
|
||||
let test_home = std::env::temp_dir().join("cc-switch-s3-sync-enabled-ok-test");
|
||||
let _ = std::fs::remove_dir_all(&test_home);
|
||||
std::fs::create_dir_all(&test_home).expect("create test home");
|
||||
std::env::set_var("CC_SWITCH_TEST_HOME", &test_home);
|
||||
|
||||
crate::settings::update_settings(AppSettings::default()).expect("reset settings");
|
||||
crate::settings::set_s3_sync_settings(Some(S3SyncSettings {
|
||||
enabled: true,
|
||||
region: "us-east-1".to_string(),
|
||||
bucket: "my-bucket".to_string(),
|
||||
access_key_id: "AKID".to_string(),
|
||||
secret_access_key: "SECRET".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
}))
|
||||
.expect("seed enabled s3 settings");
|
||||
|
||||
let settings = require_enabled_s3_settings().expect("enabled settings should be accepted");
|
||||
assert!(settings.enabled);
|
||||
assert_eq!(settings.region, "us-east-1");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,20 @@ fn merge_settings_for_save(
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match (&mut incoming.s3_sync, &existing.s3_sync) {
|
||||
// incoming 没有 s3 → 保留现有
|
||||
(None, _) => {
|
||||
incoming.s3_sync = existing.s3_sync.clone();
|
||||
}
|
||||
// incoming 有 s3 但密钥为空,且现有有密钥 → 填回现有密钥
|
||||
(Some(incoming_sync), Some(existing_sync))
|
||||
if incoming_sync.secret_access_key.is_empty()
|
||||
&& !existing_sync.secret_access_key.is_empty() =>
|
||||
{
|
||||
incoming_sync.secret_access_key = existing_sync.secret_access_key.clone();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if incoming.local_migrations.is_none() {
|
||||
incoming.local_migrations = existing.local_migrations.clone();
|
||||
} else if let (Some(incoming_migrations), Some(existing_migrations)) =
|
||||
@@ -103,7 +117,7 @@ mod tests {
|
||||
use super::merge_settings_for_save;
|
||||
use crate::settings::{
|
||||
AppSettings, CodexProviderTemplateMigration, CodexThirdPartyHistoryProviderBucketMigration,
|
||||
LocalMigrations, WebDavSyncSettings,
|
||||
LocalMigrations, S3SyncSettings, WebDavSyncSettings,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -226,6 +240,64 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_settings_should_preserve_existing_s3_when_payload_omits_it() {
|
||||
let existing = AppSettings {
|
||||
s3_sync: Some(S3SyncSettings {
|
||||
bucket: "bucket".to_string(),
|
||||
access_key_id: "ak".to_string(),
|
||||
secret_access_key: "secret".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
}),
|
||||
..AppSettings::default()
|
||||
};
|
||||
|
||||
let incoming = AppSettings::default();
|
||||
let merged = merge_settings_for_save(incoming, &existing);
|
||||
|
||||
assert!(merged.s3_sync.is_some());
|
||||
assert_eq!(
|
||||
merged
|
||||
.s3_sync
|
||||
.as_ref()
|
||||
.map(|v| v.secret_access_key.as_str()),
|
||||
Some("secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_settings_should_preserve_s3_secret_when_incoming_has_empty_secret() {
|
||||
let existing = AppSettings {
|
||||
s3_sync: Some(S3SyncSettings {
|
||||
bucket: "bucket".to_string(),
|
||||
access_key_id: "ak".to_string(),
|
||||
secret_access_key: "secret".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
}),
|
||||
..AppSettings::default()
|
||||
};
|
||||
|
||||
let incoming = AppSettings {
|
||||
s3_sync: Some(S3SyncSettings {
|
||||
bucket: "bucket".to_string(),
|
||||
access_key_id: "ak".to_string(),
|
||||
secret_access_key: "".to_string(),
|
||||
..S3SyncSettings::default()
|
||||
}),
|
||||
..AppSettings::default()
|
||||
};
|
||||
|
||||
let merged = merge_settings_for_save(incoming, &existing);
|
||||
|
||||
assert_eq!(
|
||||
merged
|
||||
.s3_sync
|
||||
.as_ref()
|
||||
.map(|v| v.secret_access_key.as_str()),
|
||||
Some("secret")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_settings_should_preserve_local_migrations_when_payload_omits_it() {
|
||||
let existing = AppSettings {
|
||||
|
||||
@@ -276,6 +276,19 @@ pub fn sync_session_usage(
|
||||
}
|
||||
}
|
||||
|
||||
// 同步 OpenCode 使用数据
|
||||
match crate::services::session_usage_opencode::sync_opencode_usage(&state.db) {
|
||||
Ok(opencode_result) => {
|
||||
result.imported += opencode_result.imported;
|
||||
result.skipped += opencode_result.skipped;
|
||||
result.files_scanned += opencode_result.files_scanned;
|
||||
result.errors.extend(opencode_result.errors);
|
||||
}
|
||||
Err(e) => {
|
||||
result.errors.push(format!("OpenCode 同步失败: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ fn register_db_change_hook(conn: &Connection) {
|
||||
|action: Action, _database: &str, table: &str, _row_id: i64| match action {
|
||||
Action::SQLITE_INSERT | Action::SQLITE_UPDATE | Action::SQLITE_DELETE => {
|
||||
crate::services::webdav_auto_sync::notify_db_changed(table);
|
||||
crate::services::s3_auto_sync::notify_db_changed(table);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
|
||||
@@ -1744,6 +1744,7 @@ impl Database {
|
||||
"0.06",
|
||||
"0.375",
|
||||
),
|
||||
("minimax-m3", "MiniMax M3", "0.60", "2.40", "0.12", "0"),
|
||||
// GLM (智谱)
|
||||
("glm-4.7", "GLM-4.7", "0.39", "1.75", "0.04", "0"),
|
||||
("glm-4.6", "GLM-4.6", "0.28", "1.11", "0.03", "0"),
|
||||
|
||||
@@ -9,7 +9,51 @@ use super::DeepLinkImportRequest;
|
||||
use crate::AppType;
|
||||
use crate::{store::AppState, Database};
|
||||
use base64::prelude::*;
|
||||
use std::sync::Arc;
|
||||
use std::{env, ffi::OsString, sync::Arc};
|
||||
|
||||
struct TestHomeGuard {
|
||||
_dir: tempfile::TempDir,
|
||||
original_home: Option<OsString>,
|
||||
original_userprofile: Option<OsString>,
|
||||
original_test_home: Option<OsString>,
|
||||
}
|
||||
|
||||
impl TestHomeGuard {
|
||||
fn new() -> Self {
|
||||
let dir = tempfile::tempdir().expect("create isolated test home");
|
||||
let original_home = env::var_os("HOME");
|
||||
let original_userprofile = env::var_os("USERPROFILE");
|
||||
let original_test_home = env::var_os("CC_SWITCH_TEST_HOME");
|
||||
|
||||
env::set_var("HOME", dir.path());
|
||||
env::set_var("USERPROFILE", dir.path());
|
||||
env::set_var("CC_SWITCH_TEST_HOME", dir.path());
|
||||
|
||||
Self {
|
||||
_dir: dir,
|
||||
original_home,
|
||||
original_userprofile,
|
||||
original_test_home,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestHomeGuard {
|
||||
fn drop(&mut self) {
|
||||
match &self.original_test_home {
|
||||
Some(value) => env::set_var("CC_SWITCH_TEST_HOME", value),
|
||||
None => env::remove_var("CC_SWITCH_TEST_HOME"),
|
||||
}
|
||||
match &self.original_userprofile {
|
||||
Some(value) => env::set_var("USERPROFILE", value),
|
||||
None => env::remove_var("USERPROFILE"),
|
||||
}
|
||||
match &self.original_home {
|
||||
Some(value) => env::set_var("HOME", value),
|
||||
None => env::remove_var("HOME"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Parser Tests
|
||||
@@ -477,8 +521,12 @@ fn test_build_claude_provider_without_config_unchanged() {
|
||||
// Prompt Tests
|
||||
// =============================================================================
|
||||
|
||||
// Integration-style unit test: prompt import reaches PromptService and resolves
|
||||
// live config file paths, so HOME must be isolated before it runs.
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn test_import_prompt_allows_space_in_base64_content() {
|
||||
let _test_home = TestHomeGuard::new();
|
||||
let url = "ccswitch://v1/import?resource=prompt&app=codex&name=PromptPlus&content=Pj4+";
|
||||
let request = parse_deeplink_url(url).unwrap();
|
||||
|
||||
|
||||
@@ -69,6 +69,22 @@ use tauri::RunEvent;
|
||||
use tauri::{Emitter, Manager};
|
||||
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_windows_app_user_model_id(app: &tauri::AppHandle) {
|
||||
let app_id = app.config().identifier.clone();
|
||||
let wide_app_id: Vec<u16> = app_id.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
|
||||
let result = unsafe {
|
||||
windows_sys::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(wide_app_id.as_ptr())
|
||||
};
|
||||
|
||||
if result < 0 {
|
||||
log::warn!("设置 Windows AppUserModelID 失败: 0x{result:08X}");
|
||||
} else {
|
||||
log::debug!("Windows AppUserModelID 已设置为 {app_id}");
|
||||
}
|
||||
}
|
||||
|
||||
fn redact_url_for_log(url_str: &str) -> String {
|
||||
match url::Url::parse(url_str) {
|
||||
Ok(url) => {
|
||||
@@ -288,6 +304,8 @@ pub fn run() {
|
||||
// 预先刷新 Store 覆盖配置,确保后续路径读取正确(日志/数据库等)
|
||||
app_store::refresh_app_config_dir_override(app.handle());
|
||||
panic_hook::init_app_config_dir(crate::config::get_app_config_dir());
|
||||
#[cfg(target_os = "windows")]
|
||||
set_windows_app_user_model_id(app.handle());
|
||||
|
||||
// 注册 Updater 插件(桌面端)
|
||||
#[cfg(desktop)]
|
||||
@@ -865,6 +883,10 @@ pub fn run() {
|
||||
app_state.db.clone(),
|
||||
app.handle().clone(),
|
||||
);
|
||||
crate::services::s3_auto_sync::start_worker(
|
||||
app_state.db.clone(),
|
||||
app.handle().clone(),
|
||||
);
|
||||
// 将同一个实例注入到全局状态,避免重复创建导致的不一致
|
||||
app.manage(app_state);
|
||||
|
||||
@@ -1021,6 +1043,10 @@ pub fn run() {
|
||||
"Gemini usage initial sync",
|
||||
crate::services::session_usage_gemini::sync_gemini_usage(db),
|
||||
);
|
||||
run_step(
|
||||
"OpenCode usage initial sync",
|
||||
crate::services::session_usage_opencode::sync_opencode_usage(db),
|
||||
);
|
||||
|
||||
// 定期同步
|
||||
let mut interval = tokio::time::interval(std::time::Duration::from_secs(
|
||||
@@ -1041,6 +1067,10 @@ pub fn run() {
|
||||
"Gemini usage periodic sync",
|
||||
crate::services::session_usage_gemini::sync_gemini_usage(db),
|
||||
);
|
||||
run_step(
|
||||
"OpenCode usage periodic sync",
|
||||
crate::services::session_usage_opencode::sync_opencode_usage(db),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1105,6 +1135,7 @@ pub fn run() {
|
||||
commands::get_claude_desktop_status,
|
||||
commands::get_claude_desktop_default_routes,
|
||||
commands::import_claude_desktop_providers_from_claude,
|
||||
commands::ensure_claude_desktop_official_provider,
|
||||
commands::get_claude_config_status,
|
||||
commands::get_config_status,
|
||||
commands::get_claude_code_config_path,
|
||||
@@ -1197,6 +1228,11 @@ pub fn run() {
|
||||
commands::webdav_sync_download,
|
||||
commands::webdav_sync_save_settings,
|
||||
commands::webdav_sync_fetch_remote_info,
|
||||
commands::s3_test_connection,
|
||||
commands::s3_sync_upload,
|
||||
commands::s3_sync_download,
|
||||
commands::s3_sync_save_settings,
|
||||
commands::s3_sync_fetch_remote_info,
|
||||
commands::save_file_dialog,
|
||||
commands::open_file_dialog,
|
||||
commands::open_zip_file_dialog,
|
||||
@@ -1424,6 +1460,11 @@ pub fn run() {
|
||||
tauri::async_runtime::spawn(async move {
|
||||
save_window_state_before_exit(&app_handle);
|
||||
cleanup_before_exit(&app_handle).await;
|
||||
// 先于 std::process::exit 显式移除托盘图标。
|
||||
// 进程直接退出时 Tauri 运行时不走正常 Drop 流程,
|
||||
// 不会向 Windows Shell 发送 NIM_DELETE,导致已退出的进程
|
||||
// 注册的图标仍残留在系统托盘(鼠标悬停 Shell 才会重绘发现进程已死)。
|
||||
remove_tray_icon_before_exit(&app_handle);
|
||||
log::info!("清理完成,退出应用");
|
||||
|
||||
// 短暂等待确保所有 I/O 操作(如数据库写入)刷新到磁盘
|
||||
@@ -1571,6 +1612,26 @@ pub async fn cleanup_before_exit(app_handle: &tauri::AppHandle) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 主动从系统托盘移除托盘图标。
|
||||
///
|
||||
/// `std::process::exit` 会绕过 Tauri 运行时,触发不了 `TrayIcon::drop()`,
|
||||
/// 也就不会向 Windows Shell 发 `NIM_DELETE`。结果是进程退出后托盘里
|
||||
/// 仍保留一个死图标的缓存占位(Shell 不会主动重绘,需要鼠标悬停才刷新)。
|
||||
///
|
||||
/// 通过 `set_visible(false)` 走 `WM_USER_HIDE_TRAYICON` 消息路径,
|
||||
/// 触发 tray-icon 内部的 `remove_tray_icon` → `Shell_NotifyIconW(NIM_DELETE)`,
|
||||
/// 在进程结束前干净地把图标摘掉。其它平台 `set_visible(false)` 也是
|
||||
/// 正常的隐藏/移除语义,作为跨平台兜底也安全。
|
||||
fn remove_tray_icon_before_exit(app_handle: &tauri::AppHandle) {
|
||||
if let Some(tray) = app_handle.tray_by_id(tray::TRAY_ID) {
|
||||
if let Err(e) = tray.set_visible(false) {
|
||||
log::warn!("退出时移除托盘图标失败: {e}");
|
||||
} else {
|
||||
log::info!("已显式从系统托盘移除图标");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 启动时恢复代理状态
|
||||
// ============================================================
|
||||
|
||||
@@ -46,6 +46,40 @@ pub fn get_opencode_config_path() -> PathBuf {
|
||||
get_opencode_dir().join("opencode.json")
|
||||
}
|
||||
|
||||
/// 获取 OpenCode SQLite 数据库路径
|
||||
/// 优先级: OPENCODE_DB 环境变量 > XDG_DATA_HOME > ~/.local/share/opencode
|
||||
pub fn get_opencode_db_path() -> PathBuf {
|
||||
// 支持 OPENCODE_DB 环境变量覆盖(忽略空字符串)
|
||||
if let Ok(custom_path) = std::env::var("OPENCODE_DB") {
|
||||
if !custom_path.is_empty() {
|
||||
let path = PathBuf::from(&custom_path);
|
||||
if path.is_absolute() {
|
||||
return path;
|
||||
}
|
||||
// 相对路径基于数据目录
|
||||
return get_opencode_data_dir().join(path);
|
||||
}
|
||||
}
|
||||
|
||||
get_opencode_data_dir().join("opencode.db")
|
||||
}
|
||||
|
||||
fn get_opencode_data_dir() -> PathBuf {
|
||||
// 尊重 XDG_DATA_HOME(按 XDG 规范,空字符串视为未设置)
|
||||
if let Ok(xdg_data) = std::env::var("XDG_DATA_HOME") {
|
||||
if !xdg_data.is_empty() {
|
||||
return PathBuf::from(xdg_data).join("opencode");
|
||||
}
|
||||
}
|
||||
|
||||
// OpenCode 使用 xdg-basedir,不遵守 macOS/Windows 平台约定,
|
||||
// 所有平台默认都落在 ~/.local/share/opencode
|
||||
crate::config::get_home_dir()
|
||||
.join(".local")
|
||||
.join("share")
|
||||
.join("opencode")
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_opencode_env_path() -> PathBuf {
|
||||
get_opencode_dir().join(".env")
|
||||
|
||||
@@ -107,6 +107,108 @@ impl Provider {
|
||||
.map(|s| s.enabled)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Resolve `(base_url, api_key)` for native usage queries (balance /
|
||||
/// coding-plan) from the stored provider config.
|
||||
///
|
||||
/// Each app persists credentials in a different shape, so callers must pass
|
||||
/// the owning app type. This mirrors the frontend `getProviderCredentials`
|
||||
/// in `UsageScriptModal.tsx`.
|
||||
///
|
||||
/// TODO: the env-only helpers in `services/provider/usage.rs`
|
||||
/// (`extract_api_key_from_provider` / `extract_base_url_from_provider`)
|
||||
/// duplicate this per-app logic on the JS-script path and could delegate
|
||||
/// here in a follow-up to remove the remaining copy.
|
||||
pub fn resolve_usage_credentials(
|
||||
&self,
|
||||
app_type: &crate::app_config::AppType,
|
||||
) -> (String, String) {
|
||||
use crate::app_config::AppType;
|
||||
|
||||
let settings = &self.settings_config;
|
||||
let str_at =
|
||||
|value: Option<&Value>| value.and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||
|
||||
// First present, non-empty string among `keys`, mirroring the frontend's
|
||||
// `a || b || c` — JS `||` skips empty strings, and presets seed fields like
|
||||
// `ANTHROPIC_AUTH_TOKEN` as present-but-empty placeholders, so a plain
|
||||
// `.get().or_else()` chain (which only skips *absent* keys) would stop short.
|
||||
fn first_non_empty(env: Option<&Value>, keys: &[&str]) -> String {
|
||||
let Some(env) = env else {
|
||||
return String::new();
|
||||
};
|
||||
for key in keys {
|
||||
if let Some(s) = env.get(key).and_then(|v| v.as_str()) {
|
||||
if !s.is_empty() {
|
||||
return s.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
let (base_url, api_key) = match app_type {
|
||||
// Codex keeps its key in `auth.OPENAI_API_KEY` and its base URL
|
||||
// inside a TOML `config` string, not in an `env` map.
|
||||
AppType::Codex => {
|
||||
let auth = settings.get("auth");
|
||||
let config_text = settings.get("config").and_then(|v| v.as_str());
|
||||
let api_key = crate::codex_config::extract_codex_api_key(auth, config_text)
|
||||
.unwrap_or_default();
|
||||
let base_url = config_text
|
||||
.and_then(crate::codex_config::extract_codex_base_url)
|
||||
.unwrap_or_default();
|
||||
(base_url, api_key)
|
||||
}
|
||||
// Gemini uses Google-specific env keys (with a legacy GOOGLE_API_KEY fallback).
|
||||
AppType::Gemini => {
|
||||
let env = settings.get("env");
|
||||
let base_url = str_at(env.and_then(|e| e.get("GOOGLE_GEMINI_BASE_URL")));
|
||||
let api_key = first_non_empty(env, &["GEMINI_API_KEY", "GOOGLE_API_KEY"]);
|
||||
(base_url, api_key)
|
||||
}
|
||||
// Hermes (config.yaml) flattens credentials at the top level, snake_case.
|
||||
AppType::Hermes => (
|
||||
str_at(settings.get("base_url")),
|
||||
str_at(settings.get("api_key")),
|
||||
),
|
||||
// OpenClaw (openclaw.json) flattens credentials at the top level, camelCase.
|
||||
AppType::OpenClaw => (
|
||||
str_at(settings.get("baseUrl")),
|
||||
str_at(settings.get("apiKey")),
|
||||
),
|
||||
// OpenCode (OMO) nests credentials under `options` (the SDK options object).
|
||||
AppType::OpenCode => {
|
||||
let options = settings.get("options");
|
||||
(
|
||||
str_at(options.and_then(|o| o.get("baseURL"))),
|
||||
str_at(options.and_then(|o| o.get("apiKey"))),
|
||||
)
|
||||
}
|
||||
// Claude and Claude Desktop both use the Anthropic-style env map, keeping
|
||||
// the OpenRouter/Google key fallbacks the JS-script path relies on.
|
||||
// Listed explicitly (not `_`) so a new AppType fails to compile here.
|
||||
AppType::Claude | AppType::ClaudeDesktop => {
|
||||
let env = settings.get("env");
|
||||
let base_url = str_at(env.and_then(|e| e.get("ANTHROPIC_BASE_URL")));
|
||||
let api_key = first_non_empty(
|
||||
env,
|
||||
&[
|
||||
"ANTHROPIC_AUTH_TOKEN",
|
||||
"ANTHROPIC_API_KEY",
|
||||
"OPENROUTER_API_KEY",
|
||||
"GOOGLE_API_KEY",
|
||||
],
|
||||
);
|
||||
(base_url, api_key)
|
||||
}
|
||||
};
|
||||
|
||||
// Normalize like the JS-script path (extract_base_url_from_provider) so a
|
||||
// future delegation from services/provider/usage.rs is behavior-preserving
|
||||
// and `{{baseUrl}}/path` concatenation never produces a double slash.
|
||||
(base_url.trim_end_matches('/').to_string(), api_key)
|
||||
}
|
||||
}
|
||||
|
||||
/// 供应商管理器
|
||||
@@ -1150,4 +1252,196 @@ mod tests {
|
||||
assert!(toml.contains("base_url = \"https://example.com/openai\""));
|
||||
assert!(!toml.contains("https://example.com/openai/v1"));
|
||||
}
|
||||
|
||||
// ── resolve_usage_credentials (per-app credential extraction) ──
|
||||
|
||||
use crate::app_config::AppType;
|
||||
|
||||
fn provider_with(settings_config: serde_json::Value) -> Provider {
|
||||
Provider::with_id("p".to_string(), "P".to_string(), settings_config, None)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_claude_env() {
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
|
||||
"ANTHROPIC_AUTH_TOKEN": "sk-claude",
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::Claude),
|
||||
(
|
||||
"https://api.deepseek.com/anthropic".to_string(),
|
||||
"sk-claude".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_claude_openrouter_fallback() {
|
||||
// OpenRouter-on-Claude keeps its key in OPENROUTER_API_KEY; the superset
|
||||
// fallback must still find it (regression guard for the per-app refactor).
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api/v1",
|
||||
"OPENROUTER_API_KEY": "sk-or",
|
||||
}
|
||||
}));
|
||||
let (base_url, api_key) = p.resolve_usage_credentials(&AppType::Claude);
|
||||
assert_eq!(base_url, "https://openrouter.ai/api/v1");
|
||||
assert_eq!(api_key, "sk-or");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_codex_auth_and_toml() {
|
||||
let p = provider_with(json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-codex" },
|
||||
"config": "model_provider = \"deepseek\"\n\
|
||||
[model_providers.deepseek]\n\
|
||||
base_url = \"https://api.deepseek.com\"\n",
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::Codex),
|
||||
(
|
||||
"https://api.deepseek.com".to_string(),
|
||||
"sk-codex".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_gemini_env_with_google_fallback() {
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"GOOGLE_GEMINI_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"GOOGLE_API_KEY": "g-legacy",
|
||||
}
|
||||
}));
|
||||
let (base_url, api_key) = p.resolve_usage_credentials(&AppType::Gemini);
|
||||
assert_eq!(base_url, "https://generativelanguage.googleapis.com");
|
||||
assert_eq!(api_key, "g-legacy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_claude_skips_empty_primary_key() {
|
||||
// Presets seed ANTHROPIC_AUTH_TOKEN as a present-but-empty placeholder.
|
||||
// The fallback chain must skip empty values (matching the frontend's
|
||||
// `a || b` semantics), not just absent keys.
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://openrouter.ai/api/v1",
|
||||
"ANTHROPIC_AUTH_TOKEN": "",
|
||||
"ANTHROPIC_API_KEY": "",
|
||||
"OPENROUTER_API_KEY": "sk-or",
|
||||
}
|
||||
}));
|
||||
let (_, api_key) = p.resolve_usage_credentials(&AppType::Claude);
|
||||
assert_eq!(api_key, "sk-or");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_gemini_skips_empty_primary_key() {
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"GOOGLE_GEMINI_BASE_URL": "https://generativelanguage.googleapis.com",
|
||||
"GEMINI_API_KEY": "",
|
||||
"GOOGLE_API_KEY": "g-real",
|
||||
}
|
||||
}));
|
||||
let (_, api_key) = p.resolve_usage_credentials(&AppType::Gemini);
|
||||
assert_eq!(api_key, "g-real");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_hermes_snake_case() {
|
||||
let p = provider_with(json!({
|
||||
"base_url": "https://api.deepseek.com",
|
||||
"api_key": "sk-hermes",
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::Hermes),
|
||||
(
|
||||
"https://api.deepseek.com".to_string(),
|
||||
"sk-hermes".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_openclaw_camel_case() {
|
||||
let p = provider_with(json!({
|
||||
"baseUrl": "https://api.deepseek.com",
|
||||
"apiKey": "sk-openclaw",
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::OpenClaw),
|
||||
(
|
||||
"https://api.deepseek.com".to_string(),
|
||||
"sk-openclaw".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_opencode_options() {
|
||||
// OpenCode (OMO) nests creds under options.{baseURL,apiKey}; useOpencodeFormState
|
||||
// writes config.options.apiKey, so the stored provider keeps them there.
|
||||
let p = provider_with(json!({
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"options": {
|
||||
"baseURL": "https://api.deepseek.com/v1",
|
||||
"apiKey": "sk-opencode",
|
||||
"setCacheKey": true,
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::OpenCode),
|
||||
(
|
||||
"https://api.deepseek.com/v1".to_string(),
|
||||
"sk-opencode".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_claude_desktop_uses_env() {
|
||||
// ClaudeDesktop persists the Anthropic env shape (ClaudeDesktopProviderForm
|
||||
// reads env.ANTHROPIC_BASE_URL / ANTHROPIC_AUTH_TOKEN), so it resolves via
|
||||
// the default env branch — it is NOT unsupported.
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
|
||||
"ANTHROPIC_AUTH_TOKEN": "sk-desktop",
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::ClaudeDesktop),
|
||||
(
|
||||
"https://api.deepseek.com/anthropic".to_string(),
|
||||
"sk-desktop".to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_trims_trailing_slash_on_base_url() {
|
||||
let p = provider_with(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic/",
|
||||
"ANTHROPIC_AUTH_TOKEN": "sk-claude",
|
||||
}
|
||||
}));
|
||||
let (base_url, _) = p.resolve_usage_credentials(&AppType::Claude);
|
||||
assert_eq!(base_url, "https://api.deepseek.com/anthropic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_credentials_missing_fields_yield_empty() {
|
||||
let p = provider_with(json!({}));
|
||||
assert_eq!(
|
||||
p.resolve_usage_credentials(&AppType::Claude),
|
||||
(String::new(), String::new())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 错误类型到 HTTP 状态码的映射
|
||||
//!
|
||||
//! 将 ProxyError 映射到合适的 HTTP 状态码,用于日志记录
|
||||
//! 将 ProxyError 映射到合适的 HTTP 状态码,用于日志记录和手动构建错误响应
|
||||
|
||||
use super::ProxyError;
|
||||
|
||||
@@ -12,14 +12,21 @@ use super::ProxyError;
|
||||
/// - 连接失败:502 Bad Gateway
|
||||
/// - 无可用 Provider:503 Service Unavailable
|
||||
/// - 重试耗尽:503 Service Unavailable
|
||||
/// - 认证错误:401 Unauthorized
|
||||
/// - 配置/请求错误:400 Bad Request
|
||||
/// - 转换错误:422 Unprocessable Entity
|
||||
/// - 其他错误:500 Internal Server Error
|
||||
pub fn map_proxy_error_to_status(error: &ProxyError) -> u16 {
|
||||
match error {
|
||||
// 服务状态错误:与 IntoResponse 保持一致
|
||||
ProxyError::AlreadyRunning => 409,
|
||||
ProxyError::NotRunning => 503,
|
||||
|
||||
// 上游错误:使用实际状态码
|
||||
ProxyError::UpstreamError { status, .. } => *status,
|
||||
|
||||
// 超时错误:504 Gateway Timeout
|
||||
ProxyError::Timeout(_) => 504,
|
||||
ProxyError::Timeout(_) | ProxyError::StreamIdleTimeout(_) => 504,
|
||||
|
||||
// 转发失败/连接失败:502 Bad Gateway
|
||||
ProxyError::ForwardFailed(_) => 502,
|
||||
@@ -39,11 +46,17 @@ pub fn map_proxy_error_to_status(error: &ProxyError) -> u16 {
|
||||
// Provider 不健康:503 Service Unavailable
|
||||
ProxyError::ProviderUnhealthy(_) => 503,
|
||||
|
||||
// 配置错误/无效请求:400 Bad Request
|
||||
ProxyError::ConfigError(_) | ProxyError::InvalidRequest(_) => 400,
|
||||
|
||||
// 认证错误:401 Unauthorized
|
||||
ProxyError::AuthError(_) => 401,
|
||||
|
||||
// 数据库错误:500 Internal Server Error
|
||||
ProxyError::DatabaseError(_) => 500,
|
||||
|
||||
// 转换错误:500 Internal Server Error
|
||||
ProxyError::TransformError(_) => 500,
|
||||
// 转换错误:422 Unprocessable Entity
|
||||
ProxyError::TransformError(_) => 422,
|
||||
|
||||
// 其他未知错误:500 Internal Server Error
|
||||
_ => 500,
|
||||
@@ -104,6 +117,30 @@ mod tests {
|
||||
assert_eq!(map_proxy_error_to_status(&error), 503);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_map_status_matches_proxy_error_response_semantics() {
|
||||
assert_eq!(
|
||||
map_proxy_error_to_status(&ProxyError::AuthError("bad token".to_string())),
|
||||
401
|
||||
);
|
||||
assert_eq!(
|
||||
map_proxy_error_to_status(&ProxyError::ConfigError("bad config".to_string())),
|
||||
400
|
||||
);
|
||||
assert_eq!(
|
||||
map_proxy_error_to_status(&ProxyError::InvalidRequest("bad request".to_string())),
|
||||
400
|
||||
);
|
||||
assert_eq!(
|
||||
map_proxy_error_to_status(&ProxyError::TransformError("bad transform".to_string())),
|
||||
422
|
||||
);
|
||||
assert_eq!(
|
||||
map_proxy_error_to_status(&ProxyError::StreamIdleTimeout(30)),
|
||||
504
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_error_message() {
|
||||
let error = ProxyError::UpstreamError {
|
||||
|
||||
@@ -122,6 +122,51 @@ pub struct RequestForwarder {
|
||||
}
|
||||
|
||||
impl RequestForwarder {
|
||||
/// 预防式 media 降级:发送前对 text-only 模型把图片块替换为标记。
|
||||
///
|
||||
/// 受 `enabled && request_media_fallback` 管辖;其中"启发式模型名单预测"
|
||||
/// 再受 `request_media_heuristic` 单独管辖(显式声明 text-only 始终生效)。
|
||||
/// 返回被替换的图片块数量(0 = 未触发或开关关闭)。
|
||||
fn apply_media_prevention(&self, body: &mut Value, provider: &Provider) -> usize {
|
||||
if !(self.rectifier_config.enabled && self.rectifier_config.request_media_fallback) {
|
||||
return 0;
|
||||
}
|
||||
let replaced_images = super::media_sanitizer::replace_images_for_text_only_model(
|
||||
body,
|
||||
provider,
|
||||
self.rectifier_config.request_media_heuristic,
|
||||
);
|
||||
if replaced_images > 0 {
|
||||
let model = body.get("model").and_then(Value::as_str).unwrap_or("");
|
||||
log::info!(
|
||||
"[Media] Replaced {replaced_images} image block(s) with {} for text-only provider={}, model={}",
|
||||
super::media_sanitizer::UNSUPPORTED_IMAGE_MARKER,
|
||||
provider.id,
|
||||
model
|
||||
);
|
||||
}
|
||||
replaced_images
|
||||
}
|
||||
|
||||
/// 反应式 media 重试判定:上游因图片输入报错后,是否应替换图片块并对同一供应商重试一次。
|
||||
///
|
||||
/// 受 `enabled && request_media_fallback` 管辖;不涉及 `request_media_heuristic`——
|
||||
/// 这里是上游"实测"错误后的纯恢复,不是预测,故启发式开关与它无关。
|
||||
fn media_retry_should_trigger(
|
||||
&self,
|
||||
adapter_name: &str,
|
||||
already_retried: bool,
|
||||
provider_body: &Value,
|
||||
error: &ProxyError,
|
||||
) -> bool {
|
||||
adapter_name == "Claude"
|
||||
&& self.rectifier_config.enabled
|
||||
&& self.rectifier_config.request_media_fallback
|
||||
&& !already_retried
|
||||
&& super::media_sanitizer::contains_image_blocks(provider_body)
|
||||
&& super::media_sanitizer::is_unsupported_image_error(error)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
router: Arc<ProviderRouter>,
|
||||
@@ -346,6 +391,7 @@ impl RequestForwarder {
|
||||
// —— 首家 provider 整流后被 5xx/timeout 击落时,下家仍能用整流后的请求体走整流流程
|
||||
let mut rectifier_retried = false;
|
||||
let mut budget_rectifier_retried = false;
|
||||
let mut media_rectifier_retried = false;
|
||||
|
||||
// 上限检查:尊重用户在 AppProxyConfig.max_retries 上配置的「重试次数」。
|
||||
// 放在熔断器 allow 检查之前,避免在已经超限时还占用 HalfOpen 探测名额。
|
||||
@@ -477,6 +523,123 @@ impl RequestForwarder {
|
||||
);
|
||||
let mut signature_rectifier_non_retryable_client_error = false;
|
||||
|
||||
if self.media_retry_should_trigger(
|
||||
adapter.name(),
|
||||
media_rectifier_retried,
|
||||
&provider_body,
|
||||
&e,
|
||||
) {
|
||||
let mut media_body = provider_body.clone();
|
||||
let replaced_images =
|
||||
super::media_sanitizer::replace_image_blocks_with_marker(
|
||||
&mut media_body,
|
||||
);
|
||||
|
||||
if replaced_images > 0 {
|
||||
let _ = std::mem::replace(&mut media_rectifier_retried, true);
|
||||
let model = media_body
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
log::info!(
|
||||
"[{app_type_str}] [Media] Upstream rejected image input; retrying provider={} model={} with {replaced_images} image block(s) replaced by {}",
|
||||
provider.id,
|
||||
model,
|
||||
super::media_sanitizer::UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
|
||||
match self
|
||||
.forward(
|
||||
app_type,
|
||||
&method,
|
||||
provider,
|
||||
endpoint,
|
||||
&media_body,
|
||||
&headers,
|
||||
&extensions,
|
||||
adapter.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((response, claude_api_format)) => {
|
||||
log::info!(
|
||||
"[{app_type_str}] [Media] Unsupported-image retry succeeded"
|
||||
);
|
||||
self.record_success_result(
|
||||
&provider.id,
|
||||
app_type_str,
|
||||
used_half_open_permit,
|
||||
)
|
||||
.await;
|
||||
|
||||
{
|
||||
let mut current_providers =
|
||||
self.current_providers.write().await;
|
||||
current_providers.insert(
|
||||
app_type_str.to_string(),
|
||||
(provider.id.clone(), provider.name.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
{
|
||||
let mut status = self.status.write().await;
|
||||
status.success_requests += 1;
|
||||
status.last_error = None;
|
||||
let should_switch =
|
||||
self.current_provider_id_at_start.as_str()
|
||||
!= provider.id.as_str();
|
||||
if should_switch {
|
||||
status.failover_count += 1;
|
||||
let fm = self.failover_manager.clone();
|
||||
let ah = self.app_handle.clone();
|
||||
let pid = provider.id.clone();
|
||||
let pname = provider.name.clone();
|
||||
let at = app_type_str.to_string();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let _ = fm
|
||||
.try_switch(ah.as_ref(), &at, &pid, &pname)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
if status.total_requests > 0 {
|
||||
status.success_rate = (status.success_requests as f32
|
||||
/ status.total_requests as f32)
|
||||
* 100.0;
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(ForwardResult {
|
||||
response,
|
||||
provider: provider.clone(),
|
||||
claude_api_format,
|
||||
connection_guard: None,
|
||||
});
|
||||
}
|
||||
Err(retry_err) => {
|
||||
log::warn!(
|
||||
"[{app_type_str}] [Media] Unsupported-image retry still failed: {retry_err}"
|
||||
);
|
||||
if let Some(err) = self
|
||||
.handle_rectifier_retry_failure(
|
||||
retry_err,
|
||||
provider,
|
||||
app_type_str,
|
||||
used_half_open_permit,
|
||||
"media 降级",
|
||||
&mut last_error,
|
||||
&mut last_provider,
|
||||
)
|
||||
.await
|
||||
{
|
||||
return Err(err);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if is_anthropic_provider {
|
||||
let error_message = extract_error_message(&e);
|
||||
if should_rectify_thinking_signature(
|
||||
@@ -1109,11 +1272,12 @@ impl RequestForwarder {
|
||||
};
|
||||
if adapter.name() == "Claude" {
|
||||
if let Some(api_format) = resolved_claude_api_format.as_deref() {
|
||||
super::providers::normalize_anthropic_tool_thinking_history_for_provider(
|
||||
super::providers::normalize_anthropic_messages_for_provider(
|
||||
&mut mapped_body,
|
||||
provider,
|
||||
api_format,
|
||||
);
|
||||
self.apply_media_prevention(&mut mapped_body, provider);
|
||||
}
|
||||
}
|
||||
let needs_transform = match resolved_claude_api_format.as_deref() {
|
||||
@@ -3106,4 +3270,160 @@ mod tests {
|
||||
assert_eq!(will_replace, should_replace, "{desc}");
|
||||
}
|
||||
}
|
||||
|
||||
// ===== P3: forwarder 层 media 开关回归测试 =====
|
||||
// 验证 gate 在 forwarder 这一层的"接线",而非 media_sanitizer 纯函数本身。
|
||||
|
||||
fn forwarder_with_rectifier(config: RectifierConfig) -> RequestForwarder {
|
||||
let mut fwd = test_forwarder(Duration::from_secs(1), Duration::from_secs(1));
|
||||
fwd.rectifier_config = config;
|
||||
fwd
|
||||
}
|
||||
|
||||
fn provider_with_settings(settings_config: Value) -> Provider {
|
||||
let mut p = test_provider_with_type(Some("anthropic"));
|
||||
p.settings_config = settings_config;
|
||||
p
|
||||
}
|
||||
|
||||
fn body_with_image(model: &str) -> Value {
|
||||
json!({
|
||||
"model": model,
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
fn image_unsupported_error() -> ProxyError {
|
||||
ProxyError::UpstreamError {
|
||||
status: 400,
|
||||
body: Some(
|
||||
r#"{"error":{"message":"This model does not support image input"}}"#.to_string(),
|
||||
),
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn prevention_replaces_when_all_switches_on_and_model_in_heuristic_list() {
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig::default());
|
||||
let provider = provider_with_settings(json!({}));
|
||||
let mut body = body_with_image("deepseek-v4-pro");
|
||||
|
||||
let replaced = fwd.apply_media_prevention(&mut body, &provider);
|
||||
|
||||
assert_eq!(replaced, 1, "默认全开 + 名单内模型应预替换");
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevention_skipped_when_media_fallback_off() {
|
||||
// 关闭 request_media_fallback:即使名单命中也不预替换。
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
request_media_fallback: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
let provider = provider_with_settings(json!({}));
|
||||
let mut body = body_with_image("deepseek-v4-pro");
|
||||
|
||||
let replaced = fwd.apply_media_prevention(&mut body, &provider);
|
||||
|
||||
assert_eq!(replaced, 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevention_skipped_when_master_switch_off() {
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
enabled: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
let provider = provider_with_settings(json!({}));
|
||||
let mut body = body_with_image("deepseek-v4-pro");
|
||||
|
||||
assert_eq!(fwd.apply_media_prevention(&mut body, &provider), 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prevention_heuristic_off_skips_list_but_keeps_explicit_text_only() {
|
||||
// 关闭 request_media_heuristic:名单预测失效,但显式声明 text-only 仍预替换。
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
request_media_heuristic: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
|
||||
// (a) 名单内模型、无显式声明 → 不再预替换
|
||||
let bare_provider = provider_with_settings(json!({}));
|
||||
let mut list_body = body_with_image("deepseek-v4-pro");
|
||||
assert_eq!(
|
||||
fwd.apply_media_prevention(&mut list_body, &bare_provider),
|
||||
0,
|
||||
"heuristic 关闭后名单模型不应被预替换"
|
||||
);
|
||||
assert_eq!(list_body["messages"][0]["content"][0]["type"], "image");
|
||||
|
||||
// (b) 显式声明 text-only → 仍预替换(声明驱动,不受 heuristic 开关影响)
|
||||
let declared_provider = provider_with_settings(json!({
|
||||
"models": [ { "id": "some-text-model", "input": ["text"] } ]
|
||||
}));
|
||||
let mut declared_body = body_with_image("some-text-model");
|
||||
assert_eq!(
|
||||
fwd.apply_media_prevention(&mut declared_body, &declared_provider),
|
||||
1,
|
||||
"显式 text-only 即使关闭 heuristic 也应预替换"
|
||||
);
|
||||
assert_eq!(declared_body["messages"][0]["content"][0]["type"], "text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactive_triggers_when_all_switches_on() {
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig::default());
|
||||
let body = body_with_image("any-model");
|
||||
assert!(fwd.media_retry_should_trigger("Claude", false, &body, &image_unsupported_error()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactive_skipped_when_media_fallback_off() {
|
||||
// 关闭 request_media_fallback:上游报图片错误也不触发兜底重试。
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
request_media_fallback: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
let body = body_with_image("any-model");
|
||||
assert!(!fwd.media_retry_should_trigger(
|
||||
"Claude",
|
||||
false,
|
||||
&body,
|
||||
&image_unsupported_error()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactive_skipped_when_master_switch_off() {
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
enabled: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
let body = body_with_image("any-model");
|
||||
assert!(!fwd.media_retry_should_trigger(
|
||||
"Claude",
|
||||
false,
|
||||
&body,
|
||||
&image_unsupported_error()
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactive_unaffected_by_heuristic_switch() {
|
||||
// 关闭 request_media_heuristic 不影响反应式兜底——它是上游实测错误后的恢复,不是预测。
|
||||
let fwd = forwarder_with_rectifier(RectifierConfig {
|
||||
request_media_heuristic: false,
|
||||
..RectifierConfig::default()
|
||||
});
|
||||
let body = body_with_image("any-model");
|
||||
assert!(fwd.media_retry_should_trigger("Claude", false, &body, &image_unsupported_error()));
|
||||
}
|
||||
}
|
||||
|
||||
+312
-11
@@ -18,7 +18,7 @@ use super::{
|
||||
providers::{
|
||||
codex_chat_history::record_responses_sse_stream, get_adapter, get_claude_api_format,
|
||||
streaming::create_anthropic_sse_stream,
|
||||
streaming_codex_chat::create_responses_sse_stream_from_chat,
|
||||
streaming_codex_chat::create_responses_sse_stream_from_chat_with_context,
|
||||
streaming_gemini::create_anthropic_sse_stream_from_gemini,
|
||||
streaming_responses::create_anthropic_sse_stream_from_responses, transform,
|
||||
transform_codex_chat, transform_gemini, transform_responses,
|
||||
@@ -62,6 +62,41 @@ pub async fn get_status(State(state): State<ProxyState>) -> Result<Json<ProxySta
|
||||
Ok(Json(status))
|
||||
}
|
||||
|
||||
/// GET /v1/models — Codex model list (reachability check)
|
||||
///
|
||||
/// Codex CLI probes this endpoint at startup and deserializes the response as a
|
||||
/// catalog with a top-level `models` field. Return the cc-switch–managed model
|
||||
/// catalog file directly so the format always matches what the current version
|
||||
/// of Codex expects.
|
||||
///
|
||||
/// Only serves the catalog when the live config.toml still references the
|
||||
/// cc-switch–owned `model_catalog_json`, using the same path ownership rules as
|
||||
/// Codex live-setting import.
|
||||
pub async fn handle_models() -> Result<Json<Value>, ProxyError> {
|
||||
let generated_path = crate::codex_config::get_codex_model_catalog_path();
|
||||
let active_catalog_path = match crate::codex_config::read_codex_config_text() {
|
||||
Ok(config_text) => {
|
||||
crate::codex_config::resolve_cc_switch_catalog_path(&config_text, &generated_path)
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
let catalog = if let Some(catalog_path) =
|
||||
active_catalog_path.as_ref().filter(|path| path.exists())
|
||||
{
|
||||
let text = std::fs::read_to_string(catalog_path).unwrap_or_default();
|
||||
serde_json::from_str(&text).unwrap_or(json!({"models": []}))
|
||||
} else {
|
||||
if active_catalog_path.is_none() {
|
||||
log::debug!(
|
||||
"[models] stale guard: catalog not served (model_catalog_json not set to cc-switch catalog)"
|
||||
);
|
||||
}
|
||||
json!({"models": []})
|
||||
};
|
||||
Ok(Json(catalog))
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Claude API 处理器(包含格式转换逻辑)
|
||||
// ============================================================================
|
||||
@@ -522,7 +557,7 @@ pub async fn handle_chat_completions(
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
return build_codex_proxy_error_response(&ctx, &endpoint, &err.error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -566,6 +601,7 @@ pub async fn handle_responses(
|
||||
.get("stream")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let codex_tool_context = transform_codex_chat::build_codex_tool_context_from_request(&body);
|
||||
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let mut result = match forwarder
|
||||
@@ -586,7 +622,7 @@ pub async fn handle_responses(
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
return build_codex_proxy_error_response(&ctx, &endpoint, &err.error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -601,6 +637,7 @@ pub async fn handle_responses(
|
||||
&state,
|
||||
is_stream,
|
||||
connection_guard,
|
||||
codex_tool_context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -641,6 +678,7 @@ pub async fn handle_responses_compact(
|
||||
.get("stream")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let codex_tool_context = transform_codex_chat::build_codex_tool_context_from_request(&body);
|
||||
|
||||
let forwarder = ctx.create_forwarder(&state);
|
||||
let mut result = match forwarder
|
||||
@@ -661,7 +699,7 @@ pub async fn handle_responses_compact(
|
||||
ctx.provider = provider;
|
||||
}
|
||||
log_forward_error(&state, &ctx, is_stream, &err.error);
|
||||
return Err(err.error);
|
||||
return build_codex_proxy_error_response(&ctx, &endpoint, &err.error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -676,6 +714,7 @@ pub async fn handle_responses_compact(
|
||||
&state,
|
||||
is_stream,
|
||||
connection_guard,
|
||||
codex_tool_context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
@@ -696,6 +735,7 @@ async fn handle_codex_chat_to_responses_transform(
|
||||
state: &ProxyState,
|
||||
is_stream: bool,
|
||||
connection_guard: Option<ActiveConnectionGuard>,
|
||||
tool_context: transform_codex_chat::CodexToolContext,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = response.status();
|
||||
|
||||
@@ -708,7 +748,7 @@ async fn handle_codex_chat_to_responses_transform(
|
||||
|
||||
if is_stream || response.is_sse() {
|
||||
let stream = response.bytes_stream();
|
||||
let sse_stream = create_responses_sse_stream_from_chat(stream);
|
||||
let sse_stream = create_responses_sse_stream_from_chat_with_context(stream, tool_context);
|
||||
let sse_stream = record_responses_sse_stream(sse_stream, state.codex_chat_history.clone());
|
||||
|
||||
let usage_collector = if usage_logging_enabled(state) {
|
||||
@@ -790,11 +830,14 @@ async fn handle_codex_chat_to_responses_transform(
|
||||
log::error!("[Codex] 解析 Chat 上游响应失败: {e}, body: {body_str}");
|
||||
ProxyError::TransformError(format!("Failed to parse upstream chat response: {e}"))
|
||||
})?;
|
||||
let responses_response = transform_codex_chat::chat_completion_to_response(chat_response)
|
||||
.map_err(|e| {
|
||||
log::error!("[Codex] Chat → Responses 响应转换失败: {e}");
|
||||
e
|
||||
})?;
|
||||
let responses_response = transform_codex_chat::chat_completion_to_response_with_context(
|
||||
chat_response,
|
||||
&tool_context,
|
||||
)
|
||||
.map_err(|e| {
|
||||
log::error!("[Codex] Chat → Responses 响应转换失败: {e}");
|
||||
e
|
||||
})?;
|
||||
state
|
||||
.codex_chat_history
|
||||
.record_response(&responses_response)
|
||||
@@ -926,6 +969,195 @@ async fn handle_codex_chat_error_response(
|
||||
})
|
||||
}
|
||||
|
||||
/// 把转发层(非上游响应)的失败构造成富化的 Codex 错误响应。
|
||||
///
|
||||
/// 与 `handle_codex_chat_error_response`(处理上游真实错误响应、复制上游头)不同,
|
||||
/// 这里没有上游响应可参照,只产出一个 `application/json` 错误体。状态码走
|
||||
/// `map_proxy_error_to_status`,该函数已与 `ProxyError::into_response` 对齐。
|
||||
///
|
||||
/// 注意:`endpoint` 经 `endpoint_with_query` 可能携带 query(如 `?beta=true`)并被
|
||||
/// 原样写入错误体。当前 Codex 端点不在 query 里放凭证,故安全;若将来复用到
|
||||
/// query 携带密钥的端点(如 Gemini 的 `?key=`),需先脱敏再回显。
|
||||
fn build_codex_proxy_error_response(
|
||||
ctx: &RequestContext,
|
||||
endpoint: &str,
|
||||
error: &ProxyError,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = axum::http::StatusCode::from_u16(map_proxy_error_to_status(error))
|
||||
.unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let body = codex_proxy_error_json(&ctx.provider.name, &ctx.request_model, endpoint, error);
|
||||
let body = serde_json::to_vec(&body).map_err(|e| {
|
||||
log::error!("[Codex] 序列化代理错误体失败: {e}");
|
||||
ProxyError::Internal(format!("Failed to serialize proxy error: {e}"))
|
||||
})?;
|
||||
|
||||
axum::response::Response::builder()
|
||||
.status(status)
|
||||
.header(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderValue::from_static("application/json"),
|
||||
)
|
||||
.body(axum::body::Body::from(body))
|
||||
.map_err(|e| {
|
||||
log::error!("[Codex] 构建代理错误响应失败: {e}");
|
||||
ProxyError::Internal(format!("Failed to build proxy error response: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn codex_proxy_error_json(
|
||||
provider_name: &str,
|
||||
request_model: &str,
|
||||
endpoint: &str,
|
||||
error: &ProxyError,
|
||||
) -> Value {
|
||||
let (mut body, upstream_status) = match error {
|
||||
ProxyError::UpstreamError { status, body } => {
|
||||
let parsed_body = body
|
||||
.as_deref()
|
||||
.map(|body| serde_json::from_str::<Value>(body).unwrap_or_else(|_| json!(body)));
|
||||
(
|
||||
transform_codex_chat::chat_error_to_response_error(parsed_body.as_ref()),
|
||||
Some(*status),
|
||||
)
|
||||
}
|
||||
_ => (
|
||||
json!({
|
||||
"error": {
|
||||
"message": get_error_message(error),
|
||||
"type": "proxy_error",
|
||||
"code": codex_proxy_error_code(error),
|
||||
"param": Value::Null,
|
||||
}
|
||||
}),
|
||||
None,
|
||||
),
|
||||
};
|
||||
|
||||
let Some(error_obj) = body
|
||||
.get_mut("error")
|
||||
.and_then(|value| value.as_object_mut())
|
||||
else {
|
||||
return body;
|
||||
};
|
||||
|
||||
let message = if upstream_status == Some(413) {
|
||||
// 413 来自上游渠道商的网关(典型是 nginx 的 client_max_body_size),不是 CC
|
||||
// Switch 本地代理的限制(本地 DefaultBodyLimit 已放到 200MB)。上游响应体往往是
|
||||
// 一整段 nginx HTML,对用户毫无价值,这里替换成明确指向上游 + 可操作的指引,
|
||||
// 避免「以为是 CC Switch 封装了 nginx / 是本地代理的锅」这种反复出现的误解。
|
||||
format!(
|
||||
concat!(
|
||||
"Upstream provider rejected the request with HTTP 413 (Payload Too Large). ",
|
||||
"The request body exceeds the upstream gateway's size limit; this is the ",
|
||||
"provider's server-side limit, not a CC Switch limit. ",
|
||||
"Provider: {provider}; model: {model}; endpoint: {endpoint}. ",
|
||||
"To recover, shrink the request: run /compact, remove large pasted logs or ",
|
||||
"inline images, or ask the provider to raise its request body limit ",
|
||||
"(e.g. nginx client_max_body_size)."
|
||||
),
|
||||
provider = provider_name,
|
||||
model = request_model,
|
||||
endpoint = endpoint,
|
||||
)
|
||||
} else {
|
||||
let cause = error_obj
|
||||
.get("message")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(ToString::to_string)
|
||||
.filter(|message| !message.trim().is_empty())
|
||||
.unwrap_or_else(|| get_error_message(error));
|
||||
let status_fragment = upstream_status
|
||||
.map(|status| format!("; upstream_status: HTTP {status}"))
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
"CC Switch local proxy failed while handling Codex endpoint {endpoint}. Provider: {provider_name}; model: {request_model}{status_fragment}; cause: {cause}"
|
||||
)
|
||||
};
|
||||
|
||||
error_obj.insert(
|
||||
"message".to_string(),
|
||||
Value::String(compact_error_message(&message, 1800)),
|
||||
);
|
||||
|
||||
if error_obj
|
||||
.get("type")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(|value| value.trim().is_empty())
|
||||
.unwrap_or(true)
|
||||
{
|
||||
error_obj.insert("type".to_string(), Value::String("proxy_error".to_string()));
|
||||
}
|
||||
|
||||
if error_obj.get("code").map(Value::is_null).unwrap_or(true) {
|
||||
error_obj.insert(
|
||||
"code".to_string(),
|
||||
Value::String(codex_proxy_error_code(error).to_string()),
|
||||
);
|
||||
}
|
||||
|
||||
if !error_obj.contains_key("param") {
|
||||
error_obj.insert("param".to_string(), Value::Null);
|
||||
}
|
||||
|
||||
error_obj.insert(
|
||||
"provider".to_string(),
|
||||
Value::String(provider_name.to_string()),
|
||||
);
|
||||
error_obj.insert(
|
||||
"model".to_string(),
|
||||
Value::String(request_model.to_string()),
|
||||
);
|
||||
// 仅用于 Codex 本地路由;不要复用到 query 可能携带凭证的端点。
|
||||
error_obj.insert("endpoint".to_string(), Value::String(endpoint.to_string()));
|
||||
if let Some(status) = upstream_status {
|
||||
error_obj.insert(
|
||||
"upstream_status".to_string(),
|
||||
Value::Number(serde_json::Number::from(status)),
|
||||
);
|
||||
}
|
||||
|
||||
body
|
||||
}
|
||||
|
||||
fn codex_proxy_error_code(error: &ProxyError) -> &'static str {
|
||||
match error {
|
||||
ProxyError::ForwardFailed(_) => "cc_switch_forward_failed",
|
||||
ProxyError::Timeout(_) | ProxyError::StreamIdleTimeout(_) => "cc_switch_timeout",
|
||||
ProxyError::NoAvailableProvider => "cc_switch_no_available_provider",
|
||||
ProxyError::AllProvidersCircuitOpen => "cc_switch_all_providers_circuit_open",
|
||||
ProxyError::NoProvidersConfigured => "cc_switch_no_providers_configured",
|
||||
ProxyError::MaxRetriesExceeded => "cc_switch_max_retries_exceeded",
|
||||
ProxyError::ProviderUnhealthy(_) => "cc_switch_provider_unhealthy",
|
||||
ProxyError::ConfigError(_) => "cc_switch_config_error",
|
||||
ProxyError::TransformError(_) => "cc_switch_transform_error",
|
||||
ProxyError::InvalidRequest(_) => "cc_switch_invalid_request",
|
||||
ProxyError::AuthError(_) => "cc_switch_auth_error",
|
||||
ProxyError::UpstreamError { .. } => "cc_switch_upstream_error",
|
||||
ProxyError::DatabaseError(_) => "cc_switch_database_error",
|
||||
ProxyError::Internal(_) => "cc_switch_internal_error",
|
||||
ProxyError::AlreadyRunning
|
||||
| ProxyError::NotRunning
|
||||
| ProxyError::BindFailed(_)
|
||||
| ProxyError::StopTimeout
|
||||
| ProxyError::StopFailed(_) => "cc_switch_proxy_error",
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_error_message(message: &str, max_chars: usize) -> String {
|
||||
let normalized = message.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
if normalized.chars().count() <= max_chars {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
let truncated = normalized
|
||||
.chars()
|
||||
.take(max_chars)
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string();
|
||||
format!("{truncated}…(truncated)")
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Gemini API 处理器
|
||||
// ============================================================================
|
||||
@@ -1176,7 +1408,10 @@ async fn log_usage(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{responses_sse_to_response_value, should_use_claude_transform_streaming};
|
||||
use super::{
|
||||
codex_proxy_error_json, responses_sse_to_response_value,
|
||||
should_use_claude_transform_streaming,
|
||||
};
|
||||
use crate::proxy::ProxyError;
|
||||
|
||||
#[test]
|
||||
@@ -1263,4 +1498,70 @@ data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\"}}\n
|
||||
|
||||
assert!(responses_sse_to_response_value(sse).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_proxy_forward_error_includes_context_and_cause() {
|
||||
let error = ProxyError::ForwardFailed("连接失败: dns lookup failed".to_string());
|
||||
let body = codex_proxy_error_json("DeepSeek", "deepseek-chat", "/responses", &error);
|
||||
|
||||
let message = body["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("CC Switch local proxy failed"));
|
||||
assert!(message.contains("DeepSeek"));
|
||||
assert!(message.contains("deepseek-chat"));
|
||||
assert!(message.contains("/responses"));
|
||||
assert!(message.contains("dns lookup failed"));
|
||||
assert_eq!(body["error"]["code"], "cc_switch_forward_failed");
|
||||
assert_eq!(body["error"]["provider"], "DeepSeek");
|
||||
assert_eq!(body["error"]["model"], "deepseek-chat");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_proxy_upstream_error_normalizes_nonstandard_body() {
|
||||
let error = ProxyError::UpstreamError {
|
||||
status: 502,
|
||||
body: Some(
|
||||
r#"{"base_resp":{"status_code":2013,"status_msg":"upstream gateway failed"}}"#
|
||||
.to_string(),
|
||||
),
|
||||
};
|
||||
let body = codex_proxy_error_json("MiniMax", "abab6.5s", "/responses", &error);
|
||||
|
||||
let message = body["error"]["message"].as_str().unwrap();
|
||||
assert!(message.contains("upstream_status: HTTP 502"));
|
||||
assert!(message.contains("upstream gateway failed"));
|
||||
assert_eq!(body["error"]["code"], 2013);
|
||||
assert_eq!(body["error"]["upstream_status"], 502);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_proxy_413_points_to_upstream_not_local_proxy() {
|
||||
// 模拟上游渠道商 nginx 因 client_max_body_size 返回的 413 HTML 页面
|
||||
// (见 issue #666:长上下文 / 大图 / 大日志撞上游体积上限)
|
||||
let error = ProxyError::UpstreamError {
|
||||
status: 413,
|
||||
body: Some(
|
||||
"<html>\r\n<head><title>413 Request Entity Too Large</title></head>\r\n\
|
||||
<body>\r\n<center><h1>413 Request Entity Too Large</h1></center>\r\n\
|
||||
<hr><center>nginx/1.29.6</center>\r\n</body>\r\n</html>"
|
||||
.to_string(),
|
||||
),
|
||||
};
|
||||
let body = codex_proxy_error_json("HCAI", "gpt-5.5", "/responses", &error);
|
||||
|
||||
let message = body["error"]["message"].as_str().unwrap();
|
||||
// 不再误导成「本地代理失败」
|
||||
assert!(!message.contains("CC Switch local proxy failed"));
|
||||
// 明确指向上游 + 体积超限 + 可操作指引
|
||||
assert!(message.contains("413"));
|
||||
assert!(message.to_lowercase().contains("upstream"));
|
||||
assert!(message.contains("/compact"));
|
||||
// 关键:不把整段 nginx HTML 回显给用户
|
||||
assert!(!message.contains("<html>"));
|
||||
assert!(!message.contains("nginx/1.29.6"));
|
||||
// 结构化字段仍然保留,便于程序化消费 / UI 呈现
|
||||
assert_eq!(body["error"]["upstream_status"], 413);
|
||||
assert_eq!(body["error"]["provider"], "HCAI");
|
||||
assert_eq!(body["error"]["model"], "gpt-5.5");
|
||||
assert_eq!(body["error"]["endpoint"], "/responses");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,703 @@
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub const UNSUPPORTED_IMAGE_MARKER: &str = "[Unsupported Image]";
|
||||
|
||||
/// Replace image blocks before sending when the routed model is text-only.
|
||||
///
|
||||
/// Two paths, both reached only when the caller's media-fallback switch is on:
|
||||
/// - explicit capability from the provider config (modelCatalog / modalities) is
|
||||
/// always trusted — it is declaration-driven, never a guess;
|
||||
/// - the curated `known_text_only_model` list is a heuristic *prediction* and only
|
||||
/// runs when `allow_heuristic` is true, so a mislabeled multimodal model cannot
|
||||
/// have its images silently stripped when the user opts out.
|
||||
pub fn replace_images_for_text_only_model(
|
||||
body: &mut Value,
|
||||
provider: &Provider,
|
||||
allow_heuristic: bool,
|
||||
) -> usize {
|
||||
if !contains_image_blocks(body) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let model = body
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.unwrap_or("");
|
||||
|
||||
match explicit_model_image_support(provider, model) {
|
||||
Some(true) => return 0,
|
||||
Some(false) => return replace_images_in_body(body),
|
||||
None => {}
|
||||
}
|
||||
|
||||
if !allow_heuristic || !known_text_only_model(model) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
replace_images_in_body(body)
|
||||
}
|
||||
|
||||
pub fn contains_image_blocks(body: &Value) -> bool {
|
||||
body.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|messages| {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| message.get("content"))
|
||||
.any(content_has_image_blocks)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn replace_image_blocks_with_marker(body: &mut Value) -> usize {
|
||||
replace_images_in_body(body)
|
||||
}
|
||||
|
||||
pub fn is_unsupported_image_error(error: &ProxyError) -> bool {
|
||||
let ProxyError::UpstreamError { status, body } = error else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !matches!(*status, 400 | 415 | 422 | 501) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(body) = body.as_deref() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let message = extract_error_text(body);
|
||||
let message = message.to_ascii_lowercase();
|
||||
let mentions_image = message.contains("image")
|
||||
|| message.contains("vision")
|
||||
|| message.contains("multimodal")
|
||||
|| message.contains("multi-modal")
|
||||
|| message.contains("modality")
|
||||
|| message.contains("modalities")
|
||||
|| message.contains("media")
|
||||
|| message.contains("attachment");
|
||||
|
||||
if !mentions_image {
|
||||
return false;
|
||||
}
|
||||
|
||||
const UNSUPPORTED_HINTS: &[&str] = &[
|
||||
"unsupported",
|
||||
"not supported",
|
||||
"does not support",
|
||||
"doesn't support",
|
||||
"do not support",
|
||||
"don't support",
|
||||
"only supports text",
|
||||
"text only",
|
||||
"text-only",
|
||||
"invalid content type",
|
||||
"invalid message content",
|
||||
"unknown content type",
|
||||
"unrecognized content type",
|
||||
"cannot process",
|
||||
"cannot handle",
|
||||
"can't process",
|
||||
"can't handle",
|
||||
"unable to process",
|
||||
];
|
||||
|
||||
UNSUPPORTED_HINTS.iter().any(|hint| message.contains(hint))
|
||||
}
|
||||
|
||||
fn content_has_image_blocks(content: &Value) -> bool {
|
||||
let Some(blocks) = content.as_array() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
blocks.iter().any(|block| {
|
||||
block.get("type").and_then(Value::as_str) == Some("image")
|
||||
|| block.get("content").is_some_and(content_has_image_blocks)
|
||||
})
|
||||
}
|
||||
|
||||
fn replace_images_in_body(body: &mut Value) -> usize {
|
||||
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
messages
|
||||
.iter_mut()
|
||||
.filter_map(|message| message.get_mut("content"))
|
||||
.map(replace_images_in_content)
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn replace_images_in_content(content: &mut Value) -> usize {
|
||||
let Some(blocks) = content.as_array_mut() else {
|
||||
return 0;
|
||||
};
|
||||
|
||||
let mut replaced = 0usize;
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) == Some("image") {
|
||||
let cache_control = block.get("cache_control").cloned();
|
||||
*block = json!({
|
||||
"type": "text",
|
||||
"text": UNSUPPORTED_IMAGE_MARKER
|
||||
});
|
||||
if let (Some(cache_control), Some(object)) = (cache_control, block.as_object_mut()) {
|
||||
object.insert("cache_control".to_string(), cache_control);
|
||||
}
|
||||
replaced += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(nested_content) = block.get_mut("content") {
|
||||
replaced += replace_images_in_content(nested_content);
|
||||
}
|
||||
}
|
||||
|
||||
replaced
|
||||
}
|
||||
|
||||
fn explicit_model_image_support(provider: &Provider, model: &str) -> Option<bool> {
|
||||
let settings = &provider.settings_config;
|
||||
[
|
||||
settings
|
||||
.get("modelCatalog")
|
||||
.and_then(|catalog| catalog.get("models")),
|
||||
settings.get("modelCatalog"),
|
||||
settings.get("models"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|value| explicit_model_image_support_in_value(value, model))
|
||||
}
|
||||
|
||||
fn known_text_only_model(model: &str) -> bool {
|
||||
let normalized = normalize_model_id(model);
|
||||
let tail = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
|
||||
|
||||
const EXACT_TAILS: &[&str] = &[
|
||||
"ark-code-latest",
|
||||
"deepseek-chat",
|
||||
"deepseek-reasoner",
|
||||
"deepseek-v4-flash",
|
||||
"deepseek-v4-pro",
|
||||
"glm-5.1",
|
||||
"kat-coder",
|
||||
"kat-coder-pro",
|
||||
"kat-coder-pro v1",
|
||||
"kat-coder-pro v2",
|
||||
"kat-coder-pro-v1",
|
||||
"kat-coder-pro-v2",
|
||||
"ling-2.5-1t",
|
||||
"longcat-flash-chat",
|
||||
"mimo-v2.5-pro",
|
||||
"us.deepseek.r1-v1",
|
||||
];
|
||||
|
||||
const TAIL_PREFIXES: &[&str] = &["minimax-m2.7", "qwen3-coder", "step-3.5-flash"];
|
||||
|
||||
EXACT_TAILS.contains(&tail) || TAIL_PREFIXES.iter().any(|prefix| tail.starts_with(prefix))
|
||||
}
|
||||
|
||||
fn explicit_model_image_support_in_value(value: &Value, model: &str) -> Option<bool> {
|
||||
if let Some(models) = value.as_array() {
|
||||
return models.iter().find_map(|entry| {
|
||||
model_entry_matches(entry, None, model).then(|| explicit_image_support(entry))?
|
||||
});
|
||||
}
|
||||
|
||||
let object = value.as_object()?;
|
||||
object.iter().find_map(|(key, entry)| {
|
||||
model_entry_matches(entry, Some(key), model).then(|| explicit_image_support(entry))?
|
||||
})
|
||||
}
|
||||
|
||||
fn explicit_image_support(entry: &Value) -> Option<bool> {
|
||||
if let Some(value) = entry
|
||||
.get("supportsImage")
|
||||
.or_else(|| entry.get("supports_image"))
|
||||
.or_else(|| entry.get("vision"))
|
||||
.and_then(Value::as_bool)
|
||||
{
|
||||
return Some(value);
|
||||
}
|
||||
|
||||
[
|
||||
entry.get("input"),
|
||||
entry.pointer("/modalities/input"),
|
||||
entry.get("input_modalities"),
|
||||
entry.get("inputModalities"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(input_modalities_support_image)
|
||||
}
|
||||
|
||||
fn input_modalities_support_image(value: &Value) -> Option<bool> {
|
||||
let modalities = value.as_array()?;
|
||||
Some(modalities.iter().any(|item| {
|
||||
item.as_str()
|
||||
.map(str::trim)
|
||||
.is_some_and(|item| item.eq_ignore_ascii_case("image"))
|
||||
}))
|
||||
}
|
||||
|
||||
fn extract_error_text(body: &str) -> String {
|
||||
if let Ok(value) = serde_json::from_str::<Value>(body) {
|
||||
let candidates = [
|
||||
value.pointer("/error/message"),
|
||||
value.pointer("/message"),
|
||||
value.pointer("/detail"),
|
||||
value.pointer("/error"),
|
||||
];
|
||||
if let Some(message) = candidates
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|value| value.as_str())
|
||||
{
|
||||
return message.to_string();
|
||||
}
|
||||
|
||||
if let Ok(compact) = serde_json::to_string(&value) {
|
||||
return compact;
|
||||
}
|
||||
}
|
||||
|
||||
body.to_string()
|
||||
}
|
||||
|
||||
fn model_entry_matches(entry: &Value, key: Option<&str>, model: &str) -> bool {
|
||||
key.is_some_and(|key| model_ids_match(key, model))
|
||||
|| ["model", "id", "name"]
|
||||
.into_iter()
|
||||
.filter_map(|field| entry.get(field).and_then(Value::as_str))
|
||||
.any(|candidate| model_ids_match(candidate, model))
|
||||
}
|
||||
|
||||
fn model_ids_match(candidate: &str, model: &str) -> bool {
|
||||
let candidate = normalize_model_id(candidate);
|
||||
let model = normalize_model_id(model);
|
||||
if candidate.is_empty() || model.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if candidate == model {
|
||||
return true;
|
||||
}
|
||||
|
||||
let candidate_tail = candidate.rsplit('/').next().unwrap_or(candidate.as_str());
|
||||
let model_tail = model.rsplit('/').next().unwrap_or(model.as_str());
|
||||
candidate_tail == model_tail || candidate == model_tail || candidate_tail == model
|
||||
}
|
||||
|
||||
fn normalize_model_id(value: &str) -> String {
|
||||
let mut normalized = value
|
||||
.trim()
|
||||
.trim_start_matches("models/")
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
if let Some(stripped) =
|
||||
normalized.strip_suffix(crate::claude_desktop_config::ONE_M_CONTEXT_MARKER)
|
||||
{
|
||||
normalized = stripped.trim().to_string();
|
||||
}
|
||||
normalized
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::provider::Provider;
|
||||
use serde_json::json;
|
||||
|
||||
fn provider(settings_config: Value) -> Provider {
|
||||
Provider {
|
||||
id: "test".to_string(),
|
||||
name: "Test".to_string(),
|
||||
settings_config,
|
||||
website_url: None,
|
||||
category: None,
|
||||
created_at: None,
|
||||
sort_index: None,
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_images_when_model_capability_is_unknown() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "unknown-model",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "text", "text": "look" },
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(body["messages"][0]["content"][1]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_models_replace_images_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek/deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_text_modalities_replace_images_before_send() {
|
||||
let provider = provider(json!({
|
||||
"models": [
|
||||
{ "id": "deepseek-v4-pro", "input": ["text"] }
|
||||
]
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "text", "text": "look" },
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(body["messages"][0]["content"][0]["text"], "look");
|
||||
assert_eq!(body["messages"][0]["content"][1]["type"], "text");
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][1]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_images_without_explicit_capability_even_for_unknown_models() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "unknown-model",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_text_modalities_can_override_visual_model_ids() {
|
||||
let provider = provider(json!({
|
||||
"models": [
|
||||
{ "id": "gpt-4o", "input": ["text"] }
|
||||
]
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "gpt-4o",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_image_modalities_preserve_model_images() {
|
||||
let provider = provider(json!({
|
||||
"modelCatalog": {
|
||||
"models": [
|
||||
{ "model": "deepseek-v4-pro", "modalities": { "input": ["text", "image"] } }
|
||||
]
|
||||
}
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_mimo_pro_replaces_but_mimo_multimodal_preserves() {
|
||||
let provider = provider(json!({}));
|
||||
let mut pro_body = json!({
|
||||
"model": "xiaomi-mimo-token-plan/mimo-v2.5-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
let mut multimodal_body = json!({
|
||||
"model": "xiaomi-mimo-token-plan/mimo-v2.5",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let pro_count = replace_images_for_text_only_model(&mut pro_body, &provider, true);
|
||||
let multimodal_count =
|
||||
replace_images_for_text_only_model(&mut multimodal_body, &provider, true);
|
||||
|
||||
assert_eq!(pro_count, 1);
|
||||
assert_eq!(multimodal_count, 0);
|
||||
assert_eq!(
|
||||
multimodal_body["messages"][0]["content"][0]["type"],
|
||||
"image"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multimodal_kimi_model_is_not_on_text_only_list() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "kimi/kimi-k2.6",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_prefixes_replace_images_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "therouter/qwen/qwen3-coder-480b",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, true);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unconditional_marker_replacement_handles_retry_path() {
|
||||
let mut body = json!({
|
||||
"model": "xiaomi-mimo-token-plan/mimo-v2.5-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
assert!(contains_image_blocks(&body));
|
||||
let count = replace_image_blocks_with_marker(&mut body);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_nested_tool_result_image_blocks() {
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": "toolu_1",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_image_blocks_with_marker(&mut body);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_unsupported_image_errors() {
|
||||
let error = ProxyError::UpstreamError {
|
||||
status: 400,
|
||||
body: Some(
|
||||
r#"{"error":{"message":"This model does not support image input"}}"#.to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
assert!(is_unsupported_image_error(&error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_image_errors() {
|
||||
let error = ProxyError::UpstreamError {
|
||||
status: 400,
|
||||
body: Some(r#"{"error":{"message":"Invalid API key"}}"#.to_string()),
|
||||
};
|
||||
|
||||
assert!(!is_unsupported_image_error(&error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_cache_control_when_replacing_image() {
|
||||
// image block 可能承载 prompt cache 断点;替换成标记时必须把
|
||||
// cache_control 迁移到新的 text block,否则会断掉缓存命中。
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "image",
|
||||
"source": { "type": "base64", "media_type": "image/png", "data": "abc" },
|
||||
"cache_control": { "type": "ephemeral" }
|
||||
}]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_image_blocks_with_marker(&mut body);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
let block = &body["messages"][0]["content"][0];
|
||||
assert_eq!(block["type"], "text");
|
||||
assert_eq!(block["text"], UNSUPPORTED_IMAGE_MARKER);
|
||||
assert_eq!(block["cache_control"]["type"], "ephemeral");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_media_and_attachment_error_phrasings() {
|
||||
let media_error = ProxyError::UpstreamError {
|
||||
status: 400,
|
||||
body: Some(
|
||||
r#"{"error":{"message":"This model cannot process media inputs"}}"#.to_string(),
|
||||
),
|
||||
};
|
||||
assert!(is_unsupported_image_error(&media_error));
|
||||
|
||||
let attachment_error = ProxyError::UpstreamError {
|
||||
status: 422,
|
||||
body: Some(r#"{"message":"attachments are not supported by this model"}"#.to_string()),
|
||||
};
|
||||
assert!(is_unsupported_image_error(&attachment_error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heuristic_disabled_keeps_images_for_listed_text_only_models() {
|
||||
// allow_heuristic = false:内置列表不再预测性剥图,避免误判多模态模型时静默丢图。
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek/deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, false);
|
||||
|
||||
assert_eq!(count, 0);
|
||||
assert_eq!(body["messages"][0]["content"][0]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_text_capability_replaces_even_when_heuristic_disabled() {
|
||||
// 显式声明 text-only 是声明驱动、零误判,即使关掉启发式也应生效。
|
||||
let provider = provider(json!({
|
||||
"models": [
|
||||
{ "id": "deepseek-v4-pro", "input": ["text"] }
|
||||
]
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "abc" } }
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let count = replace_images_for_text_only_model(&mut body, &provider, false);
|
||||
|
||||
assert_eq!(count, 1);
|
||||
assert_eq!(
|
||||
body["messages"][0]["content"][0]["text"],
|
||||
UNSUPPORTED_IMAGE_MARKER
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ pub mod http_client;
|
||||
pub mod hyper_client;
|
||||
pub(crate) mod json_canonical;
|
||||
pub mod log_codes;
|
||||
pub mod media_sanitizer;
|
||||
pub mod model_mapper;
|
||||
pub mod provider_router;
|
||||
pub mod providers;
|
||||
|
||||
@@ -21,6 +21,8 @@ use serde_json::{json, Value};
|
||||
|
||||
const ANTHROPIC_THINKING_PLACEHOLDER: &str = "tool call";
|
||||
const ANTHROPIC_REDACTED_THINKING_PLACEHOLDER: &str = "[redacted thinking]";
|
||||
// Keep hints lowercase; matching lowercases only the input value.
|
||||
const REASONING_VENDOR_HINTS: &[&str] = &["moonshot", "kimi", "deepseek", "mimo", "xiaomimimo"];
|
||||
|
||||
/// 获取 Claude 供应商的 API 格式
|
||||
///
|
||||
@@ -86,18 +88,11 @@ pub fn claude_api_format_needs_transform(api_format: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
fn is_reasoning_content_compatible_identifier(value: &str) -> bool {
|
||||
fn is_reasoning_vendor_identifier(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("moonshot")
|
||||
|| value.contains("kimi")
|
||||
|| value.contains("deepseek")
|
||||
|| value.contains("mimo")
|
||||
|| value.contains("xiaomimimo")
|
||||
}
|
||||
|
||||
fn is_anthropic_tool_thinking_history_identifier(value: &str) -> bool {
|
||||
let value = value.to_ascii_lowercase();
|
||||
value.contains("deepseek") || value.contains("mimo") || value.contains("xiaomimimo")
|
||||
REASONING_VENDOR_HINTS
|
||||
.iter()
|
||||
.any(|hint| value.contains(hint))
|
||||
}
|
||||
|
||||
fn should_normalize_anthropic_tool_thinking_history(
|
||||
@@ -112,7 +107,7 @@ fn should_normalize_anthropic_tool_thinking_history(
|
||||
if body
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.is_some_and(is_anthropic_tool_thinking_history_identifier)
|
||||
.is_some_and(is_reasoning_vendor_identifier)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -129,7 +124,7 @@ fn should_normalize_anthropic_tool_thinking_history(
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(is_anthropic_tool_thinking_history_identifier)
|
||||
.any(is_reasoning_vendor_identifier)
|
||||
}
|
||||
|
||||
/// DeepSeek's Anthropic-compatible endpoint requires thinking history to be
|
||||
@@ -150,6 +145,86 @@ pub fn normalize_anthropic_tool_thinking_history_for_provider(
|
||||
normalize_anthropic_tool_thinking_history(body)
|
||||
}
|
||||
|
||||
pub fn normalize_anthropic_messages_for_provider(
|
||||
body: &mut Value,
|
||||
provider: &Provider,
|
||||
api_format: &str,
|
||||
) -> bool {
|
||||
if api_format.trim() != "anthropic" {
|
||||
return false;
|
||||
}
|
||||
|
||||
let mut changed = normalize_anthropic_system_role_messages(body);
|
||||
changed |= normalize_anthropic_tool_thinking_history_for_provider(body, provider, api_format);
|
||||
changed
|
||||
}
|
||||
|
||||
fn normalize_anthropic_system_role_messages(body: &mut Value) -> bool {
|
||||
let mut system_parts = Vec::new();
|
||||
let changed = {
|
||||
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let original_len = messages.len();
|
||||
let mut kept_messages = Vec::with_capacity(messages.len());
|
||||
for message in std::mem::take(messages) {
|
||||
if message.get("role").and_then(Value::as_str) == Some("system") {
|
||||
if let Some(content) = message.get("content") {
|
||||
append_anthropic_system_parts(content, &mut system_parts);
|
||||
}
|
||||
} else {
|
||||
kept_messages.push(message);
|
||||
}
|
||||
}
|
||||
|
||||
let changed = kept_messages.len() != original_len;
|
||||
*messages = kept_messages;
|
||||
changed
|
||||
};
|
||||
|
||||
if !changed || system_parts.is_empty() {
|
||||
return changed;
|
||||
}
|
||||
|
||||
let mut merged_parts = Vec::new();
|
||||
if let Some(existing) = body.get("system") {
|
||||
append_anthropic_system_parts(existing, &mut merged_parts);
|
||||
}
|
||||
merged_parts.extend(system_parts);
|
||||
|
||||
if !merged_parts.is_empty() {
|
||||
body["system"] = Value::Array(merged_parts);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn append_anthropic_system_parts(content: &Value, parts: &mut Vec<Value>) {
|
||||
match content {
|
||||
Value::String(text) if !text.trim().is_empty() => {
|
||||
parts.push(json!({
|
||||
"type": "text",
|
||||
"text": text
|
||||
}));
|
||||
}
|
||||
Value::Array(items) => {
|
||||
for item in items {
|
||||
append_anthropic_system_parts(item, parts);
|
||||
}
|
||||
}
|
||||
Value::Object(obj)
|
||||
if obj
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|text| !text.trim().is_empty()) =>
|
||||
{
|
||||
parts.push(Value::Object(obj.clone()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_anthropic_tool_thinking_history(body: &mut Value) -> bool {
|
||||
let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
@@ -224,7 +299,7 @@ fn should_preserve_reasoning_content_for_openai_chat(provider: &Provider, body:
|
||||
if body
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.is_some_and(is_reasoning_content_compatible_identifier)
|
||||
.is_some_and(is_reasoning_vendor_identifier)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -243,7 +318,7 @@ fn should_preserve_reasoning_content_for_openai_chat(provider: &Provider, body:
|
||||
base_urls
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.any(is_reasoning_content_compatible_identifier)
|
||||
.any(is_reasoning_vendor_identifier)
|
||||
}
|
||||
|
||||
pub fn transform_claude_request_for_api_format(
|
||||
@@ -2000,6 +2075,95 @@ mod tests {
|
||||
assert_eq!(content[2]["type"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_system_role_messages_move_to_top_level_system() {
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}));
|
||||
let mut body = json!({
|
||||
"system": "Existing top-level system.",
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [
|
||||
{ "role": "system", "content": "Message system one." },
|
||||
{ "role": "user", "content": "hello" },
|
||||
{
|
||||
"role": "system",
|
||||
"content": [{ "type": "text", "text": "Message system two." }]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
let changed = normalize_anthropic_messages_for_provider(&mut body, &provider, "anthropic");
|
||||
|
||||
assert!(changed);
|
||||
let messages = body["messages"].as_array().unwrap();
|
||||
assert_eq!(messages.len(), 1);
|
||||
assert_eq!(messages[0]["role"], "user");
|
||||
|
||||
let system = body["system"].as_array().unwrap();
|
||||
assert_eq!(system[0]["text"], "Existing top-level system.");
|
||||
assert_eq!(system[1]["text"], "Message system one.");
|
||||
assert_eq!(system[2]["text"], "Message system two.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_system_role_messages_skip_non_anthropic_format() {
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/v1",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-pro",
|
||||
"messages": [
|
||||
{ "role": "system", "content": "Keep in messages." },
|
||||
{ "role": "user", "content": "hello" }
|
||||
]
|
||||
});
|
||||
|
||||
let changed =
|
||||
normalize_anthropic_messages_for_provider(&mut body, &provider, "openai_chat");
|
||||
|
||||
assert!(!changed);
|
||||
assert!(body.get("system").is_none());
|
||||
assert_eq!(body["messages"][0]["role"], "system");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_kimi_anthropic_tool_history_injects_missing_thinking() {
|
||||
let provider = create_provider(json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.kimi.com/coding",
|
||||
"ANTHROPIC_API_KEY": "test-key"
|
||||
}
|
||||
}));
|
||||
let mut body = json!({
|
||||
"model": "kimi-for-coding",
|
||||
"messages": [{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{"type": "tool_use", "id": "call_123", "name": "read_file", "input": {"path": "README.md"}}
|
||||
]
|
||||
}]
|
||||
});
|
||||
|
||||
let changed = normalize_anthropic_tool_thinking_history_for_provider(
|
||||
&mut body,
|
||||
&provider,
|
||||
"anthropic",
|
||||
);
|
||||
|
||||
assert!(changed);
|
||||
let content = body["messages"][0]["content"].as_array().unwrap();
|
||||
assert_eq!(content[0]["type"], "thinking");
|
||||
assert_eq!(content[0]["thinking"], ANTHROPIC_THINKING_PLACEHOLDER);
|
||||
assert_eq!(content[1]["type"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deepseek_anthropic_tool_history_rewrites_redacted_thinking() {
|
||||
let provider = create_provider(json!({
|
||||
|
||||
@@ -392,22 +392,9 @@ fn extract_codex_model_from_toml(config_text: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
fn extract_codex_base_url_from_toml(config_text: &str) -> Option<String> {
|
||||
let doc = config_text.parse::<TomlValue>().ok()?;
|
||||
|
||||
if let Some(active_provider) = doc.get("model_provider").and_then(|v| v.as_str()) {
|
||||
if let Some(base_url) = doc
|
||||
.get("model_providers")
|
||||
.and_then(|providers| providers.get(active_provider))
|
||||
.and_then(|provider| provider.get("base_url"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return Some(base_url.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
doc.get("base_url")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(ToString::to_string)
|
||||
// Canonical parser lives in codex_config; keep this thin alias so the
|
||||
// proxy hot path and the usage-credential resolver share one implementation.
|
||||
crate::codex_config::extract_codex_base_url(config_text)
|
||||
}
|
||||
|
||||
impl CodexAdapter {
|
||||
|
||||
@@ -170,6 +170,25 @@ pub(crate) fn response_function_call_item(
|
||||
item
|
||||
}
|
||||
|
||||
pub(crate) fn response_function_call_item_with_namespace(
|
||||
item_id: &str,
|
||||
status: &str,
|
||||
call_id: &str,
|
||||
name: &str,
|
||||
namespace: Option<&str>,
|
||||
arguments: &str,
|
||||
reasoning: Option<&str>,
|
||||
) -> Value {
|
||||
let mut item =
|
||||
response_function_call_item(item_id, status, call_id, name, arguments, reasoning);
|
||||
if let Some(namespace) = namespace.filter(|value| !value.is_empty()) {
|
||||
if let Some(obj) = item.as_object_mut() {
|
||||
obj.insert("namespace".to_string(), json!(namespace));
|
||||
}
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
pub(crate) fn response_item_call_id(item: &Value) -> Option<String> {
|
||||
item.get("call_id")
|
||||
.or_else(|| item.get("id"))
|
||||
|
||||
@@ -60,7 +60,7 @@ impl CodexChatHistoryStore {
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(cached_function_call)
|
||||
.filter_map(cached_call_item)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
@@ -73,8 +73,8 @@ impl CodexChatHistoryStore {
|
||||
inner.insert_calls(response_id, calls)
|
||||
}
|
||||
|
||||
async fn record_function_call(&self, response_id: Option<&str>, item: &Value) -> bool {
|
||||
let Some(call) = cached_function_call(item) else {
|
||||
async fn record_call_item(&self, response_id: Option<&str>, item: &Value) -> bool {
|
||||
let Some(call) = cached_call_item(item) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -110,14 +110,18 @@ impl CodexChatHistoryStore {
|
||||
let output_call_ids = items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
item.get("type").and_then(|value| value.as_str()) == Some("function_call_output")
|
||||
item.get("type")
|
||||
.and_then(|value| value.as_str())
|
||||
.is_some_and(is_call_output_item_type)
|
||||
})
|
||||
.filter_map(response_item_call_id)
|
||||
.collect::<HashSet<_>>();
|
||||
let existing_call_ids = items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
item.get("type").and_then(|value| value.as_str()) == Some("function_call")
|
||||
item.get("type")
|
||||
.and_then(|value| value.as_str())
|
||||
.is_some_and(is_call_item_type)
|
||||
})
|
||||
.filter_map(response_item_call_id)
|
||||
.collect::<HashSet<_>>();
|
||||
@@ -143,10 +147,10 @@ impl CodexChatHistoryStore {
|
||||
|
||||
for mut item in items {
|
||||
match item.get("type").and_then(|value| value.as_str()) {
|
||||
Some("function_call") => {
|
||||
Some(item_type) if is_call_item_type(item_type) => {
|
||||
if let Some(call_id) = response_item_call_id(&item) {
|
||||
if let Some(cached) = lookup.call(&call_id) {
|
||||
if enrich_function_call_reasoning(&mut item, cached) {
|
||||
if enrich_call_item_reasoning(&mut item, cached) {
|
||||
enriched += 1;
|
||||
}
|
||||
}
|
||||
@@ -154,7 +158,7 @@ impl CodexChatHistoryStore {
|
||||
}
|
||||
new_items.push(item);
|
||||
}
|
||||
Some("function_call_output") => {
|
||||
Some(item_type) if is_call_output_item_type(item_type) => {
|
||||
if let Some(group) = restore_group.take().filter(|group| !group.is_empty()) {
|
||||
for (call_id, cached_item) in group {
|
||||
seen_call_ids.insert(call_id);
|
||||
@@ -423,7 +427,7 @@ async fn inspect_sse_block(
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(item) = value.get("item") {
|
||||
history
|
||||
.record_function_call(current_response_id.as_deref(), item)
|
||||
.record_call_item(current_response_id.as_deref(), item)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -436,15 +440,33 @@ async fn inspect_sse_block(
|
||||
}
|
||||
}
|
||||
|
||||
fn cached_function_call(item: &Value) -> Option<(String, Value)> {
|
||||
if item.get("type").and_then(|value| value.as_str()) != Some("function_call") {
|
||||
fn cached_call_item(item: &Value) -> Option<(String, Value)> {
|
||||
if !item
|
||||
.get("type")
|
||||
.and_then(|value| value.as_str())
|
||||
.is_some_and(is_call_item_type)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let call_id = response_item_call_id(item)?;
|
||||
Some((call_id, item.clone()))
|
||||
}
|
||||
|
||||
fn enrich_function_call_reasoning(item: &mut Value, cached: &Value) -> bool {
|
||||
fn is_call_item_type(item_type: &str) -> bool {
|
||||
matches!(
|
||||
item_type,
|
||||
"function_call" | "custom_tool_call" | "tool_search_call"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_call_output_item_type(item_type: &str) -> bool {
|
||||
matches!(
|
||||
item_type,
|
||||
"function_call_output" | "custom_tool_call_output" | "tool_search_output"
|
||||
)
|
||||
}
|
||||
|
||||
fn enrich_call_item_reasoning(item: &mut Value, cached: &Value) -> bool {
|
||||
let mut changed = false;
|
||||
for key in ["reasoning_content", "reasoning"] {
|
||||
if item.get(key).is_some_and(|value| !is_empty_value(value)) {
|
||||
@@ -704,6 +726,58 @@ mod tests {
|
||||
assert_eq!(input[3]["type"], "function_call_output");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restores_custom_and_tool_search_calls_from_previous_response() {
|
||||
let history = CodexChatHistoryStore::default();
|
||||
history
|
||||
.record_response(&json!({
|
||||
"id": "resp_1",
|
||||
"output": [
|
||||
{
|
||||
"type": "custom_tool_call",
|
||||
"call_id": "call_patch",
|
||||
"name": "apply_patch",
|
||||
"input": "*** Begin Patch\n*** End Patch",
|
||||
"reasoning_content": "Need to patch the file."
|
||||
},
|
||||
{
|
||||
"type": "tool_search_call",
|
||||
"call_id": "call_search",
|
||||
"status": "completed",
|
||||
"execution": "client",
|
||||
"arguments": {"query": "Gmail tools"},
|
||||
"reasoning_content": "Need to discover tools."
|
||||
}
|
||||
]
|
||||
}))
|
||||
.await;
|
||||
|
||||
let mut request = json!({
|
||||
"previous_response_id": "resp_1",
|
||||
"input": [
|
||||
{
|
||||
"type": "custom_tool_call_output",
|
||||
"call_id": "call_patch",
|
||||
"output": "patched"
|
||||
},
|
||||
{
|
||||
"type": "tool_search_output",
|
||||
"call_id": "call_search",
|
||||
"tools": []
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
assert_eq!(history.enrich_request(&mut request).await, 2);
|
||||
let input = request["input"].as_array().unwrap();
|
||||
assert_eq!(input[0]["type"], "custom_tool_call");
|
||||
assert_eq!(input[0]["call_id"], "call_patch");
|
||||
assert_eq!(input[1]["type"], "tool_search_call");
|
||||
assert_eq!(input[1]["call_id"], "call_search");
|
||||
assert_eq!(input[2]["type"], "custom_tool_call_output");
|
||||
assert_eq!(input[3]["type"], "tool_search_output");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn records_streamed_function_call_done_items() {
|
||||
let history = Arc::new(CodexChatHistoryStore::default());
|
||||
|
||||
@@ -42,8 +42,8 @@ pub use adapter::ProviderAdapter;
|
||||
pub use auth::{AuthInfo, AuthStrategy};
|
||||
pub use claude::{
|
||||
claude_api_format_needs_transform, get_claude_api_format,
|
||||
normalize_anthropic_tool_thinking_history_for_provider,
|
||||
transform_claude_request_for_api_format, ClaudeAdapter,
|
||||
normalize_anthropic_messages_for_provider, transform_claude_request_for_api_format,
|
||||
ClaudeAdapter,
|
||||
};
|
||||
pub use codex::CodexAdapter;
|
||||
pub use codex::{
|
||||
|
||||
@@ -90,14 +90,14 @@ struct ToolBlockState {
|
||||
started: bool,
|
||||
pending_args: String,
|
||||
/// 连续空白字符计数 — 用于检测 Copilot 无限换行 bug
|
||||
/// 当 function call 参数中出现连续 20+ 空白字符时,强制终止流
|
||||
/// 当 function call 参数中的连续空白字符达到阈值时,强制终止流
|
||||
consecutive_whitespace: usize,
|
||||
/// 是否已因无限空白 bug 被中止
|
||||
aborted: bool,
|
||||
}
|
||||
|
||||
/// 无限空白 bug 的连续空白字符阈值
|
||||
const INFINITE_WHITESPACE_THRESHOLD: usize = 20;
|
||||
const INFINITE_WHITESPACE_THRESHOLD: usize = 500;
|
||||
|
||||
fn build_anthropic_usage_json(usage: &Usage) -> Value {
|
||||
let mut usage_json = json!({
|
||||
|
||||
@@ -2,11 +2,13 @@
|
||||
|
||||
use super::{
|
||||
codex_chat_common::{
|
||||
extract_reasoning_field_text, response_function_call_item, split_leading_think_block,
|
||||
strip_leading_think_open_tag,
|
||||
extract_reasoning_field_text, split_leading_think_block, strip_leading_think_open_tag,
|
||||
},
|
||||
transform_codex_chat::{
|
||||
chat_usage_to_responses_usage, response_id_from_chat_id, response_status_from_finish_reason,
|
||||
chat_usage_to_responses_usage, custom_tool_input_from_chat_arguments,
|
||||
response_id_from_chat_id, response_status_from_finish_reason,
|
||||
response_tool_call_item_from_chat_name, response_tool_call_item_id_from_chat_name,
|
||||
CodexToolContext,
|
||||
},
|
||||
};
|
||||
use crate::proxy::json_canonical::canonicalize_tool_arguments_str;
|
||||
@@ -75,6 +77,7 @@ struct ChatToResponsesState {
|
||||
output_items: Vec<(u32, Value)>,
|
||||
latest_usage: Option<Value>,
|
||||
finish_reason: Option<String>,
|
||||
tool_context: CodexToolContext,
|
||||
}
|
||||
|
||||
impl Default for ChatToResponsesState {
|
||||
@@ -93,11 +96,19 @@ impl Default for ChatToResponsesState {
|
||||
output_items: Vec::new(),
|
||||
latest_usage: None,
|
||||
finish_reason: None,
|
||||
tool_context: CodexToolContext::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChatToResponsesState {
|
||||
fn with_tool_context(tool_context: CodexToolContext) -> Self {
|
||||
Self {
|
||||
tool_context,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_chat_chunk(&mut self, chunk: &Value) -> Vec<Bytes> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
@@ -130,6 +141,7 @@ impl ChatToResponsesState {
|
||||
if let Some(delta) = choice.get("delta") {
|
||||
if let Some(reasoning) = chat_delta_reasoning_text(delta) {
|
||||
events.extend(self.push_reasoning_delta(&reasoning));
|
||||
self.append_reasoning_to_active_tools(&reasoning);
|
||||
}
|
||||
|
||||
if let Some(content) = delta.get("content").and_then(|v| v.as_str()) {
|
||||
@@ -410,6 +422,7 @@ impl ChatToResponsesState {
|
||||
let mut output_index = None;
|
||||
let mut item_id = String::new();
|
||||
let mut pending_arguments = String::new();
|
||||
let current_name: String;
|
||||
|
||||
{
|
||||
let state = self.tools.entry(chat_index).or_default();
|
||||
@@ -436,8 +449,10 @@ impl ChatToResponsesState {
|
||||
output_index = state.output_index;
|
||||
item_id = state.item_id.clone();
|
||||
}
|
||||
current_name = state.name.clone();
|
||||
}
|
||||
|
||||
let is_custom_tool = self.tool_context.is_custom_tool_chat_name(¤t_name);
|
||||
let mut events = Vec::new();
|
||||
|
||||
if should_add {
|
||||
@@ -453,16 +468,22 @@ impl ChatToResponsesState {
|
||||
state.name = "unknown_tool".to_string();
|
||||
}
|
||||
state.output_index = Some(assigned);
|
||||
state.item_id = format!("fc_{}", state.call_id);
|
||||
let is_custom_tool = self.tool_context.is_custom_tool_chat_name(&state.name);
|
||||
state.item_id = response_tool_call_item_id_from_chat_name(
|
||||
&state.call_id,
|
||||
&state.name,
|
||||
&self.tool_context,
|
||||
);
|
||||
item_id = state.item_id.clone();
|
||||
|
||||
let item = response_function_call_item(
|
||||
let item = response_tool_call_item_from_chat_name(
|
||||
&item_id,
|
||||
"in_progress",
|
||||
&state.call_id,
|
||||
&state.name,
|
||||
"",
|
||||
Some(&state.reasoning_content),
|
||||
&self.tool_context,
|
||||
);
|
||||
|
||||
events.push(sse_event(
|
||||
@@ -474,7 +495,7 @@ impl ChatToResponsesState {
|
||||
}),
|
||||
));
|
||||
|
||||
if !pending_arguments.is_empty() {
|
||||
if !pending_arguments.is_empty() && !is_custom_tool {
|
||||
events.push(sse_event(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({
|
||||
@@ -485,7 +506,7 @@ impl ChatToResponsesState {
|
||||
}),
|
||||
));
|
||||
}
|
||||
} else if !args_delta.is_empty() {
|
||||
} else if !args_delta.is_empty() && !is_custom_tool {
|
||||
if let Some(output_index) = output_index {
|
||||
events.push(sse_event(
|
||||
"response.function_call_arguments.delta",
|
||||
@@ -502,6 +523,34 @@ impl ChatToResponsesState {
|
||||
events
|
||||
}
|
||||
|
||||
fn append_reasoning_to_active_tools(&mut self, delta: &str) {
|
||||
if delta.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for state in self.tools.values_mut().filter(|state| !state.done) {
|
||||
if state.reasoning_content.is_empty() {
|
||||
state.reasoning_content = delta.trim_start().to_string();
|
||||
} else {
|
||||
state.reasoning_content.push_str(delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_substantive_output(&self) -> bool {
|
||||
!self.text.text.trim().is_empty()
|
||||
|| !self.reasoning.text.trim().is_empty()
|
||||
|| !self.inline_think.buffer.trim().is_empty()
|
||||
|| !self.output_items.is_empty()
|
||||
|| self.tools.values().any(|state| {
|
||||
state.added
|
||||
|| !state.call_id.trim().is_empty()
|
||||
|| !state.name.trim().is_empty()
|
||||
|| !state.arguments.trim().is_empty()
|
||||
|| !state.reasoning_content.trim().is_empty()
|
||||
})
|
||||
}
|
||||
|
||||
fn finalize(&mut self) -> Vec<Bytes> {
|
||||
if self.completed {
|
||||
return Vec::new();
|
||||
@@ -668,14 +717,19 @@ impl ChatToResponsesState {
|
||||
state.name = "unknown_tool".to_string();
|
||||
}
|
||||
state.output_index = Some(assigned);
|
||||
state.item_id = format!("fc_{}", state.call_id);
|
||||
let item = response_function_call_item(
|
||||
state.item_id = response_tool_call_item_id_from_chat_name(
|
||||
&state.call_id,
|
||||
&state.name,
|
||||
&self.tool_context,
|
||||
);
|
||||
let item = response_tool_call_item_from_chat_name(
|
||||
&state.item_id,
|
||||
"in_progress",
|
||||
&state.call_id,
|
||||
&state.name,
|
||||
"",
|
||||
Some(&state.reasoning_content),
|
||||
&self.tool_context,
|
||||
);
|
||||
add_event = Some(sse_event(
|
||||
"response.output_item.added",
|
||||
@@ -696,26 +750,52 @@ impl ChatToResponsesState {
|
||||
};
|
||||
let output_index = state.output_index.unwrap_or(0);
|
||||
let arguments = canonicalize_tool_arguments_str(&state.arguments);
|
||||
let item = response_function_call_item(
|
||||
let is_custom_tool = self.tool_context.is_custom_tool_chat_name(&state.name);
|
||||
let item = response_tool_call_item_from_chat_name(
|
||||
&state.item_id,
|
||||
"completed",
|
||||
&state.call_id,
|
||||
&state.name,
|
||||
&arguments,
|
||||
Some(&state.reasoning_content),
|
||||
&self.tool_context,
|
||||
);
|
||||
state.done = true;
|
||||
self.output_items.push((output_index, item.clone()));
|
||||
|
||||
events.push(sse_event(
|
||||
"response.function_call_arguments.done",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.done",
|
||||
"item_id": state.item_id,
|
||||
"output_index": output_index,
|
||||
"arguments": arguments
|
||||
}),
|
||||
));
|
||||
if is_custom_tool {
|
||||
let input = custom_tool_input_from_chat_arguments(&arguments);
|
||||
if !input.is_empty() {
|
||||
events.push(sse_event(
|
||||
"response.custom_tool_call_input.delta",
|
||||
json!({
|
||||
"type": "response.custom_tool_call_input.delta",
|
||||
"item_id": state.item_id,
|
||||
"output_index": output_index,
|
||||
"delta": input.clone()
|
||||
}),
|
||||
));
|
||||
}
|
||||
events.push(sse_event(
|
||||
"response.custom_tool_call_input.done",
|
||||
json!({
|
||||
"type": "response.custom_tool_call_input.done",
|
||||
"item_id": state.item_id,
|
||||
"output_index": output_index,
|
||||
"input": input
|
||||
}),
|
||||
));
|
||||
} else {
|
||||
events.push(sse_event(
|
||||
"response.function_call_arguments.done",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.done",
|
||||
"item_id": state.item_id,
|
||||
"output_index": output_index,
|
||||
"arguments": arguments
|
||||
}),
|
||||
));
|
||||
}
|
||||
events.push(sse_event(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
@@ -750,7 +830,8 @@ impl ChatToResponsesState {
|
||||
json!({
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
"total_tokens": 0
|
||||
"total_tokens": 0,
|
||||
"output_tokens_details": { "reasoning_tokens": 0 }
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -810,13 +891,23 @@ fn leading_think_prefix_decision(buffer: &str) -> ThinkPrefixDecision {
|
||||
}
|
||||
|
||||
/// Create a stream that converts Chat Completions SSE chunks into Responses SSE events.
|
||||
#[allow(dead_code)]
|
||||
pub fn create_responses_sse_stream_from_chat<E: std::error::Error + Send + 'static>(
|
||||
stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
create_responses_sse_stream_from_chat_with_context(stream, CodexToolContext::default())
|
||||
}
|
||||
|
||||
/// Create a stream that converts Chat Completions SSE chunks into Responses SSE
|
||||
/// events while restoring Codex tool namespace/custom/tool_search metadata.
|
||||
pub fn create_responses_sse_stream_from_chat_with_context<E: std::error::Error + Send + 'static>(
|
||||
stream: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
|
||||
tool_context: CodexToolContext,
|
||||
) -> impl Stream<Item = Result<Bytes, std::io::Error>> + Send {
|
||||
async_stream::stream! {
|
||||
let mut buffer = String::new();
|
||||
let mut utf8_remainder: Vec<u8> = Vec::new();
|
||||
let mut state = ChatToResponsesState::default();
|
||||
let mut state = ChatToResponsesState::with_tool_context(tool_context);
|
||||
let mut stream_failed = false;
|
||||
|
||||
tokio::pin!(stream);
|
||||
@@ -887,8 +978,20 @@ pub fn create_responses_sse_stream_from_chat<E: std::error::Error + Send + 'stat
|
||||
}
|
||||
|
||||
if !stream_failed {
|
||||
for event in state.finalize() {
|
||||
yield Ok(event);
|
||||
if state.completed || state.finish_reason.is_some() {
|
||||
for event in state.finalize() {
|
||||
yield Ok(event);
|
||||
}
|
||||
} else if state.has_substantive_output() {
|
||||
state.finish_reason = Some("length".to_string());
|
||||
for event in state.finalize() {
|
||||
yield Ok(event);
|
||||
}
|
||||
} else {
|
||||
yield Ok(state.failed_event(
|
||||
"Upstream Chat Completions stream ended before sending finish_reason".to_string(),
|
||||
Some("stream_truncated".to_string()),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -929,12 +1032,16 @@ mod tests {
|
||||
use futures::{stream, StreamExt};
|
||||
|
||||
async fn collect(chunks: Vec<&str>) -> String {
|
||||
collect_with_context(chunks, CodexToolContext::default()).await
|
||||
}
|
||||
|
||||
async fn collect_with_context(chunks: Vec<&str>, tool_context: CodexToolContext) -> String {
|
||||
let chunks: Vec<Result<Bytes, std::io::Error>> = chunks
|
||||
.into_iter()
|
||||
.map(|chunk| Ok(Bytes::copy_from_slice(chunk.as_bytes())))
|
||||
.collect();
|
||||
let upstream = stream::iter(chunks);
|
||||
let converted = create_responses_sse_stream_from_chat(upstream);
|
||||
let converted = create_responses_sse_stream_from_chat_with_context(upstream, tool_context);
|
||||
let bytes: Vec<Bytes> = converted.map(|item| item.unwrap()).collect().await;
|
||||
String::from_utf8(bytes.concat()).unwrap()
|
||||
}
|
||||
@@ -1011,6 +1118,35 @@ mod tests {
|
||||
assert!(output.contains("\"call_id\":\"call_1\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restores_custom_tool_input_stream_events() {
|
||||
let request = json!({
|
||||
"model": "gpt-5.4",
|
||||
"tools": [{ "type": "custom", "name": "exec" }]
|
||||
});
|
||||
let context =
|
||||
super::super::transform_codex_chat::build_codex_tool_context_from_request(&request);
|
||||
let output = collect_with_context(
|
||||
vec![
|
||||
"data: {\"id\":\"chatcmpl_custom\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_custom\",\"type\":\"function\",\"function\":{\"name\":\"exec\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_custom\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"input\\\":\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_custom\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"\\\"ls -la\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||
"data: [DONE]\n\n",
|
||||
],
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(output.contains("event: response.custom_tool_call_input.delta"));
|
||||
assert!(output.contains("event: response.custom_tool_call_input.done"));
|
||||
assert!(!output.contains("event: response.function_call_arguments.delta"));
|
||||
assert!(!output.contains("event: response.function_call_arguments.done"));
|
||||
assert!(output.contains("\"id\":\"ctc_call_custom\""));
|
||||
assert!(output.contains("\"type\":\"custom_tool_call\""));
|
||||
assert!(output.contains("\"name\":\"exec\""));
|
||||
assert!(output.contains("\"input\":\"ls -la\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canonicalizes_streamed_tool_call_arguments_on_done_events() {
|
||||
let output = collect(vec![
|
||||
@@ -1039,6 +1175,84 @@ mod tests {
|
||||
assert!(output.contains("\"reasoning_content\":\"Need file.\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn preserves_late_reasoning_content_on_streamed_tool_call_items() {
|
||||
let output = collect(vec![
|
||||
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"read_file\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"path\\\":\\\"README.md\\\"}\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{\"reasoning_content\":\"Need file.\"}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_tool_late_reasoning\",\"model\":\"deepseek-v4-flash\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||
"data: [DONE]\n\n",
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(output.contains("event: response.output_item.done"));
|
||||
assert!(output.contains("\"type\":\"function_call\""));
|
||||
assert!(output.contains("\"reasoning_content\":\"Need file.\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restores_namespace_on_streamed_tool_call_items() {
|
||||
let request = json!({
|
||||
"model": "gpt-5.4",
|
||||
"input": [{
|
||||
"type": "tool_search_output",
|
||||
"call_id": "call_tool_search_1",
|
||||
"tools": [{
|
||||
"type": "namespace",
|
||||
"name": "mcp__codex_apps__gmail",
|
||||
"tools": [{
|
||||
"type": "function",
|
||||
"name": "_search_emails",
|
||||
"description": "Search Gmail.",
|
||||
"parameters": {"type": "object"}
|
||||
}]
|
||||
}]
|
||||
}]
|
||||
});
|
||||
let context =
|
||||
super::super::transform_codex_chat::build_codex_tool_context_from_request(&request);
|
||||
let output = collect_with_context(
|
||||
vec![
|
||||
"data: {\"id\":\"chatcmpl_gmail\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_gmail\",\"type\":\"function\",\"function\":{\"name\":\"mcp__codex_apps__gmail___search_emails\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_gmail\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"query\\\":\\\"in:inbox\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||
"data: [DONE]\n\n",
|
||||
],
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(output.contains("\"type\":\"function_call\""));
|
||||
assert!(output.contains("\"namespace\":\"mcp__codex_apps__gmail\""));
|
||||
assert!(output.contains("\"name\":\"_search_emails\""));
|
||||
assert!(output.contains(r#""arguments":"{\"query\":\"in:inbox\"}""#));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn restores_tool_search_on_streamed_tool_call_items() {
|
||||
let request = json!({
|
||||
"model": "gpt-5.4",
|
||||
"tools": [{"type": "tool_search"}],
|
||||
"input": "Search for Gmail tools."
|
||||
});
|
||||
let context =
|
||||
super::super::transform_codex_chat::build_codex_tool_context_from_request(&request);
|
||||
let output = collect_with_context(
|
||||
vec![
|
||||
"data: {\"id\":\"chatcmpl_tool_search\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_tool_search_1\",\"type\":\"function\",\"function\":{\"name\":\"tool_search\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_tool_search\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"query\\\":\\\"Gmail search emails\\\",\\\"limit\\\":10}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||
"data: [DONE]\n\n",
|
||||
],
|
||||
context,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(output.contains("\"type\":\"tool_search_call\""));
|
||||
assert!(output.contains("\"execution\":\"client\""));
|
||||
assert!(output.contains("\"call_id\":\"call_tool_search_1\""));
|
||||
assert!(output.contains("\"query\":\"Gmail search emails\""));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_error_emits_failed_without_completed() {
|
||||
let upstream = stream::iter(vec![Err::<Bytes, std::io::Error>(std::io::Error::other(
|
||||
@@ -1052,6 +1266,31 @@ mod tests {
|
||||
assert!(!output.contains("event: response.completed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_end_with_output_without_finish_reason_emits_incomplete_without_failed() {
|
||||
let output = collect(vec![
|
||||
"data: {\"id\":\"chatcmpl_truncated\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n",
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(output.contains("event: response.completed"));
|
||||
assert!(output.contains("\"status\":\"incomplete\""));
|
||||
assert!(output.contains("\"incomplete_details\":{\"reason\":\"max_output_tokens\"}"));
|
||||
assert!(!output.contains("event: response.failed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stream_end_without_output_or_finish_reason_emits_failed_without_completed() {
|
||||
let output = collect(vec![
|
||||
"data: {\"id\":\"chatcmpl_truncated\",\"model\":\"gpt-5.4\",\"choices\":[{\"delta\":{}}]}\n\n",
|
||||
])
|
||||
.await;
|
||||
|
||||
assert!(output.contains("event: response.failed"));
|
||||
assert!(output.contains("stream_truncated"));
|
||||
assert!(!output.contains("event: response.completed"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_sse_error_event_emits_failed_without_completed() {
|
||||
let output = collect(vec![
|
||||
|
||||
@@ -142,18 +142,13 @@ pub fn anthropic_to_openai_with_reasoning_content(
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
}
|
||||
} else if let Some(arr) = system.as_array() {
|
||||
// 多个 system message — preserve cache_control for compatible proxies
|
||||
for msg in arr {
|
||||
if let Some(text) = msg.get("text").and_then(|t| t.as_str()) {
|
||||
let text = strip_leading_anthropic_billing_header(text);
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut sys_msg = json!({"role": "system", "content": text});
|
||||
if let Some(cc) = msg.get("cache_control") {
|
||||
sys_msg["cache_control"] = cc.clone();
|
||||
}
|
||||
messages.push(sys_msg);
|
||||
messages.push(json!({"role": "system", "content": text}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,18 +202,14 @@ pub fn anthropic_to_openai_with_reasoning_content(
|
||||
.iter()
|
||||
.filter(|t| t.get("type").and_then(|v| v.as_str()) != Some("BatchTool"))
|
||||
.map(|t| {
|
||||
let mut tool = json!({
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": t.get("name").and_then(|n| n.as_str()).unwrap_or(""),
|
||||
"description": t.get("description"),
|
||||
"parameters": clean_schema(t.get("input_schema").cloned().unwrap_or(json!({})))
|
||||
}
|
||||
});
|
||||
if let Some(cc) = t.get("cache_control") {
|
||||
tool["cache_control"] = cc.clone();
|
||||
}
|
||||
tool
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -294,10 +285,6 @@ fn normalize_openai_system_messages(messages: &mut Vec<Value>) {
|
||||
}
|
||||
|
||||
let mut parts = Vec::new();
|
||||
let mut inherited_cache_control: Option<Value> = None;
|
||||
let mut cache_control_conflict = false;
|
||||
let mut saw_cache_control = false;
|
||||
let mut saw_missing_cache_control = false;
|
||||
messages.retain(|message| {
|
||||
if message.get("role").and_then(|value| value.as_str()) != Some("system") {
|
||||
return true;
|
||||
@@ -318,28 +305,11 @@ fn normalize_openai_system_messages(messages: &mut Vec<Value>) {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if let Some(cache_control) = message.get("cache_control") {
|
||||
saw_cache_control = true;
|
||||
match &inherited_cache_control {
|
||||
None => inherited_cache_control = Some(cache_control.clone()),
|
||||
Some(existing) if existing == cache_control => {}
|
||||
Some(_) => cache_control_conflict = true,
|
||||
}
|
||||
} else {
|
||||
saw_missing_cache_control = true;
|
||||
}
|
||||
|
||||
false
|
||||
});
|
||||
|
||||
if !parts.is_empty() {
|
||||
let mut merged = json!({"role": "system", "content": parts.join("\n")});
|
||||
if !(cache_control_conflict || (saw_cache_control && saw_missing_cache_control)) {
|
||||
if let Some(cache_control) = inherited_cache_control {
|
||||
merged["cache_control"] = cache_control;
|
||||
}
|
||||
}
|
||||
messages.insert(0, merged);
|
||||
messages.insert(0, json!({"role": "system", "content": parts.join("\n")}));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,11 +349,7 @@ fn convert_message_to_openai(
|
||||
match block_type {
|
||||
"text" => {
|
||||
if let Some(text) = block.get("text").and_then(|t| t.as_str()) {
|
||||
let mut part = json!({"type": "text", "text": text});
|
||||
if let Some(cc) = block.get("cache_control") {
|
||||
part["cache_control"] = cc.clone();
|
||||
}
|
||||
content_parts.push(part);
|
||||
content_parts.push(json!({"type": "text", "text": text}));
|
||||
}
|
||||
}
|
||||
"image" => {
|
||||
@@ -458,14 +424,9 @@ fn convert_message_to_openai(
|
||||
if content_parts.is_empty() {
|
||||
msg["content"] = Value::Null;
|
||||
} else if content_parts.len() == 1 {
|
||||
// When cache_control is present, keep array format to preserve it
|
||||
let has_cache_control = content_parts[0].get("cache_control").is_some();
|
||||
if !has_cache_control {
|
||||
if let Some(text) = content_parts[0].get("text") {
|
||||
msg["content"] = text.clone();
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
// 单 text block 简化为纯字符串
|
||||
if let Some(text) = content_parts[0].get("text") {
|
||||
msg["content"] = text.clone();
|
||||
} else {
|
||||
msg["content"] = json!(content_parts);
|
||||
}
|
||||
@@ -829,7 +790,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_preserves_matching_system_cache_control_when_merging() {
|
||||
fn test_anthropic_to_openai_strips_cache_control_from_merged_system() {
|
||||
let input = json!({
|
||||
"model": "claude-3-sonnet",
|
||||
"max_tokens": 1024,
|
||||
@@ -847,12 +808,12 @@ mod tests {
|
||||
result["messages"][0]["content"],
|
||||
"You are Claude Code.\nBe concise."
|
||||
);
|
||||
assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral");
|
||||
assert!(result["messages"][0].get("cache_control").is_none());
|
||||
assert_eq!(result["messages"][1]["role"], "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_drops_mixed_present_absent_system_cache_control_when_merging() {
|
||||
fn test_anthropic_to_openai_strips_cache_control_from_mixed_system() {
|
||||
let input = json!({
|
||||
"model": "claude-3-sonnet",
|
||||
"max_tokens": 1024,
|
||||
@@ -873,7 +834,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_drops_conflicting_system_cache_control_when_merging() {
|
||||
fn test_anthropic_to_openai_strips_cache_control_from_conflicting_system() {
|
||||
let input = json!({
|
||||
"model": "claude-3-sonnet",
|
||||
"max_tokens": 1024,
|
||||
@@ -1199,7 +1160,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_cache_control_preserved() {
|
||||
fn test_anthropic_to_openai_strips_all_cache_control() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
@@ -1221,19 +1182,89 @@ mod tests {
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
// System message cache_control preserved
|
||||
assert_eq!(result["messages"][0]["cache_control"]["type"], "ephemeral");
|
||||
// Text block cache_control preserved
|
||||
assert_eq!(
|
||||
result["messages"][1]["content"][0]["cache_control"]["type"],
|
||||
"ephemeral"
|
||||
// System message: no cache_control
|
||||
assert!(result["messages"][0].get("cache_control").is_none());
|
||||
// User message: content simplified to string (no cache_control → flat string)
|
||||
assert_eq!(result["messages"][1]["content"], "Hello");
|
||||
// Tool: no cache_control
|
||||
assert!(result["tools"][0].get("cache_control").is_none());
|
||||
}
|
||||
|
||||
/// 精确复现 Issue #3805 报告的 400 错误场景:
|
||||
/// GLM/Qwen 等严格校验模型拒绝 cache_control 和 content 数组格式
|
||||
#[test]
|
||||
fn test_regression_gh3805_no_cache_control_leak_to_openai() {
|
||||
let input = json!({
|
||||
"model": "glm-5.1",
|
||||
"max_tokens": 1024,
|
||||
"system": [
|
||||
{"type": "text", "text": "You are helpful.", "cache_control": {"type": "ephemeral"}}
|
||||
],
|
||||
"messages": [
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": "Hello", "cache_control": {"type": "ephemeral"}}
|
||||
]}
|
||||
],
|
||||
"tools": [{
|
||||
"name": "search",
|
||||
"description": "Search the web",
|
||||
"input_schema": {"type": "object"},
|
||||
"cache_control": {"type": "ephemeral"}
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
|
||||
// 验证: messages 中不存在 cache_control
|
||||
for (i, msg) in result["messages"].as_array().unwrap().iter().enumerate() {
|
||||
assert!(
|
||||
msg.get("cache_control").is_none(),
|
||||
"messages[{i}] must not have cache_control"
|
||||
);
|
||||
}
|
||||
|
||||
// 验证: content 中没有 cache_control
|
||||
for (i, msg) in result["messages"].as_array().unwrap().iter().enumerate() {
|
||||
if let Some(content) = msg.get("content") {
|
||||
assert!(
|
||||
!content.is_array()
|
||||
|| content
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|part| part.get("cache_control").is_none()),
|
||||
"messages[{i}] content parts must not have cache_control"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 验证: system content 为纯字符串格式(不是数组)
|
||||
let sys_msg = &result["messages"][0];
|
||||
assert_eq!(sys_msg["role"], "system");
|
||||
assert!(
|
||||
sys_msg["content"].is_string(),
|
||||
"system content must be string, got: {}",
|
||||
sys_msg["content"]
|
||||
);
|
||||
assert_eq!(
|
||||
result["messages"][1]["content"][0]["cache_control"]["ttl"],
|
||||
"5m"
|
||||
|
||||
// 验证: user content 为纯字符串格式(不是数组)
|
||||
let user_msg = &result["messages"][1];
|
||||
assert_eq!(user_msg["role"], "user");
|
||||
assert!(
|
||||
user_msg["content"].is_string(),
|
||||
"user content must be string, got: {}",
|
||||
user_msg["content"]
|
||||
);
|
||||
// Tool cache_control preserved
|
||||
assert_eq!(result["tools"][0]["cache_control"]["type"], "ephemeral");
|
||||
|
||||
// 验证: tools 中不存在 cache_control
|
||||
if let Some(tools) = result["tools"].as_array() {
|
||||
for (i, tool) in tools.iter().enumerate() {
|
||||
assert!(
|
||||
tool.get("cache_control").is_none(),
|
||||
"tools[{i}] must not have cache_control"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -112,11 +112,15 @@ impl ProxyServer {
|
||||
let listener = tokio::net::TcpListener::bind(&addr)
|
||||
.await
|
||||
.map_err(|e| ProxyError::BindFailed(e.to_string()))?;
|
||||
let local_addr = listener
|
||||
.local_addr()
|
||||
.map_err(|e| ProxyError::BindFailed(e.to_string()))?;
|
||||
let actual_port = local_addr.port();
|
||||
|
||||
log::info!("[{}] 代理服务器启动于 {addr}", log_srv::STARTED);
|
||||
log::info!("[{}] 代理服务器启动于 {local_addr}", log_srv::STARTED);
|
||||
|
||||
// 更新全局代理端口,用于系统代理检测
|
||||
crate::proxy::http_client::set_proxy_port(self.config.listen_port);
|
||||
crate::proxy::http_client::set_proxy_port(actual_port);
|
||||
|
||||
// 保存关闭句柄
|
||||
*self.shutdown_tx.write().await = Some(shutdown_tx);
|
||||
@@ -125,7 +129,7 @@ impl ProxyServer {
|
||||
let mut status = self.state.status.write().await;
|
||||
status.running = true;
|
||||
status.address = self.config.listen_address.clone();
|
||||
status.port = self.config.listen_port;
|
||||
status.port = actual_port;
|
||||
drop(status);
|
||||
|
||||
// 记录启动时间
|
||||
@@ -213,7 +217,7 @@ impl ProxyServer {
|
||||
|
||||
Ok(ProxyServerInfo {
|
||||
address: self.config.listen_address.clone(),
|
||||
port: self.config.listen_port,
|
||||
port: actual_port,
|
||||
started_at: chrono::Utc::now().to_rfc3339(),
|
||||
})
|
||||
}
|
||||
@@ -315,6 +319,9 @@ impl ProxyServer {
|
||||
"/codex/v1/chat/completions",
|
||||
post(handlers::handle_chat_completions),
|
||||
)
|
||||
// OpenAI Models API (Codex CLI reachability check)
|
||||
.route("/models", get(handlers::handle_models))
|
||||
.route("/v1/models", get(handlers::handle_models))
|
||||
// OpenAI Responses API (Codex CLI,支持带前缀和不带前缀)
|
||||
.route("/responses", post(handlers::handle_responses))
|
||||
.route("/v1/responses", post(handlers::handle_responses))
|
||||
|
||||
@@ -148,6 +148,8 @@ mod tests {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: true,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +158,8 @@ mod tests {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: false,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +168,8 @@ mod tests {
|
||||
enabled: false,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: true,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -251,6 +251,8 @@ mod tests {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: true,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,6 +261,8 @@ mod tests {
|
||||
enabled: true,
|
||||
request_thinking_signature: false,
|
||||
request_thinking_budget: false,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,6 +271,8 @@ mod tests {
|
||||
enabled: false,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: true,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -213,6 +213,19 @@ pub struct RectifierConfig {
|
||||
/// 处理错误:budget_tokens + thinking 相关约束
|
||||
#[serde(default = "default_true")]
|
||||
pub request_thinking_budget: bool,
|
||||
/// 请求整流:不支持的图片降级(默认开启)
|
||||
///
|
||||
/// 上游拒绝图片输入时,把图片块替换为 [Unsupported Image] 标记,
|
||||
/// 让对话不中断。总开关,管辖「显式声明 text-only」与「上游报错后兜底」两条事实驱动路径。
|
||||
#[serde(default = "default_true")]
|
||||
pub request_media_fallback: bool,
|
||||
/// 请求整流:启发式 text-only 模型名匹配(默认开启)
|
||||
///
|
||||
/// 在模型未声明能力时,按内置模型名列表预测性地剥离图片(发送前)。
|
||||
/// 受 request_media_fallback 管辖;单独关闭后仅保留「显式声明」与「上游兜底」,
|
||||
/// 避免内置列表把多模态模型误判成 text-only 而静默剥图。
|
||||
#[serde(default = "default_true")]
|
||||
pub request_media_heuristic: bool,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -229,6 +242,8 @@ impl Default for RectifierConfig {
|
||||
enabled: true,
|
||||
request_thinking_signature: true,
|
||||
request_thinking_budget: true,
|
||||
request_media_fallback: true,
|
||||
request_media_heuristic: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -386,6 +401,14 @@ mod tests {
|
||||
config.request_thinking_budget,
|
||||
"thinking budget 整流器默认应为 true"
|
||||
);
|
||||
assert!(
|
||||
config.request_media_fallback,
|
||||
"media 降级总开关默认应为 true"
|
||||
);
|
||||
assert!(
|
||||
config.request_media_heuristic,
|
||||
"启发式 text-only 模型识别默认应为 true"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -396,6 +419,14 @@ mod tests {
|
||||
assert!(config.enabled);
|
||||
assert!(config.request_thinking_signature);
|
||||
assert!(config.request_thinking_budget);
|
||||
assert!(
|
||||
config.request_media_fallback,
|
||||
"缺 requestMediaFallback 时应回退默认值 true"
|
||||
);
|
||||
assert!(
|
||||
config.request_media_heuristic,
|
||||
"缺 requestMediaHeuristic 时应回退默认值 true"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -419,6 +450,19 @@ mod tests {
|
||||
assert!(config.request_thinking_budget);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rectifier_config_serde_media_explicit_false() {
|
||||
// 验证 media 两字段显式 false 时被如实反序列化(用户主动关闭须生效,不能被默认值覆盖)
|
||||
let json = r#"{"requestMediaFallback": false, "requestMediaHeuristic": false}"#;
|
||||
let config: RectifierConfig = serde_json::from_str(json).unwrap();
|
||||
assert!(!config.request_media_fallback);
|
||||
assert!(!config.request_media_heuristic);
|
||||
// 其余字段仍走默认 true
|
||||
assert!(config.enabled);
|
||||
assert!(config.request_thinking_signature);
|
||||
assert!(config.request_thinking_budget);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_log_config_default() {
|
||||
let config = LogConfig::default();
|
||||
|
||||
@@ -85,6 +85,7 @@ impl TokenUsage {
|
||||
let mut usage = Self::default();
|
||||
let mut model: Option<String> = None;
|
||||
let mut message_id: Option<String> = None;
|
||||
let mut input_from_delta = false;
|
||||
|
||||
for event in events {
|
||||
if let Some(event_type) = event.get("type").and_then(|v| v.as_str()) {
|
||||
@@ -129,32 +130,52 @@ impl TokenUsage {
|
||||
{
|
||||
usage.output_tokens = output as u32;
|
||||
}
|
||||
// OpenRouter 转换后的流式响应:input_tokens 也在 message_delta 中
|
||||
// 如果 message_start 中没有 input_tokens,则从 message_delta 获取
|
||||
if usage.input_tokens == 0 {
|
||||
if let Some(input) =
|
||||
delta_usage.get("input_tokens").and_then(|v| v.as_u64())
|
||||
{
|
||||
usage.input_tokens = input as u32;
|
||||
|
||||
let delta_input = delta_usage
|
||||
.get("input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.map(|v| v as u32);
|
||||
let delta_cache_read = delta_usage
|
||||
.get("cache_read_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.map(|v| v as u32);
|
||||
let delta_cache_creation = delta_usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.map(|v| v as u32);
|
||||
|
||||
// 部分 Anthropic-compatible SSE provider 会在 message_start 上报完整上下文,
|
||||
// 但在 message_delta 上报修正后的 fresh input。遇到更小的正数 delta input
|
||||
// 时采用 delta;若同一 usage 块带有缓存计数,也同步采用以避免重复计数。
|
||||
// 若 delta 缺少缓存字段,则保留 start 中已有的缓存值作为 best-effort fallback。
|
||||
if let Some(input) = delta_input {
|
||||
let should_use_delta_input = input > 0
|
||||
&& (usage.input_tokens == 0
|
||||
|| input < usage.input_tokens
|
||||
|| (input_from_delta && input <= usage.input_tokens));
|
||||
|
||||
if should_use_delta_input {
|
||||
usage.input_tokens = input;
|
||||
input_from_delta = true;
|
||||
if let Some(cache_read) = delta_cache_read {
|
||||
usage.cache_read_tokens = cache_read;
|
||||
}
|
||||
if let Some(cache_creation) = delta_cache_creation {
|
||||
usage.cache_creation_tokens = cache_creation;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 从 message_delta 中处理缓存命中(cache_read_input_tokens)
|
||||
if usage.cache_read_tokens == 0 {
|
||||
if let Some(cache_read) = delta_usage
|
||||
.get("cache_read_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
{
|
||||
usage.cache_read_tokens = cache_read as u32;
|
||||
if let Some(cache_read) = delta_cache_read {
|
||||
usage.cache_read_tokens = cache_read;
|
||||
}
|
||||
}
|
||||
// 从 message_delta 中处理缓存创建(cache_creation_input_tokens)
|
||||
// 注: 现在 zhipu 没有返回 cache_creation_input_tokens 字段
|
||||
if usage.cache_creation_tokens == 0 {
|
||||
if let Some(cache_creation) = delta_usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
{
|
||||
usage.cache_creation_tokens = cache_creation as u32;
|
||||
if let Some(cache_creation) = delta_cache_creation {
|
||||
usage.cache_creation_tokens = cache_creation;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -798,6 +819,115 @@ mod tests {
|
||||
assert_eq!(usage.model, Some("claude-sonnet-4-20250514".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_stream_prefers_smaller_delta_input_and_cache_pair() {
|
||||
// 部分 Anthropic-compatible provider 会在 message_start 给出包含缓存的总上下文,
|
||||
// 再在 message_delta 给出修正后的 fresh input,需要以 delta usage 为准。
|
||||
let events = vec![
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"model": "qwen-max",
|
||||
"usage": {
|
||||
"input_tokens": 200_000,
|
||||
"cache_read_input_tokens": 180_000,
|
||||
"cache_creation_input_tokens": 2_000
|
||||
}
|
||||
}
|
||||
}),
|
||||
json!({
|
||||
"type": "message_delta",
|
||||
"usage": {
|
||||
"input_tokens": 80_000,
|
||||
"output_tokens": 1_000,
|
||||
"cache_read_input_tokens": 120_000,
|
||||
"cache_creation_input_tokens": 500
|
||||
}
|
||||
}),
|
||||
];
|
||||
|
||||
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
|
||||
assert_eq!(usage.input_tokens, 80_000);
|
||||
assert_eq!(usage.output_tokens, 1_000);
|
||||
assert_eq!(usage.cache_read_tokens, 120_000);
|
||||
assert_eq!(usage.cache_creation_tokens, 500);
|
||||
assert_eq!(usage.model, Some("qwen-max".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_stream_updates_cache_pair_from_later_delta_input() {
|
||||
// 有些 provider 会多次发送带 input 的 message_delta;一旦采用过 delta input,
|
||||
// 后续相同/更小 input 的 delta 应继续更新同一块里的缓存计数。
|
||||
let events = vec![
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"model": "qwen-max",
|
||||
"usage": {
|
||||
"input_tokens": 200_000,
|
||||
"cache_read_input_tokens": 180_000,
|
||||
"cache_creation_input_tokens": 2_000
|
||||
}
|
||||
}
|
||||
}),
|
||||
json!({
|
||||
"type": "message_delta",
|
||||
"usage": {
|
||||
"input_tokens": 80_000,
|
||||
"output_tokens": 100,
|
||||
"cache_read_input_tokens": 110_000,
|
||||
"cache_creation_input_tokens": 300
|
||||
}
|
||||
}),
|
||||
json!({
|
||||
"type": "message_delta",
|
||||
"usage": {
|
||||
"input_tokens": 80_000,
|
||||
"output_tokens": 1_000,
|
||||
"cache_read_input_tokens": 120_000,
|
||||
"cache_creation_input_tokens": 500
|
||||
}
|
||||
}),
|
||||
];
|
||||
|
||||
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
|
||||
assert_eq!(usage.input_tokens, 80_000);
|
||||
assert_eq!(usage.output_tokens, 1_000);
|
||||
assert_eq!(usage.cache_read_tokens, 120_000);
|
||||
assert_eq!(usage.cache_creation_tokens, 500);
|
||||
assert_eq!(usage.model, Some("qwen-max".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_claude_stream_keeps_start_when_delta_input_is_larger() {
|
||||
// 正常 Anthropic 语义下,message_start 的 input_tokens 已经可信;
|
||||
// 如果 delta input 变大,不应覆盖 start input/cache。
|
||||
let events = vec![
|
||||
json!({
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"usage": {
|
||||
"input_tokens": 100,
|
||||
"cache_read_input_tokens": 20
|
||||
}
|
||||
}
|
||||
}),
|
||||
json!({
|
||||
"type": "message_delta",
|
||||
"usage": {
|
||||
"input_tokens": 150,
|
||||
"output_tokens": 75,
|
||||
"cache_read_input_tokens": 30
|
||||
}
|
||||
}),
|
||||
];
|
||||
|
||||
let usage = TokenUsage::from_claude_stream_events(&events).unwrap();
|
||||
assert_eq!(usage.input_tokens, 100);
|
||||
assert_eq!(usage.output_tokens, 75);
|
||||
assert_eq!(usage.cache_read_tokens, 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_native_claude_stream_parsing() {
|
||||
// 测试原生 Claude API 流式响应解析
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -16,6 +16,7 @@ enum CodingPlanProvider {
|
||||
ZhipuEn,
|
||||
MiniMaxCn,
|
||||
MiniMaxEn,
|
||||
ZenMux,
|
||||
}
|
||||
|
||||
fn detect_provider(base_url: &str) -> Option<CodingPlanProvider> {
|
||||
@@ -30,6 +31,8 @@ fn detect_provider(base_url: &str) -> Option<CodingPlanProvider> {
|
||||
Some(CodingPlanProvider::MiniMaxCn)
|
||||
} else if url.contains("api.minimax.io") {
|
||||
Some(CodingPlanProvider::MiniMaxEn)
|
||||
} else if url.contains("zenmux") {
|
||||
Some(CodingPlanProvider::ZenMux)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -145,6 +148,8 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
name: "five_hour".to_string(),
|
||||
utilization,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -166,6 +171,8 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
name: "weekly_limit".to_string(),
|
||||
utilization,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -225,17 +232,38 @@ fn parse_zhipu_token_tiers(data: &serde_json::Value) -> Vec<QuotaTier> {
|
||||
name: name.to_string(),
|
||||
utilization: percentage,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn query_zhipu(api_key: &str) -> SubscriptionQuota {
|
||||
let client = crate::proxy::http_client::get();
|
||||
/// Resolve the Zhipu quota endpoint from the user's configured `base_url`.
|
||||
///
|
||||
/// Zhipu ships as two distinct presets (Zhipu GLM = `open.bigmodel.cn`,
|
||||
/// Zhipu GLM en = `api.z.ai`) that share the same quota path and JSON shape.
|
||||
/// The quota endpoint lives on the same host as the user's coding endpoint,
|
||||
/// so we route by `base_url` and let the caller's existing reachability
|
||||
/// (they're already using this host to run coding) determine success — no
|
||||
/// cross-host fallback, no auth-error heuristics.
|
||||
fn zhipu_quota_base(base_url: &str) -> &'static str {
|
||||
if base_url.to_lowercase().contains("bigmodel.cn") {
|
||||
"https://open.bigmodel.cn"
|
||||
} else {
|
||||
"https://api.z.ai"
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
let client = crate::proxy::http_client::get();
|
||||
let url = format!(
|
||||
"{}/api/monitor/usage/quota/limit",
|
||||
zhipu_quota_base(base_url)
|
||||
);
|
||||
|
||||
// 统一走 api.z.ai 国际站(中国站 bigmodel.cn 有反爬机制)
|
||||
let resp = client
|
||||
.get("https://api.z.ai/api/monitor/usage/quota/limit")
|
||||
.get(&url)
|
||||
.header("Authorization", api_key) // 注意:智谱不加 Bearer 前缀
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept-Language", "en-US,en")
|
||||
@@ -370,50 +398,8 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
}
|
||||
}
|
||||
|
||||
let mut tiers = Vec::new();
|
||||
|
||||
if let Some(model_remains) = body.get("model_remains").and_then(|v| v.as_array()) {
|
||||
// 只取第一个模型(MiniMax-M*,主力编程模型)
|
||||
if let Some(item) = model_remains.first() {
|
||||
// usage_count 是剩余量(满额=total,用完=0),需反转为已用百分比
|
||||
let interval_total = item
|
||||
.get("current_interval_total_count")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let interval_remaining = item
|
||||
.get("current_interval_usage_count")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let end_time = item.get("end_time").and_then(|v| v.as_i64());
|
||||
|
||||
if interval_total > 0.0 {
|
||||
tiers.push(QuotaTier {
|
||||
name: "five_hour".to_string(),
|
||||
utilization: ((interval_total - interval_remaining) / interval_total) * 100.0,
|
||||
resets_at: end_time.and_then(millis_to_iso8601),
|
||||
});
|
||||
}
|
||||
|
||||
// 周额度
|
||||
let weekly_total = item
|
||||
.get("current_weekly_total_count")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let weekly_remaining = item
|
||||
.get("current_weekly_usage_count")
|
||||
.and_then(|v| v.as_f64())
|
||||
.unwrap_or(0.0);
|
||||
let weekly_end = item.get("weekly_end_time").and_then(|v| v.as_i64());
|
||||
|
||||
if weekly_total > 0.0 {
|
||||
tiers.push(QuotaTier {
|
||||
name: "weekly_limit".to_string(),
|
||||
utilization: ((weekly_total - weekly_remaining) / weekly_total) * 100.0,
|
||||
resets_at: weekly_end.and_then(millis_to_iso8601),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// 提取纯函数便于无 mock 单元测试;新接口直接给"剩余百分比",反转为已用百分比
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
|
||||
SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
@@ -427,6 +413,204 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
}
|
||||
}
|
||||
|
||||
// ── ZenMux ──────────────────────────────────────────────────
|
||||
|
||||
async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
.get(base_url)
|
||||
.header("Authorization", format!("Bearer {api_key}"))
|
||||
.header("Accept", "application/json")
|
||||
.timeout(std::time::Duration::from_secs(10))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
success: false,
|
||||
tiers: vec![],
|
||||
extra_usage: None,
|
||||
error: Some(format!("Authentication failed (HTTP {status})")),
|
||||
queried_at: Some(now_millis()),
|
||||
};
|
||||
}
|
||||
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
};
|
||||
|
||||
// 检查业务级别错误
|
||||
if body.get("success").and_then(|v| v.as_bool()) != Some(true) {
|
||||
let msg = body
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return make_error(format!("API error: {msg}"));
|
||||
}
|
||||
|
||||
let data = match body.get("data") {
|
||||
Some(d) => d,
|
||||
None => return make_error("Missing 'data' field in response".to_string()),
|
||||
};
|
||||
|
||||
let mut tiers = Vec::new();
|
||||
|
||||
// 5 小时窗口限额
|
||||
if let Some(q5h) = data.get("quota_5_hour") {
|
||||
let usage_pct = q5h
|
||||
.get("usage_percentage")
|
||||
.and_then(parse_f64)
|
||||
.unwrap_or(0.0);
|
||||
let resets_at = q5h
|
||||
.get("resets_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
let used_usd = q5h.get("used_value_usd").and_then(parse_f64);
|
||||
let max_usd = q5h.get("max_value_usd").and_then(parse_f64);
|
||||
tiers.push(QuotaTier {
|
||||
name: "five_hour".to_string(),
|
||||
utilization: usage_pct * 100.0,
|
||||
resets_at,
|
||||
used_value_usd: used_usd,
|
||||
max_value_usd: max_usd,
|
||||
});
|
||||
}
|
||||
|
||||
// 7 天窗口限额
|
||||
if let Some(q7d) = data.get("quota_7_day") {
|
||||
let usage_pct = q7d
|
||||
.get("usage_percentage")
|
||||
.and_then(parse_f64)
|
||||
.unwrap_or(0.0);
|
||||
let resets_at = q7d
|
||||
.get("resets_at")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(String::from);
|
||||
let used_usd = q7d.get("used_value_usd").and_then(parse_f64);
|
||||
let max_usd = q7d.get("max_value_usd").and_then(parse_f64);
|
||||
tiers.push(QuotaTier {
|
||||
name: "weekly_limit".to_string(),
|
||||
utilization: usage_pct * 100.0,
|
||||
resets_at,
|
||||
used_value_usd: used_usd,
|
||||
max_value_usd: max_usd,
|
||||
});
|
||||
}
|
||||
|
||||
// 套餐等级和账户状态存入 credential_message
|
||||
let plan_tier = data
|
||||
.get("plan")
|
||||
.and_then(|p| p.get("tier"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let account_status = data
|
||||
.get("account_status")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let plan_info = if !plan_tier.is_empty() {
|
||||
format!("{plan_tier} ({account_status})")
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: if plan_info.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(plan_info)
|
||||
},
|
||||
success: true,
|
||||
tiers,
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 从 `/coding_plan/remains` 响应中解析 MiniMax 编程套餐的额度 tier。
|
||||
///
|
||||
/// 新接口语义:`current_*_remaining_percent` 是"剩余百分比"(0-100),
|
||||
/// `model_remains` 数组里有 `general`(编程套餐)和 `video` 等其他模型,
|
||||
/// 这里只取 `general`,跳过 video。
|
||||
///
|
||||
/// 5h 桶始终存在;周桶并非所有套餐都有,靠 `current_weekly_status == 1`
|
||||
/// 判定激活(无周限额套餐该字段为 3,`remaining_percent` 恒为 100,不应展示)。
|
||||
fn parse_minimax_tiers(body: &serde_json::Value) -> Vec<QuotaTier> {
|
||||
let mut tiers = Vec::new();
|
||||
|
||||
let Some(model_remains) = body.get("model_remains").and_then(|v| v.as_array()) else {
|
||||
return tiers;
|
||||
};
|
||||
|
||||
// 只取 model_name == "general" 的条目,跳过 video 等非编程模型
|
||||
let Some(item) = model_remains.iter().find(|item| {
|
||||
item.get("model_name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s == "general")
|
||||
.unwrap_or(false)
|
||||
}) else {
|
||||
return tiers;
|
||||
};
|
||||
|
||||
// 5h 桶:剩余百分比 → 已用百分比
|
||||
if let Some(remain_pct) = item
|
||||
.get("current_interval_remaining_percent")
|
||||
.and_then(|v| v.as_f64())
|
||||
{
|
||||
let resets_at = item
|
||||
.get("end_time")
|
||||
.and_then(|v| v.as_i64())
|
||||
.and_then(millis_to_iso8601);
|
||||
tiers.push(QuotaTier {
|
||||
name: TIER_FIVE_HOUR.to_string(),
|
||||
utilization: 100.0 - remain_pct,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
|
||||
// 周桶:仅当 status=1 时激活;status=3 等表示该套餐无周限额,跳过
|
||||
if item.get("current_weekly_status").and_then(|v| v.as_i64()) == Some(1) {
|
||||
if let Some(remain_pct) = item
|
||||
.get("current_weekly_remaining_percent")
|
||||
.and_then(|v| v.as_f64())
|
||||
{
|
||||
let resets_at = item
|
||||
.get("weekly_end_time")
|
||||
.and_then(|v| v.as_i64())
|
||||
.and_then(millis_to_iso8601);
|
||||
tiers.push(QuotaTier {
|
||||
name: TIER_WEEKLY_LIMIT.to_string(),
|
||||
utilization: 100.0 - remain_pct,
|
||||
resets_at,
|
||||
used_value_usd: None,
|
||||
max_value_usd: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
tiers
|
||||
}
|
||||
|
||||
// ── 公开入口 ────────────────────────────────────────────────
|
||||
|
||||
pub async fn get_coding_plan_quota(
|
||||
@@ -464,9 +648,12 @@ pub async fn get_coding_plan_quota(
|
||||
|
||||
let quota = match provider {
|
||||
CodingPlanProvider::Kimi => query_kimi(api_key).await,
|
||||
CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => query_zhipu(api_key).await,
|
||||
CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => {
|
||||
query_zhipu(base_url, api_key).await
|
||||
}
|
||||
CodingPlanProvider::MiniMaxCn => query_minimax(api_key, true).await,
|
||||
CodingPlanProvider::MiniMaxEn => query_minimax(api_key, false).await,
|
||||
CodingPlanProvider::ZenMux => query_zenmux(base_url, api_key).await,
|
||||
};
|
||||
|
||||
Ok(quota)
|
||||
@@ -474,7 +661,10 @@ pub async fn get_coding_plan_quota(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{parse_zhipu_token_tiers, TIER_FIVE_HOUR, TIER_WEEKLY_LIMIT};
|
||||
use super::{
|
||||
parse_minimax_tiers, parse_zhipu_token_tiers, zhipu_quota_base, TIER_FIVE_HOUR,
|
||||
TIER_WEEKLY_LIMIT,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -604,4 +794,212 @@ mod tests {
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
|
||||
}
|
||||
|
||||
// ── MiniMax ──
|
||||
|
||||
#[test]
|
||||
fn minimax_general_two_tiers_from_remaining_percent() {
|
||||
// 主路径:general 桶 5h 剩 98% / weekly 剩 95% → 已用 2% / 5%
|
||||
let body = json!({
|
||||
"model_remains": [
|
||||
{
|
||||
"model_name": "general",
|
||||
"current_interval_remaining_percent": 98.0,
|
||||
"current_weekly_remaining_percent": 95.0,
|
||||
"current_interval_status": 1,
|
||||
"current_weekly_status": 1,
|
||||
"end_time": 1_780_329_600_000_i64,
|
||||
"weekly_end_time": 1_780_848_000_000_i64
|
||||
},
|
||||
{
|
||||
"model_name": "video",
|
||||
"current_interval_remaining_percent": 100.0,
|
||||
"current_weekly_remaining_percent": 100.0
|
||||
}
|
||||
],
|
||||
"base_resp": { "status_code": 0, "status_msg": "success" }
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 2);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(tiers[0].utilization, 2.0);
|
||||
assert!(tiers[0].resets_at.is_some());
|
||||
assert_eq!(tiers[1].name, TIER_WEEKLY_LIMIT);
|
||||
assert_eq!(tiers[1].utilization, 5.0);
|
||||
assert!(tiers[1].resets_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_skips_video_and_finds_general_in_any_position() {
|
||||
// 防御性:即使 video 排在数组前面,general 排在后面,仍应被定位到。
|
||||
let body = json!({
|
||||
"model_remains": [
|
||||
{
|
||||
"model_name": "video",
|
||||
"current_interval_remaining_percent": 50.0,
|
||||
"current_weekly_remaining_percent": 50.0
|
||||
},
|
||||
{
|
||||
"model_name": "general",
|
||||
"current_interval_remaining_percent": 80.0,
|
||||
"current_weekly_remaining_percent": 70.0,
|
||||
"current_interval_status": 1,
|
||||
"current_weekly_status": 1
|
||||
}
|
||||
]
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 2);
|
||||
// 取的是 general 桶,不是 video(20%/30% 而非 50%/50%)
|
||||
assert_eq!(tiers[0].utilization, 20.0);
|
||||
assert_eq!(tiers[1].utilization, 30.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_missing_general_returns_empty() {
|
||||
// model_remains 只有 video / 空 / 缺字段 → 不应崩溃,tiers 为空
|
||||
let body = json!({
|
||||
"model_remains": [
|
||||
{
|
||||
"model_name": "video",
|
||||
"current_interval_remaining_percent": 100.0,
|
||||
"current_weekly_remaining_percent": 100.0
|
||||
}
|
||||
]
|
||||
});
|
||||
assert!(parse_minimax_tiers(&body).is_empty());
|
||||
|
||||
let body_empty: serde_json::Value = json!({ "model_remains": [] });
|
||||
assert!(parse_minimax_tiers(&body_empty).is_empty());
|
||||
|
||||
let body_no_field = json!({});
|
||||
assert!(parse_minimax_tiers(&body_no_field).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_missing_percent_fields_skips_tier() {
|
||||
// 字段缺失时只跳过对应桶,另一边仍能展示
|
||||
let body = json!({
|
||||
"model_remains": [{
|
||||
"model_name": "general",
|
||||
"current_interval_remaining_percent": 60.0,
|
||||
"current_weekly_status": 1
|
||||
// 缺 current_weekly_remaining_percent
|
||||
}]
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 1);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(tiers[0].utilization, 40.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_negative_percent_passes_through() {
|
||||
// 防御性:与 parse_zhipu_token_tiers 约定一致,负数 / 超 100 不做范围裁剪
|
||||
let body = json!({
|
||||
"model_remains": [{
|
||||
"model_name": "general",
|
||||
"current_interval_remaining_percent": -5.0,
|
||||
"current_weekly_remaining_percent": 150.0,
|
||||
"current_interval_status": 1,
|
||||
"current_weekly_status": 1
|
||||
}]
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 2);
|
||||
assert_eq!(tiers[0].utilization, 105.0); // 100 - (-5)
|
||||
assert_eq!(tiers[1].utilization, -50.0); // 100 - 150
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_weekly_status_3_skips_weekly_tier() {
|
||||
// 无周限额套餐:current_weekly_status=3,remaining_percent 恒为 100,
|
||||
// 不应推 weekly_limit tier(否则会显示"0% 已用"的假周桶)
|
||||
let body = json!({
|
||||
"model_remains": [
|
||||
{
|
||||
"model_name": "general",
|
||||
"start_time": 1_780_347_600_000_i64,
|
||||
"end_time": 1_780_365_600_000_i64,
|
||||
"remains_time": 4_161_372_i64,
|
||||
"current_interval_remaining_percent": 99,
|
||||
"current_interval_status": 1,
|
||||
"current_weekly_total_count": 0,
|
||||
"current_weekly_usage_count": 0,
|
||||
"weekly_start_time": 1_780_243_200_000_i64,
|
||||
"weekly_end_time": 1_780_848_000_000_i64,
|
||||
"weekly_remains_time": 486_561_372_i64,
|
||||
"current_weekly_status": 3,
|
||||
"current_weekly_remaining_percent": 100
|
||||
},
|
||||
{
|
||||
"model_name": "video",
|
||||
"current_interval_remaining_percent": 100,
|
||||
"current_weekly_status": 3,
|
||||
"current_weekly_remaining_percent": 100
|
||||
}
|
||||
],
|
||||
"base_resp": { "status_code": 0, "status_msg": "success" }
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 1);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(tiers[0].utilization, 1.0);
|
||||
assert!(tiers[0].resets_at.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimax_weekly_status_2_also_skips_weekly_tier() {
|
||||
// 防御性:除 1 之外的 status 都视为周桶未激活,跳过
|
||||
let body = json!({
|
||||
"model_remains": [{
|
||||
"model_name": "general",
|
||||
"current_interval_remaining_percent": 80.0,
|
||||
"current_weekly_remaining_percent": 50.0,
|
||||
"current_weekly_status": 2
|
||||
}]
|
||||
});
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
assert_eq!(tiers.len(), 1);
|
||||
assert_eq!(tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(tiers[0].utilization, 20.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zhipu_quota_base_routes_bigmodel_url_to_cn_endpoint() {
|
||||
assert_eq!(
|
||||
zhipu_quota_base("https://open.bigmodel.cn/api/paas/v4"),
|
||||
"https://open.bigmodel.cn"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zhipu_quota_base_routes_z_ai_url_to_en_endpoint() {
|
||||
assert_eq!(
|
||||
zhipu_quota_base("https://api.z.ai/api/paas/v4"),
|
||||
"https://api.z.ai"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zhipu_quota_base_defaults_to_en_for_unknown_url() {
|
||||
// 没有明显 Zhipu 域名特征时,默认走国际站(更通用的入口)
|
||||
assert_eq!(
|
||||
zhipu_quota_base("https://example.com/zhipu"),
|
||||
"https://api.z.ai"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zhipu_quota_base_routes_uppercase_cn_url_to_cn_endpoint() {
|
||||
// 大小写不敏感:与 detect_provider 保持一致的约定,避免大写 preset URL 静默路由到国际站
|
||||
assert_eq!(
|
||||
zhipu_quota_base("HTTPS://OPEN.BIGMODEL.CN/api/paas/v4"),
|
||||
"https://open.bigmodel.cn"
|
||||
);
|
||||
assert_eq!(
|
||||
zhipu_quota_base("https://Open.BigModel.cn/api/paas/v4"),
|
||||
"https://open.bigmodel.cn"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,19 @@ pub mod omo;
|
||||
pub mod prompt;
|
||||
pub mod provider;
|
||||
pub mod proxy;
|
||||
pub mod s3;
|
||||
pub mod s3_auto_sync;
|
||||
pub mod s3_sync;
|
||||
pub mod session_usage;
|
||||
pub mod session_usage_codex;
|
||||
pub mod session_usage_gemini;
|
||||
pub mod session_usage_opencode;
|
||||
pub mod skill;
|
||||
pub mod speedtest;
|
||||
pub mod sql_helpers;
|
||||
pub mod stream_check;
|
||||
pub mod subscription;
|
||||
pub mod sync_protocol;
|
||||
pub mod usage_cache;
|
||||
pub mod usage_stats;
|
||||
pub mod webdav;
|
||||
|
||||
@@ -121,9 +121,10 @@ pub async fn fetch_models(
|
||||
///
|
||||
/// 候选顺序:
|
||||
/// 1. `models_url_override` 非空 → 只返回它
|
||||
/// 2. baseURL 直接拼 `/v1/models`(若已有 `/v1` 结尾则拼 `/models`)
|
||||
/// 3. 若 baseURL 命中 [`KNOWN_COMPAT_SUFFIXES`],剥离后缀再拼 `/v1/models`
|
||||
/// 4. 同上,但拼 `/models`(部分站点如 DeepSeek 官方只暴露 `/models`)
|
||||
/// 2. baseURL 拼 `/v1/models`;若已以版本段 `/v{N}` 结尾(`/v1`、智谱
|
||||
/// `/api/coding/paas/v4` 等),版本号已在路径里,改拼 `/models`
|
||||
/// 3. 版本段非 `/v1`(如 `/v4`)时再追加 `/v1/models` 作为兜底次候选
|
||||
/// 4. 若 baseURL 命中 [`KNOWN_COMPAT_SUFFIXES`],剥离后缀再拼 `/v1/models`、`/models`
|
||||
///
|
||||
/// 结果已去重且保持首次出现顺序。
|
||||
pub fn build_models_url_candidates(
|
||||
@@ -160,12 +161,18 @@ pub fn build_models_url_candidates(
|
||||
return Ok(candidates);
|
||||
}
|
||||
|
||||
let primary = if trimmed.ends_with("/v1") {
|
||||
format!("{trimmed}/models")
|
||||
// baseURL 已以版本段 /v{N} 结尾时(如 `/v1`、智谱 `/api/coding/paas/v4`),
|
||||
// OpenAI 惯例的模型端点是 `{base}/models`,不能再补 `/v1`
|
||||
// (否则 .../coding/paas/v4/v1/models → 404)。
|
||||
if ends_with_version_segment(trimmed) {
|
||||
candidates.push(format!("{trimmed}/models"));
|
||||
// 版本段非 /v1 时,保留旧的 /v1/models 作为兜底次候选(正确路径已在前)。
|
||||
if !trimmed.ends_with("/v1") {
|
||||
candidates.push(format!("{trimmed}/v1/models"));
|
||||
}
|
||||
} else {
|
||||
format!("{trimmed}/v1/models")
|
||||
};
|
||||
candidates.push(primary);
|
||||
candidates.push(format!("{trimmed}/v1/models"));
|
||||
}
|
||||
|
||||
if let Some(stripped) = strip_compat_suffix(trimmed) {
|
||||
let root = stripped.trim_end_matches('/');
|
||||
@@ -210,6 +217,15 @@ fn strip_compat_suffix(base_url: &str) -> Option<&str> {
|
||||
None
|
||||
}
|
||||
|
||||
/// 判断 baseURL 是否以 OpenAI 风格的版本段 `/v{N}` 结尾(`N` 为一个或多个数字),
|
||||
/// 例如 `/v1`、`.../paas/v4`。这类 URL 版本号已在路径中,模型端点应为
|
||||
/// `{base}/models`,不能再补 `/v1`(智谱 Coding Plan 即 `.../coding/paas/v4`)。
|
||||
fn ends_with_version_segment(url: &str) -> bool {
|
||||
let last = url.rsplit('/').next().unwrap_or("");
|
||||
last.strip_prefix('v')
|
||||
.is_some_and(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -232,6 +248,48 @@ mod tests {
|
||||
assert_eq!(c, vec!["https://api.example.com/v1/models"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_candidates_zhipu_coding_paas_v4() {
|
||||
// 智谱 Coding Plan 端点以 /v4 版本段结尾:模型端点是 {base}/models,
|
||||
// 正确路径必须排在 .../v4/v1/models(404)之前。
|
||||
let c =
|
||||
build_models_url_candidates("https://open.bigmodel.cn/api/coding/paas/v4", false, None)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
c,
|
||||
vec![
|
||||
"https://open.bigmodel.cn/api/coding/paas/v4/models",
|
||||
"https://open.bigmodel.cn/api/coding/paas/v4/v1/models",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_candidates_zai_coding_paas_v4() {
|
||||
let c = build_models_url_candidates("https://api.z.ai/api/coding/paas/v4", false, None)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
c,
|
||||
vec![
|
||||
"https://api.z.ai/api/coding/paas/v4/models",
|
||||
"https://api.z.ai/api/coding/paas/v4/v1/models",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ends_with_version_segment() {
|
||||
assert!(ends_with_version_segment("https://x.com/v1"));
|
||||
assert!(ends_with_version_segment(
|
||||
"https://open.bigmodel.cn/api/coding/paas/v4"
|
||||
));
|
||||
assert!(ends_with_version_segment("https://x.com/v10"));
|
||||
assert!(!ends_with_version_segment("https://x.com/api"));
|
||||
assert!(!ends_with_version_segment("https://x.com/vX"));
|
||||
assert!(!ends_with_version_segment("https://x.com/models"));
|
||||
assert!(!ends_with_version_segment("https://api.siliconflow.cn"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_candidates_full_url() {
|
||||
let c = build_models_url_candidates(
|
||||
|
||||
@@ -596,6 +596,19 @@ fn restore_live_settings_for_provider_backfill(
|
||||
);
|
||||
}
|
||||
|
||||
// `modelCatalog` is a cc-switch–private field whose SSOT is the DB. Live's
|
||||
// `config.toml` only carries a lossy projection (`model_catalog_json` →
|
||||
// generated catalog file) that proxy takeover/restore cycles and Codex.app
|
||||
// config rewrites can drop, so `read_live_settings` may reconstruct it as
|
||||
// absent. Never let a switch-away backfill from Live erase the stored
|
||||
// mapping: prefer the DB provider's `modelCatalog`, falling back to whatever
|
||||
// Live reconstructed only when the DB has none.
|
||||
if let Some(stored_catalog) = provider.settings_config.get("modelCatalog") {
|
||||
if let Some(obj) = settings.as_object_mut() {
|
||||
obj.insert("modelCatalog".to_string(), stored_catalog.clone());
|
||||
}
|
||||
}
|
||||
|
||||
settings
|
||||
}
|
||||
|
||||
@@ -910,6 +923,48 @@ pub(crate) fn sync_current_provider_for_app_to_live(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sync_current_provider_for_app_respecting_takeover(
|
||||
state: &AppState,
|
||||
app_type: &AppType,
|
||||
) -> Result<(), AppError> {
|
||||
let current_id = match crate::settings::get_effective_current_provider(&state.db, app_type)? {
|
||||
Some(id) => id,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
let Some(provider) = providers.get(¤t_id) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let has_live_backup = futures::executor::block_on(state.db.get_live_backup(app_type.as_str()))
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let live_taken_over = state
|
||||
.proxy_service
|
||||
.detect_takeover_in_live_config_for_app(app_type);
|
||||
|
||||
// `enabled` is set only after takeover writes complete. During that
|
||||
// activation window, backup/live placeholders are the authoritative signal
|
||||
// that normal provider sync must not rewrite the managed live file.
|
||||
if has_live_backup || live_taken_over {
|
||||
if matches!(app_type, AppType::ClaudeDesktop) {
|
||||
write_live_with_common_config(state.db.as_ref(), app_type, provider)?;
|
||||
} else {
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
.update_live_backup_from_provider(app_type.as_str(), provider),
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("更新 Live 备份失败: {e}")))?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
write_live_with_common_config(state.db.as_ref(), app_type, provider)
|
||||
}
|
||||
|
||||
/// Sync current provider to live configuration
|
||||
///
|
||||
/// 使用有效的当前供应商 ID(验证过存在性)。
|
||||
@@ -924,19 +979,10 @@ pub fn sync_current_to_live(state: &AppState) -> Result<(), AppError> {
|
||||
// Additive mode: sync ALL providers
|
||||
sync_all_providers_to_live(state, &app_type)?;
|
||||
} else {
|
||||
// Switch mode: sync only current provider
|
||||
let current_id =
|
||||
match crate::settings::get_effective_current_provider(&state.db, &app_type)? {
|
||||
Some(id) => id,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let providers = state.db.get_all_providers(app_type.as_str())?;
|
||||
if let Some(provider) = providers.get(¤t_id) {
|
||||
write_live_with_common_config(state.db.as_ref(), &app_type, provider)?;
|
||||
}
|
||||
// Note: get_effective_current_provider already validates existence,
|
||||
// so providers.get() should always succeed here
|
||||
// Switch mode: sync only current provider. During proxy takeover,
|
||||
// update the restore backup instead of rewriting the taken-over
|
||||
// live file.
|
||||
sync_current_provider_for_app_respecting_takeover(state, &app_type)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1647,4 +1693,78 @@ mod tests {
|
||||
.collect();
|
||||
assert_eq!(values, vec!["tool2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_switch_backfill_preserves_stored_model_catalog_when_live_lacks_it() {
|
||||
// Reproduces the data-loss bug: switching away from a Codex provider
|
||||
// backfills the outgoing provider from Live, but Live's config.toml had
|
||||
// already lost its `model_catalog_json` projection (proxy cycle /
|
||||
// Codex.app rewrite), so `read_live_settings` reconstructs no catalog.
|
||||
// The stored mapping must survive the backfill.
|
||||
let mut provider = Provider::with_id(
|
||||
"deepseek".to_string(),
|
||||
"DeepSeek".to_string(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-deepseek" },
|
||||
"config": "model_provider = \"custom\"\nmodel = \"deepseek-v4-pro\"\n",
|
||||
"modelCatalog": {
|
||||
"models": [
|
||||
{ "model": "deepseek-v4-pro", "contextWindow": 1_000_000 }
|
||||
]
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.category = Some("cn_official".to_string());
|
||||
|
||||
// Live snapshot as captured during switch: no `modelCatalog` field.
|
||||
let live_settings = json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-deepseek" },
|
||||
"config": "model_provider = \"custom\"\nmodel = \"deepseek-v4-pro\"\n"
|
||||
});
|
||||
|
||||
let result =
|
||||
restore_live_settings_for_provider_backfill(&AppType::Codex, &provider, live_settings);
|
||||
|
||||
assert_eq!(
|
||||
result.get("modelCatalog"),
|
||||
provider.settings_config.get("modelCatalog"),
|
||||
"switch-away backfill must keep the DB-stored modelCatalog when Live has none"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_switch_backfill_keeps_live_catalog_when_db_has_none() {
|
||||
// When the DB provider has no stored catalog, a catalog reconstructed
|
||||
// from Live (if any) should be left intact — the DB-preference overlay
|
||||
// must not wipe it.
|
||||
let mut provider = Provider::with_id(
|
||||
"deepseek".to_string(),
|
||||
"DeepSeek".to_string(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-deepseek" },
|
||||
"config": "model_provider = \"custom\"\nmodel = \"deepseek-v4-pro\"\n"
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.category = Some("cn_official".to_string());
|
||||
|
||||
let live_settings = json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-deepseek" },
|
||||
"config": "model_provider = \"custom\"\nmodel = \"deepseek-v4-pro\"\n",
|
||||
"modelCatalog": { "models": [ { "model": "deepseek-v4-pro" } ] }
|
||||
});
|
||||
|
||||
let result = restore_live_settings_for_provider_backfill(
|
||||
&AppType::Codex,
|
||||
&provider,
|
||||
live_settings.clone(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
result.get("modelCatalog"),
|
||||
live_settings.get("modelCatalog"),
|
||||
"backfill must keep the Live-reconstructed catalog when the DB has none"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1391,11 +1391,13 @@ impl ProviderService {
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let is_proxy_running = futures::executor::block_on(state.proxy_service.is_running());
|
||||
let live_taken_over = state
|
||||
.proxy_service
|
||||
.detect_takeover_in_live_config_for_app(&app_type);
|
||||
let should_sync_via_proxy = is_proxy_running && (has_live_backup || live_taken_over);
|
||||
// Backup or live placeholders mean the live file is currently owned
|
||||
// by proxy takeover, including the short activation window before
|
||||
// proxy_config.enabled is committed.
|
||||
let should_sync_via_proxy = has_live_backup || live_taken_over;
|
||||
|
||||
if should_sync_via_proxy {
|
||||
if matches!(app_type, AppType::ClaudeDesktop) {
|
||||
@@ -1409,7 +1411,9 @@ impl ProviderService {
|
||||
.map_err(|e| AppError::Message(format!("更新 Live 备份失败: {e}")))?;
|
||||
}
|
||||
|
||||
if matches!(app_type, AppType::Claude) {
|
||||
if matches!(app_type, AppType::Claude)
|
||||
&& futures::executor::block_on(state.proxy_service.is_running())
|
||||
{
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
@@ -1559,7 +1563,7 @@ impl ProviderService {
|
||||
/// Switch flow:
|
||||
/// 1. Validate target provider exists
|
||||
/// 2. Check if proxy takeover mode is active AND proxy server is running
|
||||
/// 3. If takeover mode active: hot-switch proxy target only (no Live config write)
|
||||
/// 3. If takeover mode active: hot-switch proxy target and refresh proxy-safe Live labels
|
||||
/// 4. If normal mode:
|
||||
/// a. **Backfill mechanism**: Backfill current live config to current provider
|
||||
/// b. Update local settings current_provider_xxx (device-level)
|
||||
@@ -1589,21 +1593,32 @@ impl ProviderService {
|
||||
return Self::switch_normal(state, app_type, id, &providers);
|
||||
}
|
||||
|
||||
// Check if proxy takeover mode is active AND proxy server is actually running
|
||||
// Both conditions must be true to use hot-switch mode
|
||||
// Use blocking wait since this is a sync function
|
||||
// Provider switches and takeover toggles both mutate live config and the
|
||||
// restore backup. Serialize them per app, then decide from the locked
|
||||
// current state so a just-started takeover cannot be overwritten by a
|
||||
// normal live write.
|
||||
let _switch_guard =
|
||||
if matches!(app_type, AppType::Claude | AppType::Codex | AppType::Gemini) {
|
||||
Some(futures::executor::block_on(
|
||||
state.proxy_service.lock_switch_for_app(app_type.as_str()),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Backup or live placeholders mean the live file is owned by proxy
|
||||
// takeover, even if the proxy server is temporarily stopped or is in the
|
||||
// activation window before enabled=true is committed.
|
||||
let is_app_taken_over =
|
||||
futures::executor::block_on(state.db.get_live_backup(app_type.as_str()))
|
||||
.ok()
|
||||
.flatten()
|
||||
.is_some();
|
||||
let is_proxy_running = futures::executor::block_on(state.proxy_service.is_running());
|
||||
let live_taken_over = state
|
||||
.proxy_service
|
||||
.detect_takeover_in_live_config_for_app(&app_type);
|
||||
|
||||
// Hot-switch only when BOTH: this app is taken over AND proxy server is actually running
|
||||
let should_hot_switch = (is_app_taken_over || live_taken_over) && is_proxy_running;
|
||||
let should_hot_switch = is_app_taken_over || live_taken_over;
|
||||
|
||||
// Block switching to official providers when proxy takeover is active.
|
||||
// Using a proxy with official APIs (Anthropic/OpenAI/Google) may cause account bans.
|
||||
@@ -1616,7 +1631,9 @@ impl ProviderService {
|
||||
}
|
||||
|
||||
if should_hot_switch {
|
||||
// Proxy takeover mode: hot-switch only, don't write Live config
|
||||
// Proxy takeover mode: hot-switch without restoring upstream Live config.
|
||||
// The proxy layer may still refresh proxy-safe Live fields so client labels
|
||||
// follow the selected provider while endpoints remain local.
|
||||
log::info!(
|
||||
"代理接管模式:热切换 {} 的目标供应商为 {}",
|
||||
app_type.as_str(),
|
||||
@@ -1626,12 +1643,12 @@ impl ProviderService {
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
.hot_switch_provider(app_type.as_str(), id),
|
||||
.hot_switch_provider_inner(app_type.as_str(), id),
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("热切换失败: {e}")))?;
|
||||
|
||||
// Note: No Live config write, no MCP sync
|
||||
// The proxy server will route requests to the new provider via is_current
|
||||
// The proxy server will route requests to the new provider via is_current.
|
||||
// MCP sync is intentionally skipped while Live config is owned by takeover.
|
||||
return Ok(SwitchResult::default());
|
||||
}
|
||||
|
||||
@@ -1800,11 +1817,6 @@ impl ProviderService {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let takeover_enabled =
|
||||
futures::executor::block_on(state.db.get_proxy_config_for_app(app_type.as_str()))
|
||||
.map(|config| config.enabled)
|
||||
.unwrap_or(false);
|
||||
|
||||
let has_live_backup =
|
||||
futures::executor::block_on(state.db.get_live_backup(app_type.as_str()))
|
||||
.ok()
|
||||
@@ -1815,7 +1827,9 @@ impl ProviderService {
|
||||
.proxy_service
|
||||
.detect_takeover_in_live_config_for_app(&app_type);
|
||||
|
||||
if takeover_enabled && (has_live_backup || live_taken_over) {
|
||||
// See the save path above: backup/placeholders are the ownership signal
|
||||
// here, not just proxy_config.enabled.
|
||||
if has_live_backup || live_taken_over {
|
||||
if matches!(app_type, AppType::ClaudeDesktop) {
|
||||
write_live_with_common_config(state.db.as_ref(), &app_type, provider)?;
|
||||
return Ok(());
|
||||
|
||||
+2167
-78
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user