mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-07-24 21:30:17 +08:00
Compare commits
71 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3d176b98cc | |||
| c154d30b7a | |||
| 6eb217b242 | |||
| ac52c851bf | |||
| 618723b42f | |||
| af58740bcd | |||
| 99573d2242 | |||
| 940ddd332b | |||
| 31ee42854a | |||
| 5c39dfbfbe | |||
| f15184edb0 | |||
| f2c6d48e19 | |||
| 51d6c458ff | |||
| 13e7c1fcc4 | |||
| b9263a8040 | |||
| 650905af2c | |||
| a078b4b207 | |||
| 0e563b50c5 | |||
| 27ce0a519c | |||
| f991726ff0 | |||
| 06039540ff | |||
| 442799879d | |||
| 7479d10db7 | |||
| 62e44c4838 | |||
| a7b4dd9405 | |||
| c6197ae324 | |||
| f39d463c44 | |||
| ded0b63a8e | |||
| 6245caa6c5 | |||
| 50270d5e42 | |||
| 99e11e0851 | |||
| 98ccde0050 | |||
| 95c917b337 | |||
| 3538b39246 | |||
| ba531ca222 | |||
| 88d5ffba44 | |||
| 94fc1cc064 | |||
| 11c173c730 | |||
| 1f36f0cfed | |||
| 6d2ee2472f | |||
| 473c2aaa9f | |||
| 93f56198da | |||
| 8b1ce764f1 | |||
| fad5b4c094 | |||
| bad3610d93 | |||
| e78aa8a7c3 | |||
| e191af4aa1 | |||
| d271d60cf9 | |||
| 358bf1e2b7 | |||
| 2df2212ceb | |||
| 468c93d409 | |||
| 525346188b | |||
| afabe80167 | |||
| 7fada72dd4 | |||
| 9f7642e29c | |||
| 22159430c6 | |||
| 754af2cc31 | |||
| 3ec83578f6 | |||
| f05ed3dbac | |||
| 4f45601f9f | |||
| 4cf6f175a7 | |||
| dbb5999d1e | |||
| 65a5464fcc | |||
| 6179c18805 | |||
| 8f018a2d45 | |||
| b3e5e32c89 | |||
| e606adfae7 | |||
| 7a7d41c873 | |||
| ffc22ea714 | |||
| 7a8b956253 | |||
| 0cda8d46c7 |
@@ -0,0 +1,14 @@
|
||||
# Code owners for cc-switch
|
||||
#
|
||||
# Branch protection on `main` has "Require review from Code Owners" enabled.
|
||||
# With this file present, a PR cannot merge to `main` without an approval from
|
||||
# the owner below. This closes the gap where two collaborators could approve
|
||||
# each other's malicious PRs (a single non-owner approval is no longer enough).
|
||||
|
||||
# Global fallback: every PR needs owner approval before merging to main.
|
||||
* @farion1231
|
||||
|
||||
# Most sensitive paths — CI/signing/release and the Rust backend. Listed
|
||||
# explicitly so they stay locked even if the global rule above is relaxed later.
|
||||
/.github/ @farion1231
|
||||
/src-tauri/ @farion1231
|
||||
@@ -0,0 +1,74 @@
|
||||
# Configuration for actions/labeler v5
|
||||
# Automatically labels PRs based on changed file paths
|
||||
|
||||
frontend:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src/**"
|
||||
- "index.html"
|
||||
- "vite.config.ts"
|
||||
- "vitest.config.ts"
|
||||
- "tailwind.config.cjs"
|
||||
- "postcss.config.cjs"
|
||||
- "tsconfig.json"
|
||||
- "tsconfig.node.json"
|
||||
- "components.json"
|
||||
- "tests/**"
|
||||
|
||||
backend:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src-tauri/**"
|
||||
|
||||
i18n:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src/locales/**"
|
||||
|
||||
actions:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- ".github/**"
|
||||
|
||||
dependencies:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
- "src-tauri/Cargo.toml"
|
||||
- "src-tauri/Cargo.lock"
|
||||
|
||||
documentation:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "*.md"
|
||||
- "docs/**"
|
||||
- "LICENSE"
|
||||
|
||||
mcp:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src/components/mcp/**"
|
||||
- "src/lib/api/mcp.ts"
|
||||
- "src-tauri/src/mcp/**"
|
||||
- "src-tauri/src/claude_mcp.rs"
|
||||
- "src-tauri/src/gemini_mcp.rs"
|
||||
- "src-tauri/src/commands/mcp.rs"
|
||||
|
||||
skills:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src/components/skills/**"
|
||||
- "src/lib/api/skills.ts"
|
||||
- "src-tauri/src/commands/skill.rs"
|
||||
- "src-tauri/src/services/skill.rs"
|
||||
- "src-tauri/src/database/dao/skills.rs"
|
||||
|
||||
proxy:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- "src/components/proxy/**"
|
||||
- "src/lib/api/proxy.ts"
|
||||
- "src-tauri/src/proxy/**"
|
||||
- "src-tauri/src/commands/proxy.rs"
|
||||
@@ -0,0 +1,17 @@
|
||||
name: Label PRs
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v5
|
||||
with:
|
||||
sync-labels: true
|
||||
@@ -15,6 +15,7 @@ concurrency:
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ${{ matrix.os }}
|
||||
environment: release
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -28,5 +28,4 @@ flatpak-repo/
|
||||
copilot-api
|
||||
.history
|
||||
CODEBUDDY.md
|
||||
.github
|
||||
mainWindow.js
|
||||
|
||||
@@ -5,6 +5,77 @@ All notable changes to CC Switch will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.17.0] - 2026-07-13
|
||||
|
||||
Development since v3.16.5 is headlined by project profiles — named snapshots of provider/MCP/Skills/prompt state, switchable per scope from a new header switcher or the tray (schema v12) — and a deep Codex push: official ChatGPT-subscription sessions can now route through the local proxy takeover with a corrected client identity, gpt-5.6 lands across context-window injection and Sol/Terra/Luna pricing with 1.25× cache-write rates, and a native Anthropic Messages upstream joins the Codex format options. A proxy-correctness wave makes the Responses↔Anthropic bridges fail closed and round-trip reasoning/tool results losslessly, strengthens prompt-cache breakpoint injection, and fixes cache-write accounting across historical token semantics (schema v13); a config.toml hardening batch stops deleted MCP servers from resurrecting, fails MCP sync closed on unparseable files, extends switch-time common-config autosync to Codex, and moves the common-config merge to backend toml_edit. Usage tooling gains Zhipu team-plan quota queries, Codex sub-agent and free-plan accounting, and transient-failure retry, while Kimi For Coding's 256K window finally takes effect — rounded out by a Codex default-model form field, renamed-session titles, OpenCode form and live-sync fixes, and preset updates (SudoCode sponsorship, LongCat-2.0, GPT-5.6 defaults, Hunyuan Hy3 pricing).
|
||||
|
||||
**Stats**: 69 commits | 172 files changed | +21,067 insertions | -2,464 deletions
|
||||
|
||||
### Added
|
||||
|
||||
- **Project Profiles for One-Click, Snapshot-Based Config Switching**: You can now save the current provider, MCP, Skills, and prompt state as a named "project" and re-apply it in one click from a new header switcher or the tray Projects submenu, so moving between per-project setups no longer means toggling each dimension by hand; it covers Claude Code, Claude Desktop, and Codex (Claude Desktop's only cc-switch-managed dimension is its provider, so its snapshots capture just that and leave the other dimensions untouched on apply). Projects are global shared entities, but capture and switching are per scope — Claude Code, Claude Desktop, and Codex each keep their own `current_profile_id_<scope>` marker and only touch their own payload slots, so picking a project on the Codex tab never disturbs the Claude config (slots use `Option` to distinguish "never captured" from "captured empty", preventing cross-side accidental disable). Applying is best-effort: `ProfileService::apply` (in `services/profile.rs`) reuses the existing switch primitives — provider switch, then minimal MCP/Skills toggle diffs, then prompt enable — and any dangling reference or per-item failure becomes a warning instead of rolling back. Switching first autosaves the leaving project's current state for the active scope, so a project always holds the configuration you last left it in, which is why there is no manual "update snapshot from current state" button. Before applying, proxy takeover is unconditionally disabled per app in the scope, the frontend invalidates takeover status, and the proxy server is stopped when the switch leaves no takeovers active so Claude Desktop's local-route master toggle reads off. Backed by a new `profiles` table introduced by the v11→v12 schema migration, wired into `commands/profile.rs`, `database/dao/profiles.rs`, the tray, and `components/profiles/`, localized in all four locales (zh/en/ja/zh-TW), with integration tests covering roundtrip, dangling refs, bidirectional autosave, and proxy-takeover teardown.
|
||||
- **Setting to Show or Hide the Project Switcher on the Main Page**: The header project switcher can now be turned off from a new "Show project switcher" toggle under the Homepage Display section of Settings, for users who don't use projects and prefer a cleaner header. It defaults to on (`show_profile_switcher` / `showProfileSwitcher`) so existing users keep the current behavior, and disabling it only hides the header control on every tab — projects and the tray Projects submenu remain fully usable. Localized in all four locales.
|
||||
- **Route Codex Official ChatGPT Sessions Through Proxy Takeover**: CC Switch can now route a Codex session authenticated with a ChatGPT subscription (native OAuth or API-key login, no stored API key) through the local proxy, so official-account traffic gets the same proxy routing, format conversion, and usage accounting that third-party providers already receive. The built-in `codex-official` "OpenAI Official" seed is restored if it was deleted (idempotent `ensure_codex_official_provider` command wired into the add-provider flow) and is now selectable during takeover from the provider panel and tray, with the provider card badge reading "Official Account Routing" while routing and "Codex Sign-in" otherwise; only that fixed seed qualifies (`is_codex_official_provider` / `official_provider_supports_proxy_takeover`, mirrored in the frontend `supportsOfficialProxyTakeover`), so copied UUID-based official entries stay blocked and still show "No Routing Support". Instead of writing an `OPENAI_API_KEY = PROXY_MANAGED` placeholder into `auth.json`, the official route projects a dedicated `cc-switch-official` `model_provider` into `config.toml` with `requires_openai_auth = true`, `wire_api = "responses"`, `supports_websockets = false`, and `base_url` pointing at the local proxy (`apply_codex_official_proxy_route`), so Codex forwards its own ChatGPT authorization to the proxy's `/responses` endpoint and the `codex-official` row never stores a credential (its `auth` stays `{}`). The forwarder passes the client's `Authorization` header through unchanged to the fixed first-party endpoint (`CHATGPT_CODEX_BASE_URL`, now shared by the Codex and Claude adapters), rejects a missing header or a stale `PROXY_MANAGED` placeholder with an actionable error (finish the ChatGPT login / restart Codex or start a new session), and treats official `401`/`403` and auth errors as non-retryable so failover never silently moves the conversation to another account or pollutes the circuit breaker. The native login is never overwritten — takeover preserves OAuth or API-key material into the backup (falling back to live `auth.json` when the backup is missing), config transforms in `codex_config.rs`/`services/proxy.rs` now fail closed instead of swallowing errors, and stale managed placeholders left in other provider tables are cleaned; the `preserveCodexOfficialAuthOnSwitch` setting copy was updated to clarify that takeover routing always preserves the official login and the toggle now only governs direct (non-routing) third-party switches.
|
||||
- **GPT-5.6 Context Window for Claude Code Codex Takeover**: When Claude Code is routed to a ChatGPT Codex (Codex OAuth) backend via proxy takeover, CC Switch now injects `CLAUDE_CODE_MAX_CONTEXT_TOKENS` and `CLAUDE_CODE_AUTO_COMPACT_WINDOW` set to `372000` into the effective live `settings.json`, so Claude Code stops assuming its default 200K window for the unrecognized GPT model id and auto-compacts before the upstream rejects an oversized prompt. 372000 matches the ChatGPT Codex catalog window for gpt-5.6 — the catalog lists a ~353K effective budget, not the 1.05M API spec — and Claude Code's built-in output reserve and compact buffer then keep the actual compact trigger below that budget. The defaults are gated on every configured model env key (`ANTHROPIC_MODEL`, the haiku/sonnet/opus/fable defaults, and `CLAUDE_CODE_SUBAGENT_MODEL`) starting with `gpt-5.6`: gpt-5.5's upstream catalog oscillates between 272K and 372K and must not inherit them; any non-gpt-5.6 or mixed mapping is skipped (and any value a legacy shared snippet dragged in is stripped), while an explicit user value always wins. The Codex OAuth presets for both Claude Code and Claude Desktop bump their default routes to the gpt-5.6 family (haiku → `gpt-5.6-luna`, main/sonnet/opus → `gpt-5.6`), the custom Codex `config.toml` template default model moves to gpt-5.6, and the Claude Code preset ships both context env keys pinned at 372000 (see the corresponding Changed entry on preset-pinned context windows). On switch-away backfill the injected values are stripped as the mirror-inverse of the injection conditions so program defaults never harden into per-provider explicit values, and both keys are held out of the shared Claude common-config snippet (`services/provider/mod.rs` strip list plus a guard in `live.rs`) because context limits must follow the actual upstream model; six Rust integration tests cover injection, user overrides, legacy-snippet strip, non-gpt5.6 skip, and the backfill round-trip. (openai/codex#31860)
|
||||
- **GPT-5.6 Sol/Terra/Luna Pricing With 1.25x Cache-Write Rate**: The usage dashboard now costs GPT-5.6 traffic using seeded pricing for the three tiers — Sol at 5 / 30 / 0.50, Terra at 2.50 / 15 / 0.25, and Luna at 1 / 6 / 0.10 USD per million input / output / cache-read tokens — cross-checked against OpenAI's pricing page and OpenRouter. Unlike GPT-5.5 and earlier, whose cache writes are seeded at zero, the 5.6 family bills prompt-cache writes at 1.25x the uncached input rate, so cache-write is seeded at 6.25 / 3.125 / 1.25 for Sol / Terra / Luna. The seed set also adds the bare `gpt-5.6` id as the official Sol alias plus effort-suffix variants (`-low`, `-medium`, `-high`, `-xhigh`, `-minimal`), all priced at Sol rates and mirroring the gpt-5.5 accounting shape. Rows are applied through the seed+repair dual-write path in `src-tauri/src/database/schema.rs`: a `repair_current_model_pricing` branch corrects the earlier zero cache-write seeds for the three tiers in existing databases, matching only rows still holding the exact old input/output/cache-read/cache-write values so user-customized prices survive, and no `SCHEMA_VERSION` bump is required.
|
||||
- **Native Anthropic Messages Protocol as Codex Upstream**: Codex providers can now target a gateway that only exposes the native Anthropic Messages protocol (`/v1/messages`) via a new `anthropic` value on the upstream-format selector in the Codex form; the local proxy performs bidirectional Responses↔Anthropic request, response, and streaming conversion (new `transform_codex_anthropic` / `streaming_codex_anthropic` modules). The form adds an auth-field selector — `ANTHROPIC_AUTH_TOKEN` sends `Authorization: Bearer` (default) and `ANTHROPIC_API_KEY` sends `x-api-key`, mutually exclusive — an optional Claude Code client-impersonation toggle (`impersonateClaudeCode`, off unless explicitly enabled, spoofing User-Agent / `anthropic-beta` / `x-app` / system-prompt first line and dropping Codex/OpenAI fingerprint headers), and a per-provider `maxOutputTokens` override (Codex omits `model_max_output_tokens`, so without it the path falls back to a conservative 8192 that can truncate long or thinking-heavy replies). The bridge injects standard 5-minute ephemeral `cache_control` so system/tools/history are cached rather than resent at full price, defers stripping the `[1m]` long-context marker until after catalog matching and re-emits the `context-1m-2025-08-07` beta header, gates extended thinking on the trailing turn only so history-resending sessions don't permanently lose it after the first tool call, disables native `web_search` for this profile, drops `tool_choice` when no tools survive filtering, treats a base URL already ending in `/v1/messages` as a full endpoint, and reports truncated streams as incomplete/failed instead of completed. (#5071)
|
||||
- **Default Model Field for Codex Provider Form**: The Codex provider form now exposes the top-level `model` key of `config.toml` as an editable field, so users can point an existing provider at a newly released model (e.g. `gpt-5.6`) without waiting for a preset update — preset changes only affect newly added providers, while existing ones keep their saved TOML. The field syncs bidirectionally with the TOML editor (mirroring the base-URL pattern), suggests models from the mapping catalog unioned with the provider's `/models` endpoint, offers a one-click "add to mapping" action when the value falls outside a non-empty catalog, and is hidden for official providers. Save-time catalog sync now backfills the first mapping row into the top-level `model` only when the field was left empty, so an explicit value always wins over the implicit row-0 fallback; model names and `base_url` are written with TOML basic-string escaping and control characters are stripped from field input, since `/models` ids are remote data and unescaped interpolation could inject `config.toml` lines such as a forged `[mcp_servers.*]`. The strict model-line matcher (`src/utils/providerConfigUtils.ts`) recognizes escaped output, empty strings, and single-quoted literals to keep extract/set round-trips stable, and the fetched model list is invalidated (with an in-flight sequence guard) whenever request identity changes — base URL, full-URL toggle, API key, or custom User-Agent — so the dropdown never shows a previous provider's models.
|
||||
- **Switch-Time Common-Config Autosync Now Covers Codex**: When switching away from a Codex provider with `common_config_enabled`, the service now re-extracts the shareable portion of its live `config.toml` into the stored common-config snippet — the same live-to-snippet sync that previously ran only for Claude — so preferences you tweak directly in the running Codex config propagate to every opted-in provider and a removed key isn't silently re-injected on the next switch. Codex was gated out before because its TOML extractor leaked provider-specific and injected content; `extract_codex_common_config` now strips top-level `model`, `model_provider`, `base_url`, and `wire_api`, the entire `[model_providers]` table, `mcp_servers` and the legacy `[mcp.servers]` form, the top-level `experimental_bearer_token` fallback (which would otherwise leak the API key into the shared snippet), the `model_catalog_json` catalog pointer, and the injected `web_search = "disabled"` sentinel, while keeping a user-set `web_search` value as a shareable preference. The sync in `services/provider/mod.rs` is scoped strictly to Claude and Codex (Gemini is still excluded), skipped when the snippet was explicitly cleared, and all failures are warn-only and never block the switch; the autosync-before-strip ordering also self-heals stale snippet values previously baked into provider snapshots, since the re-extracted snippet matches the live values and the value-match strip removes them on the same switch.
|
||||
- **Claude Subagent Model Configuration**: Claude providers can now pin a dedicated sub-agent model through a new "Subagent" row in the provider form, writing the `CLAUDE_CODE_SUBAGENT_MODEL` env key so Claude Code's spawned sub-agents run on a chosen (typically cheaper or faster) model. The row supports the `[1M]` marker but has no display-name field — it renders a "Not shown in /model" placeholder since the sub-agent model never appears in the `/model` menu — and the "quick set" button now fills it alongside the other tiers. On the proxy takeover path (`services/proxy.rs`), `CLAUDE_CODE_SUBAGENT_MODEL` is added to `CLAUDE_MODEL_OVERRIDE_ENV_KEYS` so it is written when a provider configures it and stale values are cleared when a provider omits it, and the model mapper (`proxy/model_mapper.rs`) gains a `subagent_model` field that passes a request through unchanged when its model (comparing with the 1M suffix stripped) matches the configured sub-agent model, instead of collapsing it to the default-model fallback. The key is also excluded from the shared Claude common-config snippet in `services/provider/mod.rs` so it can't leak across providers, and `modelRoleSubagent` / `modelNoDisplayName` labels were added in all four locales (zh/en/ja/zh-TW). (#4830)
|
||||
- **1M Context Checkbox on the Claude Fallback Model Field**: The Claude provider form's fallback model field (`ANTHROPIC_MODEL`, the "default/fallback model") now carries the same 1M checkbox that the role-specific Sonnet/Opus/Fable rows already had, so a fallback model backed by a 1M-token window can declare it instead of silently being treated as 200K. Checking the box appends the `[1M]` marker to the fallback model id and unchecking strips it, reusing the shared `hasClaudeOneMMarker` / `setClaudeOneMMarker` / `stripClaudeOneMMarker` helpers, and the checkbox is a no-op when the model field is empty. The marker is written in the documented uppercase form (`[1M]`), which Claude Code parses case-insensitively. This is a frontend-only change to `ClaudeFormFields.tsx`. (#5124, fixes #3679)
|
||||
- **Zhipu (智谱) Team Plan Quota Query Support**: Added quota-query support for Zhipu's team plan (团队套餐), which the personal-plan query could not reach: it hits the same `open.bigmodel.cn` quota endpoint with `?type=2` and requires two extra request headers, `bigmodel-organization` and `bigmodel-project`, so `detect_provider` cannot tell it apart from the personal plan by base URL alone. The usage-script modal gains a "Zhipu GLM Team" template with organization-ID and project-ID inputs (preserved when switching templates), and the backend routes on an explicit `coding_plan_provider == "zhipu_team"` identifier threaded through the usage script, IPC command, and background query path; the new `query_zhipu_team` in `services/coding_plan.rs` pins the CN site, appends `?type=2`, and shares response parsing (`zhipu_quota_from_body` / `parse_zhipu_token_tiers`) with the personal plan. All three of API key + organization ID + project ID are required — missing any one returns a NotFound that prompts the user to complete them (identifier match is case-insensitive) — and new copy was added across all four locales (zh/en/ja/zh-TW). (#5128)
|
||||
- **OpenCode Provider Form Gains Headers and Per-Model Token-Limit Editors**: The OpenCode provider form now exposes two previously unreachable config fields as structured editors: a Headers section for the provider's `options.headers` (arbitrary HTTP headers like `HTTP-Referer` or `X-Title` sent with provider requests) with add/remove rows and case-insensitive duplicate-name rejection that reverts the input on conflict, and per-model Token Limits (Context and Output number inputs writing `model.limit.context` / `model.limit.output`, where clearing the field removes it and negative or non-finite values are rejected while valid ones are truncated to integers). The Extra Options block was reworked into a collapsible section (its i18n label stays "Extra Options") that auto-expands when options already exist. Both the headers and extra-options editors switched their placeholder draft keys to colon-bearing prefixes (`draft-header:` / `draft-option:`) — a code comment notes a colon is invalid in an HTTP field name so a draft key cannot collide with a legitimate header, and the same technique now guards option keys — and those drafts are stripped on save, fixing a bug where the old filter discarded any real option key literally starting with `option-` (the former placeholder prefix). New i18n keys were added across all four locales (zh/en/ja/zh-TW), and `aria-label`s were added for the header add/remove and model-details toggle controls in `OpenCodeFormFields.tsx`; the headers state and draft-stripping logic live in `useOpencodeFormState.ts`. (#2907)
|
||||
- **Tencent Hunyuan Hy3 Model Pricing**: Seeded pricing for Tencent's Hunyuan Hy3 (released 2026-07-06, 256K context) so its usage is billed instead of showing $0. The rows are added to `seed_model_pricing` in `schema.rs` under both the `hunyuan-hy3` and `hy3` ids, since the upstream billing id isn't yet confirmed and one of the two should match logged usage. Prices follow Tencent's launch-day list rate (CNY 1 / 4 / 0.25 per Mtok input / output / cache-hit), converted at 1 USD ≈ 7.14 to $0.14 / $0.56 / $0.035, with `cache_write` left at `0` because no write rate is published. Hy3 actually uses input-length tiered billing (<16K / 16-32K / ≥32K) but the single-price table holds the lowest tier, so long-context requests are under-billed until this is revisited against the official billing page. Being a brand-new model it is seed-only, applied on next app start via `ensure_model_pricing_seeded` with no `SCHEMA_VERSION` bump.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Codex Chat Prompt-Cache Routing**: Added provider-aware `prompt_cache_key` injection on the Codex Responses→Chat Completions bridge. Kimi Coding and OpenAI official endpoints are enabled automatically, Kimi's preset opts in explicitly, and unknown OpenAI-compatible gateways remain off to avoid strict-schema 400s. The key is taken from an explicit client value or a real client-provided session ID—never a generated per-request UUID—with an advanced Auto/Enabled/Disabled override in all four UI locales.
|
||||
- **Provider Connectivity Configuration Simplified**: Removed the obsolete per-provider `testConfig` override (timeout, retry count, and degraded-latency threshold) from provider forms, frontend/backend provider metadata, and reachability-check merging. The lightweight `base_url` probe now always uses the single global connectivity-check configuration, while automatic failover remains driven exclusively by its separate proxy timeout and circuit-breaker settings. Also renamed the remaining settings UI and API modules from model-test terminology to connectivity-check terminology, removed the retired first-use confirmation flag, and deleted stale model/prompt/error copy across all four locales.
|
||||
- **Codex Image Capabilities Are Inferred Without a User Toggle**: Generated Codex model catalogs now advertise only models in CC Switch's confirmed, exact text-only registry as `input_modalities = ["text"]`; GPT, aliases, new suffix variants, and all unknown models fail open to `["text", "image"]`. The rectifier's “Text-Only Model Preflight” switch continues to control only proactive proxy request-body replacement and does not change Codex's catalog declaration. Live catalog reverse-import also collapses inferred modalities instead of persisting them as hidden row overrides, so a later registry correction or a model's multimodal upgrade takes effect automatically; only declarations that differ from inference survive a DB-missing/import round-trip.
|
||||
- **Context Window Values Pinned in Presets Instead of Editable Form Fields**: The `Codex` (ChatGPT/GPT-5.6) and `Kimi For Coding` presets no longer surface the "Max Context Tokens" and "Auto Compact Window" inputs in the provider form; the numbers are now hardcoded directly in the preset env (`372000`/`372000` for Codex, `262144`/`262144` for Kimi For Coding) instead of being exposed as editable `templateValues`. This drops two fields most users never need to touch while keeping both env keys present on purpose: since Claude Code resolves the compact window as `min(model window, value)`, setting it equal to the declared context window is behavior-neutral today, but pinning it explicitly shields the local compaction trigger against remote-config experiments that dial it down. The rare user who wants different numbers can still edit `CLAUDE_CODE_MAX_CONTEXT_TOKENS` / `CLAUDE_CODE_AUTO_COMPACT_WINDOW` directly in the provider's JSON editor. The change is confined to `claudeProviderPresets.ts` and its tests.
|
||||
- **Universal Provider Auto-Syncs to Live Configs After Being Added**: Adding a universal (multi-app) provider through the Add Provider dialog now immediately pushes it to its live target configs instead of only saving it to the database, so the cross-app config lands in Claude/Codex/Gemini without a separate manual sync step. After `universalProvidersApi.upsert` succeeds, `AddProviderDialog` calls `universalProvidersApi.sync(provider.id)` and reports the combined outcome: a success toast (`universalProvider.addedAndSynced`) when the sync lands, or a non-blocking warning toast (`universalProvider.addedButSyncFailed`) when the provider was saved but the sync failed — while a save failure still aborts early with the existing error toast (`universalProvider.addFailed`) and never attempts the sync. The now-unused `universalProvider.addSuccess` key was removed from all four locales (zh/en/ja/zh-TW) and a new `universalProvider.addedButSyncFailed` key was added alongside the pre-existing `addedAndSynced` key. (#2811)
|
||||
- **SudoCode Promoted to Paid Sponsor Across Six Clients**: The existing SudoCode preset — previously a `sudocode.us` provider that collided by name with an unrelated service — is replaced in place by the new paid sponsor SudoCode on `sudocode.chat`, now marked `isPartner` (gold star) with `partnerPromotionKey: "sudocode"` and a four-locale promo blurb (zh/en/ja/zh-TW). The preset spans six clients: Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes; the Gemini entry was removed as outside sponsor scope. All endpoints move to `api.sudocode.chat` (the presets that carry an `endpointCandidates` list — Claude Code, Claude Desktop, Codex — collapse it to that single host, dropping the old `sudocode.run` fallback), and the `apiKeyUrl` points to the attributed `sudocode.chat/register?utm_source=ccswitch&utm_medium=partner` signup while `websiteUrl` moves to `sudocode.chat`. Claude Code and Claude Desktop use direct Anthropic passthrough with no model mapping, whereas Codex/OpenCode/OpenClaw/Hermes default to `gpt-5.6-sol` (replacing the old `gpt-5.5`) — Codex/Hermes/OpenClaw over the native Responses format and OpenCode via `@ai-sdk/openai`. The provider icon is refreshed to the new brand PNG, and the promo copy surfaces that one key drives Claude Opus 4.8 on the Claude apps and GPT-5.6 on Codex plus a CNY ¥10 trial-credit offer.
|
||||
- **LongCat Presets Updated to LongCat-2.0**: The LongCat presets across Claude Code, Claude Desktop, Codex, Hermes, OpenClaw, and OpenCode now default to `LongCat-2.0` in place of the retired `LongCat-Flash-Chat` / `LongCat-2.0-Preview`, advertising the model's real 1M (1048576) context window and — for the Claude Code preset — a raised `CLAUDE_CODE_MAX_OUTPUT_TOKENS` of 131072 plus an added `ANTHROPIC_SMALL_FAST_MODEL` pin. OpenClaw's and OpenCode's base URL move to the `.../openai/v1` path (Codex and Hermes already used it), and the OpenClaw model entry gains `reasoning: false`, `input: ["text"]`, `maxTokens: 131072`, a bumped `contextWindow` of 1048576, and a new `compat.maxTokensField` (`max_tokens`) hint backed by a new optional `compat` field on the `OpenClawModel` type. Because LongCat-2.0 is text-only, the proxy's media sanitizer allowlist now classifies `longcat-2.0` (case-insensitively, keeping the retired `longcat-flash-chat` name for saved configs) so images pasted into a LongCat-2.0 session are replaced with the unsupported-image marker instead of being forwarded upstream and hard-rejected; a regression test covers the classification. (#4838)
|
||||
- **Volcengine/Doubao/BytePlus Website Links Restored to Invite Pages**: Reverts the v3.16.5 change (`56248087`) that had pointed the `火山Agentplan`, `DouBaoSeed`, and `BytePlus` presets' `websiteUrl` at their product homepages. Per the commit, the `websiteUrl` for these three presets is intentionally the same ccswitch-attributed campaign/invite link as `apiKeyUrl`, so it is restored across all six app preset files — `火山Agentplan` back to its `activity/codingplan` link, `BytePlus` to its `product/modelark` link, and `DouBaoSeed` to the Ark console API-key page, each carrying the `utm_*` attribution params. The `apiKeyUrl` links were already left intact by the reverted commit and are unchanged.
|
||||
- **Code0.ai Invite Link Updated to Agent Register URL**: The Code0.ai sponsor's `apiKeyUrl` moves from the `?source=ccswitch` referral to the new agent-register invite link `https://code0.ai/agent/register/B2XHxGjGmRvqgznY`, updated across all seven app presets and the Code0 sponsor rows in all four READMEs (`README.md`, `README_ZH.md`, `README_JA.md`, `README_DE.md`). The bare `code0.ai` API endpoint stays untouched.
|
||||
- **Dropped the Redundant OpenAI Compatible Preset**: Removed the `OpenAI Compatible` custom-template preset from the OpenCode and OpenClaw preset lists so the picker no longer shows two entries pointing at the same place. It was a duplicate entry point — the built-in `custom` provider flow already exposes an interface-format selector whose default (`@ai-sdk/openai-compatible` / `openai-completions`) seeds a byte-identical starting config. Existing providers are unaffected, since presets only seed form defaults on creation and saved providers store concrete `npm`/`baseUrl`/`apiKey`/`models` values; the `@ai-sdk/openai-compatible` dropdown label is deliberately kept as the format option users pick in the custom flow, not the deleted preset.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Align Codex OAuth Client Identity to Fix 404s on Newest ChatGPT Models**: The newest ChatGPT-gated subscription models (e.g. `gpt-5.6-luna`) now resolve correctly when routed through the local proxy takeover with an official Codex OAuth account, instead of returning a misleading `404 Model not found` even though the account had access. ChatGPT's Codex backend performs model cohort routing by the `originator`+`version` header pair, and cc-switch previously identified takeover requests as `originator: cc-switch` with no version, landing them in a cohort where `gpt-5.6-luna` resolved to an undeployed internal engine. The `CodexOAuth` auth strategy in `proxy/providers/claude.rs` now sends `originator: codex_cli_rs` paired with `version: 0.144.1`, matching the real Codex CLI and satisfying luna's `minimal_client_version` requirement of `0.144.0`. Both headers must be sent together (dropping either re-triggers the 404), and the `CODEX_OAUTH_CLIENT_VERSION` constant must be bumped whenever a newer target model raises the minimum. A direct HTTP A/B test against the live backend confirmed the old identity 404ed while the aligned identity completed successfully, so no WebSocket transport workaround is required.
|
||||
- **Fail Closed on Responses Upstream Failures Instead of Returning Empty Replies**: When the proxy bridges an Anthropic-format client (Claude Code / Claude Desktop pointed at a Responses gateway) to an OpenAI Responses upstream, a semantic upstream failure that arrives inside an HTTP 2xx body — a `{status:"failed"|"cancelled"}` object, an `error` envelope, or a `response.failed`/`error` SSE event before any output — is now surfaced as a real error so failover can select a different provider, instead of being converted into a silent, empty `end_turn`. The forwarder validates buffered/JSON bodies (`validate_responses_success_response`) and primes streaming responses up to 256 KB (`validate_responses_stream_start`) while still inside the retry loop, and the streaming converter emits an Anthropic `error` event then ignores every event after a terminal so a late delta cannot synthesize a spurious `message_start`. Streams that end cleanly after partial text now finalize as an explicit `max_tokens`-style incomplete turn with content blocks closed in protocol order, whereas a stream cut off mid tool-call or mid-reasoning (partial JSON or a missing thinking signature) yields a `stream_truncated` error rather than a corrupt turn, and on the Codex→Anthropic direction a truncated tool call is reported `incomplete` instead of `completed`. Gateways that ignore `stream:true` and return a single whole JSON document (even without a JSON content-type) are now recognized and expanded into a full Anthropic SSE lifecycle, and malformed client-supplied history is raised as an `InvalidRequest` — a `NonRetryable` category — so it fails fast instead of retrying across every provider. Touches `forwarder.rs`, `streaming_responses.rs`, `streaming_codex_anthropic.rs`, `transform_responses.rs`, and `transform_codex_anthropic.rs`.
|
||||
- **Preserve Reasoning, Tool Results, and System Roles Across the Responses/Anthropic Bridge**: Content and token accounting that crosses the Responses↔Anthropic bridge in multi-turn tool loops is now preserved instead of being dropped or corrupted. Encrypted Responses `reasoning` items round-trip losslessly by being carried inside a versioned bridge-owned Anthropic thinking `signature` (or a `redacted_thinking` `data` field, prefixed `ccswitch-openai-reasoning-v1:`) and restored on replay, orphaned reasoning-only assistant turns are discarded so they cannot brick the next request with a missing-following-item error, and the streaming converter now consumes the official `response.reasoning_summary_text.*` / `response.reasoning_text.*` event vocabulary (keeping `response.reasoning.*` as a compatibility alias), tracks concurrent items by stable id/output-index, emits the signature before closing the block, and recovers tool arguments from `*.done` / `output_item.done` events when a gateway skips deltas. Non-streaming Responses→Anthropic tool calls with empty arguments normalize to `{}`, invalid arguments in an incomplete turn degrade to `{}` with a warning, and invalid arguments on a completed response are rejected, while on the Codex→Anthropic request path malformed or non-object arguments raise a non-retryable `InvalidRequest`, incomplete historical tool calls are dropped, and only signed thinking blocks are re-encoded as encrypted reasoning. Structured tool results now keep their `is_error` flag, text, base64/URL images, and PDF/`input_file` documents in both directions instead of collapsing to a canonical JSON string, and historical `system`/`developer` messages are hoisted into Anthropic `system` rather than being silently demoted to user turns. For accounting, usage from a successful upstream request is recorded even when the subsequent conversion fails, and the Codex→Anthropic bridge keeps standard 5-minute prompt caching on by default while honoring the dedicated `cache_injection` sub-switch. Touches `reasoning_bridge.rs`, `transform_responses.rs`, `transform_codex_anthropic.rs`, `streaming_responses.rs`, `handlers.rs`, and `forwarder.rs`.
|
||||
- **Account for Cache-Write Tokens in Proxy Usage and Cost**: Prompt-cache write tokens are now billed correctly on the proxy usage dashboard. The parser reads cache writes from OpenAI/Codex-style usage details (`input_tokens_details.cache_write_tokens` and `prompt_tokens_details.cache_write_tokens`) and preserves them through every response-usage conversion path — Chat→Responses, Responses→Anthropic, Anthropic→Responses, and OpenAI/Chat→Anthropic (`transform_codex_chat.rs`, `transform_responses.rs`, `transform_codex_anthropic.rs`, `transform.rs`, `streaming.rs`) — so cache creation is no longer dropped when a request crosses a format boundary. Because a Codex/Gemini provider's reported `input_tokens` is inclusive of both cache reads and cache writes, the cost calculator now subtracts both before applying the input rate; previously only reads were removed, so cache-write tokens were double-charged at both the input rate and the cache-creation rate. To keep historical rows accurate across this shift, a new `input_token_semantics` column (schema v13; `0` legacy = subtract reads only, `1` total-inclusive = subtract reads and writes, `2` fresh = no subtraction) records how each row's `input_tokens` was stored, so the cost backfill subtracts reads only for pre-existing rows and reads-plus-writes for new total-inclusive rows, while daily rollups are normalized to fresh input and stamped `2`. v12 databases gain the column on both `proxy_request_logs` and `usage_daily_rollups` via `migrate_v12_to_v13`, and Claude-style rows stay fresh input with no subtraction.
|
||||
- **Stronger Prompt-Cache Breakpoint Injection on the Proxy Bridge**: On the proxy paths that inject Anthropic `cache_control` breakpoints — the `codex_responses_to_anthropic` takeover bridge and the Bedrock native optimizer — the injector now spends its four-breakpoint budget more effectively so long, tool-heavy conversations keep hitting the prompt cache instead of re-sending system, tools, and history at full price every turn. Beyond marking the tools tail, system tail, and the latest cacheable message, it now adds a second older user anchor (`msgs-prior-user`) when at least four messages exist and budget remains, keeping the stable prefix inside Anthropic's 20-block lookback from the newest breakpoint. Injection is short-circuited unless both the optimizer master switch (`enabled`) and the `cache_injection` sub-switch are on, `thinking`/`redacted_thinking` blocks are never chosen as cache targets, and injected markers use Anthropic's standard 5-minute TTL. Caller-owned breakpoints are preserved verbatim — never deleted, reordered, or rewritten — and when a caller already ships more than the supported four, the injector logs a warning, adds no automatic breakpoints, and leaves the markers in place (`cache_injector.rs`, `forwarder.rs`).
|
||||
- **Kimi For Coding's 256K Context Window Now Takes Effect**: The Kimi For Coding preset's standalone `CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144` (added in #4401 and shipped in 3.16.4) never actually applied, because Claude Code caps unrecognized non-Claude model ids at a 200K window and resolves the compact window as `min(model window, value)`, clamping 262144 back down to 200K. The preset now pairs it with `CLAUDE_CODE_MAX_CONTEXT_TOKENS` (both pinned to 262144) and explicitly routes the endpoint's `kimi-for-coding` alias across `ANTHROPIC_MODEL` and all three tier keys (`ANTHROPIC_DEFAULT_HAIKU/SONNET/OPUS_MODEL`), since Claude Code ignores both context envs for `claude-`-prefixed ids — the non-Claude alias is what unlocks the enlarged window. For already-saved providers, `build_effective_settings_with_common_config` in `services/provider/live.rs` injects the same two context defaults (262144) into the effective live settings at switch time for any provider whose `ANTHROPIC_BASE_URL` is the Kimi coding endpoint (`https://api.kimi.com/coding`), with a mirror-inverse strip on backfill so an injected default never hardens into stored provider config and an explicit user value always wins. Because the alias routing lives only in the preset and not in the injection, a provider saved from the old preset — which set neither the alias nor `CLAUDE_CODE_MAX_CONTEXT_TOKENS` — stays effectively at 200K until the preset is re-applied. Three tests cover backfill injection, user-override preservation, and injected-only strip.
|
||||
- **Deleted Codex MCP Servers No Longer Resurrected on Provider Activation**: MCP servers are owned by the database `mcp_servers` table and the `[mcp_servers]` section in Codex's live `config.toml` is only a projection re-synced after every write, but switching away used to bake that projection into the stored provider snapshot — so a server you deleted in the app came back to life the next time you activated that provider, and per-entry reconcile (which only knows rows still in the DB) could never clean up the orphan. Switch-away backfill now strips `[mcp_servers]` (and the legacy `[mcp.servers]` form) from the stored settings via `strip_codex_mcp_servers_from_settings`, and any snapshot already polluted self-heals the next time you switch away from it. One user-visible consequence: a hand-written `[mcp_servers.*]` section in a Codex provider's config is stripped out of the stored snapshot the first time you switch away, so going forward define Codex MCP servers through the MCP manager (the DB `mcp_servers` table) rather than by hand-editing the provider config.
|
||||
- **Codex MCP Sync Fails Closed on an Unparseable config.toml**: When writing a single MCP server into Codex, `sync_single_server_to_codex` silently fell back to an empty `toml_edit` document if the existing `config.toml` failed to parse and then wrote the whole file back — wiping every other section (`model`, `model_providers`, comments) and leaving only the one synced `[mcp_servers.<id>]` entry, a destructive fallback left behind when an earlier fix (`3a548152`) hardened only the removal path. The sync path now returns an `McpValidation` error and leaves the file untouched, matching the fail-closed behavior already used on the read/validate path, so a temporarily malformed config can no longer be silently truncated to a single MCP table.
|
||||
- **MCP Operations Now Report Per-App Failures Instead of Silently Blocking Others**: Importing MCP servers from apps used to swallow every importer error with `unwrap_or(0)`, so a corrupt Codex `config.toml` surfaced only as "imported 0 servers" with no hint anything went wrong; `import_from_all_apps` now imports each app (claude/codex/gemini/opencode/hermes) best-effort and, when any fail, reports an aggregated error naming the failing apps alongside the count that did import, with the frontend refreshing the server list on settle so partially-imported servers still appear. On the projection side `sync_all_enabled` iterated every app with `?`, so one app's unparseable live file (e.g. a broken `~/.claude.json` that passes the existence gate but fails to parse) blocked every app behind it in iteration order and bubbled a false "switch failed" back even though the target app's live file and the database were already updated; switch and save now re-project only the target app through the new `sync_enabled_for_app` and degrade projection failure to a warning, while config-import and cloud-restore keep the all-apps sweep but collect failures best-effort. Toggling `unify_codex_session_history`, which rewrites the current official provider's live `config.toml` in full and drops the `[mcp_servers]` projection, now re-projects Codex MCP through that same target-only path so enabled servers no longer silently vanish until the next provider switch. In every degraded case the projection self-heals on the next switch or MCP toggle.
|
||||
- **Codex Common-Config Form Preserves Comments and Key Order**: Toggling "use common config" in the Codex provider form used to route the merge through the frontend `smol-toml` implementation, which re-serialized the whole document (parse → deep-merge → stringify): comments were dropped, keys were reordered, and empty parent table headers like `[model_providers]` were synthesized — the long-standing "config.toml keeps getting reordered" symptom. The merge now runs on a backend command backed by the same `merge_toml_table_like` / `remove_toml_table_like` used to write live configs, so the form preview and the live write share one merge semantic and hand-written formatting survives edit-time merges, and the frontend helper was deleted outright so the pattern can't come back. Because the operations are now async, a landing result is discarded unless it is still current: a per-hook sequence number covers rapid toggle/save races so an earlier merge resolving after a later removal can't flip the switch back (last operation wins), and a config-baseline check keeps a stale merge from clobbering a TOML the user hand-edited while the merge was in flight, with the checkbox self-healing via the existing inference effect.
|
||||
- **Inject a Single Auth Placeholder on Managed Claude Takeover**: Switching the managed Claude provider from a third-party endpoint (DeepSeek/MiMo/…) to a Codex-managed provider wrote both `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` as `PROXY_MANAGED` into `~/.claude/settings.json`, so Claude Code warned "Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set - auth may not work as expected" on every run — an accretion artifact of the original API-key insert (#1049, Copilot) and the later `ANTHROPIC_AUTH_TOKEN` preservation that avoided a login prompt (#3784), which added the token without removing the key. The `ManagedAccount` branch of `apply_claude_takeover_fields_for_provider` now clears all token keys and injects exactly one placeholder: `ANTHROPIC_AUTH_TOKEN` for Codex-managed providers and `ANTHROPIC_API_KEY` for Copilot; local-proxy auth is unaffected because the forwarder resolves the `PROXY_MANAGED` placeholder from either header. Because enabling takeover short-circuits (`return Ok(())`) when the live config already matches the current proxy, users upgrading with an existing double-key `settings.json` may need to toggle Claude routing off and back on once (or switch providers) to trigger the rewrite. (#4919, #5095)
|
||||
- **Skip Reachability Probes for Official Providers**: Health/connectivity checks no longer derive an unauthenticated probe target from an official provider's runtime adapter defaults. Batch `stream_check_all_providers` now skips any entry whose `category` is `official`, and `StreamCheckService::resolve_base_url` returns an explicit error for official providers instead of falling back to a first-party endpoint (e.g. `https://chatgpt.com/backend-api/codex`) and probing it without credentials — a request that is meaningless and always fails. The connectivity-check button is already hidden for these providers in `ProviderCard.tsx`, so this is defense-in-depth that also matters now that the built-in Codex official provider participates in takeover; a regression test covers the Codex official provider so a future adapter change cannot silently reintroduce the probe.
|
||||
- **Usage and Quota Queries Reject Transient Transport Failures So Retry and Keep-Last-Good Work**: Usage and quota queries frequently showed spurious "query failed" states that a manual refresh could not clear, because every transport-level failure — including read-timeouts mid-body — was folded into `Ok(success:false)`, so react-query's retry never fired and the failure body poisoned the cache as if it were real data. The `balance`, `coding_plan`, and `subscription` services now return `Err` for send failures and body-read failures, reading the body via `bytes()` before `serde_json::from_slice` (reqwest's `json()` wraps read errors as `Decode`, which made error-kind checks on it dead code), while auth/4xx/parse errors stay `Ok(success:false)` and surface immediately; the script path maps transient `AppError` keys (`request_failed` / `read_response_failed`) to `Err`, Volcengine gains a `Transient` call variant, HTTP 429 is now classified transient alongside 5xx, and expired-credential retries propagate the transient error instead of rewriting it as "OAuth token has expired". The command layer skips snapshot persistence, the `usage-cache-updated` emit, and tray refresh on `Err` so the cache bridge cannot overwrite retained data. On the frontend, `resolveDisplayUsage` (generalized to subscription quotas via a new options object carrying a `rejected` flag) re-anchors stale success data retained by react-query across rejections to `dataUpdatedAt` so it expires through the same 10-minute keep-last-good window instead of masking a longer outage indefinitely, `useSubscriptionQuota` / `useCodexOauthQuota` gain keep-last-good with per-scope snapshot reset, rejected queries with no displayable value synthesize a failure placeholder carrying the real error message so the footer keeps a retry entry point, and `UsageScriptModal` surfaces string rejections via `extractErrorMessage`. (#3820)
|
||||
- **Codex Sub-Agent Session Usage Now Counted in Local Statistics**: Token usage from Codex sub-agent (spawned agent) sessions was missing from local usage statistics because the parser keyed each session's synthetic `request_id` on `session_meta.session_id`, but a sub-agent's log carries the parent thread's `session_id` while its own unique identity lives in the `id` / `thread_id` field — so multiple sub-agents under one parent collapsed onto colliding request IDs and were dropped as duplicates. `session_usage_codex.rs` now extracts a unique `thread_id` per file (preferring `id` / `thread_id` over `session_id`) and prefixes request IDs with `codex_session:thread-v1:<thread_id>:<index>`, giving each sub-agent distinct rows. Because fork/sub-agent logs first replay the parent thread's history before the takeover event, the parser detects a history-snapshot boundary (via `forked_from_id` / `subagent` source markers plus a `thread_settings_applied` or `inter_agent_communication` event) and uses the replayed `token_count` events only to restore the cumulative baseline instead of double-counting them as new usage. Archived logs under `archived_sessions/` inherit the sync cursor from their original path by filename suffix, so re-parsing an archived copy imports only appended usage rather than re-importing the whole thread; the fix ships with unit tests covering identity extraction, replay-baseline accounting, distinct request IDs, and archived-cursor inheritance. (#5187)
|
||||
- **Codex Free-Plan 30-Day Quota Window Now Renders in Footer and Tray**: Codex free accounts are metered on a rolling 30-day secondary window (`limit_window_seconds = 2,592,000`) instead of the weekly window paid plans use, and although the backend already mapped this to the tier name `30_day`, neither the frontend `TIER_I18N_KEYS` whitelist nor the tray's `TIER_LABEL_GROUPS` month group recognized it — so `SubscriptionQuotaView` filtered the tier out and, since it is the only surviving tier for a free account, the quota footer rendered nothing while the tray's `format_subscription_summary` returned `None` and showed no quota at all. A single-sourced `TIER_THIRTY_DAY` ("30_day") constant now ties together the backend `window_seconds_to_tier_name` mapping (which maps `2_592_000` explicitly), the tray's month ("m") group, and the frontend whitelist (`30_day → subscription.thirtyDay`), with the `thirtyDay` label added to all four locales (zh/en/ja/zh-TW). Two regression tests lock in the window-seconds-to-tier mappings and assert that a 30-day-only Codex account still renders in the tray, guarding the invariant that any tier visible in the footer must not leave the tray blank. (#3651, #4886)
|
||||
- **Usage Dashboard Refresh Interval Persists Across Restarts**: The usage dashboard's auto-refresh cadence was component-local state that reset to 30s on every restart, so a user who chose a different interval (off, 5s, 10s, or 60s) had to re-select it each session. The dashboard now reads and writes the choice through a new `usageDashboardRefreshIntervalMs` app setting: `UsageDashboard` takes `refreshIntervalMs` / `onRefreshIntervalChange` props wired from `SettingsPage` to the persisted settings, initializes from the saved value (normalized to a known option, falling back to the 30s default for unrecognized values), and applies changes optimistically — invalidating the usage queries immediately — while rolling back the selection if the save fails. The field is added to the Rust `AppSettings` struct, the TypeScript `Settings` type, and the zod settings schema, and three component tests cover mount-from-saved, persist-on-change, and rollback-on-failure. (#5057)
|
||||
- **Exclude Fable Tier Model Env Keys From the Shared Claude Common Config**: Fable is Claude's fourth model-mapping tier (added in v3.16.3), but its `ANTHROPIC_DEFAULT_FABLE_MODEL` / `ANTHROPIC_DEFAULT_FABLE_MODEL_NAME` env keys were missing from the provider-specific exclusion list, so a provider's Fable model pin could leak into the shared common-config snippet and then be injected into other providers on the next switch. Both keys are now stripped in `extract_claude_common_config` alongside the haiku/sonnet/opus pins, guarded by a regression test. The same commit also completes Fable's proxy-takeover support: the two keys are added to `CLAUDE_MODEL_OVERRIDE_ENV_KEYS` (now 12 entries) and the takeover writes a stable `claude-fable-5` role alias (`CLAUDE_TAKEOVER_FABLE_MODEL`), reapplying it when the provider configures Fable and clearing stale values otherwise, mirroring the other three tiers; when Fable is unconfigured no alias is written and the mapper falls back fable→opus. (#5206, fixes #4272)
|
||||
- **Default Missing Tool Schema Types and Restore the API Key Field for Uncategorized Providers**: Two provider-facing fixes. First, when a client sends a tool whose Anthropic `input_schema` omits the top-level `type` or is an empty `{}`, the proxy passed the schema through the shared `clean_schema` helper without filling in the missing type, producing an OpenAI `parameters` object that strict gateways reject. `clean_schema` (defined once in `transform.rs` and reused by the Responses converter via `super::transform::clean_schema`, so both the Anthropic→OpenAI Chat and Responses paths pick up the change) now defaults a missing root `type` to `"object"` — adding an empty `properties: {}` only when properties is also absent — and applies the defaulting only to the root schema via a new `is_root` flag threaded through a `clean_schema_inner` helper, so nested sub-schemas (an `anyOf` string/null union, an `items`-only array) are preserved unchanged rather than having a spurious `type: "object"` forced onto them. Second, editing a provider with no category (a historically imported or hand-built custom provider) hid the Claude API key input, because `useApiKeyState` only showed and auto-created the field in add mode with a defined non-official category; the gate now keys off category alone, showing and populating the field for any provider that isn't `official` or `cloud_provider` — including the undefined-category edit case — while `official` (OAuth-only, input disabled) and `cloud_provider` (which use dedicated auth fields rather than an Anthropic key) stay conservative. New unit and hook tests cover both converters and the uncategorized/official/cloud-provider key paths. (#5069)
|
||||
- **Media Fallback for Volcano GLM 5.2 Text-Only Image 400s**: When the local proxy takes over a Volcano Coding Plan provider running GLM 5.2, image blocks in a request no longer produce a dead 400 — the rectifier's media fallback in `src-tauri/src/proxy/media_sanitizer.rs` now covers GLM 5.2 on both its preventive and reactive paths. Preventively, the text-only model registry gains `glm-5.2` as an exact tail match (deliberately not a prefix, so a future multimodal `glm-5.2v` variant following Zhipu's 4v/5v naming keeps its images), stripping image blocks before they reach the text-only endpoint. Reactively, because the gateway's error `Model only support text input` never mentions image/vision/media and drops the third-person `s`, a new self-evident phrase list (`only support text` / `only supports text`) now asserts a modality rejection on its own and bypasses the `mentions_image` gate that previously discarded the error before the fallback hints could run; the old `only supports text` hint is folded into that list. Regression tests exercise the verbatim #5025 error body, the `glm-5.2[1M]` mapped-model form, and a `glm-5.2v` negative assertion. (#5025)
|
||||
- **Display Renamed Codex Session Titles**: Sessions renamed inside Codex now show their renamed titles in the session manager instead of silently falling back to the original first-message text. The scanner (`src-tauri/src/session_manager/providers/codex.rs`) loads thread titles from Codex's `session_index.jsonl` and `state_5.sqlite` — resolving the DB path from `sqlite_home` / `CODEX_SQLITE_HOME` through a new shared `codex_state_db` module that deduplicates path resolution previously copy-pasted with the history-migration code — and prefers a stored thread title over the first user message when building each session's display title. The read-only title query adds a `busy_timeout` so a lookup during a concurrent Codex write no longer fails immediately with `SQLITE_BUSY` and drops back to the first message, and the `title == first_user_message` check is pushed into a NULL-safe SQL `WHERE` clause (matching Codex's `distinct_thread_metadata_title` semantics) so the potentially large `first_user_message` column no longer crosses into Rust. (#4927)
|
||||
- **Live Config Edits for OpenCode, OpenClaw, and Hermes Now Sync Into the Database on Startup**: The startup auto-import for the live-config-managed apps previously skipped any provider whose id already existed in the database, so edits made directly to the OpenCode, OpenClaw, or Hermes (`~/.hermes/config.yaml`) live files — a changed base URL, an added or renamed model — were never picked up after the first import and silently diverged from the app's stored copy. The `import_{opencode,openclaw,hermes}_providers_from_live` functions in `services/provider/live.rs` now look up each existing provider and, when its live `settings_config` differs, rewrite the stored provider from the live file (OpenCode additionally refreshes the display name from the live `name`, falling back to the existing name rather than the id); the returned count now covers both new imports and updates, and the startup log line changed from "Imported N" to "Synced N". The sync runs on every launch from `lib.rs::run()`, is a no-op when nothing changed, and is fully non-fatal — a provider that vanishes mid-import or a DB lookup error is warned and skipped, and users with no live file still take the quiet `Ok(0)` path. (#4712, #5098)
|
||||
- **OpenCode Session Resume Command Updated to Current CLI Syntax**: The Session Manager displayed and copied `opencode session resume <id>` as the resume command for OpenCode sessions, which is not the OpenCode CLI's current resume syntax, so pasting the copied command would not resume the session. Both the SQLite-scanned (`scan_sessions_sqlite`) and JSON-parsed (`parse_session`) session paths in `session_manager/providers/opencode.rs` now emit `opencode -s <id>` to match the CLI's actual resume flag. (#2359)
|
||||
|
||||
### Docs
|
||||
|
||||
- **Codex + Kimi Local Routing Guides**: New step-by-step guides explain how to run Kimi inside the Codex CLI through CC Switch's local routing, motivated by a protocol mismatch: the newer Codex CLI targets the OpenAI Responses API while both Kimi Open Platform and Kimi For Coding expose the OpenAI Chat Completions shape (`/chat/completions`), so pointing a Kimi endpoint straight at Codex typically 404s on `/responses` or yields streams Codex cannot parse. The guides walk through adding a Codex provider from the built-in `Kimi` (Open Platform, pay-as-you-go, `kimi-k2.7-code`) or `Kimi For Coding` (membership, `kimi-for-coding`) preset, and lay out the four-step conversion chain: Codex is written to talk to `http://127.0.0.1:15721/v1` with `wire_api = "responses"` kept in place, the provider's `meta.apiFormat = "openai_chat"` flags the real upstream as Chat, the route rewrites `/responses` to `/chat/completions` and converts the body, then converts the upstream Chat JSON/SSE back into the Responses shape Codex expects. Added under `docs/guides/` in English, Japanese, and Chinese with accompanying UI screenshots.
|
||||
- **new-api Sponsor Row in READMEs**: The open-source AI infrastructure project `new-api` is appended as the newest entry in the sponsor table across all four localized READMEs (`README.md`, `README_ZH.md`, `README_JA.md`, `README_DE.md`), along with its banner asset.
|
||||
|
||||
### Internal
|
||||
|
||||
- **Harden Release Supply Chain**: Added a `.github/CODEOWNERS` that, together with branch protection's Code Owners rule, requires owner review before any PR merges to `main` (with `/.github/` and `/src-tauri/` pinned explicitly alongside the global `*` fallback, all to `@farion1231`), gated the release job behind a `release` environment in `release.yml` so signing secrets unlock only after manual approval, and removed `.github` from `.gitignore` so the previously untracked `labeler.yml` and `workflows/labeler.yml` are now versioned.
|
||||
- **Settle pnpm Build-Script Approvals**: Approved `esbuild` (via `onlyBuiltDependencies`) and ignored `msw` (via `ignoredBuiltDependencies`) in `pnpm-workspace.yaml` so pnpm 10.13+ stops appending `allowBuilds` placeholders to the file on every install.
|
||||
- **Platform-Gate the Desktop-Scope Assertion in the Profile Roundtrip Test**: The `profile_roundtrip` integration test's Claude Desktop assertion is now `cfg`-gated to macOS/Windows to match the already cfg-gated desktop switch, so on Linux CI (where desktop live writes error) it expects the seeded `d1` instead of `d2` and no longer panics, poisons the shared test mutex, and cascades into two more failures.
|
||||
|
||||
## [3.16.5] - 2026-07-01
|
||||
|
||||
Development since v3.16.4 reworks the Codex native-Responses path — restoring a generated model catalog for proxy-less direct-connect, decoupling model mapping from the local-routing toggle, and adding a host/model-prefix blacklist that disables Codex's built-in web_search on gateways that reject it — alongside a broad wave of new provider presets (Qiniu and Code0.ai across all seven apps, the FennoAI/ZetaAPI/TeamoRouter/NekoCode partners, and the non-partner Amux), Claude Sonnet 5 pricing plus a default-tier bump to it, a categorized two-level session view with group-level batch selection, live auto-sync of the shared Claude common config on switch, and a run of credential-safety, tool-detection, Doubao model-id, branding, and icon-size fixes.
|
||||
|
||||
@@ -125,8 +125,8 @@ TeamoRouter also offers enterprise features including centralized billing, team
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai?source=ccswitch"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>Thanks to <a href="https://code0.ai?source=ccswitch">code0.ai</a> for sponsoring this project! code0.ai is an AI coding service platform built for developers, supporting Claude Code, Codex, Gemini, and other mainstream AI coding capabilities. It helps individual developers and teams use AI Agents more stably and efficiently for coding, debugging, refactoring, and automation workflows. ccswitch users can contact customer support via the <a href="https://code0.ai?source=ccswitch">code0.ai website</a> to claim test credits and experience a reliable AI coding service.</td>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>Thanks to <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> for sponsoring this project! code0.ai is an AI coding service platform built for developers, supporting Claude Code, Codex, Gemini, and other mainstream AI coding capabilities. It helps individual developers and teams use AI Agents more stably and efficiently for coding, debugging, refactoring, and automation workflows. ccswitch users can contact customer support via the <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai website</a> to claim test credits and experience a reliable AI coding service.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -179,6 +179,11 @@ TeamoRouter also offers enterprise features including centralized billing, team
|
||||
<td>Thanks to <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> for sponsoring this project! NekoCode provides developers with a stable, efficient, and reliable API relay service for Claude, Codex, and other AI models. With transparent pricing and flexible pay-as-you-go billing, it offers a simple and cost-effective way to access AI models. CC Switch users can enjoy an exclusive 10% discount: register via <a href="https://nekocode.ai?aff=CCSWITCH">this link</a> and enter promo code <code>cc-switch</code> during recharge to receive 10% off your top-up!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
|
||||
<td>Thanks to the open-source AI infrastructure project <a href="https://www.newapi.ai/">new-api</a> for its strong support of this project! new-api is an open-source AI infrastructure project from QuantumNous and one of the leading unified LLM access-and-distribution projects by activity and adoption, focused on helping developers, teams, and enterprises build manageable, scalable AI service platforms at lower cost. As a fellow project rooted in the open-source ecosystem, new-api hopes to sponsor and support the continued growth of more outstanding open-source projects. 🌟 Star new-api to show your support: <a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>. Website: <a href="https://www.newapi.ai/">https://www.newapi.ai/</a>.</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
+7
-2
@@ -125,8 +125,8 @@ TeamoRouter bietet außerdem Enterprise-Funktionen wie zentrale Abrechnung, Team
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai?source=ccswitch"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>Vielen Dank an <a href="https://code0.ai?source=ccswitch">code0.ai</a> für die Unterstützung dieses Projekts! code0.ai ist eine für Entwickler entwickelte AI-Coding-Service-Plattform, die Claude Code, Codex, Gemini und weitere gängige AI-Coding-Funktionen unterstützt. Sie hilft einzelnen Entwicklern und Teams, AI-Agents stabiler und effizienter für Programmierung, Debugging, Refactoring und Automatisierungs-Workflows zu nutzen. ccswitch-Nutzer können über die <a href="https://code0.ai?source=ccswitch">code0.ai-Website</a> den Kundensupport kontaktieren, um Testguthaben zu erhalten und einen zuverlässigen AI-Coding-Service zu erleben.</td>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>Vielen Dank an <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> für die Unterstützung dieses Projekts! code0.ai ist eine für Entwickler entwickelte AI-Coding-Service-Plattform, die Claude Code, Codex, Gemini und weitere gängige AI-Coding-Funktionen unterstützt. Sie hilft einzelnen Entwicklern und Teams, AI-Agents stabiler und effizienter für Programmierung, Debugging, Refactoring und Automatisierungs-Workflows zu nutzen. ccswitch-Nutzer können über die <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai-Website</a> den Kundensupport kontaktieren, um Testguthaben zu erhalten und einen zuverlässigen AI-Coding-Service zu erleben.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -179,6 +179,11 @@ TeamoRouter bietet außerdem Enterprise-Funktionen wie zentrale Abrechnung, Team
|
||||
<td>Vielen Dank an <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> für die Unterstützung dieses Projekts! NekoCode bietet Entwicklern einen stabilen, effizienten und zuverlässigen API-Relay-Dienst für Claude, Codex und weitere KI-Modelle. Mit transparenter Preisgestaltung und flexibler nutzungsbasierter Abrechnung bietet es einen einfachen und kostengünstigen Zugang zu KI-Modellen. CC-Switch-Nutzer erhalten einen exklusiven Rabatt von 10 %: Registrieren Sie sich über <a href="https://nekocode.ai?aff=CCSWITCH">diesen Link</a> und geben Sie beim Aufladen den Gutscheincode <code>cc-switch</code> ein, um 10 % Rabatt auf Ihre Aufladung zu erhalten!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
|
||||
<td>Vielen Dank an das Open-Source-KI-Infrastrukturprojekt <a href="https://www.newapi.ai/">new-api</a> für die tatkräftige Unterstützung dieses Projekts! new-api ist ein Open-Source-KI-Infrastrukturprojekt von QuantumNous und eines der nach Aktivität und Verbreitung führenden Projekte für den einheitlichen Zugang zu und die Verteilung von LLMs, das sich darauf konzentriert, Entwicklern, Teams und Unternehmen beim Aufbau verwaltbarer und skalierbarer KI-Serviceplattformen zu geringeren Kosten zu helfen. Als ein ebenfalls im Open-Source-Ökosystem verwurzeltes Projekt möchte new-api durch Sponsoring die kontinuierliche Weiterentwicklung weiterer herausragender Open-Source-Projekte unterstützen. 🌟 Unterstützen Sie new-api mit einem Star: <a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>. Website: <a href="https://www.newapi.ai/">https://www.newapi.ai/</a>.</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
+7
-2
@@ -125,8 +125,8 @@ TeamoRouter は、集中請求、チーム管理、BYOK、スマートルーテ
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai?source=ccswitch"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>本プロジェクトをご支援いただいている <a href="https://code0.ai?source=ccswitch">code0.ai</a> に感謝します!code0.ai は開発者向けの AI コーディングサービスプラットフォームで、Claude Code、Codex、Gemini などの主要な AI コーディング機能に対応しています。個人開発者やチームが、コーディング、デバッグ、リファクタリング、自動化ワークフローで AI Agent をより安定かつ効率的に活用できるよう支援します。ccswitch ユーザーは <a href="https://code0.ai?source=ccswitch">code0.ai 公式サイト</a> からカスタマーサポートに連絡することで、テストクレジットを受け取り、信頼性の高い AI コーディングサービスを体験できます。</td>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>本プロジェクトをご支援いただいている <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> に感謝します!code0.ai は開発者向けの AI コーディングサービスプラットフォームで、Claude Code、Codex、Gemini などの主要な AI コーディング機能に対応しています。個人開発者やチームが、コーディング、デバッグ、リファクタリング、自動化ワークフローで AI Agent をより安定かつ効率的に活用できるよう支援します。ccswitch ユーザーは <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai 公式サイト</a> からカスタマーサポートに連絡することで、テストクレジットを受け取り、信頼性の高い AI コーディングサービスを体験できます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -179,6 +179,11 @@ TeamoRouter は、集中請求、チーム管理、BYOK、スマートルーテ
|
||||
<td>本プロジェクトをご支援いただいている <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> に感謝します!NekoCode は、Claude や Codex などの AI モデルに対応した、安定性・効率性・信頼性に優れた API 中継サービスを提供しています。料金体系は明瞭で、柔軟な従量課金にも対応しています。CC Switch ユーザー限定の 10%オフ特典:<a href="https://nekocode.ai?aff=CCSWITCH">こちらのリンク</a> から登録し、チャージ時にクーポンコード <code>cc-switch</code> を入力すると、チャージが 10%オフになります!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
|
||||
<td>オープンソースの AI インフラプロジェクト <a href="https://www.newapi.ai/">new-api</a> による本プロジェクトへの多大なご支援に感謝します!new-api は QuantumNous(锟腾科技)が開発したオープンソースの AI インフラプロジェクトであり、活発さと利用規模の面でリードする LLM 統合アクセス・配信プロジェクトの一つで、開発者・チーム・企業がより低コストで管理・拡張可能な AI サービスプラットフォームを構築できるよう支援することに注力しています。同じくオープンソースエコシステムに根ざすプロジェクトとして、new-api はスポンサーシップを通じて、より多くの優れたオープンソースプロジェクトの継続的な発展を支援したいと考えています。🌟 new-api への Star で応援をお願いします:<a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>。公式サイト:<a href="https://www.newapi.ai/">https://www.newapi.ai/</a>。</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
+7
-2
@@ -126,8 +126,8 @@ TeamoRouter 还提供企业级功能,包括集中账单、团队管理、BYOK
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai?source=ccswitch"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>感谢 <a href="https://code0.ai?source=ccswitch">code0.ai</a> 赞助本项目!code0.ai 是专为开发者打造的 AI 编程服务平台,支持 Claude Code、Codex、Gemini 等主流 AI 编程能力,帮助个人开发者和团队更稳定、更高效地使用 AI Agent 完成代码开发、调试与自动化任务。ccswitch 用户可通过 <a href="https://code0.ai?source=ccswitch">code0.ai 官网</a> 联系客服领取测试额度,体验高效稳定的 AI 编程服务!</td>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY"><img src="assets/partners/logos/code0.png" alt="code0.ai" width="150"></a></td>
|
||||
<td>感谢 <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai</a> 赞助本项目!code0.ai 是专为开发者打造的 AI 编程服务平台,支持 Claude Code、Codex、Gemini 等主流 AI 编程能力,帮助个人开发者和团队更稳定、更高效地使用 AI Agent 完成代码开发、调试与自动化任务。ccswitch 用户可通过 <a href="https://code0.ai/agent/register/B2XHxGjGmRvqgznY">code0.ai 官网</a> 联系客服领取测试额度,体验高效稳定的 AI 编程服务!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
@@ -180,6 +180,11 @@ TeamoRouter 还提供企业级功能,包括集中账单、团队管理、BYOK
|
||||
<td>感谢 <a href="https://nekocode.ai?aff=CCSWITCH">NekoCode</a> 赞助本项目!NekoCode 为开发者提供稳定、高效、可靠的 Claude、Codex 等 AI 模型 API 中转服务,价格透明,接入便捷,支持灵活的按量计费。CC Switch 用户专享 9 折福利:通过 <a href="https://nekocode.ai?aff=CCSWITCH">此链接</a> 注册,并在充值时输入优惠码 <code>cc-switch</code>,即可享受充值 9 折优惠!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.newapi.ai/"><img src="assets/partners/logos/newapi-banner.png" alt="new-api" width="150"></a></td>
|
||||
<td>感谢开源 AI 基础设施项目 <a href="https://www.newapi.ai/">new-api</a> 对本项目的鼎力支持!new-api 是由 QuantumNous(锟腾科技)推出的开源 AI 基础设施项目,也是活跃度与使用规模领先的大模型统一接入与分发项目之一,专注于帮助开发者、团队和企业以更低成本构建可管理、可扩展的 AI 服务平台。作为同样扎根开源生态的项目,new-api 希望通过赞助支持更多优秀开源项目持续发展。🌟 欢迎 Star 支持 new-api:<a href="https://github.com/QuantumNous/new-api">https://github.com/QuantumNous/new-api</a>,官网:<a href="https://www.newapi.ai/">https://www.newapi.ai/</a>。</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 61 KiB |
@@ -0,0 +1,112 @@
|
||||
# Using Kimi in Codex: CC Switch Local Routing Guide
|
||||
|
||||
> Applies to CC Switch 3.16.5 and nearby versions. This guide is based on the repository documentation and code, and uses Kimi 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 both the Kimi Open Platform and Kimi For Coding expose the OpenAI Chat Completions shape, `/chat/completions`. These two protocols use different request bodies, streaming events, and response structures. If you put a Kimi endpoint directly into Codex configuration, the usual result is a 404 on `/responses`, or streaming responses that Codex cannot parse correctly.
|
||||
|
||||
The third-party tools officially supported by Kimi For Coding are Anthropic-compatible coding agents such as Claude Code and Roo Code — Codex is not on the list. To use Kimi inside Codex, you need a protocol conversion layer, and that is exactly what CC Switch Local Routing does.
|
||||
|
||||
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.
|
||||
- A Kimi API key.
|
||||
|
||||
Kimi API keys come from two different places, matching two different built-in presets in CC Switch:
|
||||
|
||||
- **Kimi Open Platform** (platform.kimi.com): pay-as-you-go API keys billed by token usage, matching the `Kimi` preset. The OpenAI-compatible base URL is `https://api.moonshot.cn/v1` and the default model is `kimi-k2.7-code`.
|
||||
- **Kimi For Coding** (kimi.com/code): a dedicated key generated from the Kimi Code membership benefits, matching the `Kimi For Coding` preset. The base URL is `https://api.kimi.com/coding/v1` and the unified model is `kimi-for-coding`.
|
||||
|
||||
Both presets already contain the correct endpoint and model details, so prefer the presets 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.
|
||||
|
||||
Depending on which kind of key you have, choose the built-in `Kimi` preset (Open Platform, pay-as-you-go) or `Kimi For Coding` preset (membership subscription). You only need to do two things:
|
||||
|
||||
- Enter the matching Kimi API key.
|
||||
- Save the provider.
|
||||
|
||||

|
||||
|
||||
The preset already includes Kimi's request base URL, default model, model menu, thinking/reasoning parameters, and presets `Upstream Format` under `Advanced Options` to `Chat Completions (routing required)`. You can adjust the default model or model display names if needed — for example, the Open Platform preset defaults to `kimi-k2.7-code`, and you can switch to `kimi-k2.7-code-highspeed` following the official documentation. 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 Kimi 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 Kimi 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 Kimi preset, such as `Kimi K2.7 Code` or `Kimi For Coding`. 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
|
||||
|
||||
Kimi, DeepSeek, 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 `Upstream Format` under `Advanced Options` to `Chat Completions (routing required)`.
|
||||
|
||||
If the upstream provider directly supports the OpenAI Responses API, set `Upstream Format` to `Responses`; CC Switch then connects through Responses directly without Chat conversion.
|
||||
|
||||
## FAQ
|
||||
|
||||
**Codex reports 404 or cannot find `/responses`**
|
||||
|
||||
Usually Codex routing is not enabled, or the Kimi Chat base URL was written directly into Codex manually — the Kimi upstream has no `/responses` endpoint, so that always 404s. Check whether `~/.codex/config.toml` points to `http://127.0.0.1:15721/v1`.
|
||||
|
||||
**Kimi upstream reports 401 or 403**
|
||||
|
||||
First confirm the key matches the preset: Open Platform keys only work with the `Kimi` preset, and Kimi Code membership keys only work with the `Kimi For Coding` preset. The two key families are not interchangeable.
|
||||
|
||||
**Kimi upstream reports 404**
|
||||
|
||||
If you are using a built-in Kimi 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 Kimi 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 Kimi; 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)
|
||||
- [Kimi Open Platform: Using Kimi K2.7 Code in coding tools](https://platform.kimi.com/docs/guide/agent-support)
|
||||
- [Kimi Code Docs: Overview](https://www.kimi.com/code/docs/)
|
||||
- [Kimi Code Docs: Using with third-party coding agents](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
|
||||
@@ -0,0 +1,112 @@
|
||||
# Codex で Kimi を使う: CC Switch ローカルルーティングガイド
|
||||
|
||||
> 対象バージョン: CC Switch 3.16.5 およびその前後のバージョン。本記事はリポジトリ内のドキュメントとコードをもとに整理し、OpenAI Chat Completions 互換 API の例として Kimi を使用します。スクリーンショットは現在のフロントエンド UI から、実際の API Key やアカウント残高が漏れないよう匿名化したサンプルデータで生成しています。
|
||||
|
||||
## ローカルルーティングが必要な理由
|
||||
|
||||
新しい Codex CLI は OpenAI Responses API を前提にしています。一方で Kimi オープンプラットフォームと Kimi For Coding が実際に公開しているのは、いずれも OpenAI Chat Completions 形式、つまり `/chat/completions` です。この 2 つのプロトコルは、リクエストボディ、ストリーミングイベント、レスポンス構造が異なります。Kimi のエンドポイントをそのまま Codex 設定に入れると、`/responses` へのリクエストが 404 になる、ストリーミングレスポンスを Codex が正しく解析できない、といった問題が起きがちです。
|
||||
|
||||
Kimi For Coding が公式にサポートするサードパーティツールは、Claude Code や Roo Code など Anthropic 互換のコーディング Agent であり、Codex はリストに含まれていません。Codex で Kimi を使うにはプロトコル変換レイヤーが必要で、それこそが CC Switch のローカルルーティングの役割です。
|
||||
|
||||
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` のディレクトリ構造が存在していること。
|
||||
- Kimi の API Key。
|
||||
|
||||
Kimi の API Key には 2 つの取得元があり、CC Switch の 2 つの内蔵プリセットに対応します:
|
||||
|
||||
- **Kimi オープンプラットフォーム**(platform.kimi.com): トークン使用量に応じた従量課金の API Key。プリセット `Kimi` に対応し、OpenAI 互換 base URL は `https://api.moonshot.cn/v1`、デフォルトモデルは `kimi-k2.7-code` です。
|
||||
- **Kimi For Coding**(kimi.com/code): Kimi メンバーシップの Kimi Code 特典から生成する専用 Key。プリセット `Kimi For Coding` に対応し、base URL は `https://api.kimi.com/coding/v1`、モデルは `kimi-for-coding` に統一されています。
|
||||
|
||||
どちらのプリセットにも公式情報に基づくエンドポイントとモデルがすでに設定されているため、まずはプリセットを使い、エンドポイントパスを手で組み立てる必要はありません。
|
||||
|
||||
## Step 1: Codex プロバイダーを追加する
|
||||
|
||||
CC Switch を開き、上部の `Codex` タブへ切り替え、右上のプラスボタンからプロバイダーを追加します。
|
||||
|
||||
手元の Key の種類に応じて、内蔵プリセットの `Kimi`(オープンプラットフォーム・従量課金)または `Kimi For Coding`(メンバーシップ)を選びます。必要なのは次の 2 つだけです:
|
||||
|
||||
- 対応する Kimi API Key を入力する。
|
||||
- プロバイダーを保存する。
|
||||
|
||||

|
||||
|
||||
プリセットには Kimi のリクエスト先、デフォルトモデル、モデルメニュー、thinking/reasoning パラメータがすでに含まれており、`高級オプション` の `上流フォーマット` も `Chat Completions(ルーティング必須)` にプリセットされています。必要に応じてデフォルトモデルやモデル表示名を調整できます。たとえばオープンプラットフォームのプリセットはデフォルトが `kimi-k2.7-code` で、公式ドキュメントに従って `kimi-k2.7-code-highspeed` に変更することもできます。プロトコル変換はルーティング層に任せれば十分です。
|
||||
|
||||
## Step 2: ローカルルーティングを有効にして Codex をルーティングする
|
||||
|
||||
設定の `ルーティング` ページに入り、`ローカルルーティング` を展開して、次の 2 つのスイッチを設定します:
|
||||
|
||||
1. `ルーティング総スイッチ` をオンにしてローカルサービスを起動します。デフォルトアドレスは `127.0.0.1:15721` です。
|
||||
2. `ルーティング有効` で `Codex` をオンにします。Codex だけをルーティングしたい場合は、Claude と Gemini はオフのままで構いません。
|
||||
|
||||

|
||||
|
||||
ルーティングを有効にすると、CC Switch は Codex の live 設定をローカルルートへ向け、認証はプレースホルダーで管理します。実際の Kimi Key は CC Switch の Provider 設定内に残り、ローカルルートが転送時に注入します。そのため、Codex の live 設定に Key を露出させる必要はありません。
|
||||
|
||||
## Step 3: プロバイダーを切り替えて Codex を再起動する
|
||||
|
||||
Codex プロバイダー一覧に戻り、Kimi プロバイダーの `有効化` をクリックします。`ルーティングが必要` の表示が見える場合、そのプロバイダーはルーティング実行中に使う必要があります。ルーティングが起動していない場合、CC Switch は「ルーティングサービスが必要」という趣旨のメッセージを表示します。
|
||||
|
||||
切り替え後は、現在の Codex ターミナルセッションを再起動することをおすすめします。理由は次のとおりです:
|
||||
|
||||
- Codex プロセスがすでに古い `config.toml` を読み込んでいる可能性があります。
|
||||
- `model_catalog_json` の生成後、`/model` メニューの更新には通常、新しいプロセスが必要です。
|
||||
|
||||
Codex に入ったら、`/model` で現在のモデルが Kimi プリセット由来かどうかを確認します。たとえば `Kimi K2.7 Code` や `Kimi For Coding` などです。現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。その後、小さな質問を 1 つ送って、ルーティングパネルのリクエスト数が増えるか、usage / リクエストログに Codex リクエストが出るかを確認します。
|
||||
|
||||
## 他の Chat プロバイダーの場合
|
||||
|
||||
Kimi、DeepSeek、MiniMax、SiliconFlow など一般的な Chat 形式プロバイダーは CC Switch にプリセットがあるため、まずはプリセットを使ってください。プリセットにないプロバイダーだけ、カスタム設定を選びます。その場合は相手側のドキュメントに従って API Key、base URL、モデルを入力し、`高級オプション` の `上流フォーマット` を `Chat Completions(ルーティング必須)` に設定します。
|
||||
|
||||
上流が OpenAI Responses API を直接サポートしている場合は、`上流フォーマット` を `Responses` にすれば、CC Switch は Responses のまま直結でき、Chat 変換は行いません。
|
||||
|
||||
## よくある質問
|
||||
|
||||
**Codex が 404 を返す、または `/responses` が見つからない**
|
||||
|
||||
多くの場合、Codex ルーティングが有効になっていないか、Kimi の Chat base URL を手動で Codex に直接書いています。Kimi の上流には `/responses` エンドポイントが存在しないため、必ず 404 になります。`~/.codex/config.toml` が `http://127.0.0.1:15721/v1` を指しているか確認してください。
|
||||
|
||||
**Kimi 上流が 401 または 403 を返す**
|
||||
|
||||
まず Key とプリセットの組み合わせを確認してください。オープンプラットフォームの Key はプリセット `Kimi` 専用、Kimi Code 特典の Key はプリセット `Kimi For Coding` 専用で、2 種類の Key は相互に使えません。
|
||||
|
||||
**Kimi 上流が 404 を返す**
|
||||
|
||||
内蔵 Kimi プリセットを使っている場合は、まず現在のプロバイダーが本当にプリセット由来であること、そして Codex ルーティングが有効であることを確認してください。カスタムプロバイダーを使っている場合だけ、base URL を追加で確認します。base URL はサービスのルートであり、`/chat/completions` 付きの完全なエンドポイントパスではありません。
|
||||
|
||||
**`/model` に Kimi モデルが表示されない**
|
||||
|
||||
プロバイダーを保存した後、Codex を再起動してください。CC Switch は `cc-switch-model-catalog.json` を生成し、そのパスを `model_catalog_json` に書き込みますが、実行中の Codex プロセスがモデルカタログをホットロードするとは限りません。
|
||||
現在の Codex app は複数モデル選択に対応していないため、設定内の最初のモデルをデフォルトで使用します。
|
||||
|
||||
**ルーティングを有効にしたのに、リクエストが別のプロバイダーへ行く**
|
||||
|
||||
次の 3 つの状態が一致しているか確認してください:Codex タブの現在のプロバイダーが Kimi であること、ローカルルーティングサービスが実行中であること、`ルーティング有効` で 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)
|
||||
- [Kimi オープンプラットフォーム: コーディングツールで Kimi K2.7 Code を使う](https://platform.kimi.com/docs/guide/agent-support)
|
||||
- [Kimi Code ドキュメント: 概要](https://www.kimi.com/code/docs/)
|
||||
- [Kimi Code ドキュメント: サードパーティ Coding Agent での利用](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
|
||||
@@ -0,0 +1,112 @@
|
||||
# 在 Codex 中用 Kimi:CC Switch 本地路由攻略
|
||||
|
||||
> 适用版本:CC Switch 3.16.5 及附近版本。本文根据仓库内文档与代码整理,并用 Kimi 作为 OpenAI Chat Completions 兼容接口的示例。截图来自当前前端界面,使用去敏示例数据生成,避免泄露真实 API Key 或账户余额。
|
||||
|
||||
## 为什么需要本地路由
|
||||
|
||||
新版 Codex CLI 面向的是 OpenAI Responses API,而 Kimi 开放平台和 Kimi For Coding 实际暴露的都是 OpenAI Chat Completions 形态,也就是 `/chat/completions`。这两种协议的请求体、流式事件和返回结构不同,直接把 Kimi 的接口地址填进 Codex 配置里,常见结果就是请求 `/responses` 返回 404,或者流式响应无法被 Codex 正确解析。
|
||||
|
||||
Kimi For Coding 官方目前支持的第三方工具是 Claude Code、Roo Code 这类兼容 Anthropic 协议的编程 Agent,并没有覆盖 Codex。所以想在 Codex 里用 Kimi,需要一层协议转换——这正是 CC Switch 本地路由做的事。
|
||||
|
||||
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` 目录结构存在。
|
||||
- 一个 Kimi API Key。
|
||||
|
||||
Kimi 的 API Key 有两个来源,对应 CC Switch 里两个不同的内置预设:
|
||||
|
||||
- **Kimi 开放平台**(platform.kimi.com):按 token 用量计费的 API Key,对应预设 `Kimi`,OpenAI 兼容 base URL 是 `https://api.moonshot.cn/v1`,默认模型 `kimi-k2.7-code`。
|
||||
- **Kimi For Coding**(kimi.com/code):Kimi 会员 Kimi Code 权益生成的专用 Key,对应预设 `Kimi For Coding`,base URL 是 `https://api.kimi.com/coding/v1`,模型统一为 `kimi-for-coding`。
|
||||
|
||||
两个预设都已经按官方信息配好接口地址和模型,请优先使用预设,不需要手动拼接口路径。
|
||||
|
||||
## 第一步:添加 Codex 供应商
|
||||
|
||||
打开 CC Switch,切到顶部的 `Codex` 标签,点击右上角的加号添加供应商。
|
||||
|
||||
按你手里 Key 的类型,在内置预设里选择 `Kimi`(开放平台按量计费)或 `Kimi For Coding`(会员订阅),然后只需要做两件事:
|
||||
|
||||
- 填入对应的 Kimi API Key。
|
||||
- 保存供应商。
|
||||
|
||||

|
||||
|
||||
预设已经内置 Kimi 的请求地址、默认模型、模型菜单、thinking/reasoning 参数,并把 `高级选项` 里的 `上游格式` 预设为 `Chat Completions(需开启路由)`。你可以按需调整默认模型或模型显示名——例如开放平台预设默认是 `kimi-k2.7-code`,也可以按官方文档换成 `kimi-k2.7-code-highspeed`;协议转换交给路由层完成即可。
|
||||
|
||||
## 第二步:开启本地路由并接管 Codex
|
||||
|
||||
进入设置里的 `路由` 页面,展开 `本地路由`,完成两个开关:
|
||||
|
||||
1. 打开 `路由总开关`,启动本地服务。默认地址是 `127.0.0.1:15721`。
|
||||
2. 在 `路由启用` 中打开 `Codex`。如果只想让 Codex 走路由,可以保持 Claude、Gemini 关闭。
|
||||
|
||||

|
||||
|
||||
接管后,CC Switch 会把 Codex 的 live 配置指向本机路由,并用占位符管理认证。真实 Kimi Key 仍保存在 CC Switch 的 Provider 配置里,由本地路由在转发时注入,不需要你把 Key 暴露给 Codex live 配置。
|
||||
|
||||
## 第三步:切换供应商并重启 Codex
|
||||
|
||||
回到 Codex 供应商列表,点击 Kimi 供应商的 `启用`。如果看到 `需要路由` 标记,说明这个供应商必须在路由运行时使用;没有启动路由时,CC Switch 会弹出“需要路由服务才能正常使用”的提示。
|
||||
|
||||
切换后建议重启当前 Codex 终端会话。原因是:
|
||||
|
||||
- Codex 进程可能已经读取过旧的 `config.toml`。
|
||||
- `model_catalog_json` 生成后,`/model` 菜单通常需要新进程才能刷新。
|
||||
|
||||
进入 Codex 后,可以用 `/model` 查看当前模型是否来自 Kimi 预设,例如 `Kimi K2.7 Code` 或 `Kimi For Coding`。目前 Codex app 不支持多模型选择时,会默认使用配置里的第一个模型。随后发一个小问题,确认路由面板的请求数增长,或者在用量/请求日志里看到 Codex 请求即可。
|
||||
|
||||
## 其它 Chat 供应商怎么处理
|
||||
|
||||
Kimi、DeepSeek、MiniMax、SiliconFlow 等常见 Chat 格式供应商在 CC Switch 里已有预设,优先用预设即可。只有预设里没有的供应商,才需要选择自定义配置;这时按对方文档填 API Key、base URL 和模型,并把 `高级选项` 里的 `上游格式` 选为 `Chat Completions(需开启路由)`。
|
||||
|
||||
如果上游直接支持 OpenAI Responses API,把 `上游格式` 选为 `Responses` 即可;这时 CC Switch 按 Responses 直连,不做 Chat 转换。
|
||||
|
||||
## 常见问题
|
||||
|
||||
**Codex 报 404 或找不到 `/responses`**
|
||||
|
||||
通常是没有开启 Codex 接管,或者你手动把 Kimi 的 Chat base URL 直接写给了 Codex——Kimi 上游没有 `/responses` 端点,这样一定会 404。检查 `~/.codex/config.toml` 是否指向 `http://127.0.0.1:15721/v1`。
|
||||
|
||||
**Kimi 上游报 401 或 403**
|
||||
|
||||
先确认 Key 和预设是否匹配:开放平台的 Key 只能配 `Kimi` 预设,Kimi Code 会员权益的 Key 只能配 `Kimi For Coding` 预设,两套 Key 不能混用。
|
||||
|
||||
**Kimi 上游报 404**
|
||||
|
||||
如果用的是内置 Kimi 预设,先确认当前供应商确实来自预设,并且 Codex 路由已启用。只有在使用自定义供应商时,才需要额外检查 base URL:它应该是服务根地址,而不是带 `/chat/completions` 的完整接口路径。
|
||||
|
||||
**`/model` 看不到 Kimi 模型**
|
||||
|
||||
保存供应商后重启 Codex。CC Switch 会生成 `cc-switch-model-catalog.json` 并把路径写入 `model_catalog_json`,但正在运行的 Codex 进程不一定会热加载模型目录。
|
||||
目前 Codex app 不支持多模型选择,默认使用配置的第一个模型。
|
||||
|
||||
**开了路由但请求仍走错供应商**
|
||||
|
||||
确认三处状态一致:Codex 标签下当前供应商是 Kimi;本地路由服务正在运行;`路由启用` 里 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)
|
||||
- [Kimi 开放平台:在编程工具中使用 Kimi K2.7 Code 模型](https://platform.kimi.com/docs/guide/agent-support)
|
||||
- [Kimi Code 文档:概览](https://www.kimi.com/code/docs/)
|
||||
- [Kimi Code 文档:在第三方 Coding Agent 中使用](https://www.kimi.com/code/docs/third-party-tools/other-coding-agents.html)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 373 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 268 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 295 KiB |
@@ -0,0 +1,364 @@
|
||||
# CC Switch v3.17.0
|
||||
|
||||
> This release brings a long-awaited capability: **one-click "Projects" switching** — save your current provider, MCP, Skills, and memory files as a single named snapshot, swap the whole set for another one from the title bar or tray with a single click, and have the state of the project you're leaving automatically saved back on the way out. The Codex side gets plenty too: **your official ChatGPT subscription account can now route through the local proxy as well**, getting the same routing and usage statistics as third-party providers; the GPT-5.6 family's context window and Sol / Terra / Luna three-tier pricing land in one step; and a native Anthropic Messages upstream format is added — is Claude Code banned at your company but the Claude API isn't? You can now **use Claude-family models directly inside Codex**. On top of that comes a big wave of correctness fixes: upstream failures no longer turn into "empty replies", cache-write tokens are no longer double-billed, deleted MCP servers no longer come back from the dead, and Kimi For Coding's 256K window finally takes effect for real.
|
||||
|
||||
**[中文版 →](v3.17.0-zh.md) | [日本語版 →](v3.17.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## Usage Guides
|
||||
|
||||
The new capabilities in this release land mainly in the project switcher at the top of the home page, the Codex provider form, and the usage dashboard. The following docs are worth reading alongside it:
|
||||
|
||||
- **[Using Kimi inside Codex (local routing guide)](../guides/codex-kimi-routing-guide-en.md)**: a new step-by-step guide added in this release. Newer Codex CLI speaks the OpenAI Responses protocol, while the Kimi Open Platform and Kimi For Coding expose Chat Completions endpoints, so a direct connection usually 404s; the guide walks through using the built-in `Kimi` / `Kimi For Coding` presets together with local routing to handle the protocol conversion.
|
||||
- **[Codex Official Login Preservation](../guides/codex-official-auth-preservation-guide-en.md)**: understand how CC Switch preserves your official ChatGPT login when you switch to a third-party provider. This release goes a step further — the official account itself can now route through the proxy too (see "Added" below).
|
||||
- **[Usage Statistics](../user-manual/en/4-proxy/4.4-usage.md)**: understand the Usage Dashboard's data sources and how the statistics are counted. This release fixes cache-write billing, fills in Codex subagent session accounting, and adds GPT-5.6 and Hunyuan Hy3 pricing.
|
||||
|
||||
---
|
||||
|
||||
> [!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.17.0 is a major feature release following v3.16.5, centered on **Projects**: you can save the current provider, MCP, Skills, and memory-file state of Claude Code / Claude Desktop / Codex as a named snapshot — say a "Development" set for a coding directory and a "Drawing" set for a writing-and-drawing directory — and swap the whole set with one click from the switcher at the top of the home page or the "Projects" tray submenu. Before you switch, the state of the project you're about to leave is automatically saved back, so a project always holds exactly what you last left it as. The second main thread is Codex: **your official ChatGPT subscription account can now be taken over by the local proxy route** (no API key needed — Codex's own login credentials are passed through verbatim and your official login is never overwritten); paired with a corrected client identity, the latest subscription models like `gpt-5.6-luna` no longer falsely 404; GPT-5.6's 372K context-window injection, Sol / Terra / Luna three-tier pricing (including the 1.25× cache-write rate), and preset default models all land together; and the Codex upstream format gains a native Anthropic Messages protocol — which targets a very real scenario: plenty of companies ban the Claude Code client but do **not** ban the Claude API, and those users can now point Codex directly at the Claude API (or any gateway that only offers `/v1/messages`) and keep using Claude-family models inside Codex.
|
||||
|
||||
For everyday-use correctness, this release makes three concentrated waves of fixes. **Proxy bridge**: semantic failures returned inside a 2xx are no longer turned into an empty reply but trigger failover instead; reasoning content, tool results, and the system role round-trip losslessly across the Responses↔Anthropic bridge; prompt-cache breakpoint injection is more thorough, so long conversations no longer resend everything at full price each turn. **Usage billing**: cache-write tokens were previously billed twice — once at the input rate and once at the cache-creation rate — and are now corrected (the database is upgraded to schema v13 so historical data stays consistent); usage and quota queries automatically retry on transient network failures and no longer cache a failure body as real data. **Codex `config.toml`**: MCP servers you deleted in the app no longer come back on provider switch; when parsing a live file fails, sync errors out rather than blanking the whole file; and the "Apply Common Config" merge is moved to the backend so comments and key order are no longer scrambled. Also included: Kimi For Coding's 256K window finally taking effect, Codex subagent and free-tier quota accounting filled in, Zhipu team-plan quota queries, OpenCode form enhancements, and a batch of preset updates.
|
||||
|
||||
**Release date**: 2026-07-13
|
||||
|
||||
**Stats**: 69 commits | 172 files changed | +21,067 / -2,464 lines
|
||||
|
||||
---
|
||||
|
||||
## Highlights
|
||||
|
||||
- **One-click "Projects" switching**: save your provider, MCP, Skills, and memory files as a single named snapshot (say one set for coding, another for writing and drawing) and swap the whole thing with one click from the top of the home page or the tray; the state of the project you leave is saved back automatically on switch. Covers three scopes — Claude Code, Claude Desktop, and Codex — that don't interfere with one another.
|
||||
- **Official Codex account can route through the proxy too**: a Codex session logged in with a ChatGPT subscription can now route through the local proxy, getting routing and usage statistics identical to third-party providers; the official login credentials are never overwritten or stored.
|
||||
- **GPT-5.6 fully in place**: a 372K context window is auto-injected when Claude Code routes through Codex takeover; Sol / Terra / Luna three-tier pricing is seeded (cache writes billed at 1.25× the input rate); the relevant presets' default models are bumped to the gpt-5.6 family; and, with the client identity corrected, `gpt-5.6-luna` no longer falsely 404s.
|
||||
- **Use Claude-family models inside Codex (native Anthropic Messages upstream)**: plenty of companies ban the Claude Code client but not the Claude API — now, by setting a Codex provider's upstream format to `anthropic`, you can connect directly to the Claude API or any gateway that only offers `/v1/messages`, with the local proxy handling the two-way Responses↔Anthropic conversion and standard 5-minute prompt-cache injection built in.
|
||||
- **Proxy bridge correctness fixes**: upstream failures fail closed and trigger failover instead of an empty reply; reasoning / tool results / the system role survive the bridge losslessly; cache writes are no longer double-billed; breakpoint injection is more thorough.
|
||||
- **Codex config.toml hardening**: deleted MCP servers no longer come back; MCP sync errors out rather than blanking the file on a parse failure; common-config merges preserve comments and key order.
|
||||
- **Kimi For Coding 256K finally works**: the previous 262144 compaction window never actually took effect (clamped back to Claude Code's 200K default); this release fills in the model-alias routing and window injection; existing providers need to re-apply the preset (see "Upgrade Notes").
|
||||
|
||||
---
|
||||
|
||||
## Added
|
||||
|
||||
### Projects: Named Snapshots of a Whole Configuration, Switched in One Click
|
||||
|
||||
This is the headline feature of the release. You can save your current provider, MCP, Skills, and memory-file state as a named "project", then swap the whole set with one click from the project switcher at the top of the home page or the "Projects" tray submenu, instead of toggling each piece by hand.
|
||||
|
||||
Here's a typical scenario: you have one directory for coding and another for writing or drawing. Coding wants one provider, plus MCP like filesystem / GitHub, code-review Skills, and a memory file spelling out your engineering conventions; writing or drawing often wants a different provider, a different set of MCP, and completely different prompts. Bouncing between the two used to mean switching providers, toggling MCP and Skills one by one, and then editing the memory file; now you save the two states as two projects — "Development" and "Drawing" — and when you switch directories to work, one click in CC Switch puts the whole configuration in place.
|
||||
|
||||
Projects span three scopes — Claude Code, Claude Desktop, and Codex (the only dimension CC Switch manages for Claude Desktop is the provider, so its snapshots contain only the provider and applying one touches no other dimension).
|
||||
|
||||
A few design points worth knowing:
|
||||
|
||||
- **Projects are global entities, switched per scope**: the same project records its own current project and snapshot slot separately on the Claude Code / Claude Desktop / Codex sides, so switching projects on the Codex tab never touches Claude's configuration.
|
||||
- **Switching auto-saves**: before you switch projects, the state of the project you're about to leave in the current scope is first saved back automatically — so a project always holds exactly what you last left it as, with no (and no need for a) manual "update snapshot" button.
|
||||
- **Applying is best-effort**: applying a snapshot reuses the existing switch primitives (switch the provider first, then do the minimal MCP / Skills diff toggles, then enable memory files); if something a snapshot references has been deleted, it's only warned and skipped, never rolled back wholesale.
|
||||
- **Auto-disables proxy takeover**: before applying a project, proxy takeover for each app in that scope is disabled first, to avoid the snapshot state fighting with the routing state.
|
||||
|
||||
If you don't use Projects, you can turn off "Show project switcher" under Settings → Home Display, which only hides the home-page entry — the tray submenu and project data are unaffected. It's backed by a new `profiles` table (the database migrates automatically, no manual steps), with UI copy in sync across all four locales.
|
||||
|
||||
### Proxy Route Takeover for the Official Codex ChatGPT Account
|
||||
|
||||
A Codex session using a ChatGPT subscription (OAuth or API-key login) can now route through CC Switch's local proxy too — official-account traffic gets routing, format conversion, and usage statistics identical to third-party providers. Just pick the built-in "OpenAI Official" entry in the provider panel or tray to take it over (if you deleted it before, it's restored automatically when you add a provider); the card badge shows "Official account routing" while routing.
|
||||
|
||||
The implementation deliberately achieves **zero credential storage**: instead of writing any placeholder key to `auth.json`, it projects a dedicated `model_provider` pointing at the local proxy into `config.toml`, and Codex sends its own ChatGPT authorization header to the proxy, which passes it through verbatim to the official endpoint — the credentials on the `codex-official` line are always empty. The official login itself is never overwritten: on takeover, OAuth / API-key material is preserved into the backup, and a 401 / 403 from the official side is treated as a non-retryable error, so failover never quietly moves your conversation to another account. Accordingly, the copy for the "Preserve Codex official login on switch" setting has been updated — under route takeover the official login is always preserved, so that toggle now only governs third-party direct switches that don't route through the proxy.
|
||||
|
||||
### GPT-5.6: Context Window, Preset Defaults, and Three-Tier Pricing
|
||||
|
||||
Three things were done around the GPT-5.6 family:
|
||||
|
||||
- **372K context-window injection**: when Claude Code routes to the ChatGPT Codex (Codex OAuth) backend through proxy takeover, `CLAUDE_CODE_MAX_CONTEXT_TOKENS` and `CLAUDE_CODE_AUTO_COMPACT_WINDOW` (both 372000) are auto-injected into the live `settings.json`, so Claude Code no longer auto-compacts prematurely at its default 200K window nor overflows the upstream. The injection is strictly gated: it only injects when every configured model key points at the gpt-5.6 family (gpt-5.5's catalog window swings between 272K and 372K, so it's deliberately not inherited); your manually set values always win; and it's stripped on switch-away under mirrored conditions, so a program default is never baked into your provider config.
|
||||
- **Preset default-model bump**: the Codex OAuth presets for Claude Code and Claude Desktop bump their default routes to the gpt-5.6 family (haiku → `gpt-5.6-luna`, main model / sonnet / opus → `gpt-5.6`), and the custom Codex `config.toml` template's default model follows suit.
|
||||
- **Sol / Terra / Luna three-tier pricing**: the usage dashboard seeds all three tiers at official rates — Sol 5 / 30 / 0.50, Terra 2.50 / 15 / 0.25, Luna 1 / 6 / 0.10 (USD per million tokens, input / output / cache read). Unlike 5.5 and earlier, the 5.6 family bills **prompt-cache writes at 1.25× the input rate** (Sol 6.25 / Terra 3.125 / Luna 1.25), seeded accordingly, with existing rows previously billed at 0 auto-repaired; bare `gpt-5.6` and its per-effort suffix variants align to the Sol rate.
|
||||
|
||||
### Use Claude-Family Models inside Codex: Native Anthropic Messages Upstream
|
||||
|
||||
This feature comes from a very real need: **plenty of companies ban the Claude Code client for compliance reasons, but do not ban the Claude API.** For those users the model itself is available; what's missing is a permitted client — and Codex can now fill that slot. Pick the new `anthropic` option in a Codex provider's upstream-format selector, and you can connect directly to the Claude API or any gateway offering the native Anthropic Messages protocol (`/v1/messages`); the local proxy handles the two-way conversion of requests, responses, and streaming between Responses and Anthropic, and you chat and use tools inside Codex as usual while Claude-family models run behind the scenes. The form provides the supporting pieces: an auth-field selector (`ANTHROPIC_AUTH_TOKEN` sends `Authorization: Bearer`, the default; or `ANTHROPIC_API_KEY` sends `x-api-key`), an optional Claude Code client-impersonation toggle (off by default), and a per-provider max-output-token override (Codex doesn't send `model_max_output_tokens`, and when unset it falls back to a conservative 8192, which may truncate long or heavy-reasoning replies). The conversion bridge auto-injects standard 5-minute prompt-cache markers (system prompt, tools, and history go through the cache instead of being resent at full price each turn), supports the `[1m]` long-context marker with the corresponding beta header, and reports a truncated stream faithfully as incomplete rather than disguising it as success. ([#5071](https://github.com/farion1231/cc-switch/pull/5071))
|
||||
|
||||
### "Default Model" Field Added to the Codex Provider Form
|
||||
|
||||
The top-level `model` key in `config.toml` is now an editable field in the form: when a new model (e.g. `gpt-5.6`) ships, you can point an existing provider at it directly without waiting for a preset update (presets only affect newly added providers). The field is two-way synced with the TOML editor, its candidate list is the union of the model-mapping catalog and the provider's `/models` endpoint, and when a value isn't in the catalog it offers a one-click "Add to mapping". An explicitly entered value always wins over the implicit backfill from the mapping's first row; model names and `base_url` are TOML-escaped on write, eliminating any chance that remote data from `/models` injects a forged config line.
|
||||
|
||||
### Common-Config Switch Auto-Sync Extended to Codex
|
||||
|
||||
The "on switch-away, write shared preferences from the live config back to the common config" behavior v3.16.5 added for Claude now covers Codex: when you switch away from a Codex provider that has the common config enabled, the shareable portion is first re-extracted from its live `config.toml` to update the common config and then carried to the next provider — the preferences you edited directly in the running Codex config are no longer lost on switch, and deleted keys aren't quietly re-injected. The extractor strictly strips provider-specific and injected content (`model` / `model_provider` / `base_url` / `wire_api`, the entire `[model_providers]` table, the MCP projection, the API-key fallback field, the model-catalog pointer, and the injected `web_search` sentinel), so secrets never enter the shared snippet. All failures only warn and never block the switch.
|
||||
|
||||
### Claude Subagent Model Configuration
|
||||
|
||||
The Claude provider form gains a "subagent" model row that writes `CLAUDE_CODE_SUBAGENT_MODEL`, letting subagents spawned by Claude Code run on a model you specify (usually a cheaper or faster one). It supports the `[1M]` marker; since the subagent model never appears in the `/model` menu, the row shows a "not shown in /model" placeholder with no display-name field. The proxy takeover path and the model mapper support it too: when the request model matches the configured subagent model it's passed through as-is instead of being folded to the default model; the key is also excluded from the shared common config so it doesn't leak across providers. ([#4830](https://github.com/farion1231/cc-switch/pull/4830))
|
||||
|
||||
### 1M Context Checkbox for the Fallback Model Field
|
||||
|
||||
The Claude form's fallback model field (`ANTHROPIC_MODEL`) now carries the same 1M checkbox that the Sonnet / Opus / Fable tiers have long had: when the fallback model is backed by a 1M window you can declare it faithfully, instead of it being silently treated as 200K. Checking it appends the `[1M]` marker to the model id, unchecking strips it. ([#5124](https://github.com/farion1231/cc-switch/pull/5124), fixes #3679)
|
||||
|
||||
### Zhipu Team-Plan Quota Query
|
||||
|
||||
Zhipu's team plan (team-edition Coding Plan) uses the same quota endpoint but requires `?type=2` and two extra request headers (`bigmodel-organization` / `bigmodel-project`), which the personal-edition query can't reach. The usage-script dialog gains a "Zhipu GLM Team" template; fill in the API key + organization ID + project ID to query team quota, and if any of the three is missing you get a clear prompt to complete it. Copy is in sync across all four locales. ([#5128](https://github.com/farion1231/cc-switch/pull/5128))
|
||||
|
||||
### OpenCode Form: Headers and Per-Model Token-Limit Editors
|
||||
|
||||
The OpenCode provider form fills in two pieces of config that previously required hand-editing JSON: a **Headers editor** (provider-level `options.headers`, such as the `HTTP-Referer` / `X-Title` that OpenRouter's leaderboard wants, with add/remove rows and case-insensitive deduplication) and **per-model token limits** (`model.limit.context` / `model.limit.output` numeric inputs, cleared to remove). The "extra options" block becomes a collapsible section that auto-expands when it has content; along the way, a fix stops the old placeholder filter from wrongly deleting genuine option keys that start with `option-`. ([#2907](https://github.com/farion1231/cc-switch/pull/2907))
|
||||
|
||||
### New Model Pricing: Tencent Hunyuan Hy3
|
||||
|
||||
Seeded pricing for Tencent Hunyuan Hy3 (256K context), released 2026-07-06 (converted from the launch-day list price of CNY 1 / 4 / 0.25 per million tokens); both the `hunyuan-hy3` and `hy3` ids now hit, so their usage no longer shows $0. Note that Hy3 is actually tiered by input length, and the current price table is seeded at the lowest tier, so long-context requests will underestimate cost — to be corrected once the official billing page is clear.
|
||||
|
||||
---
|
||||
|
||||
## Changed
|
||||
|
||||
### Codex Chat Routing Injects prompt_cache_key to Improve Cache Hits
|
||||
|
||||
When Codex routes through the local proxy and converts to a Chat Completions upstream, it now injects `prompt_cache_key` in a provider-aware way: auto-enabled for Kimi Coding and the OpenAI official endpoint, explicitly on for the Kimi preset, and left off for unknown OpenAI-compatible gateways to avoid a 400 from strict-schema gateways. The key value only ever takes an explicit client value or a real client session ID, and never generates a random UUID (which would drop every request into a different cache bucket, defeating the purpose). Advanced options offer an auto / enabled / disabled tri-state override.
|
||||
|
||||
### Codex Image Capability Auto-Inferred, Manual Toggle Removed
|
||||
|
||||
The generated Codex model catalog now only declares `input_modalities = ["text"]` for models on CC Switch's confirmed **exact text-only roster**; GPT, aliases, new suffix variants, and any unknown model all fail open to `["text", "image"]` — fixing GPT-family models being falsely reported as "images not supported" in the Codex IDE extension. The rectifier's "text-only model precheck" toggle continues to govern only the proxy-side active request rewriting, not the catalog declaration; catalog reverse-import also collapses the inferable capability away, so a future roster correction or a model upgrading to multimodal takes effect automatically.
|
||||
|
||||
### Context-Window Parameters Pinned into Presets, No Longer Form Fields
|
||||
|
||||
The `Codex` (ChatGPT / GPT-5.6) and `Kimi For Coding` presets no longer show the "Max Context Tokens" and "Auto-Compact Window" inputs in the form; the values are pinned directly in the preset env (Codex 372000 / 372000, Kimi For Coding 262144 / 262144) — the vast majority of users never need to touch these two numbers. The two keys are kept in env on purpose: pinning them explicitly makes the local compaction trigger point immune to a remote experimental config dialing it down. The rare users who do want to change the numbers can still edit both keys directly in the provider's JSON editor.
|
||||
|
||||
### Provider Connectivity Configuration Simplified
|
||||
|
||||
Removed the obsolete per-provider `testConfig` overrides (timeout, retry count, degradation delay threshold): the lightweight `base_url` probe now always uses the global connectivity-check config, while automatic failover remains fully driven by the proxy's separate timeout and circuit-breaker settings. The settings UI and interface naming also migrate from "model test" terminology to "connectivity check".
|
||||
|
||||
### Universal (Multi-App) Provider Auto-Synced After Adding
|
||||
|
||||
After adding a universal (multi-app) provider through the "Add Provider" dialog, it's now immediately pushed to each live target config, no longer requiring a manual sync afterward. A sync failure doesn't block the add — the provider is saved, with a non-blocking warning shown if the sync fails. ([#2811](https://github.com/farion1231/cc-switch/pull/2811))
|
||||
|
||||
### Preset Updates
|
||||
|
||||
- **LongCat-2.0**: the Meituan LongCat presets across the board (Claude Code / Claude Desktop / Codex / Hermes / OpenClaw / OpenCode) upgrade from the retired `LongCat-Flash-Chat` / `LongCat-2.0-Preview` to `LongCat-2.0`, declaring the real 1M (1048576) context window. LongCat-2.0 is a text-only model, and the proxy's media-scrub whitelist is updated in sync — images pasted into a conversation are replaced with an unsupported marker rather than hard-rejected upstream. ([#4838](https://github.com/farion1231/cc-switch/pull/4838))
|
||||
- **SudoCode**: the old `sudocode.us` preset is replaced in place by the new sponsor SudoCode at `sudocode.chat`, covering six clients (the Claude family connects directly to Anthropic passthrough; Codex / OpenCode / OpenClaw / Hermes default to `gpt-5.6-sol`).
|
||||
- **Volcengine / Doubao / BytePlus website links**: reverted v3.16.5's change of these three presets' `websiteUrl` to product homepages, restoring the attribution-parameter campaign / invite links (this is by design).
|
||||
- **Code0.ai**: the invite link is updated to the new agent signup link; the API endpoint is unchanged.
|
||||
- **Removed duplicate OpenAI Compatible presets**: the `OpenAI Compatible` custom-template entry was removed from the OpenCode and OpenClaw preset lists — the built-in `custom` provider flow already offers the same starting point, so the selector no longer shows two entries pointing at the same place. Existing providers are unaffected.
|
||||
|
||||
---
|
||||
|
||||
## Fixed
|
||||
|
||||
### Codex OAuth Client Identity Aligned: Fixes 404 on Latest ChatGPT Models
|
||||
|
||||
When routing through local proxy takeover with an official Codex OAuth account, the latest subscription models (e.g. `gpt-5.6-luna`) previously returned a misleading `404 Model not found` — even though the account had access. The root cause is that ChatGPT's Codex backend does model-group routing by the `originator` + `version` headers, and cc-switch previously self-reported `originator: cc-switch` with no version, which routed it to a group where luna wasn't yet deployed. Takeover requests now send the same `originator: codex_cli_rs` + `version: 0.144.1` as the real Codex CLI, satisfying luna's minimum client-version requirement — confirmed fixed by A/B testing against the real backend.
|
||||
|
||||
### Responses Upstream Failures No Longer Turn into Empty Replies
|
||||
|
||||
When the proxy bridges an Anthropic-format client (Claude Code / Claude Desktop) to an OpenAI Responses upstream, a semantic failure hidden inside an HTTP 2xx body (a `status:"failed"` object, an `error` envelope, or a `response.failed` SSE event before the first output) was previously converted into a silent empty turn. These failures are now recognized as real errors inside the retry loop, so failover can retry with a different provider; a stream that ends cleanly but with incomplete content is faithfully marked truncated rather than complete; a gateway that ignores `stream:true` and returns the whole JSON document is recognized and expanded into a full streaming lifecycle; and when the client history itself is malformed, it errors immediately instead of retrying a guaranteed-to-fail request against every provider.
|
||||
|
||||
### Reasoning, Tool Results, and the System Role Preserved Across the Responses/Anthropic Bridge
|
||||
|
||||
Content crossing the Responses↔Anthropic bridge in multi-turn tool loops is no longer lost or corrupted: encrypted reasoning entries round-trip losslessly (also eliminating the problem where a failed round-trip got the next request rejected upstream); the streaming converter supports the official reasoning event vocabulary and recovers tool arguments from the terminal event when a gateway skips the deltas; a structured tool result's `is_error` flag, images, and PDF documents are fully preserved in both directions instead of being flattened into a single JSON string; and `system` / `developer` messages in history are correctly promoted to Anthropic `system` instead of being silently demoted to user turns. On billing, when the upstream request succeeds but the subsequent conversion fails, usage is still recorded rather than dropped.
|
||||
|
||||
### Cache-Write Tokens No Longer Double-Billed
|
||||
|
||||
The `input_tokens` reported by Codex / Gemini-style providers include both cache reads and cache writes, but the cost calculation previously only subtracted cache reads — so cache-write tokens were **billed twice**, once at the input rate and once at the cache-creation rate. Both are now deducted first, and the cache-write number is no longer lost across format conversions (Chat↔Responses↔Anthropic). To keep historical data consistent, the database adds a column recording the storage semantics of each row's `input_tokens` (schema v12→v13 auto-migration): old rows are recomputed under the old semantics, new rows under the new, and Claude-style rows are unaffected.
|
||||
|
||||
### Stronger Prompt-Cache Breakpoint Injection
|
||||
|
||||
On the proxy paths that inject Anthropic `cache_control` breakpoints (the Codex takeover bridge and the Bedrock native optimizer), the injector now uses the four-breakpoint budget more thoroughly: beyond the tail of tools, the tail of the system prompt, and the latest cacheable message, when budget remains it also anchors an earlier user message, keeping the stable prefix within Anthropic's 20-block lookback window — so long, tool-heavy conversations keep hitting the prompt cache instead of resending the system prompt, tools, and history at full price each turn. Caller-supplied breakpoints are preserved as-is (never removed, reordered, or rewritten); injected markers all use the standard 5-minute TTL.
|
||||
|
||||
### Kimi For Coding's 256K Context Window Actually Takes Effect
|
||||
|
||||
The `CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144` added to the Kimi For Coding preset in 3.16.4 in fact **never took effect**: Claude Code caps unrecognized model ids at a 200K window and takes the compaction window as `min(model window, configured value)`, so 262144 got clamped back to 200K. This release fills in the two missing pieces — the preset now also pins `CLAUDE_CODE_MAX_CONTEXT_TOKENS`, and it explicitly routes each tier's model to the endpoint's `kimi-for-coding` alias (a `claude-` prefixed id makes Claude Code ignore both window parameters; a non-Claude alias is the key to unlocking the large window). Saved providers also get these two window defaults auto-injected on switch, but **the alias routing only lives in the preset** — a provider saved from the old preset is still effectively 200K and needs a one-time re-apply of the preset (see "Upgrade Notes").
|
||||
|
||||
### Deleted Codex MCP Servers No Longer Come Back
|
||||
|
||||
The authoritative MCP-server data lives in the database, and the `[mcp_servers]` in the Codex live `config.toml` is only a projection re-synced after every write — but on switch-away this projection was baked into the provider snapshot, so a server you deleted in the app came back to life the next time you activated that provider, and per-entry reconciliation could never clear the orphan. On switch-away, `[mcp_servers]` (including the legacy `[mcp.servers]`) is now stripped from the stored snapshot, and an already-polluted snapshot self-heals on its next switch-away. One visible side effect: a hand-written `[mcp_servers.*]` section in a Codex provider config is stripped out of the snapshot on its first switch-away — from now on, define Codex's MCP servers through the MCP manager (see "Upgrade Notes").
|
||||
|
||||
### More Robust MCP Sync: No File-Blanking on Parse Failure, Per-App Errors
|
||||
|
||||
Two fixes. First, when writing a single MCP server to Codex, if the existing `config.toml` fails to parse, the old logic fell back to an empty document and wrote the whole thing back — **the entire file was blanked** down to that one MCP entry; it now returns a validation error and leaves the file untouched. Second, "Import from App" previously swallowed each importer's error as 0, so a broken Codex config would only show "imported 0 servers"; it now imports best-effort per app and, on failure, reports exactly which app failed. The projection on switch and save is also scoped to the target app only, so one app's live-file parse failure no longer blocks the others by association, nor falsely reports an already-successful switch as a failure.
|
||||
|
||||
### Codex Common-Config Merge Preserves Comments and Key Order
|
||||
|
||||
Checking / unchecking "Apply Common Config" in the Codex provider form previously went through a front-end TOML implementation that reformatted the whole file (parse → merge → serialize): comments were dropped, keys were reordered, and empty table headers like `[model_providers]` appeared out of nowhere — the culprit behind "config.toml keeps getting reordered". The merge now goes through a backend command sharing the same merge semantics as writing the live config, so hand-written formatting fully survives the mid-edit merge; a double guard (operation sequence number + config baseline check) was also added for the fast-switch race introduced by going async, so an earlier-issued-but-later-arriving stale result doesn't overwrite newer state.
|
||||
|
||||
### Managed Claude Takeover Injects Only a Single Auth Placeholder
|
||||
|
||||
When switching from a third-party endpoint to a Codex-managed provider, `~/.claude/settings.json` had both `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` placeholders written, causing Claude Code to warn "Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set" on every launch. It now injects only one: Codex-managed uses `ANTHROPIC_AUTH_TOKEN`, Copilot uses `ANTHROPIC_API_KEY`, and any other token key is cleared. Note: after upgrading, if the live config already carries both keys, the "skip rewrite if config unchanged" short-circuit means the warning may persist — toggle the Claude route off and on once (or switch providers once) to trigger a rewrite (see "Upgrade Notes"). ([#5095](https://github.com/farion1231/cc-switch/pull/5095), fixes #4919)
|
||||
|
||||
### Usage and Quota Queries: Auto-Retry on Transient Failures, No Longer Poison the Cache
|
||||
|
||||
Usage and quota queries frequently showed a "query failed" that a manual refresh couldn't clear, because all transport-layer failures (including a mid-read timeout while reading the response body) were folded into "succeeded, but the result is a failure" — so the front-end's auto-retry never fired, and the failure body was cached as real data. Transport failures now return an error faithfully: react-query's auto-retry kicks in, HTTP 429 is treated as transient like 5xx, retained last-good data expires normally on a 10-minute window, and the footer keeps a retry entry and the real error message in the failure state. (fixes [#3820](https://github.com/farion1231/cc-switch/issues/3820))
|
||||
|
||||
### Codex Subagent Session Usage Counted in Local Statistics
|
||||
|
||||
The token usage of Codex subagent (spawned agent) sessions previously never made it into local statistics: subagent logs carry the parent thread's `session_id`, so multiple subagents' records collided and were discarded as duplicates. The parser now builds a unique identity from each file's own `thread_id`, and recognizes the replay of the parent thread's history at the start of a subagent log — using it only to recover the cumulative baseline, not to double-bill; archived logs also inherit the sync cursor by filename, so re-parsing only imports the new portion. ([#5187](https://github.com/farion1231/cc-switch/pull/5187))
|
||||
|
||||
### Codex Free-Tier 30-Day Quota Window Displays Correctly
|
||||
|
||||
Codex free accounts are metered on a rolling 30-day window (rather than the paid tier's weekly window), but the front-end whitelist and tray grouping didn't recognize the `30_day` tier — with a free account's only tier filtered out, the quota footer went entirely blank and the tray showed no quota at all. The 30-day tier now renders correctly in both the footer and the tray, with labels in sync across all four locales. ([#4886](https://github.com/farion1231/cc-switch/pull/4886), fixes #3651)
|
||||
|
||||
### Usage Dashboard Refresh Interval Persisted
|
||||
|
||||
The usage dashboard's auto-refresh interval was previously component-local state that reset to 30 seconds on every restart. It's now persisted via a new app setting, with changes applied optimistically and rolled back automatically on save failure. ([#5057](https://github.com/farion1231/cc-switch/pull/5057))
|
||||
|
||||
### Fable-Tier Model Keys No Longer Leak into the Common Config
|
||||
|
||||
Fable is the fourth Claude model-mapping tier added in v3.16.3, but its two keys `ANTHROPIC_DEFAULT_FABLE_MODEL(_NAME)` were left off the provider-specific exclusion list — so one provider's Fable model pin could leak into the shared common config and then be injected into other providers. It's now stripped like the haiku / sonnet / opus tiers, and Fable-tier proxy takeover support was filled in along the way (writing a stable role alias on takeover, cleaning up stale values on switch-away). ([#5206](https://github.com/farion1231/cc-switch/pull/5206), fixes #4272)
|
||||
|
||||
### Tool-Schema Default-Type Fallback and API Key Input for Uncategorized Providers
|
||||
|
||||
Two provider-side fixes: when a client-sent tool's `input_schema` lacks a top-level `type` (or is an empty `{}`), the proxy conversion would be rejected by a strict gateway; the root schema now auto-fills `type: "object"` (only the root, leaving nested subschemas untouched); and the issue where an uncategorized provider imported from history or hand-built showed no Claude API Key input on edit is fixed — the field now shows for any provider that isn't an official / cloud-vendor category. ([#5069](https://github.com/farion1231/cc-switch/pull/5069))
|
||||
|
||||
### Image-Request Fallback for the Text-Only GLM 5.2 Model
|
||||
|
||||
When the local proxy takes over Volcengine Coding Plan running GLM 5.2, image blocks in a request no longer produce an unrecoverable 400: the text-only roster exactly includes `glm-5.2` (deliberately not prefix-matching, so a future multimodal `glm-5.2v` isn't caught), and the preventive path strips images before the request goes out; the gateway's error message that doesn't contain the word image (`Model only support text input`) is also recognized by the reactive path's self-identifying-phrase roster, triggering the media fallback. (fixes [#5025](https://github.com/farion1231/cc-switch/issues/5025))
|
||||
|
||||
### A Batch of Small Session and Live-Config Sync Fixes
|
||||
|
||||
- **Show renamed Codex session titles**: a session you renamed inside Codex now shows the new title in the session manager instead of falling back to the first message text; reads during concurrent writes no longer fail immediately. ([#4927](https://github.com/farion1231/cc-switch/pull/4927))
|
||||
- **OpenCode / OpenClaw / Hermes live edits synced into the store on startup**: editing a live config file directly (changing the base URL, adding a model) was previously never picked up after the first import; it's now diffed against the store on every startup and updated on difference, all non-fatal. ([#4712](https://github.com/farion1231/cc-switch/pull/4712), [#5098](https://github.com/farion1231/cc-switch/pull/5098))
|
||||
- **OpenCode session-resume command updated**: the resume command the session manager shows and copies is corrected from the outdated `opencode session resume <id>` to the current CLI's `opencode -s <id>`. ([#2359](https://github.com/farion1231/cc-switch/pull/2359))
|
||||
- **Official providers skip the connectivity probe**: the connectivity check no longer derives a guaranteed-to-fail credential-less first-party endpoint probe for official-category providers (e.g. hitting `chatgpt.com/backend-api/codex` bare); batch checks skip it, and an individual resolve reports a clear error.
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
### Codex + Kimi Local Routing Guide
|
||||
|
||||
A new step-by-step guide (in Chinese / English / Japanese, with UI screenshots) explaining how to use Kimi inside Codex CLI via CC Switch's local routing: newer Codex CLI speaks the OpenAI Responses protocol, while the Kimi Open Platform (pay-as-you-go, `kimi-k2.7-code`) and Kimi For Coding (membership, `kimi-for-coding`) both expose Chat Completions endpoints, so a direct connection usually 404s on `/responses`. The guide covers the whole flow from adding a provider from the built-in preset to the four-step protocol-conversion chain.
|
||||
|
||||
### README Sponsor Update
|
||||
|
||||
The open-source AI infrastructure project `new-api` joins the sponsor table in the four-language READMEs.
|
||||
|
||||
---
|
||||
|
||||
## Upgrade Notes
|
||||
|
||||
### Kimi For Coding Providers Need a Preset Re-Apply
|
||||
|
||||
If you're using a provider created from the Kimi For Coding preset, please **re-pick it from the preset and save once**: the key to the 256K window — routing each tier's model to the `kimi-for-coding` alias — only lives in the new preset, so a provider saved from the old preset still compacts prematurely at 200K even after upgrading.
|
||||
|
||||
### Hand-Written Codex `[mcp_servers.*]` Will Be Stripped from the Snapshot
|
||||
|
||||
To root out "deleted MCP servers coming back", switching away from a Codex provider strips the `[mcp_servers]` section from the stored snapshot. If you have an MCP server hand-written directly in a Codex provider config, it will disappear from the snapshot on the first switch-away from that provider — please instead define Codex's MCP servers through the MCP manager (MCP tab), where the entries are authoritative and get projected into the live config automatically.
|
||||
|
||||
### The Dual-Auth-Key Warning May Need a One-Time Manual Rewrite
|
||||
|
||||
If Claude Code still warns "Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set" after upgrading, it's because the takeover logic short-circuits and skips the rewrite when the live config is unchanged. Toggle Claude's route off and on once (or switch providers once) to write the corrected single-placeholder config, and the warning goes away.
|
||||
|
||||
### Automatic Database Migration
|
||||
|
||||
On the first launch of v3.17.0, the database automatically migrates from schema v11 to v13 (adding the projects table and the usage-semantics column), with no manual steps. If you're in the habit of rolling back to an older version, back up `~/.cc-switch/cc-switch.db` first.
|
||||
|
||||
---
|
||||
|
||||
## 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. The "official ChatGPT account proxy route takeover" added in this release is the same class of usage, so please be aware of the same risk.
|
||||
|
||||
**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.17.0:
|
||||
|
||||
- [#5071](https://github.com/farion1231/cc-switch/pull/5071): add the native Anthropic Messages protocol as a Codex upstream, thanks @yeeyzy.
|
||||
- [#4830](https://github.com/farion1231/cc-switch/pull/4830): add Claude subagent model configuration, thanks @AkimioJR.
|
||||
- [#5124](https://github.com/farion1231/cc-switch/pull/5124): add the 1M checkbox to the fallback model field, thanks @salarkhannn.
|
||||
- [#5128](https://github.com/farion1231/cc-switch/pull/5128): add Zhipu team-plan quota queries, thanks @zhanxin-xu.
|
||||
- [#2907](https://github.com/farion1231/cc-switch/pull/2907): add the Headers and token-limit editors to the OpenCode form, thanks @git1677967754.
|
||||
- [#2811](https://github.com/farion1231/cc-switch/pull/2811): auto-sync universal providers after adding, thanks @hubutui.
|
||||
- [#4838](https://github.com/farion1231/cc-switch/pull/4838): upgrade the LongCat presets to LongCat-2.0, thanks @solthx.
|
||||
- [#5095](https://github.com/farion1231/cc-switch/pull/5095): inject only a single auth placeholder on managed Claude takeover, thanks @fengshao1227.
|
||||
- [#5187](https://github.com/farion1231/cc-switch/pull/5187): count Codex subagent session usage in statistics, thanks @starmiaoa.
|
||||
- [#4886](https://github.com/farion1231/cc-switch/pull/4886): fix the Codex free-tier 30-day quota window not showing, thanks @SaladDay.
|
||||
- [#5057](https://github.com/farion1231/cc-switch/pull/5057), [#4927](https://github.com/farion1231/cc-switch/pull/4927), [#2359](https://github.com/farion1231/cc-switch/pull/2359): persist the refresh interval, show renamed session titles, and correct the OpenCode resume command, thanks @makoMakoGo.
|
||||
- [#5206](https://github.com/farion1231/cc-switch/pull/5206): exclude Fable model keys from the common config, thanks @fzh365.
|
||||
- [#5069](https://github.com/farion1231/cc-switch/pull/5069): tool-schema default-type fallback and API Key input restoration, thanks @Komikawayi.
|
||||
- [#4712](https://github.com/farion1231/cc-switch/pull/4712), [#5098](https://github.com/farion1231/cc-switch/pull/5098): sync OpenCode / OpenClaw / Hermes live config on startup, thanks @allenxu09.
|
||||
|
||||
Thanks also to everyone who reported Codex official routing, cache billing, MCP sync, and quota query issues — a good portion of this release's fixes came directly from reproduction clues in these real-world scenarios.
|
||||
|
||||
---
|
||||
|
||||
## 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 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey)+ | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | See table below | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| File | Description |
|
||||
| ---------------------------------------- | ------------------------------------------------ |
|
||||
| `CC-Switch-v3.17.0-Windows.msi` | **Recommended** - MSI installer with auto-update |
|
||||
| `CC-Switch-v3.17.0-Windows-Portable.zip` | Portable build, unzip and run |
|
||||
|
||||
Windows ARM64 devices should pick the artifact whose file name carries the `arm64` tag.
|
||||
|
||||
### macOS
|
||||
|
||||
| File | Description |
|
||||
| -------------------------------- | ----------------------------------------------------- |
|
||||
| `CC-Switch-v3.17.0-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
|
||||
| `CC-Switch-v3.17.0-macOS.zip` | Unzip and drag to Applications, Universal Binary |
|
||||
| `CC-Switch-v3.17.0-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.17.0-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.17.0-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` |
|
||||
</content>
|
||||
</invoke>
|
||||
@@ -0,0 +1,362 @@
|
||||
# CC Switch v3.17.0
|
||||
|
||||
> 本リリースでは、長らく待ち望まれていた**「プロジェクト」のワンクリック切り替え**を追加しました。現在のプロバイダー、MCP、Skills、メモリファイルを名前付きスナップショットとしてまとめて保存し、タイトルバーやトレイから別の構成へ一括で切り替えられます。切り替え時には、離れる側のプロジェクトの現在状態も自動保存されます。Codex 側も大きく進化しました。**公式 ChatGPT サブスクリプションアカウントもローカルプロキシ経由でルーティング**できるようになり、サードパーティプロバイダーと同じルーティング・使用量統計を利用できます。GPT-5.6 ファミリーのコンテキストウィンドウと Sol / Terra / Luna の 3 段階価格にも対応しました。さらに、ネイティブ Anthropic Messages 上流形式を追加——勤務先で Claude Code クライアントは禁止されていても Claude API は禁止されていませんか?これで **Codex の中から Claude 系モデルを直接利用できます**。このほか、上流エラーが「空の応答」になる問題、キャッシュ書き込み token の二重課金、削除した MCP サーバーの復活、Kimi For Coding の 256K ウィンドウが実際には効いていなかった問題など、多数の正確性の問題を修正しました。
|
||||
|
||||
**[English →](v3.17.0-en.md) | [中文版 →](v3.17.0-zh.md)**
|
||||
|
||||
---
|
||||
|
||||
## 利用ガイド
|
||||
|
||||
本リリースの新機能は、主にホーム画面上部のプロジェクト切り替え、Codex プロバイダーフォーム、使用量ダッシュボードにあります。以下のドキュメントもあわせてご覧ください:
|
||||
|
||||
- **[Codex で Kimi を使う(ローカルルーティングガイド)](../guides/codex-kimi-routing-guide-ja.md)**:新しい Codex CLI は OpenAI Responses 形式を使いますが、Kimi Open Platform と Kimi For Coding は Chat Completions endpoint を提供するため、直接接続すると通常は 404 になります。このガイドでは、内蔵の `Kimi` / `Kimi For Coding` プリセットとローカルルーティングを使ったプロトコル変換を説明します。
|
||||
- **[Codex の公式ログインを保持する](../guides/codex-official-auth-preservation-guide-ja.md)**:サードパーティプロバイダーへ切り替える際に、CC Switch が公式 ChatGPT ログインをどう保持するかを説明します。本リリースではさらに、公式アカウント自体をプロキシ経由でルーティングできるようになりました。
|
||||
- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**:使用量ダッシュボードのデータソースと集計方法を確認できます。本リリースではキャッシュ書き込み課金を修正し、Codex サブエージェントの使用量を補完し、GPT-5.6 と Hunyuan Hy3 の価格を追加しました。
|
||||
|
||||
---
|
||||
|
||||
> [!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.17.0 は v3.16.5 に続く大型機能リリースです。中心となるのは**「プロジェクト」**です。Claude Code / Claude Desktop / Codex の現在のプロバイダー、MCP、Skills、メモリファイルを名前付きスナップショットとして保存できます。たとえば、プログラミング用ディレクトリには「開発」、文章作成やイラスト用ディレクトリには「イラスト」という構成を用意し、ホーム上部またはトレイの「プロジェクト」サブメニューからワンクリックで一括切り替えできます。切り替える前には、離れるプロジェクトの現在状態が自動で書き戻されるため、各プロジェクトには最後に離れた時点の構成が常に保持されます。
|
||||
|
||||
もう一つの柱は Codex です。**ChatGPT サブスクリプションでログインした公式アカウントもローカルプロキシでルーティング**できるようになりました。API key は不要で、Codex 自身のログイン情報をそのまま転送し、公式ログインを上書きしません。クライアント識別情報も修正され、`gpt-5.6-luna` など最新のサブスクリプションモデルが誤って 404 になる問題を解消しました。GPT-5.6 の 372K コンテキスト注入、Sol / Terra / Luna の 3 段階価格(キャッシュ書き込みは 1.25 倍)、プリセットの既定モデルも同時に対応しています。さらに Codex の上流形式にネイティブ Anthropic Messages を追加しました。これは、**Claude Code クライアントは禁止していても Claude API は禁止していない企業が多い**という現実的な利用場面を想定したものです。Codex を Claude API、または `/v1/messages` のみを提供するゲートウェイへ接続し、Codex の中で Claude 系モデルを使えます。
|
||||
|
||||
正確性についても、3 つの領域を集中的に改善しました。**プロキシ変換**では、HTTP 2xx 内の上流エラーを空の応答に変換せず failover へ渡し、Responses↔Anthropic 間で reasoning、ツール結果、system role を保持し、プロンプトキャッシュのブレークポイントを強化しました。**使用量と課金**では、キャッシュ書き込み token が入力料金とキャッシュ作成料金の両方で計上されていた問題を修正し、ネットワークの一時障害で使用量キャッシュが壊れないようにしました。**Codex `config.toml`** では、削除した MCP サーバーの復活を防ぎ、解析不能なファイルを同期時に消去しないよう fail-closed にし、共通設定のマージでコメントやキー順序を維持するようにしました。Kimi For Coding の 256K ウィンドウ、Codex サブエージェントと無料プランの使用量表示、Zhipu チームプランのクォータ照会、OpenCode フォームの強化も含まれます。
|
||||
|
||||
**リリース日**: 2026-07-13
|
||||
|
||||
**Stats**: 69 commits | 172 files changed | +21,067 / -2,464 lines
|
||||
|
||||
---
|
||||
|
||||
## ハイライト
|
||||
|
||||
- **「プロジェクト」をワンクリック切り替え**:プロバイダー、MCP、Skills、メモリファイルをまとめて名前付きスナップショットとして保存できます(たとえばプログラミング用と、文章作成・イラスト用)。ホーム上部またはトレイから一括切り替えでき、離れるプロジェクトの現在状態は自動保存されます。Claude Code、Claude Desktop、Codex の各スコープは互いに干渉しません。
|
||||
- **Codex の公式アカウントもプロキシルーティング可能に**:ChatGPT サブスクリプションでログインした Codex セッションをローカルプロキシ経由で扱い、サードパーティプロバイダーと同じルーティング・使用量統計を利用できます。公式ログイン情報は保存も上書きもしません。
|
||||
- **GPT-5.6 に全面対応**:Claude Code の Codex テイクオーバー時に 372K コンテキストを注入し、Sol / Terra / Luna の価格(キャッシュ書き込みは入力価格の 1.25 倍)を追加。プリセットも GPT-5.6 ファミリーへ更新し、クライアント識別修正で `gpt-5.6-luna` の誤った 404 を解消しました。
|
||||
- **Codex で Claude 系モデルを使用(ネイティブ Anthropic Messages 上流)**:Claude Code クライアントは禁止されていても Claude API は禁止されていない企業環境で、Codex の上流形式を `anthropic` に設定すれば Claude API または `/v1/messages` ゲートウェイへ接続できます。ローカルプロキシが Responses↔Anthropic を双方向変換します。
|
||||
- **プロキシ変換の正確性を改善**:上流エラーを空の応答にせず failover へ渡し、reasoning / ツール結果 / system role を保持。キャッシュ書き込みの二重課金も修正しました。
|
||||
- **Codex `config.toml` を堅牢化**:削除済み MCP サーバーの復活を防ぎ、解析エラー時にファイルを消去せず、共通設定マージでコメントとキー順序を保持します。
|
||||
- **Kimi For Coding の 256K が実際に有効に**:以前の 262144 設定は Claude Code の 200K 上限に抑えられていました。本リリースでモデル別名とウィンドウ設定を補完します。既存プロバイダーはプリセットを適用し直してください。
|
||||
|
||||
---
|
||||
|
||||
## 追加機能
|
||||
|
||||
### 「プロジェクト」:構成一式を保存してワンクリック切り替え
|
||||
|
||||
本リリースの中心機能です。現在のプロバイダー、MCP、Skills、メモリファイルを名前付き「プロジェクト」として保存し、ホーム上部のプロジェクト切り替えまたはトレイの「プロジェクト」サブメニューから一括で切り替えられます。項目ごとに手作業で切り替える必要はありません。
|
||||
|
||||
典型的な例を挙げます。あるディレクトリではプログラミングを行い、別のディレクトリでは文章を書いたりイラストを作ったりするとします。プログラミングには専用のプロバイダー、ファイルシステム / GitHub MCP、コードレビュー Skills、開発ルールを書いたメモリファイルが必要です。一方、文章作成やイラストでは別のプロバイダー、別の MCP、まったく異なるプロンプトを使います。以前は作業を移るたびに、プロバイダーを変え、MCP と Skills を一つずつ切り替え、メモリファイルも変更する必要がありました。今後は 2 つの構成を「開発」と「イラスト」というプロジェクトに保存し、作業ディレクトリを変えるときに **CC Switch で一度クリックするだけ**で構成一式を切り替えられます。ディレクトリに応じて自動切り替えする機能ではなく、ユーザーが明示的に選ぶ仕組みです。
|
||||
|
||||
設計上のポイント:
|
||||
|
||||
- **プロジェクトは共有、切り替えはスコープ別**:同じプロジェクトでも Claude Code / Claude Desktop / Codex はそれぞれ独立した現在位置とスナップショットを持ちます。Codex タブで切り替えても Claude の設定には触れません。
|
||||
- **切り替え時に自動保存**:新しいプロジェクトへ移る前に、離れるプロジェクトの現在状態をそのスコープへ自動で書き戻します。このため手動の「現在状態で更新」ボタンは不要です。
|
||||
- **適用はベストエフォート**:既存の切り替え処理を再利用し、プロバイダー、MCP / Skills の差分、メモリファイルの順に適用します。削除済み項目への参照は警告してスキップし、全体をロールバックしません。
|
||||
- **プロキシテイクオーバーを自動解除**:スナップショットを適用する前に対象スコープのテイクオーバーを無効化し、ルーティング状態との競合を避けます。
|
||||
|
||||
プロジェクトを使わない場合は、「設定 → ホームページ表示」の「プロジェクト切り替えを表示」をオフにできます。ホームの入口だけが非表示になり、トレイのサブメニューやプロジェクトデータはそのまま利用できます。新しい `profiles` テーブルへのデータベース移行は自動です。
|
||||
|
||||
### Codex 公式 ChatGPT アカウントのプロキシルーティング
|
||||
|
||||
ChatGPT サブスクリプション(OAuth または API-key ログイン)で使う Codex セッションを、CC Switch のローカルプロキシ経由でルーティングできるようになりました。サードパーティプロバイダーと同じルーティング、形式変換、使用量統計を利用できます。プロバイダーパネルまたはトレイで内蔵の「OpenAI Official」を選択してください。削除済みの場合は、プロバイダー追加時に自動復元されます。
|
||||
|
||||
実装では**認証情報を保存しない**ことを重視しています。`auth.json` にダミーの API key を書かず、ローカルプロキシを指す専用 `model_provider` を `config.toml` へ投影します。Codex 自身の ChatGPT Authorization header をプロキシが公式 endpoint へそのまま転送し、`codex-official` 行の認証情報は常に空です。テイクオーバー時も OAuth / API-key 情報をバックアップへ保持します。公式 endpoint の 401 / 403 は再試行不能として扱い、failover が別アカウントへ会話を移したり circuit breaker を汚したりしません。「切り替え時に Codex 公式ログインを保持」設定は、今後、ルーティングを使わないサードパーティへの直接切り替えだけを制御します。
|
||||
|
||||
### GPT-5.6:コンテキスト、プリセット、3 段階価格
|
||||
|
||||
- **372K コンテキスト注入**:Claude Code を ChatGPT Codex(Codex OAuth)へルーティングすると、`CLAUDE_CODE_MAX_CONTEXT_TOKENS` と `CLAUDE_CODE_AUTO_COMPACT_WINDOW` を 372000 で注入します。全設定モデルが GPT-5.6 ファミリーの場合だけ適用し、GPT-5.5 や混在マッピングには適用しません。ユーザーの明示設定が常に優先され、切り替え後に既定値が保存設定へ固着しないよう逆変換で除去します。
|
||||
- **プリセット更新**:Claude Code / Claude Desktop の Codex OAuth プリセットを GPT-5.6 ファミリーへ更新(haiku → `gpt-5.6-luna`、main / sonnet / opus → `gpt-5.6`)。Codex `config.toml` テンプレートも更新しました。
|
||||
- **Sol / Terra / Luna 価格**:100 万 token あたりの入力 / 出力 / キャッシュ読み取りを、Sol 5 / 30 / 0.50、Terra 2.50 / 15 / 0.25、Luna 1 / 6 / 0.10 USD で登録。GPT-5.6 のキャッシュ書き込みは入力の 1.25 倍(6.25 / 3.125 / 1.25)で、既存データベースの誤ったゼロ値も安全に修復します。
|
||||
|
||||
### Codex で Claude 系モデルを使う:ネイティブ Anthropic Messages 上流
|
||||
|
||||
この機能は、**Claude Code クライアントを禁止していても Claude API は禁止していない企業が多い**という現実的な要望から生まれました。モデルは利用できるのに、許可されたクライアントがない——その空白を Codex で埋められます。Codex プロバイダーの上流形式で `anthropic` を選ぶと、Claude API またはネイティブ Anthropic Messages(`/v1/messages`)のみを提供するゲートウェイへ接続できます。ローカルプロキシが Responses↔Anthropic のリクエスト、応答、ストリームを双方向変換するため、Codex の操作感のまま Claude 系モデルとの対話やツール利用が可能です。
|
||||
|
||||
フォームには、認証フィールド選択(既定の `ANTHROPIC_AUTH_TOKEN` は `Authorization: Bearer`、`ANTHROPIC_API_KEY` は `x-api-key`)、任意の Claude Code クライアント偽装(既定オフ)、プロバイダー別 `maxOutputTokens` を追加しました。変換ブリッジは system、tools、history に標準 5 分の `cache_control` を注入し、`[1m]` 長コンテキストマーカーと beta header に対応します。途中で切れたストリームは成功として偽装せず、未完了 / 失敗として報告します。([#5071](https://github.com/farion1231/cc-switch/pull/5071))
|
||||
|
||||
### Codex プロバイダーフォームに「既定モデル」欄を追加
|
||||
|
||||
`config.toml` トップレベルの `model` をフォームから編集できます。新モデル(例:`gpt-5.6`)が公開されたとき、プリセット更新を待たずに既存プロバイダーを切り替えられます。TOML エディターと双方向同期し、モデルマッピングと `/models` endpoint の候補を表示します。明示値はマッピング先頭行より常に優先され、remote の model id を書き込む際は TOML エスケープと制御文字除去を行います。
|
||||
|
||||
### Codex でも切り替え時に共通設定を自動同期
|
||||
|
||||
v3.16.5 で Claude に追加した live 設定から共通設定への自動書き戻しを Codex にも拡張しました。共通設定を有効にした Codex プロバイダーから離れるとき、live `config.toml` の共有可能な部分を再抽出し、次のプロバイダーへ渡します。`model` / `model_provider` / `base_url` / `wire_api`、`[model_providers]`、MCP 投影、API key、モデルカタログ、CC Switch が注入した `web_search` は除外されるため、プロバイダー固有情報や秘密情報は共有されません。失敗は警告のみで切り替えを妨げません。
|
||||
|
||||
### Claude サブエージェントモデル設定
|
||||
|
||||
Claude プロバイダーフォームに「サブエージェント」モデル行を追加し、`CLAUDE_CODE_SUBAGENT_MODEL` を設定できるようにしました。サブエージェントを安価または高速なモデルへ固定でき、`[1M]` マーカーにも対応します。プロキシテイクオーバーとモデルマッパーもこの設定を認識し、共通設定からは除外されるため他プロバイダーへ漏れません。([#4830](https://github.com/farion1231/cc-switch/pull/4830))
|
||||
|
||||
### フォールバックモデルにも 1M チェックボックス
|
||||
|
||||
Claude フォームのフォールバックモデル(`ANTHROPIC_MODEL`)に、Sonnet / Opus / Fable と同じ 1M チェックボックスを追加しました。チェックすると model id に `[1M]` が付き、解除すると除去されます。([#5124](https://github.com/farion1231/cc-switch/pull/5124)、#3679 を修正)
|
||||
|
||||
### Zhipu チームプランのクォータ照会
|
||||
|
||||
使用量スクリプトに「Zhipu GLM Team(智谱团队)」テンプレートを追加しました。API Key、組織 ID、プロジェクト ID を入力すると、`?type=2` と必要な request headers を使ってチームプランのクォータを照会します。3 項目のいずれかが欠けている場合は補完を案内します。([#5128](https://github.com/farion1231/cc-switch/pull/5128))
|
||||
|
||||
### OpenCode フォーム:Headers とモデル別 Token 上限
|
||||
|
||||
OpenCode プロバイダーフォームに、`options.headers`(`HTTP-Referer` / `X-Title` など)と、モデル別の Context / Output token 上限(`model.limit.context` / `model.limit.output`)の編集 UI を追加しました。「Extra Options」は折りたたみ式になり、既存値があれば自動展開します。旧 draft prefix のため正当な `option-` で始まるキーが消える問題も修正しました。([#2907](https://github.com/farion1231/cc-switch/pull/2907))
|
||||
|
||||
### Tencent Hunyuan Hy3 の価格
|
||||
|
||||
2026-07-06 公開の Hunyuan Hy3(256K context)に価格を追加し、使用量が $0 と表示されないようにしました。`hunyuan-hy3` と `hy3` の両方を登録しています。実際の Hy3 は入力長で段階課金されますが、現在の単一価格テーブルでは最安段階を使用するため、長コンテキストでは費用を過小評価する可能性があります。
|
||||
|
||||
---
|
||||
|
||||
## 変更
|
||||
|
||||
### Codex Chat に `prompt_cache_key` を供給
|
||||
|
||||
Responses→Chat Completions 変換で、プロバイダーを考慮した `prompt_cache_key` を注入します。Kimi Coding と OpenAI 公式 endpoint は自動有効、Kimi プリセットは明示的に有効、未知の互換ゲートウェイは schema 400 を避けるため無効のままです。値はクライアントの明示値または実際の session ID だけを使い、リクエストごとのランダム UUID は生成しません。高度な設定で Auto / Enabled / Disabled を選べます。
|
||||
|
||||
### Codex の画像対応を自動推定
|
||||
|
||||
生成した Codex モデルカタログは、CC Switch が確認済みの**完全一致 text-only リスト**にあるモデルだけを `["text"]` として宣言します。GPT、alias、新しい suffix、未知のモデルは `["text", "image"]` へ fail-open します。これにより GPT 系モデルが Codex IDE で「画像非対応」と誤表示される問題を解消しました。整流器の text-only preflight は代理側の本文処理だけを制御し、カタログ宣言には影響しません。
|
||||
|
||||
### コンテキスト値をフォームではなくプリセットへ固定
|
||||
|
||||
`Codex`(ChatGPT / GPT-5.6)と `Kimi For Coding` の「Max Context Tokens」「Auto Compact Window」をフォームから外し、プリセット env に固定しました(Codex は 372000 / 372000、Kimi For Coding は 262144 / 262144)。遠隔実験でローカルの圧縮点が引き下げられないよう、2 つの env key 自体は意図的に残しています。必要な場合はプロバイダーの JSON エディターから直接編集できます。
|
||||
|
||||
### プロバイダー接続確認を簡素化
|
||||
|
||||
古いプロバイダー別 `testConfig`(timeout、retry、degraded latency)を削除し、軽量 `base_url` probe はグローバル設定だけを使うようにしました。自動 failover は引き続き独立した proxy timeout と circuit breaker 設定で動作します。「model test」関連の UI / API 名も「connectivity check」へ統一しました。
|
||||
|
||||
### Universal Provider を追加後すぐ live 設定へ同期
|
||||
|
||||
複数アプリ向け Universal Provider を追加すると、DB 保存後に Claude / Codex / Gemini 等の live 設定へすぐ同期します。同期に失敗しても保存は取り消さず、非ブロッキング警告を表示します。([#2811](https://github.com/farion1231/cc-switch/pull/2811))
|
||||
|
||||
### プリセット更新
|
||||
|
||||
- **LongCat-2.0**:Claude Code / Claude Desktop / Codex / Hermes / OpenClaw / OpenCode の既定モデルを廃止済みの名称から `LongCat-2.0` へ更新し、実際の 1M context を宣言しました。text-only モデルとして media sanitizer にも追加し、画像は上流で 400 になる前に非対応マーカーへ置換します。([#4838](https://github.com/farion1231/cc-switch/pull/4838))
|
||||
- **SudoCode**:旧 `sudocode.us` プリセットを新しいスポンサー SudoCode(`sudocode.chat`)へ置き換え、6 クライアントをカバーします。Codex / OpenCode / OpenClaw / Hermes の既定は `gpt-5.6-sol` です。
|
||||
- **火山 / Doubao / BytePlus**:v3.16.5 で製品ページへ変更した `websiteUrl` を、帰属パラメータ付きのキャンペーン / 招待リンクへ戻しました。これは意図された設定です。
|
||||
- **Code0.ai**:招待リンクを新しい agent 登録 URL へ更新。API endpoint は変更していません。
|
||||
- **重複した OpenAI Compatible プリセットを削除**:OpenCode / OpenClaw では内蔵 `custom` フローが同じ初期設定を提供するため、重複エントリだけを削除しました。既存プロバイダーには影響しません。
|
||||
|
||||
---
|
||||
|
||||
## 修正
|
||||
|
||||
### Codex OAuth のクライアント識別を修正し最新モデルの 404 を解消
|
||||
|
||||
公式 Codex OAuth をローカルプロキシで使うと、権限がある `gpt-5.6-luna` が `404 Model not found` になることがありました。ChatGPT Codex backend が `originator` + `version` の組み合わせで model cohort を選ぶ一方、CC Switch は `originator: cc-switch` かつ version なしで送っていたことが原因です。現在は実際の Codex CLI と同じ `originator: codex_cli_rs` + `version: 0.144.1` を送り、luna の最低バージョン要件を満たします。実 endpoint への A/B テストでも修正を確認しました。
|
||||
|
||||
### Responses 上流エラーを空の応答にしない
|
||||
|
||||
Anthropic クライアントを Responses 上流へつなぐ際、HTTP 2xx body 内の `{status:"failed"}`、error envelope、出力前の `response.failed` SSE event が空の `end_turn` に変換されていました。現在は retry loop 内で実エラーとして検出し、failover が別プロバイダーを選べます。途中終了した stream は不完全または切断エラーとして報告し、`stream:true` を無視して JSON 全体を返す gateway にも対応します。不正なクライアント履歴は再試行不能エラーとして即座に返します。
|
||||
|
||||
### Responses / Anthropic 間で reasoning・ツール結果・system role を保持
|
||||
|
||||
暗号化 reasoning を署名付き thinking block として往復し、公式 reasoning stream events、欠落 delta の tool arguments、`is_error`、画像、PDF / `input_file` を保持します。履歴中の `system` / `developer` message は user 発言へ降格せず Anthropic `system` へ移します。上流リクエストが成功した後に変換エラーとなった場合も使用量を記録します。
|
||||
|
||||
### キャッシュ書き込み token の二重課金を修正
|
||||
|
||||
Codex / Gemini の `input_tokens` は cache read と cache write を含みますが、以前は read だけを差し引いたため、write token が入力料金と cache creation 料金の両方で計上されていました。現在は両方を差し引き、Chat↔Responses↔Anthropic の変換でも cache write 値を保持します。schema v13 の `input_token_semantics` により、既存行は旧方式、新規行は新方式で安全に計算します。
|
||||
|
||||
### プロンプトキャッシュのブレークポイント注入を強化
|
||||
|
||||
ツール末尾、system 末尾、最新の cacheable message に加え、予算があれば古い user message にも anchor を追加します。長い tool-heavy 会話でも安定 prefix が Anthropic の 20-block lookback 内に残ります。呼び出し側が付けた breakpoint は削除・並べ替え・書き換えせず、4 個を超えている場合は警告して自動注入しません。注入 TTL は標準の 5 分です。
|
||||
|
||||
### Kimi For Coding の 256K context を実際に有効化
|
||||
|
||||
`CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144` だけでは、未知の非 Claude model を Claude Code が 200K とみなすため 200K に抑えられていました。本リリースは `CLAUDE_CODE_MAX_CONTEXT_TOKENS` を追加し、すべての model tier を `kimi-for-coding` alias へ明示的にルーティングします。既存プロバイダーには window 値を live 設定へ注入しますが、alias は新プリセットにのみ含まれるため、旧プリセット利用者は適用し直す必要があります。
|
||||
|
||||
### 削除した Codex MCP サーバーが復活しないように
|
||||
|
||||
Codex live `config.toml` の `[mcp_servers]` は DB の投影ですが、切り替え時にプロバイダースナップショットへ保存されていたため、アプリで削除したサーバーが次回有効化時に復活していました。切り替え時に `[mcp_servers]` と旧 `[mcp.servers]` を保存設定から除去し、汚染済みスナップショットも次回切り替えで自己修復します。手書きの `[mcp_servers.*]` も除去対象になるため、今後は MCP 管理画面を使用してください。
|
||||
|
||||
### MCP 同期:解析エラー時にファイルを消去せず、アプリ別に失敗を報告
|
||||
|
||||
Codex `config.toml` が解析不能な状態で MCP を 1 件同期すると、以前は空の TOML へフォールバックしてファイル全体を上書きし、その MCP だけを残していました。現在は検証エラーを返し、元ファイルを変更しません。全アプリからのインポートも失敗を 0 件として隠さず、成功分を取り込んだうえで失敗したアプリ名をまとめて報告します。切り替え・保存時の投影は対象アプリだけに限定し、他アプリの破損に巻き込まれません。
|
||||
|
||||
### Codex 共通設定マージでコメントとキー順序を保持
|
||||
|
||||
フロントエンドの TOML parse → merge → stringify は、コメントを削除し、キーを並べ替え、空の table header を作っていました。マージを backend の `toml_edit` ベース処理へ移し、フォームプレビューと live 書き込みで同じ意味論を使うようにしました。非同期化に伴う race も operation sequence と config baseline の 2 段階で防ぎます。
|
||||
|
||||
### 管理下 Claude テイクオーバーでは auth placeholder を 1 つだけ注入
|
||||
|
||||
Codex 管理プロバイダーへ切り替えると `ANTHROPIC_API_KEY` と `ANTHROPIC_AUTH_TOKEN` の両方が `PROXY_MANAGED` になり、Claude Code が毎回警告していました。現在は Codex で `ANTHROPIC_AUTH_TOKEN`、Copilot で `ANTHROPIC_API_KEY` の 1 つだけを使います。既存の二重設定は短絡処理で自動書き換えされない場合があるため、Claude ルーティングを一度オフ / オンするか、プロバイダーを切り替えてください。([#5095](https://github.com/farion1231/cc-switch/pull/5095)、#4919 を修正)
|
||||
|
||||
### 使用量・クォータ照会の一時障害を再試行し、キャッシュを汚さない
|
||||
|
||||
通信失敗や body 読み取り timeout が `success:false` の正常結果として扱われ、再試行されず、失敗データが cache に保存されていました。現在は一時的な transport error、HTTP 429、5xx をエラーとして返し、react-query の retry を有効にします。最後の正常値は 10 分の保持期間に従い、失敗時も footer に retry 操作と実エラーを表示します。([#3820](https://github.com/farion1231/cc-switch/issues/3820))
|
||||
|
||||
### Codex サブエージェントの使用量をローカル統計へ追加
|
||||
|
||||
サブエージェントログは親 thread の `session_id` を持つため、複数サブエージェントの request ID が衝突し重複として破棄されていました。各ファイルの `thread_id` を優先して一意な ID を作り、ログ冒頭の親履歴 replay は累積 baseline の復元だけに使って二重計上を防ぎます。archive 後も元ファイルの cursor を継承します。([#5187](https://github.com/farion1231/cc-switch/pull/5187))
|
||||
|
||||
### Codex 無料プランの 30 日クォータを footer とトレイに表示
|
||||
|
||||
無料アカウントの `30_day` window が UI whitelist と tray grouping に含まれず、唯一の tier が消えてクォータ表示全体が空になっていました。30 日 tier を単一の定数で backend / tray / frontend に追加し、4 言語のラベルを用意しました。([#4886](https://github.com/farion1231/cc-switch/pull/4886)、#3651 を修正)
|
||||
|
||||
### 使用量ダッシュボードの更新間隔を永続化
|
||||
|
||||
自動更新の off / 5s / 10s / 30s / 60s 選択をアプリ設定へ保存し、再起動後も維持します。変更は即時反映し、保存失敗時は元の値へ戻します。([#5057](https://github.com/farion1231/cc-switch/pull/5057))
|
||||
|
||||
### Fable model key を Claude 共通設定から除外
|
||||
|
||||
`ANTHROPIC_DEFAULT_FABLE_MODEL` / `_NAME` が除外リストから漏れ、あるプロバイダーの Fable mapping が共通設定経由で他へ流れる可能性がありました。Haiku / Sonnet / Opus と同様に除外し、Fable の proxy takeover role alias も補完しました。([#5206](https://github.com/farion1231/cc-switch/pull/5206)、#4272 を修正)
|
||||
|
||||
### tool schema の既定 `type` と未分類プロバイダーの API Key 欄
|
||||
|
||||
Anthropic tool の root `input_schema` に `type` がない場合、厳格な OpenAI gateway が変換後の schema を拒否していました。root にだけ `type: "object"` を補い、nested schema は変更しません。また、過去にインポートした category なしのカスタムプロバイダーを編集すると API Key 欄が隠れる問題を修正しました。([#5069](https://github.com/farion1231/cc-switch/pull/5069))
|
||||
|
||||
### Volcano GLM 5.2 の text-only 画像 400 を回避
|
||||
|
||||
GLM 5.2 を完全一致の text-only model として登録し、画像 block を上流送信前に置換します。将来の multimodal `glm-5.2v` を誤判定しないよう prefix match は使いません。`Model only support text input` という image の語を含まないエラーも reactive fallback で認識します。([#5025](https://github.com/farion1231/cc-switch/issues/5025))
|
||||
|
||||
### セッションと live 設定の小修正
|
||||
|
||||
- **Codex で変更したセッションタイトルを表示**:`session_index.jsonl` / `state_5.sqlite` の保存タイトルを優先し、同時書き込み時は busy timeout を使います。([#4927](https://github.com/farion1231/cc-switch/pull/4927))
|
||||
- **OpenCode / OpenClaw / Hermes の live 編集を起動時に DB へ同期**:base URL や model を直接変更した場合も、毎回の起動で差分を取り込みます。([#4712](https://github.com/farion1231/cc-switch/pull/4712)、[#5098](https://github.com/farion1231/cc-switch/pull/5098))
|
||||
- **OpenCode の再開コマンドを更新**:`opencode session resume <id>` を現在の `opencode -s <id>` へ修正しました。([#2359](https://github.com/farion1231/cc-switch/pull/2359))
|
||||
- **公式プロバイダーの接続 probe をスキップ**:認証情報なしでは必ず失敗する公式 endpoint を batch connectivity check で probe しません。
|
||||
|
||||
---
|
||||
|
||||
## ドキュメント
|
||||
|
||||
### Codex + Kimi ローカルルーティングガイド
|
||||
|
||||
Kimi を Codex CLI で使うための手順を、中国語 / 英語 / 日本語とスクリーンショット付きで追加しました。Codex は Responses、Kimi Open Platform(`kimi-k2.7-code`)と Kimi For Coding(`kimi-for-coding`)は Chat Completions を使うため、内蔵プリセットから追加し、CC Switch のローカルルーティングで双方向変換する流れを説明します。
|
||||
|
||||
### README のスポンサー欄を更新
|
||||
|
||||
オープンソース AI インフラプロジェクト `new-api` を 4 言語 README のスポンサー表へ追加しました。
|
||||
|
||||
---
|
||||
|
||||
## アップグレード時の注意
|
||||
|
||||
### Kimi For Coding プロバイダーはプリセットを適用し直してください
|
||||
|
||||
Kimi For Coding を使用している場合は、**新しいプリセットを選び直して保存**してください。256K を有効にする鍵である `kimi-for-coding` alias への各 model tier のルーティングは新プリセットにのみ含まれます。旧プリセットのままでは、アップグレード後も実際のウィンドウは 200K です。
|
||||
|
||||
### 手書きの Codex `[mcp_servers.*]` はスナップショットから除去されます
|
||||
|
||||
削除済み MCP サーバーの復活を防ぐため、Codex プロバイダーから切り替えるとき `[mcp_servers]` を保存スナップショットから除去します。手書きした MCP 定義も初回切り替え時に消えるため、今後は MCP 管理画面で定義してください。DB の `mcp_servers` が正本となり、live config へ自動投影されます。
|
||||
|
||||
### auth 二重キー警告は一度手動で書き換えを発火させる必要があります
|
||||
|
||||
アップグレード後も Claude Code が「Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set」と警告する場合は、live config が一致しているとテイクオーバー処理が書き換えを省略するためです。Claude ルーティングを一度オフにしてからオンに戻すか、プロバイダーを一度切り替えると、単一 placeholder に修正されます。
|
||||
|
||||
### データベースは自動移行されます
|
||||
|
||||
v3.17.0 の初回起動時に schema v11 から v13(プロジェクトテーブルと input token semantics)へ自動移行します。手動操作は不要です。古いバージョンへ戻す可能性がある場合は、先に `~/.cc-switch/cc-switch.db` をバックアップしてください。
|
||||
|
||||
---
|
||||
|
||||
## リスク通知
|
||||
|
||||
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
|
||||
|
||||
**Codex OAuth リバースプロキシ**:ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#️-リスクに関する注意事項) を参照してください。本リリースで追加した「公式 ChatGPT アカウントのプロキシルーティング」も同じ種類の利用方法であり、同様のリスクがあります。
|
||||
|
||||
**Codex サードパーティプロバイダー Chat ルーティング**:CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金・コンプライアンス・データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
|
||||
|
||||
**Claude Desktop サードパーティプロバイダープロキシ切り替え**:CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金・コンプライアンス・データ保持に関する規約に従う必要があります。
|
||||
|
||||
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
|
||||
|
||||
---
|
||||
|
||||
## 謝辞
|
||||
|
||||
v3.17.0 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
|
||||
|
||||
- [#5071](https://github.com/farion1231/cc-switch/pull/5071):Codex の上流としてネイティブ Anthropic Messages protocol を追加、@yeeyzy に感謝。
|
||||
- [#4830](https://github.com/farion1231/cc-switch/pull/4830):Claude サブエージェントモデル設定を追加、@AkimioJR に感謝。
|
||||
- [#5124](https://github.com/farion1231/cc-switch/pull/5124):フォールバックモデルに 1M チェックボックスを追加、@salarkhannn に感謝。
|
||||
- [#5128](https://github.com/farion1231/cc-switch/pull/5128):Zhipu チームプランのクォータ照会を追加、@zhanxin-xu に感謝。
|
||||
- [#2907](https://github.com/farion1231/cc-switch/pull/2907):OpenCode フォームに headers と token 上限編集を追加、@git1677967754 に感謝。
|
||||
- [#2811](https://github.com/farion1231/cc-switch/pull/2811):Universal Provider の追加後自動同期、@hubutui に感謝。
|
||||
- [#4838](https://github.com/farion1231/cc-switch/pull/4838):LongCat プリセットを LongCat-2.0 へ更新、@solthx に感謝。
|
||||
- [#5095](https://github.com/farion1231/cc-switch/pull/5095):管理下 Claude テイクオーバーの auth placeholder を 1 つに修正、@fengshao1227 に感謝。
|
||||
- [#5187](https://github.com/farion1231/cc-switch/pull/5187):Codex サブエージェントの使用量統計を修正、@starmiaoa に感謝。
|
||||
- [#4886](https://github.com/farion1231/cc-switch/pull/4886):Codex 無料プランの 30 日クォータ表示を修正、@SaladDay に感謝。
|
||||
- [#5057](https://github.com/farion1231/cc-switch/pull/5057)、[#4927](https://github.com/farion1231/cc-switch/pull/4927)、[#2359](https://github.com/farion1231/cc-switch/pull/2359):更新間隔の永続化、変更済みセッションタイトル表示、OpenCode 再開コマンド修正、@makoMakoGo に感謝。
|
||||
- [#5206](https://github.com/farion1231/cc-switch/pull/5206):Fable model key を共通設定から除外、@fzh365 に感謝。
|
||||
- [#5069](https://github.com/farion1231/cc-switch/pull/5069):tool schema の既定 type と API Key 欄を修正、@Komikawayi に感謝。
|
||||
- [#4712](https://github.com/farion1231/cc-switch/pull/4712)、[#5098](https://github.com/farion1231/cc-switch/pull/5098):OpenCode / OpenClaw / Hermes の live 設定同期、@allenxu09 に感謝。
|
||||
|
||||
Codex 公式ルーティング、キャッシュ課金、MCP 同期、クォータ照会について報告してくださったすべてのユーザーにも感謝します。本リリースの多くの修正は、実際の利用場面から得られた再現情報をもとにしています。
|
||||
|
||||
---
|
||||
|
||||
## ダウンロードとインストール
|
||||
|
||||
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から、お使いのシステムに対応するビルドをダウンロードしてください。
|
||||
|
||||
### システム要件
|
||||
|
||||
| システム | 最低バージョン | アーキテクチャ |
|
||||
| -------- | ------------------------ | ----------------------------------- |
|
||||
| Windows | Windows 10 以降 | x64 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 下表を参照 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| ファイル | 説明 |
|
||||
| ---------------------------------------- | -------------------------------------------- |
|
||||
| `CC-Switch-v3.17.0-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
|
||||
| `CC-Switch-v3.17.0-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
|
||||
|
||||
Windows ARM64 デバイスでは、ファイル名に `arm64` が含まれる対応する成果物を選択してください。
|
||||
|
||||
### macOS
|
||||
|
||||
| ファイル | 説明 |
|
||||
| -------------------------------- | ------------------------------------------------------ |
|
||||
| `CC-Switch-v3.17.0-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
|
||||
| `CC-Switch-v3.17.0-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
|
||||
| `CC-Switch-v3.17.0-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.17.0-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.17.0-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,362 @@
|
||||
# CC Switch v3.17.0
|
||||
|
||||
> 这一版带来一个盼了很久的能力:**「项目」一键切换**——把当前的供应商、MCP、Skills、记忆文件整套保存为命名快照,在标题栏或托盘里一键换成另一套,切换时还会自动把你离开的项目当前状态存回去。Codex 侧同样收获颇丰:**官方 ChatGPT 订阅账号现在也能走本地代理路由**,享受与第三方供应商相同的路由与用量统计;GPT-5.6 全家的上下文窗口与 Sol / Terra / Luna 三档定价一步到位;还新增了原生 Anthropic Messages 上游格式——所在企业禁用了 Claude Code、但没有禁用 Claude API?现在可以**在 Codex 里直接用上 Claude 系列模型**。此外是一大波正确性修复:上游失败不再变成「空回复」、缓存写入不再被双重计费、删掉的 MCP 服务器不再复活、Kimi For Coding 的 256K 窗口终于真正生效。
|
||||
|
||||
**[English →](v3.17.0-en.md) | [日本語版 →](v3.17.0-ja.md)**
|
||||
|
||||
---
|
||||
|
||||
## 使用攻略
|
||||
|
||||
本版的新能力主要落在主页顶部的项目切换器、Codex 供应商表单与用量看板里,建议结合以下文档了解:
|
||||
|
||||
- **[在 Codex 里使用 Kimi(本地路由攻略)](../guides/codex-kimi-routing-guide-zh.md)**:本版新增的分步攻略。较新的 Codex CLI 走 OpenAI Responses 协议,而 Kimi 开放平台与 Kimi For Coding 暴露的是 Chat Completions 端点,直连通常 404;攻略讲解如何用内置的 `Kimi` / `Kimi For Coding` 预设配合本地路由完成协议转换。
|
||||
- **[Codex 官方登录保留](../guides/codex-official-auth-preservation-guide-zh.md)**:了解 CC Switch 如何在切换第三方供应商时保留你的官方 ChatGPT 登录。本版在此基础上更进一步——官方账号本身也可以走代理路由(见下方「新功能」)。
|
||||
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源与统计口径。本版修正了缓存写入计费、补齐了 Codex 子代理会话统计,并新增 GPT-5.6 与混元 Hy3 定价。
|
||||
|
||||
---
|
||||
|
||||
> [!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.17.0 是 v3.16.5 之后的一个功能大版本,核心是**「项目」**:你可以把 Claude Code / Claude Desktop / Codex 当前的供应商、MCP、Skills、记忆文件状态保存为命名快照——比如编程目录一套「开发」、写作绘图目录一套「创作」——在主页顶部的切换器或托盘的「项目」子菜单里一键整套切换——切换前会自动把你正要离开的项目状态存回去,所以项目里保存的永远是你上次离开时的样子。第二条主线是 Codex:**官方 ChatGPT 订阅账号现在也能走本地代理路由接管**(不需要 API Key,Codex 自己的登录凭据原样透传,绝不覆盖你的官方登录);配合修正后的客户端身份,`gpt-5.6-luna` 这类最新订阅模型不再误报 404;GPT-5.6 的 372K 上下文窗口注入、Sol / Terra / Luna 三档定价(含 1.25 倍缓存写入费率)与预设默认模型同步就位;Codex 上游格式还新增了原生 Anthropic Messages 协议——它瞄准一个很现实的场景:不少企业禁用了 Claude Code 客户端、但并没有禁用 Claude API,这些用户现在可以让 Codex 直连 Claude API(或任何只提供 `/v1/messages` 的网关),在 Codex 里照常使用 Claude 系列模型。
|
||||
|
||||
围绕日常使用的正确性,本版做了三波集中修复。**代理桥**:上游在 2xx 里返回的语义失败不再被转成空回复,而是触发 failover;推理内容、工具结果、system 角色跨 Responses↔Anthropic 桥无损往返;提示缓存断点注入更充分,长对话不再每轮全价重发。**用量计费**:缓存写入 token 此前被同时按输入价和缓存创建价双重计费,现已修正(数据库升级到 schema v13 以保证历史数据口径不乱);用量与配额查询遇到网络瞬时失败会自动重试、不再把失败体当真实数据缓存。**Codex `config.toml`**:在应用里删掉的 MCP 服务器不再随供应商切换复活;live 文件解析失败时同步宁可报错也不再清空整个文件;「使用通用配置」的合并挪到后端执行,注释与键序不再被打乱。另有 Kimi For Coding 256K 窗口真正生效、Codex 子代理与免费版配额统计补齐、智谱团队套餐配额查询、OpenCode 表单增强与一批预设更新。
|
||||
|
||||
**发布日期**:2026-07-13
|
||||
|
||||
**更新规模**:69 commits | 172 files changed | +21,067 / -2,464 lines
|
||||
|
||||
---
|
||||
|
||||
## 重点内容
|
||||
|
||||
- **「项目」一键切换**:把供应商、MCP、Skills、记忆文件整套保存为命名快照(比如编程一套、写作绘图一套),从主页顶部或托盘一键切换;切换时自动保存离开项目的当前状态。覆盖 Claude Code、Claude Desktop、Codex 三个作用域,互不干扰。
|
||||
- **Codex 官方账号也能走代理路由**:ChatGPT 订阅登录的 Codex 会话可通过本地代理路由,获得与第三方供应商一致的路由与用量统计;官方登录凭据绝不被覆盖或存储。
|
||||
- **GPT-5.6 全面就位**:Claude Code 走 Codex 接管时自动注入 372K 上下文窗口;Sol / Terra / Luna 三档定价入库(缓存写入按 1.25 倍输入价计费);相关预设默认模型升级到 gpt-5.6 家族;修正客户端身份后 `gpt-5.6-luna` 不再误报 404。
|
||||
- **在 Codex 里使用 Claude 系列模型(原生 Anthropic Messages 上游)**:不少企业禁用了 Claude Code 客户端、但没有禁用 Claude API——现在把 Codex 供应商的上游格式选为 `anthropic`,即可直连 Claude API 或任何只提供 `/v1/messages` 的网关,本地代理完成 Responses↔Anthropic 双向转换,自带标准 5 分钟提示缓存注入。
|
||||
- **代理桥正确性修复**:上游失败 fail-closed 触发 failover 而非空回复;推理 / 工具结果 / system 角色跨桥无损;缓存写入不再双重计费;断点注入更充分。
|
||||
- **Codex config.toml 加固**:删掉的 MCP 服务器不再复活;解析失败时 MCP 同步宁可报错也不清空文件;通用配置合并保留注释与键序。
|
||||
- **Kimi For Coding 256K 真正生效**:此前的 262144 压缩窗口从未实际生效(被 Claude Code 的 200K 默认钳回),本版补齐模型别名路由与窗口注入;存量供应商需重新套用预设(见「升级提醒」)。
|
||||
|
||||
---
|
||||
|
||||
## 新功能
|
||||
|
||||
### 「项目」:整套配置的命名快照与一键切换
|
||||
|
||||
这是本版的头号功能。你可以把当前的供应商、MCP、Skills、记忆文件状态保存为一个命名「项目」,之后在主页顶部的项目切换器或托盘的「项目」子菜单里一键整套切换,不必再逐项手动勾选。
|
||||
|
||||
举个典型场景:你有一个目录用来编程、另一个目录用来写作或绘图。编程时要的是一套供应商,配上文件系统 / GitHub 这类 MCP、代码审查 Skills 和写着工程约定的记忆文件;写作或绘图时往往换另一家供应商、另一组 MCP 和完全不同的提示词。以前在两件事之间来回,意味着切供应商、逐个开关 MCP 和 Skills、再改记忆文件;现在把两套状态分别存成「开发」和「绘图」两个项目,换目录干活时在 CC Switch 里点一下,整套配置随之就位。
|
||||
|
||||
项目功能覆盖 Claude Code、Claude Desktop 与 Codex 三个作用域(Claude Desktop 由 CC Switch 管理的维度只有供应商,因此其快照只含供应商、应用时不动其它维度)。
|
||||
|
||||
几个值得了解的设计:
|
||||
|
||||
- **项目是全局实体、按作用域切换**:同一个项目在 Claude Code / Claude Desktop / Codex 三侧各自记录自己的当前项目与快照槽位,在 Codex 页签切换项目绝不会动到 Claude 的配置。
|
||||
- **切换即自动保存**:切换项目前,会先把你正要离开的项目在当前作用域下的状态自动存回去——所以项目里保存的永远是你上次离开它时的样子,不需要(也没有)手动「更新快照」按钮。
|
||||
- **应用是尽力而为的**:套用快照复用现有的切换原语(先切供应商,再做 MCP / Skills 的最小差异开关,最后启用记忆文件);快照里引用的某项如果已被删除,只会告警跳过,不会整体回滚。
|
||||
- **自动关闭代理接管**:套用项目前会先关闭该作用域内各应用的代理接管,避免快照状态和路由状态打架。
|
||||
|
||||
不用项目功能的用户可以在「设置 → 主页显示」里关闭「显示项目切换」,只隐藏主页入口,托盘子菜单与项目数据不受影响。底层由新的 `profiles` 表支撑(数据库自动迁移,无需手动操作),四语界面文案同步就位。
|
||||
|
||||
### Codex 官方 ChatGPT 账号的代理路由接管
|
||||
|
||||
用 ChatGPT 订阅(OAuth 或 API-key 登录)的 Codex 会话,现在也可以走 CC Switch 的本地代理路由了——官方账号流量获得与第三方供应商一致的路由、格式转换与用量统计。在供应商面板或托盘里选择内置的「OpenAI Official」条目进行接管即可(如果你此前删掉过它,添加供应商时会自动恢复);路由中的卡片徽标显示「官方账号路由中」。
|
||||
|
||||
实现上刻意做到**零凭据存储**:不向 `auth.json` 写任何占位密钥,而是往 `config.toml` 投影一个指向本地代理的专用 `model_provider`,Codex 把自己的 ChatGPT 授权头原样发给代理、代理原样透传给官方端点——`codex-official` 这一行的凭据永远是空的。官方登录本身绝不被覆盖:接管时 OAuth / API-key 材料会保留进备份;官方端返回的 401 / 403 被视为不可重试错误,failover 绝不会把你的对话悄悄挪到另一个账号上。相应地,「切换时保留 Codex 官方登录」这个设置项的文案已更新——路由接管场景下官方登录总是被保留,该开关现在只管不走路由的第三方直切。
|
||||
|
||||
### GPT-5.6:上下文窗口、预设默认与三档定价
|
||||
|
||||
围绕 GPT-5.6 家族做了三件事:
|
||||
|
||||
- **372K 上下文窗口注入**:Claude Code 经代理接管路由到 ChatGPT Codex(Codex OAuth)后端时,自动往生效的 `settings.json` 注入 `CLAUDE_CODE_MAX_CONTEXT_TOKENS` 与 `CLAUDE_CODE_AUTO_COMPACT_WINDOW`(均为 372000),让 Claude Code 不再按默认 200K 窗口过早自动压缩、也不再撑爆上游。注入门控严格:只有当所有已配置的模型键都指向 gpt-5.6 家族时才注入(gpt-5.5 的目录窗口在 272K / 372K 间摇摆,故意不继承);你手动设置的值永远优先;切走时按镜像条件剥离,程序默认永远不会固化进你的供应商配置。
|
||||
- **预设默认模型升级**:Claude Code 与 Claude Desktop 的 Codex OAuth 预设默认路由升级到 gpt-5.6 家族(haiku → `gpt-5.6-luna`,主模型 / sonnet / opus → `gpt-5.6`),自定义 Codex `config.toml` 模板的默认模型同步跟进。
|
||||
- **Sol / Terra / Luna 三档定价**:用量看板按官方价目为三档入库——Sol 5 / 30 / 0.50、Terra 2.50 / 15 / 0.25、Luna 1 / 6 / 0.10(美元每百万 token,输入 / 输出 / 缓存读)。与 5.5 及更早版本不同,5.6 家族的**提示缓存写入按 1.25 倍输入价计费**(Sol 6.25 / Terra 3.125 / Luna 1.25),已按此入库并自动修复此前按 0 计的存量行;裸 `gpt-5.6` 及各 effort 后缀变体按 Sol 价对齐。
|
||||
|
||||
### 在 Codex 里使用 Claude 系列模型:原生 Anthropic Messages 上游
|
||||
|
||||
这个功能来自一个很现实的诉求:**不少企业出于合规策略禁用了 Claude Code 客户端,但并没有禁用 Claude API**。对这些用户来说,模型本身是可用的,缺的只是一个被允许的客户端——现在 Codex 可以补上这个位置。在 Codex 供应商的上游格式选择器里选新增的 `anthropic`,即可直连 Claude API 或任何只提供原生 Anthropic Messages 协议(`/v1/messages`)的网关,本地代理完成 Responses↔Anthropic 的请求、响应与流式双向转换,你在 Codex 里照常对话、照常用工具,背后跑的是 Claude 系列模型。表单配套提供:认证字段选择器(`ANTHROPIC_AUTH_TOKEN` 发 `Authorization: Bearer`,默认;或 `ANTHROPIC_API_KEY` 发 `x-api-key`)、可选的 Claude Code 客户端伪装开关(默认关闭)、以及按供应商的最大输出 token 覆盖(Codex 不发 `model_max_output_tokens`,不设置时回退到保守的 8192,可能截断长回复或重思考回复)。转换桥自动注入标准 5 分钟提示缓存标记(系统提示、工具与历史走缓存而非每轮全价重发),支持 `[1m]` 长上下文标记并补发对应 beta 头,截断的流会如实上报为未完成而不是伪装成功。([#5071](https://github.com/farion1231/cc-switch/pull/5071))
|
||||
|
||||
### Codex 供应商表单新增「默认模型」输入框
|
||||
|
||||
`config.toml` 顶层的 `model` 键现在是表单里的一个可编辑字段:新模型(如 `gpt-5.6`)发布后,你可以直接把现有供应商指过去,不必等预设更新(预设只影响新添加的供应商)。字段与 TOML 编辑器双向同步,候选列表来自模型映射目录与供应商 `/models` 端点的并集,值不在目录里时提供一键「加入映射」。显式填写的值永远优先于映射第一行的隐式回填;模型名与 `base_url` 写入时做了 TOML 转义,杜绝 `/models` 返回的远端数据注入伪造配置行的可能。
|
||||
|
||||
### 通用配置切换自动同步扩展到 Codex
|
||||
|
||||
v3.16.5 给 Claude 加的「切走时自动把 live 配置里的共享偏好回写到通用配置」现在覆盖 Codex 了:切走一个启用了通用配置的 Codex 供应商时,会先从它的 live `config.toml` 重新提取可共享部分更新到通用配置,再带给下一个供应商——你直接在运行中的 Codex 配置里改的偏好不再在切换时丢失,删掉的键也不会被悄悄注回。提取器会严格剥离供应商专属与注入内容(`model` / `model_provider` / `base_url` / `wire_api`、整个 `[model_providers]` 表、MCP 投影、API key 兜底字段、模型目录指针与注入的 `web_search` 哨兵),密钥永远不会进入共享片段。所有失败仅告警、绝不阻断切换。
|
||||
|
||||
### Claude 子代理模型配置
|
||||
|
||||
Claude 供应商表单新增「子代理」模型行,写入 `CLAUDE_CODE_SUBAGENT_MODEL`,让 Claude Code 派生的子代理跑在你指定的(通常更便宜或更快的)模型上。支持 `[1M]` 标记;由于子代理模型不会出现在 `/model` 菜单里,该行显示「不在 /model 中展示」占位而没有显示名字段。代理接管路径与模型映射器已同步支持:请求模型与配置的子代理模型一致时原样放行,不再被折叠到默认模型;该键也被排除在共享通用配置之外,不会跨供应商泄漏。([#4830](https://github.com/farion1231/cc-switch/pull/4830))
|
||||
|
||||
### 回退模型字段的 1M 上下文复选框
|
||||
|
||||
Claude 表单的回退模型字段(`ANTHROPIC_MODEL`)现在带上了 Sonnet / Opus / Fable 各档早已有的 1M 复选框:回退模型背后是 1M 窗口时可以如实声明,不再被静默当作 200K。勾选即在模型 id 后追加 `[1M]` 标记,取消即剥离。([#5124](https://github.com/farion1231/cc-switch/pull/5124),修复 #3679)
|
||||
|
||||
### 智谱团队套餐配额查询
|
||||
|
||||
智谱的团队套餐(团队版 Coding Plan)走同一个配额端点但需要 `?type=2` 与两个额外请求头(`bigmodel-organization` / `bigmodel-project`),个人版查询够不到。用量脚本弹窗新增「Zhipu GLM Team(智谱团队)」模板,填入 API Key + 组织 ID + 项目 ID 即可查询团队配额;三项缺一会明确提示补全。四语文案同步。([#5128](https://github.com/farion1231/cc-switch/pull/5128))
|
||||
|
||||
### OpenCode 表单:请求头与模型 Token 上限编辑器
|
||||
|
||||
OpenCode 供应商表单补上了两块此前只能手改 JSON 的配置:**Headers 编辑器**(供应商级 `options.headers`,如 OpenRouter 排行榜要求的 `HTTP-Referer` / `X-Title`,支持增删行、大小写不敏感去重)与**按模型 Token 上限**(`model.limit.context` / `model.limit.output` 数字输入,清空即移除)。「额外选项」块改为可折叠区,已有内容时自动展开;顺带修复了旧占位符过滤会误删真实以 `option-` 开头的选项键的问题。([#2907](https://github.com/farion1231/cc-switch/pull/2907))
|
||||
|
||||
### 新增模型定价:腾讯混元 Hy3
|
||||
|
||||
为 2026-07-06 发布的腾讯混元 Hy3(256K 上下文)入库定价(按发布日牌价 CNY 1 / 4 / 0.25 每百万 token 折算),`hunyuan-hy3` 与 `hy3` 两个 id 都能命中,其用量不再显示 $0。注意 Hy3 实际是按输入长度分档计费,当前单价表按最低档入库,长上下文请求会低估成本,待官方计费页明确后再修正。
|
||||
|
||||
---
|
||||
|
||||
## 变更
|
||||
|
||||
### Codex Chat 路由注入 prompt_cache_key,提升缓存命中
|
||||
|
||||
Codex 经本地路由转换到 Chat Completions 上游时,现在会按供应商感知地注入 `prompt_cache_key`:Kimi Coding 与 OpenAI 官方端点自动启用、Kimi 预设显式开启,未知的 OpenAI 兼容网关保持关闭以避免严格 schema 网关报 400。键值只取显式客户端值或真实的客户端会话 ID,绝不生成随机 UUID(那会让每个请求落到不同缓存桶、适得其反)。高级选项里提供自动 / 启用 / 禁用三态覆盖。
|
||||
|
||||
### Codex 图片能力自动推断,去掉手动开关
|
||||
|
||||
生成的 Codex 模型目录现在只把 CC Switch 确认过的**精确文本-only 名录**内的模型声明为 `input_modalities = ["text"]`;GPT、别名、新后缀变体和一切未知模型一律 fail-open 到 `["text", "image"]`——修复了 GPT 系模型在 Codex IDE 扩展里被误报「不支持图片」的问题。整流器的「纯文本模型预检」开关继续只管代理侧的主动请求改写,不影响目录声明;目录反向导入也会把可推断的能力坍缩掉,未来名录修正或模型升级多模态时自动生效。
|
||||
|
||||
### 上下文窗口参数钉进预设,不再作为表单字段
|
||||
|
||||
`Codex`(ChatGPT / GPT-5.6)与 `Kimi For Coding` 预设不再在表单里展示「最大上下文 Tokens」「自动压缩窗口」两个输入框,数值直接钉死在预设 env 里(Codex 372000 / 372000,Kimi For Coding 262144 / 262144)——绝大多数用户从不需要碰这两个数字。两个键刻意保留在 env 里:显式钉住能让本地压缩触发点免疫远端实验性配置的下调。极少数想改数字的用户仍可在供应商的 JSON 编辑器里直接编辑这两个键。
|
||||
|
||||
### 供应商连通性配置简化
|
||||
|
||||
移除了过时的按供应商 `testConfig` 覆盖(超时、重试次数、降级延迟阈值):轻量的 `base_url` 探测现在始终使用全局连通性检查配置,自动 failover 仍完全由代理超时与熔断器的独立设置驱动。设置界面与接口命名也从「模型测试」术语统一迁移到「连通性检查」。
|
||||
|
||||
### 通用(多应用)供应商添加后自动同步
|
||||
|
||||
通过「添加供应商」弹窗添加通用(多应用)供应商后,现在会立即推送到各 live 目标配置,不再需要手动再点一次同步。同步失败不阻塞添加——供应商已保存但同步失败时给出非阻断的警告提示。([#2811](https://github.com/farion1231/cc-switch/pull/2811))
|
||||
|
||||
### 预设更新
|
||||
|
||||
- **LongCat-2.0**:美团 LongCat 预设全线(Claude Code / Claude Desktop / Codex / Hermes / OpenClaw / OpenCode)从已退役的 `LongCat-Flash-Chat` / `LongCat-2.0-Preview` 升级到 `LongCat-2.0`,声明真实的 1M(1048576)上下文窗口。LongCat-2.0 是纯文本模型,代理的媒体清洗白名单已同步收录——粘贴进会话的图片会被替换为不支持标记而不是被上游硬拒。([#4838](https://github.com/farion1231/cc-switch/pull/4838))
|
||||
- **SudoCode**:原 `sudocode.us` 预设原位替换为 `sudocode.chat` 的新赞助商 SudoCode,覆盖六个客户端(Claude 系直连 Anthropic 透传,Codex / OpenCode / OpenClaw / Hermes 默认 `gpt-5.6-sol`)。
|
||||
- **火山 / 豆包 / BytePlus 官网链接**:撤销了 v3.16.5 把这三个预设 `websiteUrl` 改为产品主页的改动,恢复为带归因参数的活动 / 邀请链接(这是有意为之的设计)。
|
||||
- **Code0.ai**:邀请链接更新为新的 agent 注册链接;API 端点不变。
|
||||
- **删除重复的 OpenAI Compatible 预设**:OpenCode 与 OpenClaw 预设列表里的 `OpenAI Compatible` 自定义模板条目被移除——内置的 `custom` 供应商流程本就提供相同的起点,选择器里不再出现两个指向同一处的入口。存量供应商不受影响。
|
||||
|
||||
---
|
||||
|
||||
## 修复
|
||||
|
||||
### Codex OAuth 客户端身份对齐:修复最新 ChatGPT 模型 404
|
||||
|
||||
用官方 Codex OAuth 账号经本地代理接管路由时,最新的订阅模型(如 `gpt-5.6-luna`)此前会返回误导性的 `404 Model not found`——明明账号有权限。根因是 ChatGPT 的 Codex 后端按 `originator` + `version` 头做模型分组路由,而 cc-switch 此前自报 `originator: cc-switch` 且不带版本号,被路由到一个 luna 尚未部署的分组。现在接管请求发送与真实 Codex CLI 一致的 `originator: codex_cli_rs` + `version: 0.144.1`,满足 luna 的最低客户端版本要求,经真实后端 A/B 实测确认修复。
|
||||
|
||||
### Responses 上游失败不再变成空回复
|
||||
|
||||
代理把 Anthropic 格式客户端(Claude Code / Claude Desktop)桥接到 OpenAI Responses 上游时,上游藏在 HTTP 2xx 体里的语义失败(`status:"failed"` 对象、`error` 信封、首个输出前的 `response.failed` SSE 事件)此前会被转换成一个悄无声息的空回合。现在这些失败在重试循环内就被识别为真实错误,failover 能够换一个供应商重试;干净结束但内容不完整的流会如实标记为截断而非完成;无视 `stream:true` 直接返回整个 JSON 文档的网关也能被识别并展开为完整的流式生命周期;客户端历史本身格式错误时立即报错,不再拿着必败的请求把每个供应商都重试一遍。
|
||||
|
||||
### 跨 Responses/Anthropic 桥保留推理、工具结果与 system 角色
|
||||
|
||||
多轮工具循环里跨 Responses↔Anthropic 桥的内容不再丢失或损坏:加密的推理(reasoning)条目无损往返(往返失败会导致下一轮请求被上游拒绝的问题同步消除);流式转换器支持官方的推理事件词汇表并在网关跳过增量时从终结事件恢复工具参数;结构化工具结果的 `is_error` 标志、图片与 PDF 文档在两个方向都完整保留,不再被压平成一个 JSON 字符串;历史里的 `system` / `developer` 消息被正确提升为 Anthropic `system`,不再被静默降级成用户发言。计费上,上游请求成功但后续转换失败时用量照记,不再漏账。
|
||||
|
||||
### 缓存写入 token 不再双重计费
|
||||
|
||||
Codex / Gemini 类供应商上报的 `input_tokens` 同时包含缓存读与缓存写,而成本计算此前只减掉了缓存读——缓存写入 token 被按输入价和缓存创建价**计了两次费**。现在两者都会先行扣除,并且缓存写入数字在跨格式转换(Chat↔Responses↔Anthropic)时不再丢失。为了让历史数据口径不乱,数据库新增一列记录每行 `input_tokens` 的存储语义(schema v12→v13 自动迁移):旧行按旧口径回算、新行按新口径,Claude 类行不受影响。
|
||||
|
||||
### 更强的提示缓存断点注入
|
||||
|
||||
在注入 Anthropic `cache_control` 断点的代理路径上(Codex 接管桥与 Bedrock 原生优化器),注入器现在会更充分地使用四个断点预算:除了工具尾、系统尾与最新可缓存消息外,预算有余时再给较早的用户消息加一个锚点,让稳定前缀保持在 Anthropic 20 块回看窗口内——长的、工具密集的对话能持续命中提示缓存,而不是每轮把系统提示、工具与历史全价重发。调用方自带的断点被原样保留(绝不删除、重排或改写);注入的标记一律使用标准 5 分钟 TTL。
|
||||
|
||||
### Kimi For Coding 的 256K 上下文窗口真正生效
|
||||
|
||||
Kimi For Coding 预设在 3.16.4 加的 `CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144` 其实**从未生效**:Claude Code 对不认识的模型 id 按 200K 窗口封顶,且压缩窗口取 `min(模型窗口, 设定值)`,262144 被钳回 200K。本版补齐了缺失的两环——预设同时钉上 `CLAUDE_CODE_MAX_CONTEXT_TOKENS`,并把各档模型显式路由到端点的 `kimi-for-coding` 别名(`claude-` 前缀 id 会让 Claude Code 无视这两个窗口参数,非 Claude 别名才是解锁大窗口的关键)。已保存的供应商在切换时也会自动注入这两个窗口默认值,但**别名路由只存在于预设里**——旧预设存下来的供应商实际仍是 200K,需要重新套用一次预设(见「升级提醒」)。
|
||||
|
||||
### 删除的 Codex MCP 服务器不再复活
|
||||
|
||||
MCP 服务器的权威数据在数据库里,Codex live `config.toml` 中的 `[mcp_servers]` 只是每次写入后重新同步的投影——但切走供应商时这份投影会被固化进供应商快照,导致你在应用里删掉的服务器在下次激活该供应商时死而复生,且逐条对账永远清不掉这个孤儿。现在切走时会把 `[mcp_servers]`(含旧式 `[mcp.servers]`)从存储快照中剥离,已被污染的快照在下次切走时自愈。一个可见的副作用:手写在 Codex 供应商配置里的 `[mcp_servers.*]` 段会在首次切走时被剥出快照——今后请通过 MCP 管理器定义 Codex 的 MCP 服务器(见「升级提醒」)。
|
||||
|
||||
### MCP 同步更健壮:解析失败不清空文件、按应用报错
|
||||
|
||||
两处修复。其一,向 Codex 写入单个 MCP 服务器时,如果现有 `config.toml` 解析失败,旧逻辑会退到空文档再整体写回——**整个文件被清空**、只剩那一个 MCP 条目;现在直接返回校验错误并保持文件原样。其二,「从应用导入」此前把每个导入器的错误吞成 0,坏掉的 Codex 配置只会显示「导入了 0 个服务器」;现在逐应用尽力导入、失败时报出具体是哪个应用出了问题。切换与保存时的投影也改为只针对目标应用,一个应用的 live 文件解析失败不再连坐阻塞其它应用、也不再把已经成功的切换误报为失败。
|
||||
|
||||
### Codex 通用配置合并保留注释与键序
|
||||
|
||||
Codex 供应商表单里勾选 / 取消「应用通用配置」此前走前端 TOML 实现整篇重排(解析 → 合并 → 序列化):注释被丢弃、键被重排、还会凭空多出 `[model_providers]` 这类空表头——就是「config.toml 老被重排」的元凶。现在合并走后端命令、与写 live 配置共用同一套合并语义,手写格式在编辑期合并中完整幸存;针对异步化引入的快速切换竞态也加了双重守卫(操作序号 + 配置基线核对),先发后至的旧结果不会覆盖新状态。
|
||||
|
||||
### 受管 Claude 接管只注入单个 auth 占位符
|
||||
|
||||
从第三方端点切到 Codex 受管供应商时,`~/.claude/settings.json` 里会同时写入 `ANTHROPIC_API_KEY` 和 `ANTHROPIC_AUTH_TOKEN` 两个占位符,导致 Claude Code 每次启动都警告「Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set」。现在只注入一个:Codex 受管走 `ANTHROPIC_AUTH_TOKEN`、Copilot 走 `ANTHROPIC_API_KEY`,其余 token 键一律清除。注意:升级后如果 live 配置已带着双键,由于「配置未变则跳过重写」的短路逻辑,警告可能仍在——把 Claude 路由开关关再开一次(或切换一次供应商)即可触发重写(见「升级提醒」)。([#5095](https://github.com/farion1231/cc-switch/pull/5095),修复 #4919)
|
||||
|
||||
### 用量与配额查询:瞬时失败可自动重试、不再毒化缓存
|
||||
|
||||
用量与配额查询频繁出现手动刷新也清不掉的「查询失败」,根因是所有传输层失败(包括读响应体中途超时)都被折叠成了「成功但结果为失败」——前端的自动重试从不触发,失败体还被当作真实数据缓存。现在传输失败如实返回错误:react-query 自动重试生效,HTTP 429 与 5xx 一样按瞬时失败处理,保留的上次成功数据按 10 分钟窗口正常过期,失败状态下页脚保留重试入口与真实错误信息。(修复 [#3820](https://github.com/farion1231/cc-switch/issues/3820))
|
||||
|
||||
### Codex 子代理会话用量计入本地统计
|
||||
|
||||
Codex 子代理(spawned agent)会话的 token 用量此前完全没进本地统计:子代理日志里携带的是父线程的 `session_id`,多个子代理的记录互相碰撞、被当作重复丢弃。现在解析器按每个文件自己的 `thread_id` 建立唯一身份,并识别子代理日志开头对父线程历史的重放、只用它恢复累计基线而不重复计费;归档日志也按文件名继承同步游标,重新解析只导入新增部分。([#5187](https://github.com/farion1231/cc-switch/pull/5187))
|
||||
|
||||
### Codex 免费版 30 天配额窗口正常显示
|
||||
|
||||
Codex 免费账号按 30 天滚动窗口计量(而非付费版的周窗口),但前端白名单和托盘分组都不认识 `30_day` 这个档位——免费账号唯一的档位被过滤掉后,配额页脚整个空白、托盘也不显示任何配额。现在 30 天档位在页脚和托盘都正常渲染,四语标签同步。([#4886](https://github.com/farion1231/cc-switch/pull/4886),修复 #3651)
|
||||
|
||||
### 用量看板刷新间隔持久化
|
||||
|
||||
用量看板的自动刷新间隔此前是组件内状态,每次重启都重置回 30 秒。现在通过新的应用设置持久化,改动乐观生效、保存失败自动回滚。([#5057](https://github.com/farion1231/cc-switch/pull/5057))
|
||||
|
||||
### Fable 档模型键不再泄漏进通用配置
|
||||
|
||||
Fable 是 v3.16.3 加入的第四个 Claude 模型映射档,但它的 `ANTHROPIC_DEFAULT_FABLE_MODEL(_NAME)` 两个键漏在了供应商专属排除名单之外——某个供应商的 Fable 模型钉选可能泄漏进共享通用配置、再被注入到其它供应商。现已与 haiku / sonnet / opus 三档一样剥离,并顺带补全了 Fable 档的代理接管支持(接管时写入稳定的角色别名、切走时清理陈旧值)。([#5206](https://github.com/farion1231/cc-switch/pull/5206),修复 #4272)
|
||||
|
||||
### 工具 schema 缺省 type 兜底与无分类供应商的 API Key 输入框
|
||||
|
||||
两个供应商侧修复:客户端发来的工具如果 `input_schema` 缺顶层 `type`(或干脆是空 `{}`),代理转换后会被严格网关拒绝,现在根 schema 自动补 `type: "object"`(只补根、不动嵌套子 schema);历史导入或手工构建的无分类供应商在编辑时看不到 Claude API Key 输入框的问题也已修复——现在只要不是官方 / 云厂商类供应商就显示该字段。([#5069](https://github.com/farion1231/cc-switch/pull/5069))
|
||||
|
||||
### GLM 5.2 纯文本模型的图片请求兜底
|
||||
|
||||
本地代理接管火山 Coding Plan 跑 GLM 5.2 时,请求里的图片块不再产生一个无法恢复的 400:文本-only 名录精确收录 `glm-5.2`(刻意不用前缀匹配,未来的多模态 `glm-5.2v` 不受牵连),预防路径在请求到达前剥离图片;网关那句不含 image 字样的报错(`Model only support text input`)也被反应路径的自证短语名录识别,触发媒体兜底。(修复 [#5025](https://github.com/farion1231/cc-switch/issues/5025))
|
||||
|
||||
### 会话与 live 配置同步小修一组
|
||||
|
||||
- **显示重命名的 Codex 会话标题**:在 Codex 里重命名过的会话,会话管理器现在显示新标题而不是回退到首条消息文本;并发写入时的读取也不再立即失败。([#4927](https://github.com/farion1231/cc-switch/pull/4927))
|
||||
- **OpenCode / OpenClaw / Hermes 的 live 编辑在启动时同步入库**:直接改 live 配置文件(换 base URL、加模型)此前在首次导入后就再也不会被拾取;现在每次启动时对比 live 与库存,差异即更新,全程非致命。([#4712](https://github.com/farion1231/cc-switch/pull/4712)、[#5098](https://github.com/farion1231/cc-switch/pull/5098))
|
||||
- **OpenCode 会话恢复命令更新**:会话管理器展示与复制的恢复命令从过时的 `opencode session resume <id>` 更正为当前 CLI 的 `opencode -s <id>`。([#2359](https://github.com/farion1231/cc-switch/pull/2359))
|
||||
- **官方供应商跳过连通性探测**:连通性检查不再对官方类供应商推导出一个无凭据必失败的第一方端点探测(例如裸打 `chatgpt.com/backend-api/codex`),批量检查直接跳过、单独解析明确报错。
|
||||
|
||||
---
|
||||
|
||||
## 文档
|
||||
|
||||
### Codex + Kimi 本地路由攻略
|
||||
|
||||
新增分步攻略(中 / 英 / 日三语,含界面截图),讲解如何借助 CC Switch 的本地路由在 Codex CLI 里使用 Kimi:较新的 Codex CLI 走 OpenAI Responses 协议,而 Kimi 开放平台(按量付费,`kimi-k2.7-code`)与 Kimi For Coding(会员制,`kimi-for-coding`)暴露的都是 Chat Completions 端点,直连通常在 `/responses` 上 404。攻略覆盖从内置预设添加供应商到四步协议转换链的完整流程。
|
||||
|
||||
### README 赞助商更新
|
||||
|
||||
开源 AI 基建项目 `new-api` 加入四语 README 的赞助商表。
|
||||
|
||||
---
|
||||
|
||||
## 升级提醒
|
||||
|
||||
### Kimi For Coding 供应商需重新套用预设
|
||||
|
||||
如果你在用 Kimi For Coding 预设创建的供应商,请**重新从预设选择一次并保存**:256K 窗口的关键——把各档模型路由到 `kimi-for-coding` 别名——只存在于新版预设里,旧预设存下来的供应商即使升级后实际仍按 200K 窗口过早压缩。
|
||||
|
||||
### 手写的 Codex `[mcp_servers.*]` 会被剥出快照
|
||||
|
||||
为了根治「删掉的 MCP 服务器复活」,切走 Codex 供应商时会把 `[mcp_servers]` 段从存储快照中剥离。如果你有直接手写在某个 Codex 供应商配置里的 MCP 服务器,它会在首次切走该供应商时从快照消失——请改用 MCP 管理器(MCP 页签)定义 Codex 的 MCP 服务器,那里的条目才是权威数据、会被自动投影到 live 配置。
|
||||
|
||||
### 双 auth 键警告可能需要手动触发一次重写
|
||||
|
||||
如果升级后 Claude Code 仍提示「Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY set」,这是因为 live 配置未变时接管逻辑会短路跳过重写。把 Claude 的路由开关关掉再打开一次(或切换一次供应商)即可写入修正后的单占位符配置,警告随之消失。
|
||||
|
||||
### 数据库自动迁移
|
||||
|
||||
首次启动 v3.17.0 时数据库会自动从 schema v11 迁移到 v13(新增项目表与用量语义列),无需任何手动操作。如果你有回退到旧版本的习惯,建议先备份 `~/.cc-switch/cc-switch.db`。
|
||||
|
||||
---
|
||||
|
||||
## 风险提示
|
||||
|
||||
本版本继续沿用此前版本对反向代理类功能的风险提示。
|
||||
|
||||
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#️-风险提示)。本版新增的「官方 ChatGPT 账号代理路由接管」同样属于此类用法,请知悉相同的风险。
|
||||
|
||||
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
|
||||
|
||||
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
|
||||
|
||||
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
感谢以下贡献者在 v3.17.0 中提交的功能与修复:
|
||||
|
||||
- [#5071](https://github.com/farion1231/cc-switch/pull/5071):新增原生 Anthropic Messages 协议作为 Codex 上游,感谢 @yeeyzy。
|
||||
- [#4830](https://github.com/farion1231/cc-switch/pull/4830):新增 Claude 子代理模型配置,感谢 @AkimioJR。
|
||||
- [#5124](https://github.com/farion1231/cc-switch/pull/5124):给回退模型字段加上 1M 复选框,感谢 @salarkhannn。
|
||||
- [#5128](https://github.com/farion1231/cc-switch/pull/5128):新增智谱团队套餐配额查询,感谢 @zhanxin-xu。
|
||||
- [#2907](https://github.com/farion1231/cc-switch/pull/2907):OpenCode 表单新增请求头与 Token 上限编辑器,感谢 @git1677967754。
|
||||
- [#2811](https://github.com/farion1231/cc-switch/pull/2811):通用供应商添加后自动同步,感谢 @hubutui。
|
||||
- [#4838](https://github.com/farion1231/cc-switch/pull/4838):LongCat 预设升级到 LongCat-2.0,感谢 @solthx。
|
||||
- [#5095](https://github.com/farion1231/cc-switch/pull/5095):受管 Claude 接管只注入单个 auth 占位符,感谢 @fengshao1227。
|
||||
- [#5187](https://github.com/farion1231/cc-switch/pull/5187):Codex 子代理会话用量计入统计,感谢 @starmiaoa。
|
||||
- [#4886](https://github.com/farion1231/cc-switch/pull/4886):修复 Codex 免费版 30 天配额窗口不显示,感谢 @SaladDay。
|
||||
- [#5057](https://github.com/farion1231/cc-switch/pull/5057)、[#4927](https://github.com/farion1231/cc-switch/pull/4927)、[#2359](https://github.com/farion1231/cc-switch/pull/2359):刷新间隔持久化、重命名会话标题显示与 OpenCode 恢复命令修正,感谢 @makoMakoGo。
|
||||
- [#5206](https://github.com/farion1231/cc-switch/pull/5206):Fable 模型键排除出通用配置,感谢 @fzh365。
|
||||
- [#5069](https://github.com/farion1231/cc-switch/pull/5069):工具 schema 缺省 type 兜底与 API Key 输入框恢复,感谢 @Komikawayi。
|
||||
- [#4712](https://github.com/farion1231/cc-switch/pull/4712)、[#5098](https://github.com/farion1231/cc-switch/pull/5098):OpenCode / OpenClaw / Hermes live 配置启动同步,感谢 @allenxu09。
|
||||
|
||||
也感谢所有反馈 Codex 官方路由、缓存计费、MCP 同步与配额查询问题的用户——本版相当一部分修复来自这些真实使用场景里的复现线索。
|
||||
|
||||
---
|
||||
|
||||
## 下载与安装
|
||||
|
||||
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
|
||||
|
||||
### 系统要求
|
||||
|
||||
| 系统 | 最低版本 | 架构 |
|
||||
| ------- | -------------------------- | ----------------------------------- |
|
||||
| Windows | Windows 10 及以上 | x64 / ARM64 |
|
||||
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
|
||||
| Linux | 见下表 | x64 / ARM64 |
|
||||
|
||||
### Windows
|
||||
|
||||
| 文件 | 说明 |
|
||||
| ---------------------------------------- | ----------------------------------- |
|
||||
| `CC-Switch-v3.17.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
|
||||
| `CC-Switch-v3.17.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
|
||||
|
||||
Windows ARM64 设备请选择文件名中带 `arm64` 标识的对应制品。
|
||||
|
||||
### macOS
|
||||
|
||||
| 文件 | 说明 |
|
||||
| -------------------------------- | --------------------------------------------- |
|
||||
| `CC-Switch-v3.17.0-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
|
||||
| `CC-Switch-v3.17.0-macOS.zip` | 解压后拖入 Applications,Universal Binary |
|
||||
| `CC-Switch-v3.17.0-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.17.0-Linux-x86_64.AppImage` / `.deb` / `.rpm`
|
||||
- `CC-Switch-v3.17.0-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
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cc-switch",
|
||||
"version": "3.16.5",
|
||||
"version": "3.17.0",
|
||||
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,3 +2,7 @@ packages: []
|
||||
|
||||
onlyBuiltDependencies:
|
||||
- '@tailwindcss/oxide'
|
||||
- esbuild
|
||||
|
||||
ignoredBuiltDependencies:
|
||||
- msw
|
||||
|
||||
Generated
+1
-1
@@ -758,7 +758,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cc-switch"
|
||||
version = "3.16.5"
|
||||
version = "3.17.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arboard",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cc-switch"
|
||||
version = "3.16.5"
|
||||
version = "3.17.0"
|
||||
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
|
||||
authors = ["Jason Young"]
|
||||
license = "MIT"
|
||||
|
||||
+546
-34
@@ -6,23 +6,30 @@ use crate::config::{
|
||||
write_json_file, write_text_file,
|
||||
};
|
||||
use crate::error::AppError;
|
||||
use crate::model_capabilities::{image_input_capability_from_modalities, ImageInputCapability};
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
pub const CC_SWITCH_CODEX_MODEL_PROVIDER_ID: &str = "custom";
|
||||
/// Temporary model-provider id used while the built-in `codex-official`
|
||||
/// provider is routed through CC Switch. A dedicated id is an ownership
|
||||
/// marker: unlike a generic localhost `base_url`, it can be detected and
|
||||
/// cleaned up without mistaking a user's own local provider for takeover.
|
||||
pub const CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID: &str = "cc-switch-official";
|
||||
pub const CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME: &str = "cc-switch-model-catalog.json";
|
||||
const CODEX_PROXY_AUTH_PLACEHOLDER: &str = "PROXY_MANAGED";
|
||||
|
||||
/// Top-level `config.toml` key that controls Codex's built-in web-search tool.
|
||||
const CODEX_WEB_SEARCH_FIELD: &str = "web_search";
|
||||
pub(crate) const CODEX_WEB_SEARCH_FIELD: &str = "web_search";
|
||||
/// Value that disables the web-search tool. Some native `/responses` gateways
|
||||
/// reject a `web_search` tool with `responses_feature_not_supported` ("tool type
|
||||
/// 'web_search' is not supported by this gateway phase"), so for those we write
|
||||
/// this per the vendors' official Codex docs. Also doubles as cc-switch's
|
||||
/// ownership sentinel: we only ever remove a `web_search` key whose value equals
|
||||
/// this string, never a user's own setting.
|
||||
const CODEX_WEB_SEARCH_DISABLED: &str = "disabled";
|
||||
pub(crate) const CODEX_WEB_SEARCH_DISABLED: &str = "disabled";
|
||||
|
||||
/// Native `/responses` gateways whose first-party models do NOT support the Codex
|
||||
/// `web_search` hosted tool. A BLACKLIST (default-on): everything not listed keeps
|
||||
@@ -108,14 +115,27 @@ const CODEX_MODEL_CATALOG_TEMPLATE_SLUG: &str = "gpt-5.5";
|
||||
pub enum CodexCatalogToolProfile {
|
||||
ProxyChat,
|
||||
NativeResponses,
|
||||
/// Codex talks (through cc-switch's proxy) to a native Anthropic Messages
|
||||
/// gateway. Like `NativeResponses` it must suppress Codex's freeform custom
|
||||
/// tools — the Responses→Anthropic transform keeps only `function` tools.
|
||||
/// Additionally the Codex `web_search` hosted tool is unusable on this path
|
||||
/// (the transform drops it), so it is always disabled — see
|
||||
/// `prepare_codex_config_text_with_model_catalog`.
|
||||
Anthropic,
|
||||
}
|
||||
|
||||
impl CodexCatalogToolProfile {
|
||||
/// Pick the catalog tool profile from a provider's `apiFormat` meta value.
|
||||
/// Native (direct) Responses providers must suppress the custom apply_patch
|
||||
/// tool; everything else keeps the proxy-chat behavior.
|
||||
///
|
||||
/// Prefer [`crate::proxy::providers::codex::resolve_codex_catalog_tool_profile`],
|
||||
/// which also honors settings-level `apiFormat` and the TOML `wire_api` (matching
|
||||
/// the proxy router). This string-only mapping is the fallback for non-Anthropic
|
||||
/// cases.
|
||||
pub fn from_api_format(api_format: Option<&str>) -> Self {
|
||||
match api_format {
|
||||
Some("anthropic") => CodexCatalogToolProfile::Anthropic,
|
||||
// Native (direct) Responses gateways reject Codex's freeform custom
|
||||
// tools (apply_patch, etc.); strip them via the NativeResponses profile.
|
||||
Some("openai_responses") => CodexCatalogToolProfile::NativeResponses,
|
||||
_ => CodexCatalogToolProfile::ProxyChat,
|
||||
}
|
||||
@@ -418,6 +438,17 @@ fn extract_codex_top_level_u64(config_text: &str, field: &str) -> Option<u64> {
|
||||
.filter(|value| *value > 0)
|
||||
}
|
||||
|
||||
fn codex_catalog_input_modalities(
|
||||
model: &str,
|
||||
declared_modalities: Option<&[String]>,
|
||||
) -> Vec<String> {
|
||||
let modalities = match image_input_capability_from_modalities(model, declared_modalities) {
|
||||
ImageInputCapability::Unsupported => &["text"][..],
|
||||
ImageInputCapability::Supported | ImageInputCapability::Unknown => &["text", "image"][..],
|
||||
};
|
||||
modalities.iter().map(|item| (*item).to_string()).collect()
|
||||
}
|
||||
|
||||
fn codex_catalog_model_entry(
|
||||
template: &Value,
|
||||
spec: &CodexCatalogModelSpec,
|
||||
@@ -440,10 +471,22 @@ fn codex_catalog_model_entry(
|
||||
entry_obj.insert("availability_nux".to_string(), Value::Null);
|
||||
entry_obj.insert("upgrade".to_string(), Value::Null);
|
||||
|
||||
if profile == CodexCatalogToolProfile::NativeResponses {
|
||||
// Native `/responses` gateways reject Codex's freeform `apply_patch`
|
||||
// (type=="custom") tool. Strip any key that would make Codex emit a
|
||||
// custom/freeform tool, and rely on shell_type="shell_command" for
|
||||
// Image support is a model capability, not a tool-profile capability.
|
||||
// Trust hidden preset metadata first, then the confirmed text-only registry;
|
||||
// every unknown model fails open so GPT/relay aliases are never declared
|
||||
// text-only merely because a template had a conservative default.
|
||||
entry_obj.insert(
|
||||
"input_modalities".to_string(),
|
||||
json!(codex_catalog_input_modalities(
|
||||
&spec.model,
|
||||
spec.input_modalities.as_deref(),
|
||||
)),
|
||||
);
|
||||
|
||||
if profile != CodexCatalogToolProfile::ProxyChat {
|
||||
// Native `/responses` and Anthropic gateways reject / drop Codex's freeform
|
||||
// `apply_patch` (type=="custom") tool. Strip any key that would make Codex
|
||||
// emit a custom/freeform tool, and rely on shell_type="shell_command" for
|
||||
// edits. Defensive even though the native template is already clean
|
||||
// (guards against template drift / an accidental gpt-5.5 clone).
|
||||
//
|
||||
@@ -472,9 +515,6 @@ fn codex_catalog_model_entry(
|
||||
if let Some(parallel) = spec.supports_parallel_tool_calls {
|
||||
entry_obj.insert("supports_parallel_tool_calls".to_string(), json!(parallel));
|
||||
}
|
||||
if let Some(modalities) = &spec.input_modalities {
|
||||
entry_obj.insert("input_modalities".to_string(), json!(modalities));
|
||||
}
|
||||
}
|
||||
|
||||
entry
|
||||
@@ -488,8 +528,9 @@ struct CodexCatalogModelSpec {
|
||||
/// Per-row override for the native template's `supports_parallel_tool_calls`
|
||||
/// (e.g. MiniMax=true, MiMo=false). Only consulted for `NativeResponses`.
|
||||
supports_parallel_tool_calls: Option<bool>,
|
||||
/// Per-row override for the native template's `input_modalities`
|
||||
/// (e.g. `["text","image"]`). Only consulted for `NativeResponses`.
|
||||
/// Hidden per-row capability declaration from built-in provider metadata.
|
||||
/// When omitted, all catalog profiles consult the shared text-only model
|
||||
/// registry and otherwise default to `["text", "image"]`.
|
||||
input_modalities: Option<Vec<String>>,
|
||||
/// Per-row override for the native template's `base_instructions` (the
|
||||
/// model identity / system preamble). Carries each vendor's OFFICIAL value
|
||||
@@ -870,7 +911,9 @@ fn codex_model_catalog_from_settings(
|
||||
// no cache dependency); proxy-chat providers keep cloning Codex's gpt-5.5
|
||||
// entry so the proxy can rewrite custom<->function tools as before.
|
||||
let template = match profile {
|
||||
CodexCatalogToolProfile::NativeResponses => load_codex_native_responses_template(),
|
||||
CodexCatalogToolProfile::NativeResponses | CodexCatalogToolProfile::Anthropic => {
|
||||
load_codex_native_responses_template()
|
||||
}
|
||||
CodexCatalogToolProfile::ProxyChat => load_codex_model_catalog_template()?,
|
||||
};
|
||||
Ok(Some(codex_model_catalog_from_specs(
|
||||
@@ -954,21 +997,32 @@ pub fn prepare_codex_config_text_with_model_catalog(
|
||||
// (MiMo/LongCat/MiniMax by host or model brand; Qwen3-Coder by model).
|
||||
// Everything else — relays, DouBao, web-search-capable Qwen models,
|
||||
// unknown providers — keeps Codex's default.
|
||||
let disable_web_search = profile == CodexCatalogToolProfile::NativeResponses
|
||||
&& codex_native_gateway_rejects_web_search(&config_text);
|
||||
let disable_web_search = match profile {
|
||||
// The Responses→Anthropic transform silently drops the Codex web_search
|
||||
// hosted tool, so always disable it here rather than present a dead tool.
|
||||
CodexCatalogToolProfile::Anthropic => true,
|
||||
CodexCatalogToolProfile::NativeResponses => {
|
||||
codex_native_gateway_rejects_web_search(&config_text)
|
||||
}
|
||||
CodexCatalogToolProfile::ProxyChat => false,
|
||||
};
|
||||
let config_text = set_codex_native_web_search_field(&config_text, disable_web_search)?;
|
||||
write_json_file(&catalog_path, &catalog)?;
|
||||
Ok(config_text)
|
||||
} else {
|
||||
let config_text = set_codex_model_catalog_json_field(config_text, None)?;
|
||||
set_codex_native_web_search_field(&config_text, false)
|
||||
// Even without a generated catalog, the Responses→Anthropic transform drops the
|
||||
// Codex web_search hosted tool, so keep the invariant that an Anthropic provider
|
||||
// never presents it as a dead tool.
|
||||
let disable_web_search = profile == CodexCatalogToolProfile::Anthropic;
|
||||
set_codex_native_web_search_field(&config_text, disable_web_search)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reverse of `prepare_codex_config_text_with_model_catalog`: read the
|
||||
/// cc-switch–maintained catalog file referenced by `~/.codex/config.toml` and
|
||||
/// convert it back into the simplified shape the frontend table uses:
|
||||
/// `{ "models": [{ "model", "displayName"?, "contextWindow"? }, ...] }`.
|
||||
/// `{ "models": [{ "model", "displayName"?, "contextWindow"?, hidden overrides... }, ...] }`.
|
||||
///
|
||||
/// We only reverse-parse catalogs whose `model_catalog_json` path is the
|
||||
/// cc-switch–generated file (identified by filename
|
||||
@@ -976,14 +1030,14 @@ pub fn prepare_codex_config_text_with_model_catalog(
|
||||
/// left alone — surfacing its richer structure as the simplified table would
|
||||
/// be a downgrade we can't safely round-trip.
|
||||
///
|
||||
/// `displayName` and `contextWindow` are omitted from the returned entry when
|
||||
/// the on-disk value matches the fallback that
|
||||
/// `displayName`, `contextWindow`, and `inputModalities` are omitted from the
|
||||
/// returned entry when the on-disk value matches the fallback that
|
||||
/// `codex_model_catalog_from_settings` injects for unset inputs (slug for
|
||||
/// display_name, `model_context_window` or 128_000 for context_window). This
|
||||
/// preserves the "user left it blank" intent across round-trip; an unavoidable
|
||||
/// edge case is that a user-typed value that happens to equal the fallback
|
||||
/// will also collapse to blank, but the next save writes the same fallback so
|
||||
/// behavior stays consistent.
|
||||
/// display_name, `model_context_window` or 128_000 for context_window, and the
|
||||
/// shared confirmed-text-only inference for input modalities). This preserves
|
||||
/// the "user left it blank" intent across round-trip; an unavoidable edge case
|
||||
/// is that a user-typed value that happens to equal the fallback also collapses
|
||||
/// to blank, but the next save writes the same fallback so behavior is stable.
|
||||
///
|
||||
/// All failure modes (missing file, parse error, no `model_catalog_json`,
|
||||
/// entries without `slug`) collapse to `Ok(None)` so callers can treat this
|
||||
@@ -1038,9 +1092,8 @@ pub(crate) fn resolve_cc_switch_catalog_path(
|
||||
}
|
||||
|
||||
/// Pure reverse-parsing core: convert Codex catalog JSON text back into the
|
||||
/// frontend's simplified `{ models: [{ model, displayName?, contextWindow? }] }`
|
||||
/// shape. Returns `None` when the catalog is unparseable, has no `models`
|
||||
/// array, or yields zero valid entries.
|
||||
/// frontend's simplified model-mapping shape. Returns `None` when the catalog
|
||||
/// is unparseable, has no `models` array, or yields zero valid entries.
|
||||
fn build_simplified_catalog_from_texts(config_text: &str, catalog_text: &str) -> Option<Value> {
|
||||
let catalog: Value = serde_json::from_str(catalog_text).ok()?;
|
||||
let models = catalog.get("models").and_then(|m| m.as_array())?;
|
||||
@@ -1080,8 +1133,7 @@ fn build_simplified_catalog_from_texts(config_text: &str, catalog_text: &str) ->
|
||||
}
|
||||
|
||||
// Preserve native-profile per-row overrides so a DB-SSOT-missing
|
||||
// fallback round-trip doesn't silently drop them (they are ignored by
|
||||
// the ProxyChat profile, so carrying them is harmless).
|
||||
// fallback round-trip doesn't silently drop them.
|
||||
if let Some(parallel) = entry
|
||||
.get("supports_parallel_tool_calls")
|
||||
.and_then(|v| v.as_bool())
|
||||
@@ -1094,7 +1146,8 @@ fn build_simplified_catalog_from_texts(config_text: &str, catalog_text: &str) ->
|
||||
.filter_map(|m| m.as_str())
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
if !mods.is_empty() {
|
||||
let inferred = codex_catalog_input_modalities(model, None);
|
||||
if !mods.is_empty() && mods != inferred {
|
||||
obj.insert("inputModalities".to_string(), json!(mods));
|
||||
}
|
||||
}
|
||||
@@ -1312,15 +1365,139 @@ pub fn read_codex_live_settings() -> Result<Value, AppError> {
|
||||
/// backend), `name = "OpenAI"` keeps Codex's `is_openai()` feature gates
|
||||
/// (web search, remote compaction), and `supports_websockets` restores the
|
||||
/// built-in default that custom entries otherwise lose.
|
||||
fn codex_unified_official_provider_table() -> toml_edit::Table {
|
||||
fn codex_official_provider_table(
|
||||
base_url: Option<&str>,
|
||||
supports_websockets: bool,
|
||||
) -> toml_edit::Table {
|
||||
let mut table = toml_edit::Table::new();
|
||||
table["name"] = toml_edit::value("OpenAI");
|
||||
table["requires_openai_auth"] = toml_edit::value(true);
|
||||
table["supports_websockets"] = toml_edit::value(true);
|
||||
table["supports_websockets"] = toml_edit::value(supports_websockets);
|
||||
table["wire_api"] = toml_edit::value("responses");
|
||||
if let Some(base_url) = base_url {
|
||||
table["base_url"] = toml_edit::value(base_url.trim_end_matches('/'));
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
fn codex_unified_official_provider_table() -> toml_edit::Table {
|
||||
codex_official_provider_table(None, true)
|
||||
}
|
||||
|
||||
fn remove_codex_proxy_placeholders_from_providers(providers: &mut toml_edit::Table) {
|
||||
for (_, item) in providers.iter_mut() {
|
||||
if let Some(table) = item.as_table_mut() {
|
||||
let should_remove = table
|
||||
.get("experimental_bearer_token")
|
||||
.and_then(|item| item.as_str())
|
||||
== Some(CODEX_PROXY_AUTH_PLACEHOLDER);
|
||||
if should_remove {
|
||||
table.remove("experimental_bearer_token");
|
||||
}
|
||||
} else if let Some(table) = item.as_inline_table_mut() {
|
||||
let should_remove = table
|
||||
.get("experimental_bearer_token")
|
||||
.and_then(|value| value.as_str())
|
||||
== Some(CODEX_PROXY_AUTH_PLACEHOLDER);
|
||||
if should_remove {
|
||||
table.remove("experimental_bearer_token");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Project the built-in Codex official provider through the local proxy while
|
||||
/// keeping authentication owned by Codex itself.
|
||||
///
|
||||
/// The resulting custom provider explicitly opts into OpenAI authentication,
|
||||
/// so Codex forwards its existing ChatGPT login to the local `/responses`
|
||||
/// endpoint. No API key or bearer placeholder is written to `auth.json`.
|
||||
pub fn apply_codex_official_proxy_route(
|
||||
config_text: &str,
|
||||
proxy_base_url: &str,
|
||||
) -> Result<String, AppError> {
|
||||
let mut doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
|
||||
|
||||
// A third-party takeover may have left the proxy placeholder in config.toml.
|
||||
// The official route must use Codex's native OpenAI login instead.
|
||||
doc.as_table_mut().remove("experimental_bearer_token");
|
||||
doc["model_provider"] = toml_edit::value(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID);
|
||||
|
||||
let mut providers = match doc.as_table_mut().remove("model_providers") {
|
||||
Some(item) => item.into_table().map_err(|_| {
|
||||
AppError::Message(
|
||||
"Invalid Codex config.toml: model_providers must be a table".to_string(),
|
||||
)
|
||||
})?,
|
||||
None => {
|
||||
let mut table = toml_edit::Table::new();
|
||||
table.set_implicit(true);
|
||||
table
|
||||
}
|
||||
};
|
||||
|
||||
// Clean only CC Switch's placeholder from every stale provider table. Real
|
||||
// user bearer tokens are preserved, as are all unrelated provider fields.
|
||||
remove_codex_proxy_placeholders_from_providers(&mut providers);
|
||||
|
||||
// The local proxy currently exposes HTTP/SSE, not Codex websocket routes.
|
||||
let table = codex_official_provider_table(Some(proxy_base_url), false);
|
||||
|
||||
providers.insert(
|
||||
CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID,
|
||||
toml_edit::Item::Table(table),
|
||||
);
|
||||
doc["model_providers"] = toml_edit::Item::Table(providers);
|
||||
Ok(doc.to_string())
|
||||
}
|
||||
|
||||
/// Whether a live Codex config is the official route projected by CC Switch.
|
||||
pub fn codex_config_has_official_proxy_route(config_text: &str) -> bool {
|
||||
if !config_text.contains(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID) {
|
||||
return false;
|
||||
}
|
||||
config_text
|
||||
.parse::<DocumentMut>()
|
||||
.ok()
|
||||
.and_then(|doc| {
|
||||
doc.get("model_provider")
|
||||
.and_then(|item| item.as_str())
|
||||
.map(str::to_string)
|
||||
})
|
||||
.as_deref()
|
||||
== Some(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID)
|
||||
}
|
||||
|
||||
/// Remove only the official takeover route owned by CC Switch. This is a
|
||||
/// last-resort crash cleanup when no live backup or provider SSOT is usable.
|
||||
pub fn remove_codex_official_proxy_route(config_text: &str) -> Result<String, AppError> {
|
||||
let mut doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
|
||||
if doc.get("model_provider").and_then(|item| item.as_str())
|
||||
!= Some(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID)
|
||||
{
|
||||
return Ok(config_text.to_string());
|
||||
}
|
||||
|
||||
doc.as_table_mut().remove("model_provider");
|
||||
if let Some(item) = doc.as_table_mut().remove("model_providers") {
|
||||
let mut providers = item.into_table().map_err(|_| {
|
||||
AppError::Message(
|
||||
"Invalid Codex config.toml: model_providers must be a table".to_string(),
|
||||
)
|
||||
})?;
|
||||
providers.remove(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID);
|
||||
remove_codex_proxy_placeholders_from_providers(&mut providers);
|
||||
if !providers.is_empty() {
|
||||
doc["model_providers"] = toml_edit::Item::Table(providers);
|
||||
}
|
||||
}
|
||||
Ok(doc.to_string())
|
||||
}
|
||||
|
||||
fn table_matches_codex_unified_official_provider(table: &toml_edit::Table) -> bool {
|
||||
table.len() == 4
|
||||
&& table.get("name").and_then(|item| item.as_str()) == Some("OpenAI")
|
||||
@@ -1473,6 +1650,45 @@ pub fn strip_codex_unified_session_bucket_from_settings(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Backfill helper: strip `[mcp_servers]` from a live `{ auth, config }`
|
||||
/// settings object before it is stored back to the DB.
|
||||
///
|
||||
/// MCP 服务器的 SSOT 是 DB 的 mcp_servers 表,live `config.toml` 里的
|
||||
/// `[mcp_servers]` 只是每次写 live 之后由 MCP 同步重新投影的产物。若回填时
|
||||
/// 烙进供应商存储配置,已在应用里删除的服务器会随下次激活该供应商被写回
|
||||
/// live,而逐条 reconcile 只认识 DB 现存条目、永远清不掉这种孤儿。
|
||||
pub fn strip_codex_mcp_servers_from_settings(settings: &mut Value) -> Result<(), AppError> {
|
||||
let Some(config_text) = settings
|
||||
.get("config")
|
||||
.and_then(|value| value.as_str())
|
||||
.map(str::to_string)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
if !config_text.contains("mcp") {
|
||||
return Ok(());
|
||||
}
|
||||
let mut doc = config_text
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?;
|
||||
let mut changed = doc.as_table_mut().remove("mcp_servers").is_some();
|
||||
// 历史错误格式 [mcp.servers] 一并清理(live 侧 MCP 同步也做同样迁移)
|
||||
if let Some(mcp_tbl) = doc.get_mut("mcp").and_then(|item| item.as_table_like_mut()) {
|
||||
if mcp_tbl.remove("servers").is_some() {
|
||||
changed = true;
|
||||
}
|
||||
if mcp_tbl.is_empty() {
|
||||
doc.as_table_mut().remove("mcp");
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
if let Some(obj) = settings.as_object_mut() {
|
||||
obj.insert("config".to_string(), Value::String(doc.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Route a Codex live write between full auth+config or config-only.
|
||||
///
|
||||
/// Official providers with usable login material own `auth.json`. Third-party
|
||||
@@ -1700,6 +1916,26 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn catalog_tool_profile_from_api_format() {
|
||||
assert_eq!(
|
||||
CodexCatalogToolProfile::from_api_format(Some("anthropic")),
|
||||
CodexCatalogToolProfile::Anthropic
|
||||
);
|
||||
assert_eq!(
|
||||
CodexCatalogToolProfile::from_api_format(Some("openai_responses")),
|
||||
CodexCatalogToolProfile::NativeResponses
|
||||
);
|
||||
assert_eq!(
|
||||
CodexCatalogToolProfile::from_api_format(Some("openai_chat")),
|
||||
CodexCatalogToolProfile::ProxyChat
|
||||
);
|
||||
assert_eq!(
|
||||
CodexCatalogToolProfile::from_api_format(None),
|
||||
CodexCatalogToolProfile::ProxyChat
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unified_session_bucket_injects_for_empty_official_config() {
|
||||
let injected = inject_codex_unified_session_bucket("").expect("inject");
|
||||
@@ -1727,6 +1963,98 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_proxy_route_uses_native_auth_and_local_responses_provider() {
|
||||
let input = r#"model = "gpt-5.4"
|
||||
experimental_bearer_token = "PROXY_MANAGED"
|
||||
|
||||
[mcp_servers.example]
|
||||
command = "example"
|
||||
"#;
|
||||
let output = apply_codex_official_proxy_route(input, "http://127.0.0.1:15721/v1")
|
||||
.expect("apply official proxy route");
|
||||
let doc: toml::Value = toml::from_str(&output).expect("parse output");
|
||||
|
||||
assert_eq!(
|
||||
doc.get("model_provider").and_then(toml::Value::as_str),
|
||||
Some(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID)
|
||||
);
|
||||
assert!(doc.get("experimental_bearer_token").is_none());
|
||||
assert!(
|
||||
doc.get("mcp_servers").is_some(),
|
||||
"unrelated config survives"
|
||||
);
|
||||
|
||||
let provider = &doc["model_providers"][CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID];
|
||||
assert_eq!(
|
||||
provider.get("base_url").and_then(toml::Value::as_str),
|
||||
Some("http://127.0.0.1:15721/v1")
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.get("requires_openai_auth")
|
||||
.and_then(toml::Value::as_bool),
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(
|
||||
provider
|
||||
.get("supports_websockets")
|
||||
.and_then(toml::Value::as_bool),
|
||||
Some(false)
|
||||
);
|
||||
assert!(codex_config_has_official_proxy_route(&output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_proxy_route_cleanup_only_removes_owned_provider() {
|
||||
let projected =
|
||||
apply_codex_official_proxy_route("model = \"gpt-5.4\"\n", "http://127.0.0.1:15721/v1")
|
||||
.expect("project");
|
||||
let cleaned = remove_codex_official_proxy_route(&projected).expect("clean");
|
||||
let doc: toml::Value = toml::from_str(&cleaned).expect("parse cleaned");
|
||||
assert!(doc.get("model_provider").is_none());
|
||||
assert!(doc.get("model_providers").is_none());
|
||||
assert_eq!(
|
||||
doc.get("model").and_then(toml::Value::as_str),
|
||||
Some("gpt-5.4")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_proxy_route_rejects_non_table_model_providers_without_panicking() {
|
||||
for input in [
|
||||
"model_providers = 3\n",
|
||||
"[[model_providers]]\nname = \"broken\"\n",
|
||||
] {
|
||||
let result = apply_codex_official_proxy_route(input, "http://127.0.0.1:15721/v1");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_proxy_route_normalizes_inline_tables_and_cleans_stale_placeholder() {
|
||||
let input = r#"model_provider = "rightcode"
|
||||
model_providers = { rightcode = { name = "RightCode", experimental_bearer_token = "PROXY_MANAGED" } }
|
||||
"#;
|
||||
let projected = apply_codex_official_proxy_route(input, "http://127.0.0.1:15721/v1")
|
||||
.expect("project inline provider table");
|
||||
let projected_doc: toml::Value = toml::from_str(&projected).expect("parse projected");
|
||||
assert!(projected_doc["model_providers"]["rightcode"]
|
||||
.get("experimental_bearer_token")
|
||||
.is_none());
|
||||
assert!(projected_doc["model_providers"]
|
||||
.get(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID)
|
||||
.is_some());
|
||||
|
||||
let cleaned = remove_codex_official_proxy_route(&projected).expect("clean projected");
|
||||
let cleaned_doc: toml::Value = toml::from_str(&cleaned).expect("parse cleaned");
|
||||
assert!(cleaned_doc.get("model_provider").is_none());
|
||||
assert!(cleaned_doc["model_providers"].get("rightcode").is_some());
|
||||
assert!(cleaned_doc["model_providers"]
|
||||
.get(CC_SWITCH_CODEX_OFFICIAL_PROXY_PROVIDER_ID)
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unified_session_bucket_preserves_other_keys_and_explicit_routing() {
|
||||
let with_catalog = "model_catalog_json = \"cc-switch-model-catalog.json\"\n";
|
||||
@@ -1803,6 +2131,41 @@ requires_openai_auth = true
|
||||
assert!(settings.pointer("/auth/tokens/access_token").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_mcp_servers_from_settings_removes_table_and_legacy_form() {
|
||||
let mut settings = json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-test" },
|
||||
"config": "# user comment\nmodel = \"gpt-5.5\"\n\n[mcp_servers.echo]\ntype = \"stdio\"\ncommand = \"echo\"\n\n[mcp.servers.legacy]\ncommand = \"noop\"\n",
|
||||
});
|
||||
strip_codex_mcp_servers_from_settings(&mut settings).expect("strip mcp");
|
||||
let config = settings
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("config text");
|
||||
assert!(!config.contains("mcp_servers"), "got: {config}");
|
||||
assert!(
|
||||
!config.contains("[mcp"),
|
||||
"legacy [mcp.servers] gone: {config}"
|
||||
);
|
||||
assert!(config.contains("# user comment"), "comments preserved");
|
||||
assert!(config.contains("model = \"gpt-5.5\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_mcp_servers_from_settings_is_noop_without_mcp() {
|
||||
let original = "# comment\nmodel = \"gpt-5.5\"\n";
|
||||
let mut settings = json!({
|
||||
"auth": {},
|
||||
"config": original,
|
||||
});
|
||||
strip_codex_mcp_servers_from_settings(&mut settings).expect("strip mcp");
|
||||
assert_eq!(
|
||||
settings.get("config").and_then(|v| v.as_str()),
|
||||
Some(original),
|
||||
"config text must be byte-identical when nothing is stripped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_base_url_prefers_active_provider_section() {
|
||||
let input = r#"model_provider = "azure"
|
||||
@@ -2455,6 +2818,85 @@ base_url = "https://production.api/v1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_infers_image_input_independently_of_tool_profile() {
|
||||
// Start from a deliberately text-only template to prove that every
|
||||
// profile overwrites template defaults with shared capability logic.
|
||||
let template = json!({
|
||||
"input_modalities": ["text"],
|
||||
"apply_patch_tool_type": "freeform"
|
||||
});
|
||||
let specs = vec![
|
||||
CodexCatalogModelSpec {
|
||||
model: "gpt-5.4".to_string(),
|
||||
display_name: "GPT 5.4".to_string(),
|
||||
context_window: 128_000,
|
||||
supports_parallel_tool_calls: None,
|
||||
input_modalities: None,
|
||||
base_instructions: None,
|
||||
},
|
||||
CodexCatalogModelSpec {
|
||||
model: "deepseek/deepseek-v4-pro".to_string(),
|
||||
display_name: "DeepSeek V4 Pro".to_string(),
|
||||
context_window: 128_000,
|
||||
supports_parallel_tool_calls: None,
|
||||
input_modalities: None,
|
||||
base_instructions: None,
|
||||
},
|
||||
CodexCatalogModelSpec {
|
||||
model: "glm-5.2v".to_string(),
|
||||
display_name: "GLM 5.2V".to_string(),
|
||||
context_window: 128_000,
|
||||
supports_parallel_tool_calls: None,
|
||||
input_modalities: None,
|
||||
base_instructions: None,
|
||||
},
|
||||
CodexCatalogModelSpec {
|
||||
model: "deepseek-v4-flash".to_string(),
|
||||
display_name: "Explicit Visual Override".to_string(),
|
||||
context_window: 128_000,
|
||||
supports_parallel_tool_calls: None,
|
||||
input_modalities: Some(vec!["text".to_string(), "image".to_string()]),
|
||||
base_instructions: None,
|
||||
},
|
||||
CodexCatalogModelSpec {
|
||||
model: "custom-text-alias".to_string(),
|
||||
display_name: "Explicit Text Override".to_string(),
|
||||
context_window: 128_000,
|
||||
supports_parallel_tool_calls: None,
|
||||
input_modalities: Some(vec!["text".to_string()]),
|
||||
base_instructions: None,
|
||||
},
|
||||
];
|
||||
|
||||
for profile in [
|
||||
CodexCatalogToolProfile::ProxyChat,
|
||||
CodexCatalogToolProfile::NativeResponses,
|
||||
CodexCatalogToolProfile::Anthropic,
|
||||
] {
|
||||
let catalog = codex_model_catalog_from_specs(&specs, &template, profile);
|
||||
let models = catalog["models"].as_array().expect("models array");
|
||||
let modalities = |slug: &str| {
|
||||
models
|
||||
.iter()
|
||||
.find(|entry| entry["slug"] == slug)
|
||||
.and_then(|entry| entry.get("input_modalities"))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null)
|
||||
};
|
||||
|
||||
assert_eq!(modalities("gpt-5.4"), json!(["text", "image"]));
|
||||
assert_eq!(modalities("deepseek/deepseek-v4-pro"), json!(["text"]));
|
||||
assert_eq!(modalities("glm-5.2v"), json!(["text", "image"]));
|
||||
assert_eq!(
|
||||
modalities("deepseek-v4-flash"),
|
||||
json!(["text", "image"]),
|
||||
"explicit provider metadata must override the text-only registry"
|
||||
);
|
||||
assert_eq!(modalities("custom-text-alias"), json!(["text"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_responses_catalog_always_carries_base_instructions() {
|
||||
// Regression guard for the "missing field `base_instructions`" parse
|
||||
@@ -2598,6 +3040,42 @@ web_search = "disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anthropic_profile_disables_web_search_without_catalog() {
|
||||
// Regression: even when no model catalog is generated (empty/absent
|
||||
// modelCatalog), an Anthropic provider must still disable web_search — the
|
||||
// Responses→Anthropic transform drops the hosted tool, so leaving it on
|
||||
// exposes a dead tool. The None-catalog branch previously always left it on.
|
||||
let config = "model = \"claude-sonnet-4-6\"\n";
|
||||
let settings = serde_json::json!({});
|
||||
|
||||
let anthropic = prepare_codex_config_text_with_model_catalog(
|
||||
&settings,
|
||||
config,
|
||||
CodexCatalogToolProfile::Anthropic,
|
||||
)
|
||||
.unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&anthropic).unwrap();
|
||||
assert_eq!(
|
||||
parsed.get("web_search").and_then(|v| v.as_str()),
|
||||
Some("disabled"),
|
||||
"Anthropic profile must disable web_search even with no catalog"
|
||||
);
|
||||
|
||||
// ProxyChat on the same no-catalog path must NOT add a disable line.
|
||||
let proxy = prepare_codex_config_text_with_model_catalog(
|
||||
&settings,
|
||||
config,
|
||||
CodexCatalogToolProfile::ProxyChat,
|
||||
)
|
||||
.unwrap();
|
||||
let parsed: toml::Value = toml::from_str(&proxy).unwrap();
|
||||
assert!(
|
||||
parsed.get("web_search").is_none(),
|
||||
"ProxyChat profile must not disable web_search on the no-catalog path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn web_search_blacklist_disables_only_known_reject_gateways() {
|
||||
let cfg = |model: &str, base_url: &str| {
|
||||
@@ -2610,7 +3088,7 @@ web_search = "disabled"
|
||||
for (model, host) in [
|
||||
("mimo-v2.5-pro", "https://api.xiaomimimo.com/v1"),
|
||||
("mimo-v2.5", "https://token-plan-cn.xiaomimimo.com/v1"),
|
||||
("LongCat-2.0-Preview", "https://api.longcat.chat/openai/v1"),
|
||||
("LongCat-2.0", "https://api.longcat.chat/openai/v1"),
|
||||
("MiniMax-M3", "https://api.minimax.io/v1"),
|
||||
("MiniMax-M3", "https://api.minimaxi.com/v1"),
|
||||
] {
|
||||
@@ -2768,6 +3246,40 @@ web_search = "disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_simplified_catalog_squashes_inferred_modalities_and_keeps_overrides() {
|
||||
let catalog = r#"{
|
||||
"models": [
|
||||
{ "slug": "gpt-5.4", "input_modalities": ["text", "image"] },
|
||||
{ "slug": "deepseek-v4-pro", "input_modalities": ["text"] },
|
||||
{ "slug": "gpt-text-override", "input_modalities": ["text"] },
|
||||
{ "slug": "deepseek-v4-flash", "input_modalities": ["text", "image"] }
|
||||
]
|
||||
}"#;
|
||||
|
||||
let result = build_simplified_catalog_from_texts("", catalog).expect("entries");
|
||||
let models = result.get("models").unwrap().as_array().unwrap();
|
||||
|
||||
assert!(
|
||||
models[0].get("inputModalities").is_none(),
|
||||
"GPT text+image is inferred and must not become a sticky hidden override"
|
||||
);
|
||||
assert!(
|
||||
models[1].get("inputModalities").is_none(),
|
||||
"confirmed text-only capability is inferred and must remain registry-driven"
|
||||
);
|
||||
assert_eq!(
|
||||
models[2].get("inputModalities"),
|
||||
Some(&json!(["text"])),
|
||||
"an unknown model explicitly forced to text-only must round-trip"
|
||||
);
|
||||
assert_eq!(
|
||||
models[3].get("inputModalities"),
|
||||
Some(&json!(["text", "image"])),
|
||||
"an explicit image override for a registered text-only model must round-trip"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_simplified_catalog_returns_none_when_unparseable() {
|
||||
assert!(build_simplified_catalog_from_texts("", "not json").is_none());
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use crate::codex_config::{
|
||||
get_codex_config_dir, read_codex_config_text, CC_SWITCH_CODEX_MODEL_PROVIDER_ID,
|
||||
};
|
||||
use crate::codex_state_db::codex_state_db_paths;
|
||||
use crate::config::{atomic_write, copy_file, get_app_config_dir};
|
||||
use crate::database::{is_official_seed_id, Database};
|
||||
use crate::error::AppError;
|
||||
@@ -28,7 +29,6 @@ const MIGRATION_NAME: &str = "codex-history-provider-migration-v1";
|
||||
const OFFICIAL_UNIFY_MIGRATION_NAME: &str = "codex-official-history-unify-v1";
|
||||
/// 还原操作自身的备份目录(与迁移备份分开,保持迁移账本目录纯净)。
|
||||
const OFFICIAL_UNIFY_RESTORE_BACKUP_NAME: &str = "codex-official-history-unify-restore-v1";
|
||||
const CODEX_STATE_DB_FILENAME: &str = "state_5.sqlite";
|
||||
/// SQLite 变量上限保守值,IN 列表按此分块。
|
||||
const STATE_DB_ID_CHUNK: usize = 500;
|
||||
|
||||
@@ -1116,55 +1116,6 @@ fn migrate_codex_state_dbs(
|
||||
Ok(migrated)
|
||||
}
|
||||
|
||||
fn codex_state_db_paths(codex_dir: &Path, config_text: &str) -> Vec<PathBuf> {
|
||||
let mut paths = Vec::new();
|
||||
push_unique_path(&mut paths, codex_dir.join(CODEX_STATE_DB_FILENAME));
|
||||
// Codex lets SQLite state move away from CODEX_HOME; config takes precedence.
|
||||
if let Some(sqlite_home) = sqlite_home_from_codex_config(config_text) {
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
} else if let Some(sqlite_home) = sqlite_home_from_env() {
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_home_from_codex_config(config_text: &str) -> Option<PathBuf> {
|
||||
let doc = config_text.parse::<DocumentMut>().ok()?;
|
||||
let raw = doc.get("sqlite_home")?.as_str()?.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn sqlite_home_from_env() -> Option<PathBuf> {
|
||||
let raw = std::env::var("CODEX_SQLITE_HOME").ok()?;
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn resolve_user_path(raw: &str) -> PathBuf {
|
||||
if raw == "~" {
|
||||
return crate::config::get_home_dir();
|
||||
}
|
||||
if let Some(rest) = raw.strip_prefix("~/") {
|
||||
return crate::config::get_home_dir().join(rest);
|
||||
}
|
||||
if let Some(rest) = raw.strip_prefix("~\\") {
|
||||
return crate::config::get_home_dir().join(rest);
|
||||
}
|
||||
PathBuf::from(raw)
|
||||
}
|
||||
|
||||
fn migrate_codex_state_db_provider_bucket(
|
||||
db_path: &Path,
|
||||
codex_dir: &Path,
|
||||
@@ -1329,6 +1280,7 @@ fn relative_backup_path(path: &Path, root: &Path) -> PathBuf {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::codex_state_db::CODEX_STATE_DB_FILENAME;
|
||||
use crate::provider::Provider;
|
||||
use serial_test::serial;
|
||||
use std::ffi::OsString;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! Locating Codex's per-thread state SQLite databases.
|
||||
//!
|
||||
//! Codex stores thread metadata in `state_5.sqlite`, normally inside the Codex
|
||||
//! config dir (`CODEX_HOME` / `~/.codex`). The SQLite location can be moved with
|
||||
//! the `sqlite_home` key in `config.toml` or the `CODEX_SQLITE_HOME` env var;
|
||||
//! when set, a second DB lives there. Both history migration and the session
|
||||
//! list's title lookup need the same resolution, so it lives here once.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use toml_edit::DocumentMut;
|
||||
|
||||
use crate::config::get_home_dir;
|
||||
|
||||
/// Filename of Codex's per-thread state database. Codex bumps the version
|
||||
/// number across releases; update this single source of truth when a new state
|
||||
/// DB version ships.
|
||||
pub(crate) const CODEX_STATE_DB_FILENAME: &str = "state_5.sqlite";
|
||||
|
||||
/// Env var that overrides the Codex SQLite state directory.
|
||||
const CODEX_SQLITE_HOME_ENV: &str = "CODEX_SQLITE_HOME";
|
||||
|
||||
/// Resolve every candidate `state_5.sqlite` path: the config-dir DB plus, when
|
||||
/// Codex is configured to keep its SQLite state elsewhere, that DB too.
|
||||
///
|
||||
/// `config_dir` is the Codex config dir (`~/.codex`); `config_text` is the raw
|
||||
/// `config.toml` contents, used to detect a `sqlite_home` override.
|
||||
pub(crate) fn codex_state_db_paths(config_dir: &Path, config_text: &str) -> Vec<PathBuf> {
|
||||
let mut paths = Vec::new();
|
||||
push_unique_path(&mut paths, config_dir.join(CODEX_STATE_DB_FILENAME));
|
||||
// Codex lets SQLite state move away from CODEX_HOME; config takes precedence.
|
||||
if let Some(sqlite_home) = sqlite_home_from_codex_config(config_text) {
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
} else if let Some(sqlite_home) = sqlite_home_from_env() {
|
||||
push_unique_path(&mut paths, sqlite_home.join(CODEX_STATE_DB_FILENAME));
|
||||
}
|
||||
paths
|
||||
}
|
||||
|
||||
fn push_unique_path(paths: &mut Vec<PathBuf>, path: PathBuf) {
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
fn sqlite_home_from_codex_config(config_text: &str) -> Option<PathBuf> {
|
||||
let doc = config_text.parse::<DocumentMut>().ok()?;
|
||||
let raw = doc.get("sqlite_home")?.as_str()?.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn sqlite_home_from_env() -> Option<PathBuf> {
|
||||
let raw = std::env::var(CODEX_SQLITE_HOME_ENV).ok()?;
|
||||
let raw = raw.trim();
|
||||
if raw.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(resolve_user_path(raw))
|
||||
}
|
||||
|
||||
fn resolve_user_path(raw: &str) -> PathBuf {
|
||||
if raw == "~" {
|
||||
return get_home_dir();
|
||||
}
|
||||
if let Some(rest) = raw.strip_prefix("~/") {
|
||||
return get_home_dir().join(rest);
|
||||
}
|
||||
if let Some(rest) = raw.strip_prefix("~\\") {
|
||||
return get_home_dir().join(rest);
|
||||
}
|
||||
PathBuf::from(raw)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn includes_config_sqlite_home() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let sqlite_home = temp.path().join("sqlite-home");
|
||||
let config_text = format!("sqlite_home = \"{}\"\n", sqlite_home.display());
|
||||
|
||||
let paths = codex_state_db_paths(temp.path(), &config_text);
|
||||
|
||||
assert_eq!(
|
||||
paths,
|
||||
vec![
|
||||
temp.path().join(CODEX_STATE_DB_FILENAME),
|
||||
sqlite_home.join(CODEX_STATE_DB_FILENAME),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -49,13 +49,14 @@ pub async fn get_codex_oauth_quota(
|
||||
}
|
||||
};
|
||||
|
||||
Ok(query_codex_quota(
|
||||
// 瞬时传输失败以 Err 传播(前端 reject → retry + 保留上次成功值)。
|
||||
query_codex_quota(
|
||||
&token,
|
||||
Some(&id),
|
||||
"codex_oauth",
|
||||
"Codex OAuth access token expired or rejected. Please re-login via cc-switch.",
|
||||
)
|
||||
.await)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 获取 Codex OAuth (ChatGPT Plus/Pro) 可用模型列表
|
||||
|
||||
@@ -7,12 +7,19 @@ pub async fn get_coding_plan_quota(
|
||||
// 火山方舟用控制面 AK/SK 签名查询用量;其他供应商不传,沿用 api_key。
|
||||
access_key_id: Option<String>,
|
||||
secret_access_key: Option<String>,
|
||||
// 智谱团队版(zhipu_team)靠显式标识路由(base_url 与个人版相同无法区分)。
|
||||
coding_plan_provider: Option<String>,
|
||||
team_organization_id: Option<String>,
|
||||
team_project_id: Option<String>,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
crate::services::coding_plan::get_coding_plan_quota(
|
||||
&base_url,
|
||||
&api_key,
|
||||
access_key_id.as_deref(),
|
||||
secret_access_key.as_deref(),
|
||||
coding_plan_provider.as_deref(),
|
||||
team_organization_id.as_deref(),
|
||||
team_project_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -275,6 +275,23 @@ pub async fn get_common_config_snippet(
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 对前端编辑器里的 config.toml 文本做通用配置片段的合并/剥离。
|
||||
/// 放后端是为了走 toml_edit(保注释、保键序);前端 smol-toml 的
|
||||
/// 整文档重序列化会破坏用户手写格式。
|
||||
#[tauri::command]
|
||||
pub async fn update_toml_common_config_snippet(
|
||||
config_toml: String,
|
||||
snippet_toml: String,
|
||||
enabled: bool,
|
||||
) -> Result<String, String> {
|
||||
crate::services::provider::update_toml_common_config_snippet(
|
||||
&config_toml,
|
||||
&snippet_toml,
|
||||
enabled,
|
||||
)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn set_common_config_snippet(
|
||||
app_type: String,
|
||||
|
||||
@@ -197,11 +197,5 @@ pub async fn toggle_mcp_app(
|
||||
/// 从所有应用导入 MCP 服务器(复用已有的导入逻辑)
|
||||
#[tauri::command]
|
||||
pub async fn import_mcp_from_apps(state: State<'_, AppState>) -> Result<usize, String> {
|
||||
let mut total = 0;
|
||||
total += McpService::import_from_claude(&state).unwrap_or(0);
|
||||
total += McpService::import_from_codex(&state).unwrap_or(0);
|
||||
total += McpService::import_from_gemini(&state).unwrap_or(0);
|
||||
total += McpService::import_from_opencode(&state).unwrap_or(0);
|
||||
total += McpService::import_from_hermes(&state).unwrap_or(0);
|
||||
Ok(total)
|
||||
McpService::import_from_all_apps(&state).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ mod model_fetch;
|
||||
mod omo;
|
||||
mod openclaw;
|
||||
mod plugin;
|
||||
mod profile;
|
||||
mod prompt;
|
||||
mod provider;
|
||||
mod proxy;
|
||||
@@ -52,6 +53,7 @@ pub use model_fetch::*;
|
||||
pub use omo::*;
|
||||
pub use openclaw::*;
|
||||
pub use plugin::*;
|
||||
pub use profile::*;
|
||||
pub use prompt::*;
|
||||
pub use provider::*;
|
||||
pub use proxy::*;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! 项目 Profile 管理命令
|
||||
|
||||
use serde::Serialize;
|
||||
use tauri::{Emitter, Manager, State};
|
||||
|
||||
use crate::database::Profile;
|
||||
use crate::services::profile::{ProfilePayload, ProfileScope, ProfileService};
|
||||
use crate::store::AppState;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfileDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub payload: ProfilePayload,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub created_at: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub updated_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl From<Profile> for ProfileDto {
|
||||
fn from(profile: Profile) -> Self {
|
||||
// 单条 payload 损坏不应拖垮整个列表:降级为默认值并记日志
|
||||
let payload = serde_json::from_str(&profile.payload).unwrap_or_else(|e| {
|
||||
log::warn!(
|
||||
"解析 profile '{}' payload 失败,使用默认值: {e}",
|
||||
profile.id
|
||||
);
|
||||
ProfilePayload::default()
|
||||
});
|
||||
Self {
|
||||
id: profile.id,
|
||||
name: profile.name,
|
||||
payload,
|
||||
created_at: profile.created_at,
|
||||
updated_at: profile.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 每个分组当前激活的项目 id(未使用项目时为 null)
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CurrentProfileIds {
|
||||
pub claude: Option<String>,
|
||||
pub claude_desktop: Option<String>,
|
||||
pub codex: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfilesResponse {
|
||||
pub profiles: Vec<ProfileDto>,
|
||||
pub current_ids: CurrentProfileIds,
|
||||
}
|
||||
|
||||
/// Profile 应用完成后的统一收尾:发事件 + 重建托盘菜单
|
||||
///
|
||||
/// 只对项目所属分组内的应用发 provider-switched。UI 与托盘两个入口必须
|
||||
/// 共用此函数,保证事件 payload 形状一致(前端 App.tsx 的
|
||||
/// provider-switched 监听依赖该形状)。
|
||||
pub fn emit_profile_apply_events(
|
||||
app: &tauri::AppHandle,
|
||||
state: &AppState,
|
||||
profile_id: &str,
|
||||
scope: ProfileScope,
|
||||
) {
|
||||
for app_type in scope.apps().iter() {
|
||||
let app_str = app_type.as_str();
|
||||
let (proxy_enabled, auto_failover_enabled) = state.db.get_proxy_flags_sync(app_str);
|
||||
let provider_id = crate::settings::get_effective_current_provider(&state.db, app_type)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
let event_data = serde_json::json!({
|
||||
"appType": app_str,
|
||||
"proxyEnabled": proxy_enabled,
|
||||
"autoFailoverEnabled": auto_failover_enabled,
|
||||
"providerId": provider_id,
|
||||
});
|
||||
if let Err(e) = app.emit("provider-switched", event_data) {
|
||||
log::error!("发射 provider-switched 事件失败: {e}");
|
||||
}
|
||||
}
|
||||
if let Err(e) = app.emit(
|
||||
"profile-applied",
|
||||
serde_json::json!({ "profileId": profile_id, "scope": scope.as_str() }),
|
||||
) {
|
||||
log::error!("发射 profile-applied 事件失败: {e}");
|
||||
}
|
||||
crate::tray::refresh_tray_menu(app);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_profiles(state: State<'_, AppState>) -> Result<ProfilesResponse, String> {
|
||||
let profiles = ProfileService::list(&state).map_err(|e| e.to_string())?;
|
||||
let current_ids = CurrentProfileIds {
|
||||
claude: state
|
||||
.db
|
||||
.get_current_profile_id(ProfileScope::Claude.as_str())
|
||||
.map_err(|e| e.to_string())?,
|
||||
claude_desktop: state
|
||||
.db
|
||||
.get_current_profile_id(ProfileScope::ClaudeDesktop.as_str())
|
||||
.map_err(|e| e.to_string())?,
|
||||
codex: state
|
||||
.db
|
||||
.get_current_profile_id(ProfileScope::Codex.as_str())
|
||||
.map_err(|e| e.to_string())?,
|
||||
};
|
||||
Ok(ProfilesResponse {
|
||||
profiles: profiles.into_iter().map(ProfileDto::from).collect(),
|
||||
current_ids,
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn create_profile(
|
||||
state: State<'_, AppState>,
|
||||
name: String,
|
||||
scope: String,
|
||||
) -> Result<ProfileDto, String> {
|
||||
let scope = ProfileScope::parse(&scope).map_err(|e| e.to_string())?;
|
||||
ProfileService::create(&state, &name, scope)
|
||||
.map(ProfileDto::from)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn update_profile(
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
name: Option<String>,
|
||||
resnapshot: Option<bool>,
|
||||
scope: Option<String>,
|
||||
) -> Result<ProfileDto, String> {
|
||||
let scope = scope
|
||||
.map(|s| ProfileScope::parse(&s))
|
||||
.transpose()
|
||||
.map_err(|e| e.to_string())?;
|
||||
ProfileService::update(&state, &id, name, resnapshot.unwrap_or(false), scope)
|
||||
.map(ProfileDto::from)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(state: State<'_, AppState>, id: String) -> Result<(), String> {
|
||||
ProfileService::delete(&state, &id).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn clear_current_profile(state: State<'_, AppState>, scope: String) -> Result<(), String> {
|
||||
let scope = ProfileScope::parse(&scope).map_err(|e| e.to_string())?;
|
||||
state
|
||||
.db
|
||||
.set_current_profile_id(scope.as_str(), None)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// 应用项目快照(只作用于发起页所属分组内的应用)。
|
||||
///
|
||||
/// 注意:必须保持同步命令(跑在 Tauri 线程池)——`ProviderService::switch`
|
||||
/// 内部使用 block_on 获取切换锁,放进 async 命令会在运行时线程上 panic。
|
||||
#[tauri::command]
|
||||
pub fn apply_profile(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
id: String,
|
||||
scope: String,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let scope = ProfileScope::parse(&scope).map_err(|e| e.to_string())?;
|
||||
let (warnings, should_stop_proxy) =
|
||||
ProfileService::apply(&state, &id, scope).map_err(|e| e.to_string())?;
|
||||
|
||||
if should_stop_proxy {
|
||||
// sync 命令线程没有 Tokio runtime,无法直接 await stop();
|
||||
// 把停止服务放到 Tauri async runtime,停止后再补发事件刷新 UI。
|
||||
let app_handle = app.clone();
|
||||
let profile_id = id.clone();
|
||||
let proxy_service = state.proxy_service.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = proxy_service.stop().await {
|
||||
log::warn!("切换项目后停止代理服务失败: {e}");
|
||||
}
|
||||
if let Some(app_state) = app_handle.try_state::<AppState>() {
|
||||
emit_profile_apply_events(&app_handle, app_state.inner(), &profile_id, scope);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
emit_profile_apply_events(&app, &state, &id, scope);
|
||||
}
|
||||
|
||||
Ok(warnings)
|
||||
}
|
||||
@@ -231,6 +231,14 @@ pub fn ensure_claude_desktop_official_provider(state: State<'_, AppState>) -> Re
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn ensure_codex_official_provider(state: State<'_, AppState>) -> Result<bool, String> {
|
||||
state
|
||||
.db
|
||||
.ensure_official_seed_by_id(crate::database::CODEX_OFFICIAL_PROVIDER_ID, AppType::Codex)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn claude_provider_models_are_claude_safe(provider: &Provider) -> bool {
|
||||
let Some(env) = provider
|
||||
.settings_config
|
||||
@@ -381,32 +389,30 @@ pub async fn queryProviderUsage(
|
||||
) -> Result<crate::provider::UsageResult, String> {
|
||||
let app_type = AppType::from_str(&app).map_err(|e| e.to_string())?;
|
||||
// inner 可能以两种形式失败:
|
||||
// 1) 返回 Ok(UsageResult { success: false, .. }) —— 业务失败(401、脚本报错等)
|
||||
// 2) 返回 Err(String) —— RPC/DB/Copilot fetch_usage 等 transport 层失败
|
||||
// 两种都要把"失败"写进 UsageCache 并刷新托盘,让 format_script_summary 的
|
||||
// success 守卫生效、suffix 自然消失,避免旧 success 快照长期滞留。
|
||||
// 同时保持原始 Err 返回给前端 React Query 的 onError 回调,不吞错误。
|
||||
// 1) 返回 Ok(UsageResult { success: false, .. }) —— 确定性失败(401、脚本
|
||||
// 报错、未知供应商等)。写进 UsageCache 并刷新托盘,让
|
||||
// format_script_summary 的 success 守卫生效、suffix 自然消失。
|
||||
// 2) 返回 Err(String) —— 瞬时传输失败(网络/超时)及 DB/Copilot fetch 等。
|
||||
// 不写失败快照、不 emit:保留上一份托盘快照,与前端 react-query reject
|
||||
// 保留上次 data 的语义一致;否则失败快照会经 useUsageCacheBridge 盲写
|
||||
// 回 query 缓存,抹掉 reject 本该保留的旧值。
|
||||
let inner =
|
||||
query_provider_usage_inner(&state, &copilot_state, app_type.clone(), &providerId).await;
|
||||
let snapshot = match &inner {
|
||||
Ok(r) => r.clone(),
|
||||
Err(err_msg) => crate::provider::UsageResult {
|
||||
success: false,
|
||||
data: None,
|
||||
error: Some(err_msg.clone()),
|
||||
},
|
||||
};
|
||||
let payload = serde_json::json!({
|
||||
"kind": "script",
|
||||
"appType": app_type.as_str(),
|
||||
"providerId": &providerId,
|
||||
"data": &snapshot,
|
||||
});
|
||||
if let Err(e) = app_handle.emit("usage-cache-updated", payload) {
|
||||
log::error!("emit usage-cache-updated (script) 失败: {e}");
|
||||
if let Ok(snapshot) = &inner {
|
||||
let payload = serde_json::json!({
|
||||
"kind": "script",
|
||||
"appType": app_type.as_str(),
|
||||
"providerId": &providerId,
|
||||
"data": snapshot,
|
||||
});
|
||||
if let Err(e) = app_handle.emit("usage-cache-updated", payload) {
|
||||
log::error!("emit usage-cache-updated (script) 失败: {e}");
|
||||
}
|
||||
state
|
||||
.usage_cache
|
||||
.put_script(app_type, providerId, snapshot.clone());
|
||||
crate::tray::schedule_tray_refresh(&app_handle);
|
||||
}
|
||||
state.usage_cache.put_script(app_type, providerId, snapshot);
|
||||
crate::tray::schedule_tray_refresh(&app_handle);
|
||||
inner
|
||||
}
|
||||
|
||||
@@ -518,12 +524,20 @@ async fn query_provider_usage_inner(
|
||||
// 其他供应商为 None,service 层沿用 api_key。
|
||||
let access_key_id = usage_script.and_then(|s| s.access_key_id.clone());
|
||||
let secret_access_key = usage_script.and_then(|s| s.secret_access_key.clone());
|
||||
// 智谱团队版:显式 provider 标识 + 组织/项目 ID(与个人版智谱 base_url 相同,
|
||||
// 靠 coding_plan_provider == "zhipu_team" 在 service 层路由)。
|
||||
let coding_plan_provider = usage_script.and_then(|s| s.coding_plan_provider.clone());
|
||||
let team_organization_id = usage_script.and_then(|s| s.team_organization_id.clone());
|
||||
let team_project_id = usage_script.and_then(|s| s.team_project_id.clone());
|
||||
|
||||
let quota = crate::services::coding_plan::get_coding_plan_quota(
|
||||
&base_url,
|
||||
&api_key,
|
||||
access_key_id.as_deref(),
|
||||
secret_access_key.as_deref(),
|
||||
coding_plan_provider.as_deref(),
|
||||
team_organization_id.as_deref(),
|
||||
team_project_id.as_deref(),
|
||||
)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to query coding plan: {e}"))?;
|
||||
@@ -1081,6 +1095,8 @@ mod native_query_credentials_tests {
|
||||
coding_plan_provider: coding_plan_provider.map(str::to_string),
|
||||
access_key_id: None,
|
||||
secret_access_key: None,
|
||||
team_organization_id: None,
|
||||
team_project_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::error::AppError;
|
||||
use crate::proxy::types::*;
|
||||
use crate::proxy::{CircuitBreakerConfig, CircuitBreakerStats};
|
||||
use crate::store::AppState;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// 启动代理服务器(仅启动服务,不接管 Live 配置)
|
||||
#[tauri::command]
|
||||
@@ -279,13 +280,18 @@ pub async fn switch_proxy_provider(
|
||||
app_type: String,
|
||||
provider_id: String,
|
||||
) -> Result<(), String> {
|
||||
// Block official providers during proxy takeover
|
||||
// Codex's built-in official provider can use the client's native OpenAI
|
||||
// login through takeover. Other official providers remain blocked.
|
||||
let provider = state
|
||||
.db
|
||||
.get_provider_by_id(&provider_id, &app_type)
|
||||
.map_err(|e| format!("读取供应商失败: {e}"))?
|
||||
.ok_or_else(|| format!("供应商不存在: {provider_id}"))?;
|
||||
if provider.category.as_deref() == Some("official") {
|
||||
let app = crate::app_config::AppType::from_str(&app_type)
|
||||
.map_err(|e| format!("无效的应用类型: {e}"))?;
|
||||
if provider.category.as_deref() == Some("official")
|
||||
&& !crate::services::provider::official_provider_supports_proxy_takeover(&app, &provider)
|
||||
{
|
||||
return Err(
|
||||
"代理接管模式下不能切换到官方供应商 (Cannot switch to official provider during proxy takeover)"
|
||||
.to_string(),
|
||||
|
||||
@@ -661,15 +661,6 @@ pub async fn set_optimizer_config(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
config: crate::proxy::types::OptimizerConfig,
|
||||
) -> Result<bool, String> {
|
||||
// Validate cache_ttl: only allow known values
|
||||
match config.cache_ttl.as_str() {
|
||||
"5m" | "1h" => {}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"Invalid cache_ttl value: '{other}'. Allowed values: '5m', '1h'"
|
||||
))
|
||||
}
|
||||
}
|
||||
state
|
||||
.db
|
||||
.set_optimizer_config(&config)
|
||||
|
||||
@@ -72,6 +72,12 @@ pub async fn stream_check_all_providers(
|
||||
|
||||
let mut results = Vec::new();
|
||||
for (id, provider) in providers {
|
||||
// Official OAuth providers intentionally have no user-configured probe
|
||||
// target. Never turn their runtime adapter defaults into unauthenticated
|
||||
// network probes against first-party endpoints.
|
||||
if provider.category.as_deref() == Some("official") {
|
||||
continue;
|
||||
}
|
||||
if let Some(ids) = &allowed_ids {
|
||||
if !ids.contains(&id) {
|
||||
continue;
|
||||
|
||||
@@ -2,17 +2,19 @@ use std::str::FromStr;
|
||||
use tauri::{Emitter, State};
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::services::subscription::{CredentialStatus, SubscriptionQuota};
|
||||
use crate::services::subscription::SubscriptionQuota;
|
||||
use crate::store::AppState;
|
||||
|
||||
/// 查询官方订阅额度
|
||||
///
|
||||
/// 读取 CLI 工具已有的 OAuth 凭据并调用官方 API 获取使用额度。
|
||||
/// 结果(无论业务失败还是 transport 层 Err)都会写入 `UsageCache`、通知托盘
|
||||
/// 刷新,并 emit `usage-cache-updated`,让前端 React Query 与托盘共享同一份
|
||||
/// 最新数据。失败快照写入后 `format_subscription_summary` 会通过 `success=false`
|
||||
/// 守卫返回 `None`,托盘 suffix 自然消失,避免长期滞留旧配额数字。
|
||||
/// Err 原样向前端返回,React Query 的 onError 不会被吞掉。
|
||||
/// `Ok`(成功或确定性失败)写入 `UsageCache`、通知托盘刷新并 emit
|
||||
/// `usage-cache-updated`,让前端 React Query 与托盘共享同一份最新数据;失败
|
||||
/// 快照写入后 `format_subscription_summary` 会通过 `success=false` 守卫返回
|
||||
/// `None`,托盘 suffix 自然消失,避免长期滞留旧配额数字。
|
||||
/// `Err`(瞬时传输失败)不写快照、不 emit:保留上一份托盘快照,与前端
|
||||
/// react-query reject 保留上次 data 的语义一致(emit 失败快照会经
|
||||
/// `useUsageCacheBridge` 盲写回 query 缓存,抹掉本该保留的旧值)。
|
||||
#[tauri::command]
|
||||
pub async fn get_subscription_quota(
|
||||
app: tauri::AppHandle,
|
||||
@@ -20,22 +22,21 @@ pub async fn get_subscription_quota(
|
||||
tool: String,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
let inner = crate::services::subscription::get_subscription_quota(&tool).await;
|
||||
let snapshot = match &inner {
|
||||
Ok(q) => q.clone(),
|
||||
// transport 层 Err —— 凭据状态不明,用 Valid 表达"凭据没问题,是通信/parse 出错"。
|
||||
Err(err_msg) => SubscriptionQuota::error(&tool, CredentialStatus::Valid, err_msg.clone()),
|
||||
};
|
||||
if let Ok(app_type) = AppType::from_str(&tool) {
|
||||
let payload = serde_json::json!({
|
||||
"kind": "subscription",
|
||||
"appType": app_type.as_str(),
|
||||
"data": &snapshot,
|
||||
});
|
||||
if let Err(e) = app.emit("usage-cache-updated", payload) {
|
||||
log::error!("emit usage-cache-updated (subscription) 失败: {e}");
|
||||
if let Ok(snapshot) = &inner {
|
||||
if let Ok(app_type) = AppType::from_str(&tool) {
|
||||
let payload = serde_json::json!({
|
||||
"kind": "subscription",
|
||||
"appType": app_type.as_str(),
|
||||
"data": snapshot,
|
||||
});
|
||||
if let Err(e) = app.emit("usage-cache-updated", payload) {
|
||||
log::error!("emit usage-cache-updated (subscription) 失败: {e}");
|
||||
}
|
||||
state
|
||||
.usage_cache
|
||||
.put_subscription(app_type, snapshot.clone());
|
||||
crate::tray::schedule_tray_refresh(&app);
|
||||
}
|
||||
state.usage_cache.put_subscription(app_type, snapshot);
|
||||
crate::tray::schedule_tray_refresh(&app);
|
||||
}
|
||||
inner
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
pub mod failover;
|
||||
pub mod mcp;
|
||||
pub mod profiles;
|
||||
pub mod prompts;
|
||||
pub mod providers;
|
||||
pub mod providers_seed;
|
||||
@@ -15,5 +16,6 @@ pub mod universal_providers;
|
||||
pub mod usage_rollup;
|
||||
|
||||
// 所有 DAO 方法都通过 Database impl 提供,无需单独导出
|
||||
// 导出 FailoverQueueItem 供外部使用
|
||||
// 导出 FailoverQueueItem / Profile 供外部使用
|
||||
pub use failover::FailoverQueueItem;
|
||||
pub use profiles::Profile;
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
//! 项目 Profile 数据访问对象
|
||||
//!
|
||||
//! profiles 表存放全应用共享的项目实体(供应商/MCP/Skills/Prompt 快照),
|
||||
//! payload 为原始 JSON 文本(按 app 分槽),解析在 service 层进行。
|
||||
//! 各应用分组(scope)独立的 current 标记存放于 settings 表(key-value)。
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use rusqlite::params;
|
||||
|
||||
/// 每个 scope 的 current 标记 key = 前缀 + scope(如 current_profile_id_claude)
|
||||
const CURRENT_PROFILE_ID_KEY_PREFIX: &str = "current_profile_id_";
|
||||
|
||||
fn current_profile_key(scope: &str) -> String {
|
||||
format!("{CURRENT_PROFILE_ID_KEY_PREFIX}{scope}")
|
||||
}
|
||||
|
||||
/// 项目 Profile 记录(全应用共享,无所属分组)
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Profile {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// 原始 JSON 快照文本(ProfilePayload),解析在 service 层
|
||||
pub payload: String,
|
||||
pub sort_order: Option<i64>,
|
||||
pub created_at: Option<i64>,
|
||||
pub updated_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// 获取所有项目(按 sort_order 优先、created_at 兜底排序)
|
||||
pub fn get_all_profiles(&self) -> Result<Vec<Profile>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, name, payload, sort_order, created_at, updated_at
|
||||
FROM profiles
|
||||
ORDER BY sort_order IS NULL, sort_order, created_at, id",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok(Profile {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
payload: row.get(2)?,
|
||||
sort_order: row.get(3)?,
|
||||
created_at: row.get(4)?,
|
||||
updated_at: row.get(5)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
let mut profiles = Vec::new();
|
||||
for row in rows {
|
||||
profiles.push(row.map_err(|e| AppError::Database(e.to_string()))?);
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
/// 获取单个项目
|
||||
pub fn get_profile(&self, id: &str) -> Result<Option<Profile>, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT id, name, payload, sort_order, created_at, updated_at
|
||||
FROM profiles WHERE id = ?1",
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
match stmt.query_row(params![id], |row| {
|
||||
Ok(Profile {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
payload: row.get(2)?,
|
||||
sort_order: row.get(3)?,
|
||||
created_at: row.get(4)?,
|
||||
updated_at: row.get(5)?,
|
||||
})
|
||||
}) {
|
||||
Ok(profile) => Ok(Some(profile)),
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
|
||||
Err(e) => Err(AppError::Database(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存项目(插入或整行替换)
|
||||
pub fn save_profile(&self, profile: &Profile) -> Result<(), AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO profiles
|
||||
(id, name, payload, sort_order, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
params![
|
||||
profile.id,
|
||||
profile.name,
|
||||
profile.payload,
|
||||
profile.sort_order,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 删除项目,返回是否实际删除了记录
|
||||
pub fn delete_profile(&self, id: &str) -> Result<bool, AppError> {
|
||||
let conn = lock_conn!(self.conn);
|
||||
let affected = conn
|
||||
.execute("DELETE FROM profiles WHERE id = ?1", params![id])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(affected > 0)
|
||||
}
|
||||
|
||||
/// 读取某分组当前激活的项目 id(未使用项目时为 None)
|
||||
pub fn get_current_profile_id(&self, scope: &str) -> Result<Option<String>, AppError> {
|
||||
self.get_setting(¤t_profile_key(scope))
|
||||
}
|
||||
|
||||
/// 设置某分组当前激活的项目 id;None 表示"不使用项目"(删除 key)
|
||||
pub fn set_current_profile_id(&self, scope: &str, id: Option<&str>) -> Result<(), AppError> {
|
||||
let key = current_profile_key(scope);
|
||||
match id {
|
||||
Some(id) => self.set_setting(&key, id),
|
||||
None => {
|
||||
let conn = lock_conn!(self.conn);
|
||||
conn.execute("DELETE FROM settings WHERE key = ?1", params![key])
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(id: &str, name: &str, sort_order: Option<i64>) -> Profile {
|
||||
Profile {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
payload: r#"{"providers":{"claude":null,"codex":null}}"#.to_string(),
|
||||
sort_order,
|
||||
created_at: Some(1_000),
|
||||
updated_at: Some(1_000),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_profile_crud_roundtrip() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
db.save_profile(&sample("a", "Dev", Some(2)))?;
|
||||
db.save_profile(&sample("b", "Draw", Some(1)))?;
|
||||
db.save_profile(&sample("c", "Misc", None))?;
|
||||
|
||||
// sort_order 优先,NULL 排最后
|
||||
let all = db.get_all_profiles()?;
|
||||
assert_eq!(
|
||||
all.iter().map(|p| p.id.as_str()).collect::<Vec<_>>(),
|
||||
vec!["b", "a", "c"]
|
||||
);
|
||||
|
||||
let got = db.get_profile("a")?.expect("profile a exists");
|
||||
assert_eq!(got.name, "Dev");
|
||||
assert!(got.payload.contains("providers"));
|
||||
|
||||
// 整行替换更新
|
||||
let mut updated = sample("a", "Dev Renamed", Some(2));
|
||||
updated.updated_at = Some(2_000);
|
||||
db.save_profile(&updated)?;
|
||||
let got = db.get_profile("a")?.expect("profile a exists");
|
||||
assert_eq!(got.name, "Dev Renamed");
|
||||
assert_eq!(got.updated_at, Some(2_000));
|
||||
|
||||
assert!(db.delete_profile("a")?);
|
||||
assert!(!db.delete_profile("a")?);
|
||||
assert!(db.get_profile("a")?.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_current_profile_id_is_scoped() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
assert_eq!(db.get_current_profile_id("claude")?, None);
|
||||
assert_eq!(db.get_current_profile_id("codex")?, None);
|
||||
|
||||
// 两个分组的标记互不影响
|
||||
db.set_current_profile_id("claude", Some("a"))?;
|
||||
db.set_current_profile_id("codex", Some("b"))?;
|
||||
assert_eq!(db.get_current_profile_id("claude")?, Some("a".to_string()));
|
||||
assert_eq!(db.get_current_profile_id("codex")?, Some("b".to_string()));
|
||||
|
||||
db.set_current_profile_id("claude", None)?;
|
||||
assert_eq!(db.get_current_profile_id("claude")?, None);
|
||||
assert_eq!(db.get_current_profile_id("codex")?, Some("b".to_string()));
|
||||
|
||||
// 重复清除应幂等
|
||||
db.set_current_profile_id("claude", None)?;
|
||||
assert_eq!(db.get_current_profile_id("claude")?, None);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -710,7 +710,9 @@ impl Database {
|
||||
#[cfg(test)]
|
||||
mod ensure_official_seed_tests {
|
||||
use crate::app_config::AppType;
|
||||
use crate::database::{Database, CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID};
|
||||
use crate::database::{
|
||||
Database, CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID, CODEX_OFFICIAL_PROVIDER_ID,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn ensure_inserts_when_missing() {
|
||||
@@ -769,6 +771,25 @@ mod ensure_official_seed_tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_recreates_codex_official_seed_after_deletion() {
|
||||
let db = Database::memory().expect("memory db");
|
||||
db.init_default_official_providers().expect("seed");
|
||||
db.delete_provider(AppType::Codex.as_str(), CODEX_OFFICIAL_PROVIDER_ID)
|
||||
.expect("delete Codex official");
|
||||
|
||||
let inserted = db
|
||||
.ensure_official_seed_by_id(CODEX_OFFICIAL_PROVIDER_ID, AppType::Codex)
|
||||
.expect("ensure Codex official");
|
||||
assert!(inserted);
|
||||
let provider = db
|
||||
.get_provider_by_id(CODEX_OFFICIAL_PROVIDER_ID, AppType::Codex.as_str())
|
||||
.expect("query")
|
||||
.expect("Codex official restored");
|
||||
assert_eq!(provider.category.as_deref(), Some("official"));
|
||||
assert_eq!(provider.settings_config["auth"], serde_json::json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ensure_rejects_unknown_seed() {
|
||||
let db = Database::memory().expect("memory db");
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
use crate::app_config::AppType;
|
||||
|
||||
pub(crate) const CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID: &str = "claude-desktop-official";
|
||||
pub(crate) const CODEX_OFFICIAL_PROVIDER_ID: &str = "codex-official";
|
||||
|
||||
/// 单条官方供应商种子定义。
|
||||
pub(crate) struct OfficialProviderSeed {
|
||||
@@ -49,7 +50,7 @@ pub(crate) const OFFICIAL_SEEDS: &[OfficialProviderSeed] = &[
|
||||
settings_config_json: r#"{"env":{}}"#,
|
||||
},
|
||||
OfficialProviderSeed {
|
||||
id: "codex-official",
|
||||
id: CODEX_OFFICIAL_PROVIDER_ID,
|
||||
app_type: AppType::Codex,
|
||||
name: "OpenAI Official",
|
||||
website_url: "https://chatgpt.com/codex",
|
||||
|
||||
@@ -494,6 +494,23 @@ impl Database {
|
||||
Ok(count > 0)
|
||||
}
|
||||
|
||||
/// 同步版本:检查是否有任一 app 的 enabled = true
|
||||
///
|
||||
/// 用于 `ProfileService::apply` 等 sync 路径判断是否需要停止代理服务。
|
||||
pub fn is_live_takeover_active_sync(&self) -> bool {
|
||||
let conn = match self.conn.lock() {
|
||||
Ok(c) => c,
|
||||
Err(_) => return false,
|
||||
};
|
||||
conn.query_row(
|
||||
"SELECT COUNT(*) FROM proxy_config WHERE enabled = 1",
|
||||
[],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)
|
||||
.unwrap_or(0)
|
||||
> 0
|
||||
}
|
||||
|
||||
// ==================== Provider Health ====================
|
||||
|
||||
/// 获取Provider健康状态
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::services::sql_helpers::{fresh_input_sql, INPUT_TOKEN_SEMANTICS_FRESH};
|
||||
use crate::services::usage_stats::effective_usage_log_filter;
|
||||
use chrono::{Duration, Local, TimeZone};
|
||||
|
||||
@@ -115,6 +116,8 @@ impl Database {
|
||||
fn do_rollup_and_prune(conn: &rusqlite::Connection, cutoff: i64) -> Result<u64, AppError> {
|
||||
// Aggregate old logs, merging with any pre-existing rollup rows via LEFT JOIN.
|
||||
let effective_filter = effective_usage_log_filter("l");
|
||||
let fresh_detail_input = fresh_input_sql("l");
|
||||
let fresh_old_input = fresh_input_sql("old");
|
||||
// request_model 维度保留路由接管的「客户端别名 → 真实模型」映射,
|
||||
// pricing_model 维度保留写入时的计价基准(request 计价模式下与 model 分叉);
|
||||
// 明细行的这两列可能为 NULL(历史/手工数据),归一为 ''。
|
||||
@@ -124,15 +127,16 @@ impl Database {
|
||||
request_count, success_count,
|
||||
input_tokens, output_tokens,
|
||||
cache_read_tokens, cache_creation_tokens,
|
||||
total_cost_usd, avg_latency_ms)
|
||||
input_token_semantics, total_cost_usd, avg_latency_ms)
|
||||
SELECT
|
||||
d, a, p, m, rm, pm,
|
||||
COALESCE(old.request_count, 0) + new_req,
|
||||
COALESCE(old.success_count, 0) + new_succ,
|
||||
COALESCE(old.input_tokens, 0) + new_in,
|
||||
COALESCE({fresh_old_input}, 0) + new_in,
|
||||
COALESCE(old.output_tokens, 0) + new_out,
|
||||
COALESCE(old.cache_read_tokens, 0) + new_cr,
|
||||
COALESCE(old.cache_creation_tokens, 0) + new_cc,
|
||||
{INPUT_TOKEN_SEMANTICS_FRESH},
|
||||
CAST(COALESCE(CAST(old.total_cost_usd AS REAL), 0) + new_cost AS TEXT),
|
||||
CASE WHEN COALESCE(old.request_count, 0) + new_req > 0
|
||||
THEN (COALESCE(old.avg_latency_ms, 0) * COALESCE(old.request_count, 0)
|
||||
@@ -147,7 +151,7 @@ impl Database {
|
||||
COALESCE(l.pricing_model, '') as pm,
|
||||
COUNT(*) as new_req,
|
||||
SUM(CASE WHEN l.status_code >= 200 AND l.status_code < 300 THEN 1 ELSE 0 END) as new_succ,
|
||||
COALESCE(SUM(l.input_tokens), 0) as new_in,
|
||||
COALESCE(SUM({fresh_detail_input}), 0) as new_in,
|
||||
COALESCE(SUM(l.output_tokens), 0) as new_out,
|
||||
COALESCE(SUM(l.cache_read_tokens), 0) as new_cr,
|
||||
COALESCE(SUM(l.cache_creation_tokens), 0) as new_cc,
|
||||
@@ -327,7 +331,7 @@ mod tests {
|
||||
let (provider_id, request_count, input_tokens, output_tokens, cache_read_tokens) = &rows[0];
|
||||
assert_eq!(provider_id, "openai");
|
||||
assert_eq!(*request_count, 1);
|
||||
assert_eq!(*input_tokens, 100);
|
||||
assert_eq!(*input_tokens, 90, "rollup stores normalized fresh input");
|
||||
assert_eq!(*output_tokens, 20);
|
||||
assert_eq!(*cache_read_tokens, 10);
|
||||
|
||||
@@ -340,6 +344,40 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rollup_normalizes_total_cache_semantics_to_fresh() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
let old_ts = chrono::Utc::now().timestamp() - 40 * 86400;
|
||||
|
||||
{
|
||||
let conn = crate::database::lock_conn!(db.conn);
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_request_logs (
|
||||
request_id, provider_id, app_type, model,
|
||||
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
|
||||
input_token_semantics, total_cost_usd,
|
||||
latency_ms, status_code, created_at
|
||||
) VALUES ('total-semantics-rollup', 'p1', 'codex', 'gpt-5.5',
|
||||
100, 5, 10, 20, 1, '0.10', 100, 200, ?1)",
|
||||
[old_ts],
|
||||
)?;
|
||||
}
|
||||
|
||||
assert_eq!(db.rollup_and_prune(30)?, 1);
|
||||
|
||||
let conn = crate::database::lock_conn!(db.conn);
|
||||
let row: (i64, i64, i64, i64) = conn.query_row(
|
||||
"SELECT input_tokens, cache_read_tokens, cache_creation_tokens,
|
||||
input_token_semantics
|
||||
FROM usage_daily_rollups WHERE model = 'gpt-5.5'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|
||||
)?;
|
||||
assert_eq!(row, (70, 10, 20, 2));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rollup_preserves_request_model_dimension() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
@@ -32,12 +32,15 @@ mod schema;
|
||||
mod tests;
|
||||
|
||||
// DAO 类型导出供外部使用
|
||||
pub(crate) use dao::providers_seed::{is_official_seed_id, CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID};
|
||||
pub(crate) use dao::providers_seed::{
|
||||
is_official_seed_id, CLAUDE_DESKTOP_OFFICIAL_PROVIDER_ID, CODEX_OFFICIAL_PROVIDER_ID,
|
||||
};
|
||||
pub(crate) use dao::proxy::{
|
||||
validate_cost_multiplier, validate_pricing_source, PRICING_SOURCE_REQUEST,
|
||||
PRICING_SOURCE_RESPONSE,
|
||||
};
|
||||
pub use dao::FailoverQueueItem;
|
||||
pub use dao::Profile;
|
||||
|
||||
use crate::config::get_app_config_dir;
|
||||
use crate::error::AppError;
|
||||
@@ -49,7 +52,7 @@ use std::sync::Mutex;
|
||||
|
||||
/// 当前 Schema 版本号
|
||||
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
|
||||
pub(crate) const SCHEMA_VERSION: i32 = 11;
|
||||
pub(crate) const SCHEMA_VERSION: i32 = 13;
|
||||
|
||||
/// 安全地序列化 JSON,避免 unwrap panic
|
||||
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
|
||||
|
||||
@@ -189,6 +189,7 @@ impl Database {
|
||||
pricing_model TEXT,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_token_semantics INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0', output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0', cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0', latency_ms INTEGER NOT NULL, first_token_ms INTEGER,
|
||||
@@ -275,6 +276,7 @@ impl Database {
|
||||
output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_token_semantics INTEGER NOT NULL DEFAULT 0,
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
avg_latency_ms INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (date, app_type, provider_id, model, request_model, pricing_model)
|
||||
@@ -295,6 +297,35 @@ impl Database {
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 19. Profiles 表(全应用共享的项目实体,payload 按 app 分槽快照
|
||||
// 供应商/MCP/Skills/Prompt;各应用分组的 current 标记在 settings 表)
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
sort_order INTEGER,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(e.to_string()))?;
|
||||
|
||||
// 修复跑过未发布开发版的库:current 标记曾是全局 key,现按应用分组
|
||||
// (随 v12 定稿为 current_profile_id_<scope>,不单独 bump 版本)
|
||||
if conn
|
||||
.execute(
|
||||
"INSERT OR REPLACE INTO settings (key, value)
|
||||
SELECT 'current_profile_id_claude', value FROM settings
|
||||
WHERE key = 'current_profile_id'",
|
||||
[],
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
let _ = conn.execute("DELETE FROM settings WHERE key = 'current_profile_id'", []);
|
||||
}
|
||||
|
||||
// 尝试添加 live_takeover_active 列到 proxy_config 表
|
||||
let _ = conn.execute(
|
||||
"ALTER TABLE proxy_config ADD COLUMN live_takeover_active INTEGER NOT NULL DEFAULT 0",
|
||||
@@ -444,6 +475,16 @@ impl Database {
|
||||
Self::migrate_v10_to_v11(conn)?;
|
||||
Self::set_user_version(conn, 11)?;
|
||||
}
|
||||
11 => {
|
||||
log::info!("迁移数据库从 v11 到 v12(添加项目 Profiles 表)");
|
||||
Self::migrate_v11_to_v12(conn)?;
|
||||
Self::set_user_version(conn, 12)?;
|
||||
}
|
||||
12 => {
|
||||
log::info!("迁移数据库从 v12 到 v13(记录输入 token 缓存语义)");
|
||||
Self::migrate_v12_to_v13(conn)?;
|
||||
Self::set_user_version(conn, 13)?;
|
||||
}
|
||||
_ => {
|
||||
return Err(AppError::Database(format!(
|
||||
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
|
||||
@@ -616,6 +657,7 @@ impl Database {
|
||||
request_model TEXT,
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0, output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0, cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_token_semantics INTEGER NOT NULL DEFAULT 0,
|
||||
input_cost_usd TEXT NOT NULL DEFAULT '0', output_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
cache_read_cost_usd TEXT NOT NULL DEFAULT '0', cache_creation_cost_usd TEXT NOT NULL DEFAULT '0',
|
||||
total_cost_usd TEXT NOT NULL DEFAULT '0', latency_ms INTEGER NOT NULL, first_token_ms INTEGER,
|
||||
@@ -1270,6 +1312,48 @@ impl Database {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// v11 -> v12 迁移:添加项目 Profiles 表
|
||||
/// 与 create_tables_on_conn 中的建表语句保持一致(IF NOT EXISTS 保证幂等)
|
||||
fn migrate_v11_to_v12(conn: &Connection) -> Result<(), AppError> {
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
sort_order INTEGER,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.map_err(|e| AppError::Database(format!("v11 -> v12 创建 profiles 表失败: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// v12 -> v13:记录 input_tokens 是否包含缓存写入。
|
||||
///
|
||||
/// 默认 0 表示旧版/未知语义;旧 Codex 行只包含 cache read,不包含
|
||||
/// cache creation。新代理行会显式写入 1(total-inclusive) 或 2(fresh)。
|
||||
fn migrate_v12_to_v13(conn: &Connection) -> Result<(), AppError> {
|
||||
if Self::table_exists(conn, "proxy_request_logs")? {
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"proxy_request_logs",
|
||||
"input_token_semantics",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
}
|
||||
if Self::table_exists(conn, "usage_daily_rollups")? {
|
||||
Self::add_column_if_missing(
|
||||
conn,
|
||||
"usage_daily_rollups",
|
||||
"input_token_semantics",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 插入默认模型定价数据
|
||||
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
|
||||
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
|
||||
@@ -1403,6 +1487,25 @@ impl Database {
|
||||
"0.30",
|
||||
"3.75",
|
||||
),
|
||||
// GPT-5.6 系列(Sol / Terra / Luna,2026-06 发布)
|
||||
// 5.6 家族起 cache write 收 1.25× 输入价(此前 GPT 模型写缓存免费,勿回填旧系列)
|
||||
("gpt-5.6-sol", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
(
|
||||
"gpt-5.6-terra",
|
||||
"GPT-5.6 Terra",
|
||||
"2.50",
|
||||
"15",
|
||||
"0.25",
|
||||
"3.125",
|
||||
),
|
||||
("gpt-5.6-luna", "GPT-5.6 Luna", "1", "6", "0.10", "1.25"),
|
||||
// 裸名 gpt-5.6 是 sol 的官方别名;effort 后缀对齐 gpt-5.5 系列的记账形态
|
||||
("gpt-5.6", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
("gpt-5.6-low", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
("gpt-5.6-medium", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
("gpt-5.6-high", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
("gpt-5.6-xhigh", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
("gpt-5.6-minimal", "GPT-5.6 Sol", "5", "30", "0.50", "6.25"),
|
||||
// GPT-5.5 系列
|
||||
("gpt-5.5", "GPT-5.5", "5", "30", "0.50", "0"),
|
||||
("gpt-5.5-low", "GPT-5.5", "5", "30", "0.50", "0"),
|
||||
@@ -1840,6 +1943,9 @@ impl Database {
|
||||
"0.19",
|
||||
"0",
|
||||
),
|
||||
// 腾讯混元 (Tencent Hunyuan)(官方 CNY 1/4/0.25 按 1 USD ≈ 7.14 折算;Hy3 阶梯计价取最低档)
|
||||
("hunyuan-hy3", "Hunyuan Hy3", "0.14", "0.56", "0.035", "0"),
|
||||
("hy3", "Hunyuan Hy3", "0.14", "0.56", "0.035", "0"),
|
||||
// MiniMax 系列
|
||||
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
|
||||
(
|
||||
@@ -2135,6 +2241,44 @@ impl Database {
|
||||
|
||||
fn repair_current_model_pricing(conn: &Connection) -> Result<(), AppError> {
|
||||
let pricing_fixes = [
|
||||
// 2026-07-12 GPT-5.6 家族 cache write=1.25× 输入价(OpenAI 5.6 起的新规),
|
||||
// 修正早期 seed 的 0 值;只匹配未被用户改过的行
|
||||
(
|
||||
"gpt-5.6-sol",
|
||||
"GPT-5.6 Sol",
|
||||
"5",
|
||||
"30",
|
||||
"0.50",
|
||||
"6.25",
|
||||
"5",
|
||||
"30",
|
||||
"0.50",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"gpt-5.6-terra",
|
||||
"GPT-5.6 Terra",
|
||||
"2.50",
|
||||
"15",
|
||||
"0.25",
|
||||
"3.125",
|
||||
"2.50",
|
||||
"15",
|
||||
"0.25",
|
||||
"0",
|
||||
),
|
||||
(
|
||||
"gpt-5.6-luna",
|
||||
"GPT-5.6 Luna",
|
||||
"1",
|
||||
"6",
|
||||
"0.10",
|
||||
"1.25",
|
||||
"1",
|
||||
"6",
|
||||
"0.10",
|
||||
"0",
|
||||
),
|
||||
// 2026-06-10 全量核价(厂商官方 list 价;CNY 按 ~7.14 折算)
|
||||
// GLM 4.6/4.7:旧值是中转/OpenRouter 折扣价,统一到 Z.ai 官方(与 glm-5/5.1 一致)
|
||||
(
|
||||
@@ -2602,3 +2746,45 @@ impl Database {
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn migrate_v12_to_v13_adds_input_token_semantics_columns() -> Result<(), AppError> {
|
||||
let conn = Connection::open_in_memory()?;
|
||||
conn.execute(
|
||||
"CREATE TABLE proxy_request_logs (request_id TEXT PRIMARY KEY)",
|
||||
[],
|
||||
)?;
|
||||
conn.execute(
|
||||
"CREATE TABLE usage_daily_rollups (date TEXT PRIMARY KEY)",
|
||||
[],
|
||||
)?;
|
||||
Database::set_user_version(&conn, 12)?;
|
||||
|
||||
Database::apply_schema_migrations_on_conn(&conn)?;
|
||||
|
||||
assert_eq!(Database::get_user_version(&conn)?, 13);
|
||||
assert!(Database::has_column(
|
||||
&conn,
|
||||
"proxy_request_logs",
|
||||
"input_token_semantics"
|
||||
)?);
|
||||
assert!(Database::has_column(
|
||||
&conn,
|
||||
"usage_daily_rollups",
|
||||
"input_token_semantics"
|
||||
)?);
|
||||
let log_default: i64 = conn.query_row(
|
||||
"SELECT dflt_value = '0' FROM pragma_table_info('proxy_request_logs')
|
||||
WHERE name = 'input_token_semantics'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
assert_eq!(log_default, 1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -426,6 +426,62 @@ fn migration_v10_to_v11_rebuilds_rollups_with_request_model_dimension() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_create_tables_repairs_dev_global_profile_marker() {
|
||||
let conn = Connection::open_in_memory().expect("open memory db");
|
||||
|
||||
// 模拟跑过未发布开发版的库:user_version 已是 12(迁移不会再跑),
|
||||
// 但 current 标记还是全局 key(现按应用分组)
|
||||
conn.execute_batch(
|
||||
r#"
|
||||
CREATE TABLE profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
payload TEXT NOT NULL,
|
||||
sort_order INTEGER,
|
||||
created_at INTEGER,
|
||||
updated_at INTEGER
|
||||
);
|
||||
INSERT INTO profiles (id, name, payload) VALUES ('p1', 'Project A', '{}');
|
||||
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
|
||||
INSERT INTO settings (key, value) VALUES ('current_profile_id', 'p1');
|
||||
"#,
|
||||
)
|
||||
.expect("seed dev v12 shape");
|
||||
Database::set_user_version(&conn, 12).expect("set user_version=12");
|
||||
|
||||
Database::create_tables_on_conn(&conn).expect("create tables should repair marker");
|
||||
|
||||
// 全局 current 标记改名为 claude 组标记,旧 key 删除
|
||||
let claude_marker: String = conn
|
||||
.query_row(
|
||||
"SELECT value FROM settings WHERE key = 'current_profile_id_claude'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("scoped current marker");
|
||||
assert_eq!(claude_marker, "p1");
|
||||
let old_marker: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM settings WHERE key = 'current_profile_id'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("count old marker");
|
||||
assert_eq!(old_marker, 0);
|
||||
|
||||
// 修复必须幂等:再跑一遍不应破坏已迁移的标记
|
||||
Database::create_tables_on_conn(&conn).expect("repair is idempotent");
|
||||
let claude_marker: String = conn
|
||||
.query_row(
|
||||
"SELECT value FROM settings WHERE key = 'current_profile_id_claude'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("scoped current marker survives");
|
||||
assert_eq!(claude_marker, "p1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_create_tables_repairs_legacy_proxy_config_singleton_to_per_app() {
|
||||
let conn = Connection::open_in_memory().expect("open memory db");
|
||||
|
||||
@@ -267,6 +267,8 @@ fn build_provider_meta(request: &DeepLinkImportRequest) -> Result<Option<Provide
|
||||
coding_plan_provider: None,
|
||||
access_key_id: None,
|
||||
secret_access_key: None,
|
||||
team_organization_id: None,
|
||||
team_project_id: None,
|
||||
};
|
||||
|
||||
Ok(Some(ProviderMeta {
|
||||
|
||||
+26
-11
@@ -6,6 +6,7 @@ mod claude_mcp;
|
||||
mod claude_plugin;
|
||||
mod codex_config;
|
||||
mod codex_history_migration;
|
||||
mod codex_state_db;
|
||||
mod commands;
|
||||
mod config;
|
||||
mod database;
|
||||
@@ -19,6 +20,7 @@ mod lightweight;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_fix;
|
||||
mod mcp;
|
||||
mod model_capabilities;
|
||||
mod openclaw_config;
|
||||
mod opencode_config;
|
||||
mod panic_hook;
|
||||
@@ -41,7 +43,7 @@ pub use codex_config::{get_codex_auth_path, get_codex_config_path, write_codex_l
|
||||
pub use commands::open_provider_terminal;
|
||||
pub use commands::*;
|
||||
pub use config::{get_claude_mcp_path, get_claude_settings_path, read_json_file};
|
||||
pub use database::Database;
|
||||
pub use database::{Database, Profile};
|
||||
pub use deeplink::{import_provider_from_deeplink, parse_deeplink_url, DeepLinkImportRequest};
|
||||
pub use error::AppError;
|
||||
pub use mcp::{
|
||||
@@ -50,8 +52,11 @@ pub use mcp::{
|
||||
sync_enabled_to_codex, sync_enabled_to_gemini, sync_single_server_to_claude,
|
||||
sync_single_server_to_codex, sync_single_server_to_gemini,
|
||||
};
|
||||
pub use prompt::Prompt;
|
||||
pub use provider::{Provider, ProviderMeta};
|
||||
pub use services::{
|
||||
profile::{ProfilePayload, ProfileScope, ProfileService},
|
||||
provider::reapply_current_codex_official_live,
|
||||
skill::{migrate_skills_to_ssot, ImportSkillSelection},
|
||||
ConfigService, EndpointLatency, McpService, PromptService, ProviderService, ProxyService,
|
||||
SkillService, SpeedtestService,
|
||||
@@ -669,32 +674,33 @@ pub fn run() {
|
||||
|
||||
// 1.6. 自动同步 OpenCode / OpenClaw 的 live providers 到数据库
|
||||
//
|
||||
// additive 模式(OpenCode / OpenClaw)的 import 函数本身按 id 幂等,
|
||||
// 已有的 provider 会被跳过,所以每次启动都跑是安全的——既保证新装
|
||||
// 用户开箱可见 live 中的供应商,也让外部修改的 live 文件能在重启
|
||||
// 后同步到数据库(与之前依赖前端"导入当前配置"按钮手动触发不同)。
|
||||
// additive 模式(OpenCode / OpenClaw)的 import 函数按 id 幂等——
|
||||
// 新 id 执行导入,已有 id 则更新 settings 和 display name,所以每次
|
||||
// 启动都跑是安全的:既保证新装用户开箱可见 live 中的供应商,也让外部
|
||||
// 修改的 live 文件能在重启后同步到数据库(与之前依赖前端"导入当前配置"
|
||||
// 按钮手动触发不同)。
|
||||
//
|
||||
// 底层 read_*_config 在文件不存在时返回默认空配置,因此新装且无
|
||||
// live 文件的用户走 Ok(0) 路径,不会产生错误日志噪音。
|
||||
match crate::services::provider::import_opencode_providers_from_live(&app_state) {
|
||||
Ok(count) if count > 0 => {
|
||||
log::info!("✓ Imported {count} OpenCode provider(s) from live config");
|
||||
log::info!("✓ Synced {count} OpenCode provider(s) from live config");
|
||||
}
|
||||
Ok(_) => log::debug!("○ No new OpenCode providers to import"),
|
||||
Ok(_) => log::debug!("○ No OpenCode provider changes from live config"),
|
||||
Err(e) => log::warn!("✗ Failed to import OpenCode providers: {e}"),
|
||||
}
|
||||
match crate::services::provider::import_openclaw_providers_from_live(&app_state) {
|
||||
Ok(count) if count > 0 => {
|
||||
log::info!("✓ Imported {count} OpenClaw provider(s) from live config");
|
||||
log::info!("✓ Synced {count} OpenClaw provider(s) from live config");
|
||||
}
|
||||
Ok(_) => log::debug!("○ No new OpenClaw providers to import"),
|
||||
Ok(_) => log::debug!("○ No OpenClaw provider changes from live config"),
|
||||
Err(e) => log::warn!("✗ Failed to import OpenClaw providers: {e}"),
|
||||
}
|
||||
match crate::services::provider::import_hermes_providers_from_live(&app_state) {
|
||||
Ok(count) if count > 0 => {
|
||||
log::info!("✓ Imported {count} Hermes provider(s) from live config");
|
||||
log::info!("✓ Synced {count} Hermes provider(s) from live config");
|
||||
}
|
||||
Ok(_) => log::debug!("○ No new Hermes providers to import"),
|
||||
Ok(_) => log::debug!("○ No Hermes provider changes from live config"),
|
||||
Err(e) => log::warn!("✗ Failed to import Hermes providers: {e}"),
|
||||
}
|
||||
|
||||
@@ -1194,6 +1200,7 @@ pub fn run() {
|
||||
commands::get_claude_desktop_default_routes,
|
||||
commands::import_claude_desktop_providers_from_claude,
|
||||
commands::ensure_claude_desktop_official_provider,
|
||||
commands::ensure_codex_official_provider,
|
||||
commands::get_claude_config_status,
|
||||
commands::get_config_status,
|
||||
commands::get_claude_code_config_path,
|
||||
@@ -1210,6 +1217,7 @@ pub fn run() {
|
||||
commands::set_claude_common_config_snippet,
|
||||
commands::get_common_config_snippet,
|
||||
commands::set_common_config_snippet,
|
||||
commands::update_toml_common_config_snippet,
|
||||
commands::extract_common_config_snippet,
|
||||
commands::read_live_provider_settings,
|
||||
commands::get_settings,
|
||||
@@ -1269,6 +1277,13 @@ pub fn run() {
|
||||
commands::enable_prompt,
|
||||
commands::import_prompt_from_file,
|
||||
commands::get_current_prompt_file_content,
|
||||
// Profile management (项目配置方案)
|
||||
commands::list_profiles,
|
||||
commands::create_profile,
|
||||
commands::update_profile,
|
||||
commands::delete_profile,
|
||||
commands::clear_current_profile,
|
||||
commands::apply_profile,
|
||||
// model list fetch (OpenAI-compatible /v1/models)
|
||||
commands::fetch_models_for_config,
|
||||
// ours: endpoint speed test + custom endpoint management
|
||||
|
||||
@@ -361,14 +361,11 @@ pub fn sync_single_server_to_codex(
|
||||
let mut doc = if config_path.exists() {
|
||||
let content =
|
||||
std::fs::read_to_string(&config_path).map_err(|e| AppError::io(&config_path, e))?;
|
||||
// 尝试解析现有配置,如果失败则创建新文档(容错处理)
|
||||
match content.parse::<toml_edit::DocumentMut>() {
|
||||
Ok(doc) => doc,
|
||||
Err(e) => {
|
||||
log::warn!("解析 Codex config.toml 失败: {e},将创建新配置");
|
||||
toml_edit::DocumentMut::new()
|
||||
}
|
||||
}
|
||||
// 解析失败必须报错而不是用空文档顶替:写回空文档会把用户
|
||||
// config.toml 里的其它段落(model/model_providers/注释等)整体清空
|
||||
content
|
||||
.parse::<toml_edit::DocumentMut>()
|
||||
.map_err(|e| AppError::McpValidation(format!("解析 config.toml 失败: {e}")))?
|
||||
} else {
|
||||
toml_edit::DocumentMut::new()
|
||||
};
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
use serde_json::Value;
|
||||
|
||||
/// Image-input capability shared by Codex catalog generation and proxy request
|
||||
/// rectification.
|
||||
///
|
||||
/// `Unknown` is intentionally distinct from `Supported`: callers may choose
|
||||
/// different execution policies without duplicating the model-name registry.
|
||||
/// The Codex catalog treats unknown models as image-capable (fail open), while
|
||||
/// the media rectifier leaves their request bodies untouched.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ImageInputCapability {
|
||||
Supported,
|
||||
Unsupported,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Resolve image-input capability from an explicit declaration first, then the
|
||||
/// confirmed text-only model registry when the caller enables registry lookup.
|
||||
pub(crate) fn resolve_image_input_capability(
|
||||
model: &str,
|
||||
declared_support: Option<bool>,
|
||||
use_confirmed_registry: bool,
|
||||
) -> ImageInputCapability {
|
||||
match declared_support {
|
||||
Some(true) => ImageInputCapability::Supported,
|
||||
Some(false) => ImageInputCapability::Unsupported,
|
||||
None if use_confirmed_registry && is_confirmed_text_only_model(model) => {
|
||||
ImageInputCapability::Unsupported
|
||||
}
|
||||
None => ImageInputCapability::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a model's image-input capability from the provider settings shapes
|
||||
/// accepted by the proxy (`modelCatalog.models`, `modelCatalog`, or `models`).
|
||||
pub(crate) fn image_input_capability_from_settings(
|
||||
settings: &Value,
|
||||
model: &str,
|
||||
use_confirmed_registry: bool,
|
||||
) -> ImageInputCapability {
|
||||
resolve_image_input_capability(
|
||||
model,
|
||||
declared_model_image_support(settings, model),
|
||||
use_confirmed_registry,
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert a catalog row's explicit modality list into the shared capability
|
||||
/// representation, falling back to the text-only registry when omitted.
|
||||
pub(crate) fn image_input_capability_from_modalities(
|
||||
model: &str,
|
||||
modalities: Option<&[String]>,
|
||||
) -> ImageInputCapability {
|
||||
let declared_support = modalities.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item.trim().eq_ignore_ascii_case("image"))
|
||||
});
|
||||
resolve_image_input_capability(model, declared_support, true)
|
||||
}
|
||||
|
||||
/// Models that CC Switch is willing to advertise to clients as text-only.
|
||||
///
|
||||
/// This registry is deliberately exact and fail-open. A new suffix is not
|
||||
/// inherited automatically: it remains image-capable until its capability is
|
||||
/// confirmed, preventing a future `-vision`/`-vl` variant from being blocked by
|
||||
/// the Codex client before a request can reach the proxy.
|
||||
pub(crate) fn is_confirmed_text_only_model(model: &str) -> bool {
|
||||
let normalized = normalize_model_id(model);
|
||||
let tail = normalized.rsplit('/').next().unwrap_or(normalized.as_str());
|
||||
|
||||
const CONFIRMED_TAILS: &[&str] = &[
|
||||
"ark-code-latest",
|
||||
"deepseek-chat",
|
||||
"deepseek-reasoner",
|
||||
"deepseek-v4-flash",
|
||||
"deepseek-v4-pro",
|
||||
"glm-5.1",
|
||||
// Exact rather than prefix matching: GLM visual models use a `v`
|
||||
// suffix (for example glm-5.2v), which must remain image-capable.
|
||||
"glm-5.2",
|
||||
"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-2.0",
|
||||
"longcat-flash-chat",
|
||||
"minimax-m2.7",
|
||||
"minimax-m2.7-highspeed",
|
||||
"mimo-v2.5-pro",
|
||||
"qwen3-coder-480b",
|
||||
"qwen3-coder-480b-a35b-instruct",
|
||||
"qwen3-coder-flash",
|
||||
"qwen3-coder-next",
|
||||
"qwen3-coder-plus",
|
||||
"step-3.5-flash",
|
||||
"step-3.5-flash-2603",
|
||||
"us.deepseek.r1-v1",
|
||||
];
|
||||
|
||||
CONFIRMED_TAILS.contains(&tail)
|
||||
}
|
||||
|
||||
fn declared_model_image_support(settings: &Value, model: &str) -> Option<bool> {
|
||||
[
|
||||
settings
|
||||
.get("modelCatalog")
|
||||
.and_then(|catalog| catalog.get("models")),
|
||||
settings.get("modelCatalog"),
|
||||
settings.get("models"),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|value| declared_model_image_support_in_value(value, model))
|
||||
}
|
||||
|
||||
fn declared_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 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 serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn gpt_and_unknown_models_remain_unknown_without_declarations() {
|
||||
for model in ["gpt-5.4", "gpt-5.5", "gpt-5.6-sol", "custom-alias"] {
|
||||
assert_eq!(
|
||||
resolve_image_input_capability(model, None, true),
|
||||
ImageInputCapability::Unknown,
|
||||
"{model} must fail open"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_text_only_registry_normalizes_namespaces_and_context_markers() {
|
||||
assert!(is_confirmed_text_only_model("deepseek/deepseek-v4-pro"));
|
||||
assert!(is_confirmed_text_only_model("GLM-5.2[1M]"));
|
||||
assert!(is_confirmed_text_only_model("qwen/qwen3-coder-plus"));
|
||||
assert!(is_confirmed_text_only_model(
|
||||
"Qwen/Qwen3-Coder-480B-A35B-Instruct"
|
||||
));
|
||||
assert!(is_confirmed_text_only_model("MiniMax-M2.7-Highspeed"));
|
||||
assert!(is_confirmed_text_only_model("step-3.5-flash-2603"));
|
||||
assert!(!is_confirmed_text_only_model("glm-5.2v"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unconfirmed_family_suffixes_fail_open() {
|
||||
for model in [
|
||||
"minimax-m2.7-vision",
|
||||
"qwen3-coder-ultra",
|
||||
"qwen3-coder-vl",
|
||||
"step-3.5-flash-vision",
|
||||
] {
|
||||
assert!(
|
||||
!is_confirmed_text_only_model(model),
|
||||
"unconfirmed variant {model} must not be hard-gated"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_capability_overrides_the_registry() {
|
||||
assert_eq!(
|
||||
resolve_image_input_capability("deepseek-v4-pro", Some(true), true),
|
||||
ImageInputCapability::Supported
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_image_input_capability("gpt-5.4", Some(false), true),
|
||||
ImageInputCapability::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_settings_support_multiple_capability_shapes() {
|
||||
let settings = json!({
|
||||
"modelCatalog": {
|
||||
"models": [
|
||||
{ "model": "vision", "modalities": { "input": ["text", "image"] } },
|
||||
{ "model": "text", "inputModalities": ["text"] }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
image_input_capability_from_settings(&settings, "vision", true),
|
||||
ImageInputCapability::Supported
|
||||
);
|
||||
assert_eq!(
|
||||
image_input_capability_from_settings(&settings, "text", true),
|
||||
ImageInputCapability::Unsupported
|
||||
);
|
||||
}
|
||||
}
|
||||
+56
-23
@@ -259,6 +259,14 @@ pub struct UsageScript {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "secretAccessKey")]
|
||||
pub secret_access_key: Option<String>,
|
||||
/// 智谱团队套餐(Team Plan)的组织 ID(用量查询请求头 bigmodel-organization)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "teamOrganizationId")]
|
||||
pub team_organization_id: Option<String>,
|
||||
/// 智谱团队套餐(Team Plan)的项目 ID(用量查询请求头 bigmodel-project)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "teamProjectId")]
|
||||
pub team_project_id: Option<String>,
|
||||
}
|
||||
|
||||
/// 用量数据
|
||||
@@ -295,26 +303,6 @@ pub struct UsageResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// 供应商单独的连通检测配置
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ProviderTestConfig {
|
||||
/// 是否启用单独配置(false 时使用全局配置)
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
/// 超时时间(秒)
|
||||
#[serde(rename = "timeoutSecs", skip_serializing_if = "Option::is_none")]
|
||||
pub timeout_secs: Option<u64>,
|
||||
/// 降级阈值(毫秒)
|
||||
#[serde(
|
||||
rename = "degradedThresholdMs",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub degraded_threshold_ms: Option<u64>,
|
||||
/// 最大重试次数
|
||||
#[serde(rename = "maxRetries", skip_serializing_if = "Option::is_none")]
|
||||
pub max_retries: Option<u32>,
|
||||
}
|
||||
|
||||
/// 认证绑定来源
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
@@ -446,9 +434,6 @@ pub struct ProviderMeta {
|
||||
/// 每月消费限额(USD)
|
||||
#[serde(rename = "limitMonthlyUsd", skip_serializing_if = "Option::is_none")]
|
||||
pub limit_monthly_usd: Option<String>,
|
||||
/// 供应商单独的模型测试配置
|
||||
#[serde(rename = "testConfig", skip_serializing_if = "Option::is_none")]
|
||||
pub test_config: Option<ProviderTestConfig>,
|
||||
/// Claude API 格式(仅 Claude 供应商使用)
|
||||
/// - "anthropic": 原生 Anthropic Messages API,直接透传
|
||||
/// - "openai_chat": OpenAI Chat Completions 格式,需要转换
|
||||
@@ -472,12 +457,36 @@ pub struct ProviderMeta {
|
||||
/// identity when available; generated session IDs are not sent upstream.
|
||||
#[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_cache_key: Option<String>,
|
||||
/// Session-based prompt-cache routing for Codex Responses -> Chat conversions.
|
||||
/// "auto" enables known-compatible upstreams; "enabled" / "disabled" are overrides.
|
||||
#[serde(rename = "promptCacheRouting", skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_cache_routing: Option<String>,
|
||||
/// Codex OAuth FAST mode: inject `service_tier = "priority"` for ChatGPT Codex requests.
|
||||
#[serde(rename = "codexFastMode", skip_serializing_if = "Option::is_none")]
|
||||
pub codex_fast_mode: Option<bool>,
|
||||
/// Codex Responses -> Chat Completions reasoning capability metadata.
|
||||
#[serde(rename = "codexChatReasoning", skip_serializing_if = "Option::is_none")]
|
||||
pub codex_chat_reasoning: Option<CodexChatReasoningConfig>,
|
||||
/// Codex → Anthropic path: whether to emulate the Claude Code client
|
||||
/// (User-Agent / anthropic-beta / x-app + injecting the Claude Code system
|
||||
/// prompt first line). Disabled by default; only an explicit `true` enables it.
|
||||
#[serde(
|
||||
rename = "impersonateClaudeCode",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub impersonate_claude_code: Option<bool>,
|
||||
/// Codex → Anthropic path: override the Anthropic `max_tokens` (output ceiling).
|
||||
///
|
||||
/// Codex does not forward its `model_max_output_tokens` in the Responses
|
||||
/// request body, so without this the path falls back to a conservative
|
||||
/// default (8192), which truncates long or thinking-heavy responses
|
||||
/// (`stop_reason=max_tokens`). When set (>0), this value is injected as the
|
||||
/// request's `max_output_tokens` before conversion, taking precedence over
|
||||
/// both any request-supplied value and the default. Kept per-provider on
|
||||
/// purpose: a global large default would hard-400 on low-output-ceiling
|
||||
/// models/gateways (and that error is non-retryable).
|
||||
#[serde(rename = "maxOutputTokens", skip_serializing_if = "Option::is_none")]
|
||||
pub max_output_tokens: Option<u64>,
|
||||
/// Custom User-Agent for local proxy routing.
|
||||
#[serde(rename = "customUserAgent", skip_serializing_if = "Option::is_none")]
|
||||
pub custom_user_agent: Option<String>,
|
||||
@@ -985,6 +994,30 @@ mod tests {
|
||||
assert!(value.get("pricingModelSource").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_meta_roundtrips_max_output_tokens() {
|
||||
let meta = ProviderMeta {
|
||||
max_output_tokens: Some(64000),
|
||||
..ProviderMeta::default()
|
||||
};
|
||||
|
||||
let value = serde_json::to_value(&meta).expect("serialize ProviderMeta");
|
||||
assert_eq!(
|
||||
value.get("maxOutputTokens").and_then(|v| v.as_u64()),
|
||||
Some(64000)
|
||||
);
|
||||
assert!(value.get("max_output_tokens").is_none());
|
||||
|
||||
let parsed: ProviderMeta = serde_json::from_value(value).expect("deserialize ProviderMeta");
|
||||
assert_eq!(parsed.max_output_tokens, Some(64000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_meta_omits_max_output_tokens_when_none() {
|
||||
let value = serde_json::to_value(ProviderMeta::default()).expect("serialize ProviderMeta");
|
||||
assert!(value.get("maxOutputTokens").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_meta_roundtrips_local_proxy_request_overrides() {
|
||||
let meta = ProviderMeta {
|
||||
|
||||
@@ -7,25 +7,24 @@ use serde_json::{json, Value};
|
||||
|
||||
/// 在请求体关键位置注入 cache_control 断点
|
||||
pub fn inject(body: &mut Value, config: &OptimizerConfig) {
|
||||
if !config.cache_injection {
|
||||
if !config.enabled || !config.cache_injection {
|
||||
return;
|
||||
}
|
||||
|
||||
let existing = count_existing(body);
|
||||
|
||||
// 升级已有断点的 TTL
|
||||
upgrade_existing_ttl(body, &config.cache_ttl);
|
||||
if existing > 4 {
|
||||
// Existing markers are caller-owned. Do not silently delete or reorder
|
||||
// them; surface the invalid/unsupported total and leave validation to
|
||||
// the upstream provider.
|
||||
log::warn!(
|
||||
"[OPT] cache: existing breakpoint count {existing} exceeds the supported total of 4; preserving caller input"
|
||||
);
|
||||
}
|
||||
|
||||
let mut budget = 4_usize.saturating_sub(existing);
|
||||
if budget == 0 {
|
||||
if existing > 0 {
|
||||
log::info!(
|
||||
"[OPT] cache: ttl-upgrade({existing}->{},existing={existing})",
|
||||
config.cache_ttl
|
||||
);
|
||||
} else {
|
||||
log::info!("[OPT] cache: no-op(existing={existing})");
|
||||
}
|
||||
log::info!("[OPT] cache: no-op(existing={existing})");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -37,10 +36,7 @@ pub fn inject(body: &mut Value, config: &OptimizerConfig) {
|
||||
if let Some(last) = tools.last_mut() {
|
||||
if last.get("cache_control").is_none() {
|
||||
if let Some(o) = last.as_object_mut() {
|
||||
o.insert(
|
||||
"cache_control".to_string(),
|
||||
make_cache_control(&config.cache_ttl),
|
||||
);
|
||||
o.insert("cache_control".to_string(), make_cache_control());
|
||||
}
|
||||
budget -= 1;
|
||||
injected.push("tools");
|
||||
@@ -64,10 +60,7 @@ pub fn inject(body: &mut Value, config: &OptimizerConfig) {
|
||||
if let Some(last) = system.last_mut() {
|
||||
if last.get("cache_control").is_none() {
|
||||
if let Some(o) = last.as_object_mut() {
|
||||
o.insert(
|
||||
"cache_control".to_string(),
|
||||
make_cache_control(&config.cache_ttl),
|
||||
);
|
||||
o.insert("cache_control".to_string(), make_cache_control());
|
||||
}
|
||||
budget -= 1;
|
||||
injected.push("system");
|
||||
@@ -76,32 +69,33 @@ pub fn inject(body: &mut Value, config: &OptimizerConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
// (c) 最后一条 assistant 消息的最后一个非 thinking block
|
||||
// (c) 最后一条可缓存消息的最后一个非 thinking block。工具循环通常以
|
||||
// user/tool_result 结束;只标 assistant 会让最新稳定前缀无法命中缓存。
|
||||
if budget > 0 {
|
||||
if let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) {
|
||||
if let Some(assistant_msg) = messages
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|m| m.get("role").and_then(|r| r.as_str()) == Some("assistant"))
|
||||
{
|
||||
if let Some(content) = assistant_msg
|
||||
.get_mut("content")
|
||||
.and_then(|c| c.as_array_mut())
|
||||
{
|
||||
// 逆序找最后一个非 thinking/redacted_thinking block
|
||||
if let Some(block) = content.iter_mut().rev().find(|b| {
|
||||
let bt = b.get("type").and_then(|t| t.as_str()).unwrap_or("");
|
||||
bt != "thinking" && bt != "redacted_thinking"
|
||||
}) {
|
||||
if block.get("cache_control").is_none() {
|
||||
if let Some(o) = block.as_object_mut() {
|
||||
o.insert(
|
||||
"cache_control".to_string(),
|
||||
make_cache_control(&config.cache_ttl),
|
||||
);
|
||||
}
|
||||
injected.push("msgs");
|
||||
for message in messages.iter_mut().rev() {
|
||||
if inject_message_breakpoint(message) {
|
||||
budget -= 1;
|
||||
injected.push("msgs-latest");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// (d) A second, older user anchor helps long tool-result turns where
|
||||
// the stable prefix falls outside Anthropic's 20-block lookback from
|
||||
// the newest breakpoint. Keep this best-effort and inside the 4-BP cap.
|
||||
if budget > 0 && messages.len() >= 4 {
|
||||
let mut user_count = 0;
|
||||
for message in messages.iter_mut().rev() {
|
||||
if message.get("role").and_then(Value::as_str) != Some("user") {
|
||||
continue;
|
||||
}
|
||||
user_count += 1;
|
||||
if user_count == 2 {
|
||||
if inject_message_breakpoint(message) {
|
||||
injected.push("msgs-prior-user");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -112,16 +106,34 @@ pub fn inject(body: &mut Value, config: &OptimizerConfig) {
|
||||
"[OPT] cache: {}bp({},{},pre={existing})",
|
||||
injected.len(),
|
||||
injected.join("+"),
|
||||
config.cache_ttl,
|
||||
"5m",
|
||||
);
|
||||
}
|
||||
|
||||
fn make_cache_control(ttl: &str) -> Value {
|
||||
if ttl == "5m" {
|
||||
json!({"type": "ephemeral"})
|
||||
} else {
|
||||
json!({"type": "ephemeral", "ttl": ttl})
|
||||
fn inject_message_breakpoint(message: &mut Value) -> bool {
|
||||
let Some(content) = message.get_mut("content").and_then(Value::as_array_mut) else {
|
||||
return false;
|
||||
};
|
||||
let Some(block) = content.iter_mut().rev().find(|block| {
|
||||
!matches!(
|
||||
block.get("type").and_then(Value::as_str),
|
||||
Some("thinking" | "redacted_thinking")
|
||||
)
|
||||
}) else {
|
||||
return false;
|
||||
};
|
||||
if block.get("cache_control").is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(object) = block.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
object.insert("cache_control".to_string(), make_cache_control());
|
||||
true
|
||||
}
|
||||
|
||||
fn make_cache_control() -> Value {
|
||||
json!({"type": "ephemeral"})
|
||||
}
|
||||
|
||||
fn count_existing(body: &Value) -> usize {
|
||||
@@ -155,40 +167,6 @@ fn count_existing(body: &Value) -> usize {
|
||||
count
|
||||
}
|
||||
|
||||
fn upgrade_existing_ttl(body: &mut Value, ttl: &str) {
|
||||
let upgrade = |val: &mut Value| {
|
||||
if let Some(cc) = val.get_mut("cache_control").and_then(|c| c.as_object_mut()) {
|
||||
if ttl == "5m" {
|
||||
cc.remove("ttl");
|
||||
} else {
|
||||
cc.insert("ttl".to_string(), json!(ttl));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(tools) = body.get_mut("tools").and_then(|t| t.as_array_mut()) {
|
||||
for tool in tools.iter_mut() {
|
||||
upgrade(tool);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(system) = body.get_mut("system").and_then(|s| s.as_array_mut()) {
|
||||
for block in system.iter_mut() {
|
||||
upgrade(block);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) {
|
||||
for msg in messages.iter_mut() {
|
||||
if let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) {
|
||||
for block in content.iter_mut() {
|
||||
upgrade(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -199,17 +177,16 @@ mod tests {
|
||||
enabled: true,
|
||||
thinking_optimizer: true,
|
||||
cache_injection: true,
|
||||
cache_ttl: "1h".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_body_no_injection() {
|
||||
let mut body = json!({"model": "test", "messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]});
|
||||
let original = body.clone();
|
||||
inject(&mut body, &default_config());
|
||||
// No tools, no system, no assistant → no injection
|
||||
assert_eq!(body, original);
|
||||
assert!(body["messages"][0]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -230,7 +207,7 @@ mod tests {
|
||||
|
||||
// tools last element
|
||||
assert!(body["tools"][1].get("cache_control").is_some());
|
||||
assert_eq!(body["tools"][1]["cache_control"]["ttl"], "1h");
|
||||
assert!(body["tools"][1]["cache_control"].get("ttl").is_none());
|
||||
// system last element
|
||||
assert!(body["system"][0].get("cache_control").is_some());
|
||||
// assistant last non-thinking block
|
||||
@@ -240,26 +217,50 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_existing_four_breakpoints_only_upgrades_ttl() {
|
||||
fn test_long_history_uses_fourth_prior_user_breakpoint() {
|
||||
let mut body = json!({
|
||||
"model":"test",
|
||||
"tools":[{"name":"tool1"}],
|
||||
"system":[{"type":"text","text":"sys"}],
|
||||
"messages":[
|
||||
{"role":"user","content":[{"type":"text","text":"first"}]},
|
||||
{"role":"assistant","content":[{"type":"text","text":"answer"}]},
|
||||
{"role":"user","content":[{"type":"tool_result","tool_use_id":"c1","content":"result"}]},
|
||||
{"role":"assistant","content":[{"type":"text","text":"latest"}]}
|
||||
]
|
||||
});
|
||||
|
||||
inject(&mut body, &default_config());
|
||||
assert_eq!(count_existing(&body), 4);
|
||||
assert!(body["messages"][0]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_some());
|
||||
assert!(body["messages"][3]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_existing_four_breakpoints_preserve_caller_ttl() {
|
||||
let mut body = json!({
|
||||
"model": "test",
|
||||
"tools": [
|
||||
{"name": "t1", "cache_control": {"type": "ephemeral", "ttl": "5m"}},
|
||||
{"name": "t2", "cache_control": {"type": "ephemeral", "ttl": "5m"}}
|
||||
{"name": "t1", "cache_control": {"type": "ephemeral", "ttl": "1h"}},
|
||||
{"name": "t2", "cache_control": {"type": "ephemeral", "ttl": "1h"}}
|
||||
],
|
||||
"system": [
|
||||
{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral", "ttl": "5m"}}
|
||||
{"type": "text", "text": "sys", "cache_control": {"type": "ephemeral", "ttl": "1h"}}
|
||||
],
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [
|
||||
{"type": "text", "text": "ok", "cache_control": {"type": "ephemeral", "ttl": "5m"}}
|
||||
{"type": "text", "text": "ok", "cache_control": {"type": "ephemeral", "ttl": "1h"}}
|
||||
]}
|
||||
]
|
||||
});
|
||||
|
||||
inject(&mut body, &default_config());
|
||||
|
||||
// All TTLs upgraded to 1h, no new breakpoints
|
||||
// Existing markers are caller-owned; only newly injected markers are fixed to 5m.
|
||||
assert_eq!(body["tools"][0]["cache_control"]["ttl"], "1h");
|
||||
assert_eq!(body["tools"][1]["cache_control"]["ttl"], "1h");
|
||||
assert_eq!(body["system"][0]["cache_control"]["ttl"], "1h");
|
||||
@@ -292,6 +293,32 @@ mod tests {
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_more_than_four_existing_breakpoints_are_preserved() {
|
||||
let mut body = json!({
|
||||
"model": "test",
|
||||
"tools": [
|
||||
{"name": "t1", "cache_control": {"type": "ephemeral"}},
|
||||
{"name": "t2", "cache_control": {"type": "ephemeral"}}
|
||||
],
|
||||
"system": [
|
||||
{"type": "text", "text": "s1", "cache_control": {"type": "ephemeral"}},
|
||||
{"type": "text", "text": "s2", "cache_control": {"type": "ephemeral"}}
|
||||
],
|
||||
"messages": [{"role": "user", "content": [
|
||||
{"type": "text", "text": "m1", "cache_control": {"type": "ephemeral"}},
|
||||
{"type": "text", "text": "m2"}
|
||||
]}]
|
||||
});
|
||||
|
||||
inject(&mut body, &default_config());
|
||||
|
||||
assert_eq!(count_existing(&body), 5);
|
||||
assert!(body["messages"][0]["content"][1]
|
||||
.get("cache_control")
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_string_converted_to_array() {
|
||||
let mut body = json!({
|
||||
@@ -311,18 +338,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ttl_5m_no_ttl_field() {
|
||||
let config = OptimizerConfig {
|
||||
cache_ttl: "5m".to_string(),
|
||||
..default_config()
|
||||
};
|
||||
fn test_standard_five_minute_cache_control_omits_ttl() {
|
||||
let mut body = json!({
|
||||
"model": "test",
|
||||
"tools": [{"name": "tool1"}],
|
||||
"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]
|
||||
});
|
||||
|
||||
inject(&mut body, &config);
|
||||
inject(&mut body, &default_config());
|
||||
|
||||
let cc = &body["tools"][0]["cache_control"];
|
||||
assert_eq!(cc["type"], "ephemeral");
|
||||
@@ -348,6 +371,24 @@ mod tests {
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_optimizer_disabled_no_change() {
|
||||
let config = OptimizerConfig {
|
||||
enabled: false,
|
||||
cache_injection: true,
|
||||
..default_config()
|
||||
};
|
||||
let mut body = json!({
|
||||
"model":"test",
|
||||
"tools":[{"name":"tool1"}],
|
||||
"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}]
|
||||
});
|
||||
let original = body.clone();
|
||||
|
||||
inject(&mut body, &config);
|
||||
assert_eq!(body, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_skip_thinking_blocks_in_assistant() {
|
||||
let mut body = json!({
|
||||
@@ -374,4 +415,23 @@ mod tests {
|
||||
.get("cache_control")
|
||||
.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_injects_latest_tool_result_instead_of_older_assistant() {
|
||||
let mut body = json!({
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [{"type": "tool_use", "id": "call_1", "name": "Read", "input": {}}]},
|
||||
{"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "done"}]}
|
||||
]
|
||||
});
|
||||
|
||||
inject(&mut body, &default_config());
|
||||
|
||||
assert!(body["messages"][0]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_none());
|
||||
assert!(body["messages"][1]["content"][0]
|
||||
.get("cache_control")
|
||||
.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+397
-52
@@ -18,12 +18,18 @@ use super::{
|
||||
handler_context::RequestContext,
|
||||
providers::{
|
||||
codex_chat_common::extract_reasoning_field_text,
|
||||
codex_chat_history::record_responses_sse_stream, get_adapter, get_claude_api_format,
|
||||
codex_chat_history::record_responses_sse_stream,
|
||||
get_adapter, get_claude_api_format,
|
||||
streaming::create_anthropic_sse_stream,
|
||||
streaming_codex_anthropic::{
|
||||
create_responses_sse_stream_from_anthropic_with_context,
|
||||
responses_sse_events_from_anthropic_message,
|
||||
},
|
||||
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,
|
||||
streaming_responses::create_anthropic_sse_stream_from_responses,
|
||||
transform, transform_codex_anthropic, transform_codex_chat, transform_gemini,
|
||||
transform_responses,
|
||||
},
|
||||
response_processor::{
|
||||
create_logged_passthrough_stream, process_response, read_decoded_body,
|
||||
@@ -277,6 +283,90 @@ fn validate_claude_desktop_gateway_auth(
|
||||
/// Claude 格式转换处理(独有逻辑)
|
||||
///
|
||||
/// 支持 OpenAI Chat Completions 和 Responses API 两种格式的转换
|
||||
struct ClaudeUsageLog {
|
||||
model: String,
|
||||
request_model: String,
|
||||
outbound_model: String,
|
||||
app_type: &'static str,
|
||||
provider_id: String,
|
||||
session_id: String,
|
||||
usage: TokenUsage,
|
||||
latency_ms: u64,
|
||||
status_code: u16,
|
||||
is_streaming: bool,
|
||||
}
|
||||
|
||||
fn prepare_claude_usage_log(
|
||||
ctx: &RequestContext,
|
||||
response: &Value,
|
||||
status_code: u16,
|
||||
is_streaming: bool,
|
||||
) -> Option<ClaudeUsageLog> {
|
||||
let usage =
|
||||
TokenUsage::from_claude_response(response).filter(TokenUsage::has_billable_tokens)?;
|
||||
|
||||
let model = response
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|model| !model.is_empty())
|
||||
.map(str::to_string)
|
||||
.or_else(|| ctx.outbound_model.clone())
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
|
||||
Some(ClaudeUsageLog {
|
||||
model,
|
||||
request_model: ctx.request_model.clone(),
|
||||
outbound_model: ctx
|
||||
.outbound_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| ctx.request_model.clone()),
|
||||
app_type: ctx.app_type_str,
|
||||
provider_id: ctx.provider.id.clone(),
|
||||
session_id: ctx.session_id.clone(),
|
||||
usage,
|
||||
latency_ms: ctx.latency_ms(),
|
||||
status_code,
|
||||
is_streaming,
|
||||
})
|
||||
}
|
||||
|
||||
async fn write_claude_usage_log(state: &ProxyState, log: ClaudeUsageLog) {
|
||||
log_usage(
|
||||
state,
|
||||
&log.provider_id,
|
||||
log.app_type,
|
||||
&log.model,
|
||||
&log.request_model,
|
||||
&log.outbound_model,
|
||||
log.usage,
|
||||
log.latency_ms,
|
||||
None,
|
||||
log.is_streaming,
|
||||
log.status_code,
|
||||
Some(log.session_id),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
fn spawn_claude_usage_log(
|
||||
state: &ProxyState,
|
||||
ctx: &RequestContext,
|
||||
response: &Value,
|
||||
status_code: u16,
|
||||
is_streaming: bool,
|
||||
) {
|
||||
if !usage_logging_enabled(state) {
|
||||
return;
|
||||
}
|
||||
let Some(log) = prepare_claude_usage_log(ctx, response, status_code, is_streaming) else {
|
||||
return;
|
||||
};
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move {
|
||||
write_claude_usage_log(&state, log).await;
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_claude_transform(
|
||||
response: super::hyper_client::ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
@@ -468,8 +558,20 @@ async fn handle_claude_transform(
|
||||
}
|
||||
};
|
||||
|
||||
// Preserve raw Responses usage so a post-upstream conversion failure still
|
||||
// records the tokens already consumed by the successful upstream request.
|
||||
let raw_usage_response = (api_format == "openai_responses").then(|| {
|
||||
json!({
|
||||
"id": upstream_response.get("id").cloned().unwrap_or(Value::Null),
|
||||
"model": upstream_response.get("model").cloned().unwrap_or(Value::Null),
|
||||
"usage": transform_responses::build_anthropic_usage_from_responses(
|
||||
upstream_response.get("usage")
|
||||
)
|
||||
})
|
||||
});
|
||||
|
||||
// 根据 api_format 选择非流式转换器
|
||||
let anthropic_response = if api_format == "openai_responses" {
|
||||
let transform_result = if api_format == "openai_responses" {
|
||||
transform_responses::responses_to_anthropic(upstream_response)
|
||||
} else if api_format == "gemini_native" {
|
||||
transform_gemini::gemini_to_anthropic_with_shadow_and_hints(
|
||||
@@ -481,58 +583,28 @@ async fn handle_claude_transform(
|
||||
)
|
||||
} else {
|
||||
transform::openai_to_anthropic(upstream_response)
|
||||
}
|
||||
.map_err(|e| {
|
||||
log::error!("[Claude] 转换响应失败: {e}");
|
||||
e
|
||||
})?;
|
||||
};
|
||||
let anthropic_response = match transform_result {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
log::error!("[Claude] 转换响应失败: {error}");
|
||||
if usage_logging_enabled(state) {
|
||||
if let Some(log) = raw_usage_response.as_ref().and_then(|response| {
|
||||
prepare_claude_usage_log(ctx, response, status.as_u16(), false)
|
||||
}) {
|
||||
// The upstream request already succeeded and consumed tokens. Persist
|
||||
// usage before returning the terminal transform error to the client.
|
||||
write_claude_usage_log(state, log).await;
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
|
||||
// 记录使用量
|
||||
// 全 0 usage 不落账(对齐 Codex 流式收集器的 skip):SSE 聚合兜底救回的流
|
||||
// 在上游缺 stream_options.include_usage 时没有 usage,写入只会产生无意义空行
|
||||
if let Some(usage) =
|
||||
TokenUsage::from_claude_response(&anthropic_response).filter(|u| u.has_billable_tokens())
|
||||
{
|
||||
// 转换后的响应缺失/合成空 model 时,回退到映射后的出站模型(接管真值),
|
||||
// 再回退到客户端请求别名
|
||||
let model = anthropic_response
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.filter(|m| !m.is_empty())
|
||||
.map(str::to_string)
|
||||
.or_else(|| ctx.outbound_model.clone())
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
let latency_ms = ctx.latency_ms();
|
||||
|
||||
let request_model = ctx.request_model.clone();
|
||||
let outbound_model = ctx
|
||||
.outbound_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
let app_type_str = ctx.app_type_str;
|
||||
tokio::spawn({
|
||||
let state = state.clone();
|
||||
let provider_id = ctx.provider.id.clone();
|
||||
let session_id = ctx.session_id.clone();
|
||||
async move {
|
||||
log_usage(
|
||||
&state,
|
||||
&provider_id,
|
||||
app_type_str,
|
||||
&model,
|
||||
&request_model,
|
||||
&outbound_model,
|
||||
usage,
|
||||
latency_ms,
|
||||
None,
|
||||
false,
|
||||
status.as_u16(),
|
||||
Some(session_id),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
spawn_claude_usage_log(state, ctx, &anthropic_response, status.as_u16(), false);
|
||||
|
||||
// 构建响应
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
@@ -739,6 +811,18 @@ pub async fn handle_responses(
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
if super::providers::should_convert_codex_responses_to_anthropic(&ctx.provider, &endpoint) {
|
||||
return handle_codex_anthropic_to_responses_transform(
|
||||
response,
|
||||
&ctx,
|
||||
&state,
|
||||
is_stream,
|
||||
connection_guard,
|
||||
codex_tool_context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if super::providers::should_convert_codex_responses_to_chat(&ctx.provider, &endpoint) {
|
||||
return handle_codex_chat_to_responses_transform(
|
||||
response,
|
||||
@@ -818,6 +902,18 @@ pub async fn handle_responses_compact(
|
||||
ctx.provider = result.provider;
|
||||
let response = result.response;
|
||||
|
||||
if super::providers::should_convert_codex_responses_to_anthropic(&ctx.provider, &endpoint) {
|
||||
return handle_codex_anthropic_to_responses_transform(
|
||||
response,
|
||||
&ctx,
|
||||
&state,
|
||||
is_stream,
|
||||
connection_guard,
|
||||
codex_tool_context,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
if super::providers::should_convert_codex_responses_to_chat(&ctx.provider, &endpoint) {
|
||||
return handle_codex_chat_to_responses_transform(
|
||||
response,
|
||||
@@ -1065,6 +1161,255 @@ async fn handle_codex_chat_to_responses_transform(
|
||||
})
|
||||
}
|
||||
|
||||
/// Response-transform handler for the Codex (Responses) ↔ Anthropic Messages gateway.
|
||||
///
|
||||
/// Parallel to `handle_codex_chat_to_responses_transform`: the upstream speaks
|
||||
/// Anthropic Messages, and this converts the response back into the Responses form
|
||||
/// Codex expects (both streaming and non-streaming). Error bodies reuse
|
||||
/// `handle_codex_chat_error_response` (whose extraction logic also works for
|
||||
/// Anthropic's `{"error":{type,message}}`). It does not involve codex_chat_history
|
||||
/// (tool ids round-trip natively through Anthropic).
|
||||
async fn handle_codex_anthropic_to_responses_transform(
|
||||
response: super::hyper_client::ProxyResponse,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
is_stream: bool,
|
||||
connection_guard: Option<ActiveConnectionGuard>,
|
||||
codex_tool_context: transform_codex_chat::CodexToolContext,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let status = response.status();
|
||||
|
||||
if !status.is_success() {
|
||||
return handle_codex_chat_error_response(response, ctx, status).await;
|
||||
}
|
||||
|
||||
// Preserve live streaming when the gateway marks SSE correctly or omits an
|
||||
// explicit JSON media type. Explicit JSON is buffered below so 2xx error
|
||||
// envelopes and gateways that ignore stream:true can be converted faithfully.
|
||||
if response.is_sse() || (is_stream && !response.is_json()) {
|
||||
let stream = response.bytes_stream();
|
||||
let sse_stream =
|
||||
create_responses_sse_stream_from_anthropic_with_context(stream, codex_tool_context);
|
||||
return build_codex_anthropic_sse_response(
|
||||
sse_stream,
|
||||
ctx,
|
||||
state,
|
||||
status,
|
||||
connection_guard,
|
||||
);
|
||||
}
|
||||
|
||||
let body_timeout =
|
||||
if ctx.app_config.auto_failover_enabled && ctx.app_config.non_streaming_timeout > 0 {
|
||||
std::time::Duration::from_secs(ctx.app_config.non_streaming_timeout as u64)
|
||||
} else {
|
||||
std::time::Duration::ZERO
|
||||
};
|
||||
let (mut response_headers, status, body_bytes) =
|
||||
read_decoded_body(response, ctx.tag, body_timeout).await?;
|
||||
let body_str = String::from_utf8_lossy(&body_bytes);
|
||||
let anthropic_response: Value = match serde_json::from_slice(&body_bytes) {
|
||||
Ok(value) => value,
|
||||
// Fallback sniffing symmetric to the chat / claude side (#2234): when the
|
||||
// upstream returns an Anthropic SSE body with an unmarked Content-Type,
|
||||
// aggregate it back into a message before continuing the conversion.
|
||||
Err(_) if body_looks_like_sse(&body_str) => {
|
||||
log::warn!("[Codex] Upstream returned an unmarked Anthropic SSE body, falling back to aggregation");
|
||||
transform_codex_anthropic::anthropic_sse_to_message_value(&body_str).map_err(|e| {
|
||||
log::error!("[Codex] Failed to aggregate Anthropic SSE body: {e}");
|
||||
e
|
||||
})?
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(
|
||||
"[Codex] Failed to parse Anthropic upstream response: {e}, body: {body_str}"
|
||||
);
|
||||
return Err(upstream_body_parse_error(
|
||||
"Failed to parse upstream anthropic response",
|
||||
&e,
|
||||
&response_headers,
|
||||
&body_str,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if is_stream {
|
||||
let events =
|
||||
responses_sse_events_from_anthropic_message(&anthropic_response, codex_tool_context);
|
||||
let sse_stream = futures::stream::iter(events.into_iter().map(Ok::<Bytes, std::io::Error>));
|
||||
return build_codex_anthropic_sse_response(
|
||||
sse_stream,
|
||||
ctx,
|
||||
state,
|
||||
status,
|
||||
connection_guard,
|
||||
);
|
||||
}
|
||||
|
||||
let _connection_guard = connection_guard;
|
||||
let responses_response =
|
||||
transform_codex_anthropic::anthropic_response_to_responses_with_context(
|
||||
anthropic_response,
|
||||
&codex_tool_context,
|
||||
)
|
||||
.map_err(|e| {
|
||||
log::error!("[Codex] Failed to convert Anthropic response to Responses: {e}");
|
||||
e
|
||||
})?;
|
||||
|
||||
if let Some(usage) = TokenUsage::from_codex_response_auto(&responses_response)
|
||||
.filter(TokenUsage::has_billable_tokens)
|
||||
{
|
||||
let model = responses_response
|
||||
.get("model")
|
||||
.and_then(|m| m.as_str())
|
||||
.filter(|m| !m.is_empty())
|
||||
.map(str::to_string)
|
||||
.or_else(|| ctx.outbound_model.clone())
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
let request_model = ctx.request_model.clone();
|
||||
let outbound_model = ctx
|
||||
.outbound_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
let app_type_str = ctx.app_type_str;
|
||||
tokio::spawn({
|
||||
let state = state.clone();
|
||||
let provider_id = ctx.provider.id.clone();
|
||||
let session_id = ctx.session_id.clone();
|
||||
let latency_ms = ctx.latency_ms();
|
||||
async move {
|
||||
log_usage(
|
||||
&state,
|
||||
&provider_id,
|
||||
app_type_str,
|
||||
&model,
|
||||
&request_model,
|
||||
&outbound_model,
|
||||
usage,
|
||||
latency_ms,
|
||||
None,
|
||||
false,
|
||||
status.as_u16(),
|
||||
Some(session_id),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
strip_entity_headers_for_rebuilt_body(&mut response_headers);
|
||||
strip_hop_by_hop_response_headers(&mut response_headers);
|
||||
response_headers.remove(axum::http::header::CONTENT_TYPE);
|
||||
|
||||
let mut builder = axum::response::Response::builder().status(status);
|
||||
for (key, value) in response_headers.iter() {
|
||||
builder = builder.header(key, value);
|
||||
}
|
||||
builder = builder.header(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
|
||||
let response_body = serde_json::to_vec(&responses_response).map_err(|e| {
|
||||
log::error!("[Codex] Failed to serialize Responses response: {e}");
|
||||
ProxyError::TransformError(format!("Failed to serialize responses response: {e}"))
|
||||
})?;
|
||||
|
||||
builder
|
||||
.body(axum::body::Body::from(response_body))
|
||||
.map_err(|e| {
|
||||
log::error!("[Codex] Failed to build Responses response: {e}");
|
||||
ProxyError::Internal(format!("Failed to build response: {e}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn build_codex_anthropic_sse_response(
|
||||
sse_stream: impl futures::Stream<Item = Result<Bytes, std::io::Error>> + Send + 'static,
|
||||
ctx: &RequestContext,
|
||||
state: &ProxyState,
|
||||
status: StatusCode,
|
||||
connection_guard: Option<ActiveConnectionGuard>,
|
||||
) -> Result<axum::response::Response, ProxyError> {
|
||||
let usage_collector = if usage_logging_enabled(state) {
|
||||
let state = state.clone();
|
||||
let provider_id = ctx.provider.id.clone();
|
||||
let request_model = ctx.request_model.clone();
|
||||
let fallback_model = ctx
|
||||
.outbound_model
|
||||
.clone()
|
||||
.unwrap_or_else(|| ctx.request_model.clone());
|
||||
let app_type_str = ctx.app_type_str;
|
||||
let start_time = ctx.start_time;
|
||||
let session_id = ctx.session_id.clone();
|
||||
|
||||
Some(SseUsageCollector::new(
|
||||
start_time,
|
||||
Some(codex_stream_usage_event_filter),
|
||||
move |events, first_token_ms| {
|
||||
let usage = TokenUsage::from_codex_stream_events_auto(&events).unwrap_or_default();
|
||||
if !usage.has_billable_tokens() {
|
||||
log::debug!("[Codex] Anthropic streaming response usage is all-zero or missing, skipping usage recording");
|
||||
return;
|
||||
}
|
||||
let model = usage
|
||||
.model
|
||||
.clone()
|
||||
.filter(|m| !m.is_empty())
|
||||
.unwrap_or_else(|| fallback_model.clone());
|
||||
let latency_ms = start_time.elapsed().as_millis() as u64;
|
||||
|
||||
let state = state.clone();
|
||||
let provider_id = provider_id.clone();
|
||||
let request_model = request_model.clone();
|
||||
let outbound_model = fallback_model.clone();
|
||||
let session_id = session_id.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
log_usage(
|
||||
&state,
|
||||
&provider_id,
|
||||
app_type_str,
|
||||
&model,
|
||||
&request_model,
|
||||
&outbound_model,
|
||||
usage,
|
||||
latency_ms,
|
||||
first_token_ms,
|
||||
true,
|
||||
status.as_u16(),
|
||||
Some(session_id),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
},
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let logged_stream = create_logged_passthrough_stream(
|
||||
sse_stream,
|
||||
ctx.tag,
|
||||
usage_collector,
|
||||
ctx.streaming_timeout_config(),
|
||||
connection_guard,
|
||||
);
|
||||
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
headers.insert(
|
||||
"Content-Type",
|
||||
axum::http::HeaderValue::from_static("text/event-stream"),
|
||||
);
|
||||
headers.insert(
|
||||
"Cache-Control",
|
||||
axum::http::HeaderValue::from_static("no-cache"),
|
||||
);
|
||||
|
||||
let body = axum::body::Body::from_stream(logged_stream);
|
||||
Ok((headers, body).into_response())
|
||||
}
|
||||
|
||||
/// 把上游 Chat Completions 的错误响应转换为 Responses API 错误形状。
|
||||
///
|
||||
/// 与正常响应分支配套:正常响应已经被改写成 Responses 形式,错误响应若仍保留
|
||||
|
||||
@@ -142,6 +142,21 @@ impl ProxyResponse {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Check whether the response explicitly declares a JSON media type.
|
||||
pub fn is_json(&self) -> bool {
|
||||
self.content_type()
|
||||
.map(|content_type| {
|
||||
let media_type = content_type
|
||||
.split(';')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_ascii_lowercase();
|
||||
media_type == "application/json" || media_type.ends_with("+json")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Consume the response and collect the full body into `Bytes`.
|
||||
pub async fn bytes(self) -> Result<Bytes, ProxyError> {
|
||||
match self {
|
||||
@@ -737,3 +752,27 @@ impl<S: Unpin> tokio::io::AsyncWrite for WriteFilter<S> {
|
||||
std::task::Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn buffered_with_content_type(content_type: Option<&str>) -> ProxyResponse {
|
||||
let mut headers = http::HeaderMap::new();
|
||||
if let Some(content_type) = content_type {
|
||||
headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_str(content_type).unwrap(),
|
||||
);
|
||||
}
|
||||
ProxyResponse::buffered(http::StatusCode::OK, headers, Bytes::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_content_type_detection_accepts_json_suffixes() {
|
||||
assert!(buffered_with_content_type(Some("application/json; charset=utf-8")).is_json());
|
||||
assert!(buffered_with_content_type(Some("application/problem+json")).is_json());
|
||||
assert!(!buffered_with_content_type(Some("text/event-stream")).is_json());
|
||||
assert!(!buffered_with_content_type(None).is_json());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#[cfg(test)]
|
||||
use crate::model_capabilities::is_confirmed_text_only_model as confirmed_text_only_model;
|
||||
use crate::model_capabilities::{image_input_capability_from_settings, ImageInputCapability};
|
||||
use crate::provider::Provider;
|
||||
use crate::proxy::error::ProxyError;
|
||||
use serde_json::{json, Value};
|
||||
@@ -9,9 +12,9 @@ pub const UNSUPPORTED_IMAGE_MARKER: &str = "[Unsupported Image]";
|
||||
/// 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.
|
||||
/// - the confirmed text-only registry is used for proactive replacement only
|
||||
/// when `allow_heuristic` is true. This switch controls silent request-body
|
||||
/// mutation, not the capability truth advertised by the Codex model catalog.
|
||||
pub fn replace_images_for_text_only_model(
|
||||
body: &mut Value,
|
||||
provider: &Provider,
|
||||
@@ -27,13 +30,9 @@ pub fn replace_images_for_text_only_model(
|
||||
.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) {
|
||||
if image_input_capability_from_settings(&provider.settings_config, model, allow_heuristic)
|
||||
!= ImageInputCapability::Unsupported
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -63,6 +62,19 @@ pub fn is_unsupported_image_error(error: &ProxyError) -> bool {
|
||||
|
||||
let message = extract_error_text(body);
|
||||
let message = message.to_ascii_lowercase();
|
||||
|
||||
// 自证性表述:这类短语本身就断言了"仅接受文本",属于模态拒绝,无需再要求
|
||||
// 错误提到 image/media 等字样——火山方舟等网关的报错是
|
||||
// "Model only support text input",全程不出现 image(issue #5025)。
|
||||
// 国产网关的英文常缺三单 s,因此带 s / 不带 s 两种形式都要列。
|
||||
const TEXT_ONLY_SELF_EVIDENT_HINTS: &[&str] = &["only support text", "only supports text"];
|
||||
if TEXT_ONLY_SELF_EVIDENT_HINTS
|
||||
.iter()
|
||||
.any(|hint| message.contains(hint))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let mentions_image = message.contains("image")
|
||||
|| message.contains("vision")
|
||||
|| message.contains("multimodal")
|
||||
@@ -83,7 +95,6 @@ pub fn is_unsupported_image_error(error: &ProxyError) -> bool {
|
||||
"doesn't support",
|
||||
"do not support",
|
||||
"don't support",
|
||||
"only supports text",
|
||||
"text only",
|
||||
"text-only",
|
||||
"invalid content type",
|
||||
@@ -225,91 +236,6 @@ fn replace_image_block_with_text_marker(block: &mut Value, text_type: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
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 = [
|
||||
@@ -334,43 +260,6 @@ fn extract_error_text(body: &str) -> String {
|
||||
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::*;
|
||||
@@ -415,7 +304,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_models_replace_images_before_send() {
|
||||
fn confirmed_text_only_models_replace_images_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek/deepseek-v4-pro",
|
||||
@@ -437,7 +326,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_models_replace_chat_image_url_before_send() {
|
||||
fn confirmed_text_only_models_replace_chat_image_url_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-flash",
|
||||
@@ -461,7 +350,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_models_replace_codex_input_image_before_send() {
|
||||
fn confirmed_text_only_models_replace_codex_input_image_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "deepseek-v4-flash",
|
||||
@@ -484,6 +373,15 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn longcat_models_are_classified_text_only() {
|
||||
// LongCat-2.0 (like the retired Flash Chat) is a text-only model; the
|
||||
// preset ships it in mixed case, so the classifier must normalize first.
|
||||
assert!(confirmed_text_only_model("LongCat-2.0"));
|
||||
assert!(confirmed_text_only_model("longcat/LongCat-2.0"));
|
||||
assert!(confirmed_text_only_model("LongCat-Flash-Chat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_text_modalities_replace_images_before_send() {
|
||||
let provider = provider(json!({
|
||||
@@ -637,7 +535,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_text_only_prefixes_replace_images_before_send() {
|
||||
fn confirmed_text_only_variant_replaces_images_before_send() {
|
||||
let provider = provider(json!({}));
|
||||
let mut body = json!({
|
||||
"model": "therouter/qwen/qwen3-coder-480b",
|
||||
@@ -717,6 +615,32 @@ mod tests {
|
||||
assert!(is_unsupported_image_error(&error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_text_only_errors_without_image_mention() {
|
||||
// 火山方舟真实报错(issue #5025):不含 image/media 等字样,且英文缺
|
||||
// 三单 s——旧逻辑的 mentions_image 门与 "only supports text" 提示都拦不住。
|
||||
let error = ProxyError::UpstreamError {
|
||||
status: 400,
|
||||
body: Some(
|
||||
r#"{"error":{"message":"Model only support text input Request id: 021783"}}"#
|
||||
.to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
assert!(is_unsupported_image_error(&error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glm_52_is_classified_text_only() {
|
||||
// issue #5025:火山 Coding Plan 的 GLM 5.2 是纯文本端点,
|
||||
// 映射链 glm-5.2[1M] 归一化后尾部为 glm-5.2。
|
||||
assert!(confirmed_text_only_model("glm-5.2"));
|
||||
assert!(confirmed_text_only_model("GLM-5.2[1M]"));
|
||||
assert!(confirmed_text_only_model("zai-org/GLM-5.2"));
|
||||
// 未来视觉版(智谱 4v/5v 命名惯例)不能被误判为纯文本。
|
||||
assert!(!confirmed_text_only_model("glm-5.2v"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_image_errors() {
|
||||
let error = ProxyError::UpstreamError {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub struct ModelMapping {
|
||||
pub sonnet_model: Option<String>,
|
||||
pub opus_model: Option<String>,
|
||||
pub fable_model: Option<String>,
|
||||
pub subagent_model: Option<String>,
|
||||
pub default_model: Option<String>,
|
||||
}
|
||||
|
||||
@@ -41,6 +42,11 @@ impl ModelMapping {
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
subagent_model: env
|
||||
.and_then(|e| e.get("CLAUDE_CODE_SUBAGENT_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from),
|
||||
default_model: env
|
||||
.and_then(|e| e.get("ANTHROPIC_MODEL"))
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -55,6 +61,7 @@ impl ModelMapping {
|
||||
|| self.sonnet_model.is_some()
|
||||
|| self.opus_model.is_some()
|
||||
|| self.fable_model.is_some()
|
||||
|| self.subagent_model.is_some()
|
||||
|| self.default_model.is_some()
|
||||
}
|
||||
|
||||
@@ -89,6 +96,13 @@ impl ModelMapping {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref m) = self.subagent_model {
|
||||
if strip_one_m_suffix_for_upstream(original_model) == strip_one_m_suffix_for_upstream(m)
|
||||
{
|
||||
return original_model.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 默认模型
|
||||
if let Some(ref m) = self.default_model {
|
||||
return m.clone();
|
||||
@@ -327,6 +341,42 @@ mod tests {
|
||||
assert_eq!(mapped, Some("default-model".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subagent_model_preserved_before_default_fallback() {
|
||||
let mut provider = create_provider_with_mapping();
|
||||
provider.settings_config = json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "default-model",
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL": "gpt-5.4-mini"
|
||||
}
|
||||
});
|
||||
|
||||
let body = json!({"model": "gpt-5.4-mini"});
|
||||
let (result, original, mapped) = apply_model_mapping(body, &provider);
|
||||
|
||||
assert_eq!(result["model"], "gpt-5.4-mini");
|
||||
assert_eq!(original, Some("gpt-5.4-mini".to_string()));
|
||||
assert!(mapped.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subagent_model_preserved_with_one_m_suffix_before_default_fallback() {
|
||||
let mut provider = create_provider_with_mapping();
|
||||
provider.settings_config = json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "default-model",
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL": "gpt-5.4-mini"
|
||||
}
|
||||
});
|
||||
|
||||
let body = json!({"model": "gpt-5.4-mini[1M]"});
|
||||
let (result, original, mapped) = apply_model_mapping(body, &provider);
|
||||
|
||||
assert_eq!(result["model"], "gpt-5.4-mini[1M]");
|
||||
assert_eq!(original, Some("gpt-5.4-mini[1M]".to_string()));
|
||||
assert!(mapped.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_mapping_configured() {
|
||||
let provider = create_provider_without_mapping();
|
||||
|
||||
@@ -124,7 +124,7 @@ pub enum AuthStrategy {
|
||||
///
|
||||
/// - Header: `Authorization: Bearer <access_token>`
|
||||
/// - Header: `ChatGPT-Account-Id: <account_id>` (来自 forwarder 注入)
|
||||
/// - Header: `originator: cc-switch`
|
||||
/// - Header: `originator: codex_cli_rs` + `version: <codex 版本>`(成对,后端按此做模型 cohort 路由)
|
||||
///
|
||||
/// 使用动态获取的 OpenAI access_token(通过 Device Code 流程获取)
|
||||
CodexOAuth,
|
||||
|
||||
@@ -24,6 +24,13 @@ 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"];
|
||||
|
||||
// ChatGPT Codex 后端按 originator+version 组合做模型 cohort 路由:非官方身份会把
|
||||
// gpt-5.6-luna 解析到未部署的内部引擎(HTTP 404 Model not found,openai/codex#31967,
|
||||
// 本机 A/B 实测确认)。两个头必须成对发送,缺一即 404;version 需 ≥ 目标模型
|
||||
// catalog 的 minimal_client_version(luna=0.144.0),新模型抬门槛时同步 bump。
|
||||
const CODEX_OAUTH_ORIGINATOR: &str = "codex_cli_rs";
|
||||
const CODEX_OAUTH_CLIENT_VERSION: &str = "0.144.1";
|
||||
|
||||
/// 获取 Claude 供应商的 API 格式
|
||||
///
|
||||
/// 供 handler/forwarder 外部使用的公开函数。
|
||||
@@ -666,7 +673,7 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
fn extract_base_url(&self, provider: &Provider) -> Result<String, ProxyError> {
|
||||
// Codex OAuth: 强制使用 ChatGPT 后端 API 端点(忽略用户配置的 base_url)
|
||||
if self.is_codex_oauth(provider) {
|
||||
return Ok("https://chatgpt.com/backend-api/codex".to_string());
|
||||
return Ok(super::CHATGPT_CODEX_BASE_URL.to_string());
|
||||
}
|
||||
|
||||
// 1. 从 env 中获取
|
||||
@@ -778,9 +785,9 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
|
||||
fn build_url(&self, base_url: &str, endpoint: &str) -> String {
|
||||
// Codex OAuth: 所有请求统一走 /responses 端点
|
||||
if base_url == "https://chatgpt.com/backend-api/codex" {
|
||||
if base_url == super::CHATGPT_CODEX_BASE_URL {
|
||||
let _ = endpoint; // 忽略原始 endpoint
|
||||
return "https://chatgpt.com/backend-api/codex/responses".to_string();
|
||||
return format!("{}/responses", super::CHATGPT_CODEX_BASE_URL);
|
||||
}
|
||||
|
||||
// NOTE:
|
||||
@@ -843,7 +850,11 @@ impl ProviderAdapter for ClaudeAdapter {
|
||||
(HeaderName::from_static("authorization"), hv(&bearer)?),
|
||||
(
|
||||
HeaderName::from_static("originator"),
|
||||
HeaderValue::from_static("cc-switch"),
|
||||
HeaderValue::from_static(CODEX_OAUTH_ORIGINATOR),
|
||||
),
|
||||
(
|
||||
HeaderName::from_static("version"),
|
||||
HeaderValue::from_static(CODEX_OAUTH_CLIENT_VERSION),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -84,6 +84,158 @@ pub fn should_convert_codex_responses_to_chat(provider: &Provider, endpoint: &st
|
||||
) && codex_provider_uses_chat_completions(provider)
|
||||
}
|
||||
|
||||
/// Whether a converted Codex Responses request may send `prompt_cache_key` to
|
||||
/// its Chat Completions upstream. Unknown OpenAI-compatible gateways default to
|
||||
/// false because many reject unsupported request fields with HTTP 400.
|
||||
pub fn should_send_codex_chat_prompt_cache_key(provider: &Provider) -> bool {
|
||||
match provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.prompt_cache_routing.as_deref())
|
||||
.unwrap_or("auto")
|
||||
{
|
||||
"enabled" => return true,
|
||||
"disabled" => return false,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let base_url = provider
|
||||
.settings_config
|
||||
.get("base_url")
|
||||
.or_else(|| provider.settings_config.get("baseURL"))
|
||||
.and_then(|value| value.as_str())
|
||||
.map(ToString::to_string)
|
||||
.or_else(|| {
|
||||
provider
|
||||
.settings_config
|
||||
.get("config")
|
||||
.and_then(|value| value.as_str())
|
||||
.and_then(extract_codex_base_url_from_toml)
|
||||
});
|
||||
|
||||
let Some(base_url) = base_url else {
|
||||
return false;
|
||||
};
|
||||
let Ok(url) = url::Url::parse(&base_url) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
match url.host_str() {
|
||||
Some("api.openai.com") => true,
|
||||
Some("api.kimi.com") => {
|
||||
let path = url.path().trim_end_matches('/');
|
||||
path == "/coding" || path.starts_with("/coding/")
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a stable cache-routing key after Responses -> Chat conversion. An
|
||||
/// explicit client key wins; otherwise only a real client-provided session ID
|
||||
/// is eligible. Generated per-request UUIDs must never be used here.
|
||||
pub fn inject_codex_chat_prompt_cache_key(
|
||||
provider: &Provider,
|
||||
chat_body: &mut JsonValue,
|
||||
explicit_key: Option<&str>,
|
||||
client_session_id: Option<&str>,
|
||||
) -> bool {
|
||||
if !should_send_codex_chat_prompt_cache_key(provider) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let key = explicit_key
|
||||
.map(str::trim)
|
||||
.filter(|key| !key.is_empty())
|
||||
.or_else(|| {
|
||||
client_session_id
|
||||
.map(str::trim)
|
||||
.filter(|session_id| !session_id.is_empty())
|
||||
});
|
||||
let Some(key) = key else {
|
||||
return false;
|
||||
};
|
||||
|
||||
chat_body["prompt_cache_key"] = JsonValue::String(key.to_string());
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether this Codex provider's real upstream speaks the native Anthropic
|
||||
/// Messages protocol (`/v1/messages`). The local Codex client always talks to CC
|
||||
/// Switch through the Responses API, so CC Switch bridges Responses ⇄ Anthropic.
|
||||
///
|
||||
/// Determined solely from explicit config (apiFormat / wire_api); no base_url
|
||||
/// guessing — Anthropic gateway addresses vary widely and guessing easily misfires.
|
||||
pub fn codex_provider_uses_anthropic(provider: &Provider) -> bool {
|
||||
if let Some(api_format) = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.api_format.as_deref())
|
||||
.or_else(|| {
|
||||
provider
|
||||
.settings_config
|
||||
.get("api_format")
|
||||
.and_then(|v| v.as_str())
|
||||
})
|
||||
.or_else(|| {
|
||||
provider
|
||||
.settings_config
|
||||
.get("apiFormat")
|
||||
.and_then(|v| v.as_str())
|
||||
})
|
||||
{
|
||||
return is_anthropic_wire_api(api_format);
|
||||
}
|
||||
|
||||
provider
|
||||
.settings_config
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.and_then(extract_codex_wire_api_from_toml)
|
||||
.map(|wire_api| is_anthropic_wire_api(&wire_api))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn should_convert_codex_responses_to_anthropic(provider: &Provider, endpoint: &str) -> bool {
|
||||
let path = endpoint
|
||||
.split_once('?')
|
||||
.map_or(endpoint, |(path, _query)| path);
|
||||
|
||||
matches!(
|
||||
path,
|
||||
"/responses" | "/v1/responses" | "/responses/compact" | "/v1/responses/compact"
|
||||
) && codex_provider_uses_anthropic(provider)
|
||||
}
|
||||
|
||||
/// The single built-in official Codex provider. Unlike managed Codex OAuth
|
||||
/// providers used by Claude, this route receives authentication from the
|
||||
/// calling Codex client (`requires_openai_auth = true`).
|
||||
pub fn is_codex_official_provider(provider: &Provider) -> bool {
|
||||
provider.id == crate::database::CODEX_OFFICIAL_PROVIDER_ID
|
||||
&& provider.category.as_deref() == Some("official")
|
||||
}
|
||||
|
||||
/// Resolve the model-catalog tool profile for a Codex provider using the SAME
|
||||
/// Anthropic detection as the proxy router ([`codex_provider_uses_anthropic`]), so the
|
||||
/// generated catalog never disagrees with the routed transform. A provider whose
|
||||
/// Anthropic upstream is declared only via settings `apiFormat` or TOML `wire_api`
|
||||
/// (not `meta.api_format`) would otherwise get a `ProxyChat` catalog and emit the
|
||||
/// freeform `apply_patch` tool that the Anthropic transform then silently drops.
|
||||
/// Non-Anthropic providers keep the existing `meta.api_format` classification.
|
||||
pub fn resolve_codex_catalog_tool_profile(
|
||||
provider: &Provider,
|
||||
) -> crate::codex_config::CodexCatalogToolProfile {
|
||||
use crate::codex_config::CodexCatalogToolProfile;
|
||||
if is_codex_official_provider(provider) {
|
||||
return CodexCatalogToolProfile::NativeResponses;
|
||||
}
|
||||
if codex_provider_uses_anthropic(provider) {
|
||||
return CodexCatalogToolProfile::Anthropic;
|
||||
}
|
||||
CodexCatalogToolProfile::from_api_format(
|
||||
provider.meta.as_ref().and_then(|m| m.api_format.as_deref()),
|
||||
)
|
||||
}
|
||||
|
||||
/// Extract the real upstream model configured for a Codex provider.
|
||||
pub fn codex_provider_upstream_model(provider: &Provider) -> Option<String> {
|
||||
provider
|
||||
@@ -129,7 +281,13 @@ pub fn apply_codex_chat_upstream_model(
|
||||
if !codex_provider_uses_chat_completions(provider) {
|
||||
return None;
|
||||
}
|
||||
apply_codex_upstream_model(provider, body)
|
||||
}
|
||||
|
||||
/// Same model-substitution logic as `apply_codex_chat_upstream_model`, but without
|
||||
/// the chat gating check. Reused by the anthropic conversion path (the forwarder has
|
||||
/// already confirmed this provider uses anthropic).
|
||||
pub fn apply_codex_upstream_model(provider: &Provider, body: &mut JsonValue) -> Option<String> {
|
||||
let catalog_model_ids = codex_provider_catalog_model_ids(provider);
|
||||
if let Some(request_model) = body
|
||||
.get("model")
|
||||
@@ -345,6 +503,13 @@ fn is_chat_wire_api(value: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
fn is_anthropic_wire_api(value: &str) -> bool {
|
||||
matches!(
|
||||
value.trim().to_ascii_lowercase().as_str(),
|
||||
"anthropic" | "anthropic_messages" | "anthropic-messages" | "claude" | "messages"
|
||||
)
|
||||
}
|
||||
|
||||
fn is_chat_completions_url(value: &str) -> bool {
|
||||
value
|
||||
.trim_end_matches('/')
|
||||
@@ -480,6 +645,10 @@ impl ProviderAdapter for CodexAdapter {
|
||||
}
|
||||
|
||||
fn extract_base_url(&self, provider: &Provider) -> Result<String, ProxyError> {
|
||||
if is_codex_official_provider(provider) {
|
||||
return Ok(super::CHATGPT_CODEX_BASE_URL.to_string());
|
||||
}
|
||||
|
||||
// 1. 尝试直接获取 base_url 字段
|
||||
if let Some(url) = provider
|
||||
.settings_config
|
||||
@@ -527,8 +696,28 @@ impl ProviderAdapter for CodexAdapter {
|
||||
}
|
||||
|
||||
fn extract_auth(&self, provider: &Provider) -> Option<AuthInfo> {
|
||||
// Anthropic upstream: the auth field is chosen by the user in the UI (meta.apiKeyField).
|
||||
// ANTHROPIC_API_KEY → x-api-key (AuthStrategy::Anthropic)
|
||||
// ANTHROPIC_AUTH_TOKEN → Authorization: Bearer (default, AuthStrategy::Bearer)
|
||||
// The two are mutually exclusive to avoid a 401 from the gateway receiving
|
||||
// both auth headers at once. All other Codex upstreams stay pure Bearer.
|
||||
let strategy = if codex_provider_uses_anthropic(provider) {
|
||||
let uses_x_api_key = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.api_key_field.as_deref())
|
||||
.map(|field| field.eq_ignore_ascii_case("ANTHROPIC_API_KEY"))
|
||||
.unwrap_or(false);
|
||||
if uses_x_api_key {
|
||||
AuthStrategy::Anthropic
|
||||
} else {
|
||||
AuthStrategy::Bearer
|
||||
}
|
||||
} else {
|
||||
AuthStrategy::Bearer
|
||||
};
|
||||
self.extract_key(provider)
|
||||
.map(|key| AuthInfo::new(key, AuthStrategy::Bearer))
|
||||
.map(|key| AuthInfo::new(key, strategy))
|
||||
}
|
||||
|
||||
fn build_url(&self, base_url: &str, endpoint: &str) -> String {
|
||||
@@ -569,6 +758,15 @@ impl ProviderAdapter for CodexAdapter {
|
||||
) -> Result<Vec<(http::HeaderName, http::HeaderValue)>, ProxyError> {
|
||||
use super::adapter::auth_header_value;
|
||||
let bearer = format!("Bearer {}", auth.api_key);
|
||||
// Anthropic gateway: send only x-api-key (anthropic-version is filled in by
|
||||
// the forwarder). Mutually exclusive with Bearer to avoid a 401 from the
|
||||
// gateway receiving both auth headers at once.
|
||||
if auth.strategy == AuthStrategy::Anthropic {
|
||||
return Ok(vec![(
|
||||
http::HeaderName::from_static("x-api-key"),
|
||||
auth_header_value(&auth.api_key)?,
|
||||
)]);
|
||||
}
|
||||
Ok(vec![(
|
||||
http::HeaderName::from_static("authorization"),
|
||||
auth_header_value(&bearer)?,
|
||||
@@ -598,6 +796,124 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn official_provider_uses_fixed_chatgpt_backend_without_stored_key() {
|
||||
let mut provider = create_provider(json!({ "auth": {}, "config": "" }));
|
||||
provider.id = "codex-official".to_string();
|
||||
provider.category = Some("official".to_string());
|
||||
let adapter = CodexAdapter::new();
|
||||
|
||||
assert!(is_codex_official_provider(&provider));
|
||||
assert_eq!(
|
||||
adapter
|
||||
.extract_base_url(&provider)
|
||||
.expect("official base url"),
|
||||
"https://chatgpt.com/backend-api/codex"
|
||||
);
|
||||
assert!(adapter.extract_auth(&provider).is_none());
|
||||
assert_eq!(
|
||||
adapter.build_url(
|
||||
"https://chatgpt.com/backend-api/codex",
|
||||
"/responses/compact"
|
||||
),
|
||||
"https://chatgpt.com/backend-api/codex/responses/compact"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_cache_routing_auto_enables_known_upstreams_only() {
|
||||
let kimi = create_provider(json!({
|
||||
"config": r#"
|
||||
model_provider = "custom"
|
||||
[model_providers.custom]
|
||||
base_url = "https://api.kimi.com/coding/v1"
|
||||
wire_api = "responses"
|
||||
"#
|
||||
}));
|
||||
let openai = create_provider(json!({
|
||||
"base_url": "https://api.openai.com/v1"
|
||||
}));
|
||||
let unknown = create_provider(json!({
|
||||
"base_url": "https://strict.example.com/v1"
|
||||
}));
|
||||
|
||||
assert!(should_send_codex_chat_prompt_cache_key(&kimi));
|
||||
assert!(should_send_codex_chat_prompt_cache_key(&openai));
|
||||
assert!(!should_send_codex_chat_prompt_cache_key(&unknown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_cache_routing_user_override_wins_over_auto_detection() {
|
||||
let mut kimi = create_provider(json!({
|
||||
"base_url": "https://api.kimi.com/coding/v1"
|
||||
}));
|
||||
kimi.meta = Some(crate::provider::ProviderMeta {
|
||||
prompt_cache_routing: Some("disabled".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(!should_send_codex_chat_prompt_cache_key(&kimi));
|
||||
|
||||
let mut unknown = create_provider(json!({
|
||||
"base_url": "https://strict.example.com/v1"
|
||||
}));
|
||||
unknown.meta = Some(crate::provider::ProviderMeta {
|
||||
prompt_cache_routing: Some("enabled".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(should_send_codex_chat_prompt_cache_key(&unknown));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_cache_key_prefers_explicit_key_then_real_session() {
|
||||
let provider = create_provider(json!({
|
||||
"base_url": "https://api.kimi.com/coding/v1"
|
||||
}));
|
||||
let mut explicit_body = json!({ "model": "kimi-for-coding" });
|
||||
assert!(inject_codex_chat_prompt_cache_key(
|
||||
&provider,
|
||||
&mut explicit_body,
|
||||
Some("request-key"),
|
||||
Some("session-key"),
|
||||
));
|
||||
assert_eq!(explicit_body["prompt_cache_key"], "request-key");
|
||||
|
||||
let mut session_body = json!({ "model": "kimi-for-coding" });
|
||||
assert!(inject_codex_chat_prompt_cache_key(
|
||||
&provider,
|
||||
&mut session_body,
|
||||
None,
|
||||
Some("session-key"),
|
||||
));
|
||||
assert_eq!(session_body["prompt_cache_key"], "session-key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_cache_key_is_not_injected_without_real_session_or_support() {
|
||||
let kimi = create_provider(json!({
|
||||
"base_url": "https://api.kimi.com/coding/v1"
|
||||
}));
|
||||
let mut no_session_body = json!({ "model": "kimi-for-coding" });
|
||||
assert!(!inject_codex_chat_prompt_cache_key(
|
||||
&kimi,
|
||||
&mut no_session_body,
|
||||
None,
|
||||
None,
|
||||
));
|
||||
assert!(no_session_body.get("prompt_cache_key").is_none());
|
||||
|
||||
let unknown = create_provider(json!({
|
||||
"base_url": "https://strict.example.com/v1"
|
||||
}));
|
||||
let mut unsupported_body = json!({ "model": "other" });
|
||||
assert!(!inject_codex_chat_prompt_cache_key(
|
||||
&unknown,
|
||||
&mut unsupported_body,
|
||||
Some("request-key"),
|
||||
Some("session-key"),
|
||||
));
|
||||
assert!(unsupported_body.get("prompt_cache_key").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_base_url_direct() {
|
||||
let adapter = CodexAdapter::new();
|
||||
@@ -662,6 +978,197 @@ experimental_bearer_token = "sk-config-key"
|
||||
assert_eq!(url, "https://api.openai.com/v1/responses");
|
||||
}
|
||||
|
||||
// ==================== anthropic upstream detection ====================
|
||||
|
||||
#[test]
|
||||
fn test_uses_anthropic_from_settings_api_format() {
|
||||
let provider = create_provider(json!({ "apiFormat": "anthropic" }));
|
||||
assert!(codex_provider_uses_anthropic(&provider));
|
||||
|
||||
let provider = create_provider(json!({ "api_format": "anthropic_messages" }));
|
||||
assert!(codex_provider_uses_anthropic(&provider));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_uses_anthropic_from_meta_api_format() {
|
||||
let mut provider = create_provider(json!({}));
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
api_format: Some("anthropic".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(codex_provider_uses_anthropic(&provider));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_uses_anthropic_from_toml_wire_api() {
|
||||
let provider = create_provider(json!({
|
||||
"config": r#"model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
wire_api = "anthropic"
|
||||
"#
|
||||
}));
|
||||
assert!(codex_provider_uses_anthropic(&provider));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_false_for_chat_and_responses() {
|
||||
let chat = create_provider(json!({ "apiFormat": "openai_chat" }));
|
||||
assert!(!codex_provider_uses_anthropic(&chat));
|
||||
let responses = create_provider(json!({ "apiFormat": "openai_responses" }));
|
||||
assert!(!codex_provider_uses_anthropic(&responses));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_and_chat_are_mutually_exclusive() {
|
||||
let anth = create_provider(json!({ "apiFormat": "anthropic" }));
|
||||
assert!(codex_provider_uses_anthropic(&anth));
|
||||
assert!(!codex_provider_uses_chat_completions(&anth));
|
||||
|
||||
let chat = create_provider(json!({ "apiFormat": "openai_chat" }));
|
||||
assert!(codex_provider_uses_chat_completions(&chat));
|
||||
assert!(!codex_provider_uses_anthropic(&chat));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_convert_responses_to_anthropic_path_guard() {
|
||||
let provider = create_provider(json!({ "apiFormat": "anthropic" }));
|
||||
assert!(should_convert_codex_responses_to_anthropic(
|
||||
&provider,
|
||||
"/responses"
|
||||
));
|
||||
assert!(should_convert_codex_responses_to_anthropic(
|
||||
&provider,
|
||||
"/v1/responses/compact"
|
||||
));
|
||||
assert!(should_convert_codex_responses_to_anthropic(
|
||||
&provider,
|
||||
"/responses?x=1"
|
||||
));
|
||||
assert!(!should_convert_codex_responses_to_anthropic(
|
||||
&provider,
|
||||
"/chat/completions"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_catalog_profile_matches_router() {
|
||||
use crate::codex_config::CodexCatalogToolProfile;
|
||||
|
||||
// Anthropic declared only via TOML wire_api (no meta.api_format) must still
|
||||
// resolve to the Anthropic catalog profile — this is the routing/catalog
|
||||
// divergence that let apply_patch leak through.
|
||||
let toml_anthropic = create_provider(json!({
|
||||
"config": r#"model_provider = "custom"
|
||||
|
||||
[model_providers.custom]
|
||||
wire_api = "anthropic"
|
||||
"#
|
||||
}));
|
||||
assert_eq!(
|
||||
resolve_codex_catalog_tool_profile(&toml_anthropic),
|
||||
CodexCatalogToolProfile::Anthropic
|
||||
);
|
||||
|
||||
// Anthropic via settings apiFormat.
|
||||
let settings_anthropic = create_provider(json!({ "apiFormat": "anthropic" }));
|
||||
assert_eq!(
|
||||
resolve_codex_catalog_tool_profile(&settings_anthropic),
|
||||
CodexCatalogToolProfile::Anthropic
|
||||
);
|
||||
|
||||
// Native openai_responses (meta) → NativeResponses; chat → ProxyChat.
|
||||
let mut native = create_provider(json!({}));
|
||||
native.meta = Some(crate::provider::ProviderMeta {
|
||||
api_format: Some("openai_responses".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(
|
||||
resolve_codex_catalog_tool_profile(&native),
|
||||
CodexCatalogToolProfile::NativeResponses
|
||||
);
|
||||
|
||||
let chat = create_provider(json!({ "apiFormat": "openai_chat" }));
|
||||
assert_eq!(
|
||||
resolve_codex_catalog_tool_profile(&chat),
|
||||
CodexCatalogToolProfile::ProxyChat
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply_codex_upstream_model_preserves_one_m_catalog_model() {
|
||||
// Regression for the [1m] path: a request model carrying the [1m] marker must
|
||||
// match its catalog entry and be preserved (not overridden by the provider
|
||||
// default) so the transform can later strip [1m] and emit the context-1m beta.
|
||||
// This only works because the forwarder no longer strips [1m] before this call
|
||||
// on the Anthropic path.
|
||||
let provider = create_provider(json!({
|
||||
"config": r#"model_provider = "custom"
|
||||
model = "claude-opus-4-1"
|
||||
|
||||
[model_providers.custom]
|
||||
wire_api = "anthropic"
|
||||
"#,
|
||||
"modelCatalog": {
|
||||
"models": [
|
||||
{ "model": "claude-opus-4-1[1m]" }
|
||||
]
|
||||
}
|
||||
}));
|
||||
let mut body = json!({ "model": "claude-opus-4-1[1m]", "input": "hi" });
|
||||
let result = apply_codex_upstream_model(&provider, &mut body);
|
||||
assert_eq!(result.as_deref(), Some("claude-opus-4-1[1m]"));
|
||||
assert_eq!(
|
||||
body.get("model").and_then(|v| v.as_str()),
|
||||
Some("claude-opus-4-1[1m]")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_auth_defaults_to_bearer() {
|
||||
// No meta.apiKeyField (defaults to ANTHROPIC_AUTH_TOKEN) → Authorization: Bearer only
|
||||
let adapter = CodexAdapter::new();
|
||||
let provider = create_provider(json!({
|
||||
"apiFormat": "anthropic",
|
||||
"auth": { "OPENAI_API_KEY": "sk-anthropic-key-123" }
|
||||
}));
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert_eq!(auth.strategy, AuthStrategy::Bearer);
|
||||
|
||||
let headers = adapter.get_auth_headers(&auth).unwrap();
|
||||
let names: Vec<String> = headers
|
||||
.iter()
|
||||
.map(|(name, _)| name.as_str().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["authorization".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_auth_x_api_key_when_selected() {
|
||||
// meta.apiKeyField = ANTHROPIC_API_KEY → x-api-key only
|
||||
let adapter = CodexAdapter::new();
|
||||
let mut provider = create_provider(json!({
|
||||
"apiFormat": "anthropic",
|
||||
"auth": { "OPENAI_API_KEY": "sk-anthropic-key-123" }
|
||||
}));
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
api_format: Some("anthropic".to_string()),
|
||||
api_key_field: Some("ANTHROPIC_API_KEY".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let auth = adapter.extract_auth(&provider).unwrap();
|
||||
assert_eq!(auth.strategy, AuthStrategy::Anthropic);
|
||||
|
||||
let headers = adapter.get_auth_headers(&auth).unwrap();
|
||||
let names: Vec<String> = headers
|
||||
.iter()
|
||||
.map(|(name, _)| name.as_str().to_string())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["x-api-key".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_url_origin_adds_v1() {
|
||||
let adapter = CodexAdapter::new();
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Shared builders for the OpenAI Responses SSE envelope.
|
||||
//!
|
||||
//! The two Codex streaming converters — `streaming_codex_chat` (Chat Completions SSE →
|
||||
//! Responses SSE) and `streaming_codex_anthropic` (Anthropic Messages SSE → Responses
|
||||
//! SSE) — have completely different *input* state machines but must emit the identical
|
||||
//! Responses event stream the Codex client understands. This module owns that output
|
||||
//! envelope so the two converters cannot drift when an event's shape changes: a wire fix
|
||||
//! lands here once instead of being mirrored in both files.
|
||||
//!
|
||||
//! Each function is pure — it takes primitives or a caller-built `item` `Value` and
|
||||
//! returns the exact bytes the converters previously constructed inline. Item shapes that
|
||||
//! vary per converter (including function, namespace, custom, and tool-search calls)
|
||||
//! are supplied by the caller via the generic
|
||||
//! `output_item_added` / `output_item_done` helpers.
|
||||
|
||||
use bytes::Bytes;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Serialize one Responses SSE event with the standard `event:`/`data:` framing.
|
||||
pub(crate) fn sse_event(event: &str, data: Value) -> Bytes {
|
||||
Bytes::from(format!(
|
||||
"event: {event}\ndata: {}\n\n",
|
||||
serde_json::to_string(&data).unwrap_or_default()
|
||||
))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Response lifecycle (created / in_progress / completed / failed)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `response.created`, wrapping a caller-built `response` object (usage/created_at differ
|
||||
/// per converter, so the caller supplies the whole object).
|
||||
pub(crate) fn response_created(response: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.created",
|
||||
json!({ "type": "response.created", "response": response }),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.in_progress`.
|
||||
pub(crate) fn response_in_progress(response: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.in_progress",
|
||||
json!({ "type": "response.in_progress", "response": response }),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.completed`.
|
||||
pub(crate) fn response_completed(response: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.completed",
|
||||
json!({ "type": "response.completed", "response": response }),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.failed`.
|
||||
pub(crate) fn response_failed(response: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.failed",
|
||||
json!({ "type": "response.failed", "response": response }),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Generic output-item add/done (item value supplied by the caller)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `response.output_item.added` with a caller-built item (message / reasoning /
|
||||
/// function_call / custom_tool_call).
|
||||
pub(crate) fn output_item_added(output_index: u32, item: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": item
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.output_item.done` with a caller-built item.
|
||||
pub(crate) fn output_item_done(output_index: u32, item: &Value) -> Bytes {
|
||||
sse_event(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": item
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Assistant message (text) lifecycle
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `response.output_item.added` for an in-progress assistant message.
|
||||
pub(crate) fn message_item_added(output_index: u32, item_id: &str) -> Bytes {
|
||||
output_item_added(
|
||||
output_index,
|
||||
&json!({
|
||||
"id": item_id,
|
||||
"type": "message",
|
||||
"status": "in_progress",
|
||||
"role": "assistant",
|
||||
"content": []
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.content_part.added` for the (empty) output_text part of a message.
|
||||
pub(crate) fn message_content_part_added(output_index: u32, item_id: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.content_part.added",
|
||||
json!({
|
||||
"type": "response.content_part.added",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": { "type": "output_text", "text": "", "annotations": [] }
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.output_text.delta`.
|
||||
pub(crate) fn output_text_delta(output_index: u32, item_id: &str, delta: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.output_text.delta",
|
||||
json!({
|
||||
"type": "response.output_text.delta",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"delta": delta
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The completed assistant-message item value.
|
||||
pub(crate) fn message_item(item_id: &str, text: &str) -> Value {
|
||||
json!({
|
||||
"id": item_id,
|
||||
"type": "message",
|
||||
"status": "completed",
|
||||
"role": "assistant",
|
||||
"content": [{ "type": "output_text", "text": text, "annotations": [] }]
|
||||
})
|
||||
}
|
||||
|
||||
/// Close an assistant message: emits `output_text.done` → `content_part.done` →
|
||||
/// `output_item.done`, and returns the completed item so the caller can record it.
|
||||
pub(crate) fn message_close(output_index: u32, item_id: &str, text: &str) -> (Vec<Bytes>, Value) {
|
||||
let item = message_item(item_id, text);
|
||||
let events = vec![
|
||||
sse_event(
|
||||
"response.output_text.done",
|
||||
json!({
|
||||
"type": "response.output_text.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"text": text
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.content_part.done",
|
||||
json!({
|
||||
"type": "response.content_part.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": { "type": "output_text", "text": text, "annotations": [] }
|
||||
}),
|
||||
),
|
||||
output_item_done(output_index, &item),
|
||||
];
|
||||
(events, item)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Reasoning (summary) lifecycle
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `response.output_item.added` for an in-progress reasoning item.
|
||||
pub(crate) fn reasoning_item_added(output_index: u32, item_id: &str) -> Bytes {
|
||||
output_item_added(
|
||||
output_index,
|
||||
&json!({
|
||||
"id": item_id,
|
||||
"type": "reasoning",
|
||||
"status": "in_progress",
|
||||
"summary": []
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.reasoning_summary_part.added` for the (empty) summary part.
|
||||
pub(crate) fn reasoning_summary_part_added(output_index: u32, item_id: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.reasoning_summary_part.added",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.added",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": { "type": "summary_text", "text": "" }
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.reasoning_summary_text.delta`.
|
||||
pub(crate) fn reasoning_summary_text_delta(output_index: u32, item_id: &str, delta: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.reasoning_summary_text.delta",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.delta",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"delta": delta
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The completed reasoning item value (note: no `status` field, matching both converters).
|
||||
pub(crate) fn reasoning_item(item_id: &str, text: &str) -> Value {
|
||||
json!({
|
||||
"id": item_id,
|
||||
"type": "reasoning",
|
||||
"summary": [{ "type": "summary_text", "text": text }]
|
||||
})
|
||||
}
|
||||
|
||||
/// Close a reasoning item: emits `reasoning_summary_text.done` →
|
||||
/// `reasoning_summary_part.done` → `output_item.done`, and returns the completed item.
|
||||
pub(crate) fn reasoning_close(output_index: u32, item_id: &str, text: &str) -> (Vec<Bytes>, Value) {
|
||||
let item = reasoning_item(item_id, text);
|
||||
let events = reasoning_close_with_item(output_index, item_id, text, &item, true);
|
||||
(events, item)
|
||||
}
|
||||
|
||||
/// Close a reasoning item whose completed shape is supplied by the converter.
|
||||
/// Anthropic uses this to attach opaque signed/redacted thinking in
|
||||
/// `encrypted_content` while keeping the standard Responses event lifecycle.
|
||||
pub(crate) fn reasoning_close_with_item(
|
||||
output_index: u32,
|
||||
item_id: &str,
|
||||
text: &str,
|
||||
item: &Value,
|
||||
has_visible_summary: bool,
|
||||
) -> Vec<Bytes> {
|
||||
let mut events = Vec::new();
|
||||
if has_visible_summary {
|
||||
events.extend([
|
||||
sse_event(
|
||||
"response.reasoning_summary_text.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"text": text
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.reasoning_summary_part.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": { "type": "summary_text", "text": text }
|
||||
}),
|
||||
),
|
||||
]);
|
||||
}
|
||||
events.push(output_item_done(output_index, item));
|
||||
events
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tool-call argument streaming (item value supplied by the caller)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `response.function_call_arguments.delta`.
|
||||
pub(crate) fn function_call_arguments_delta(
|
||||
output_index: u32,
|
||||
item_id: &str,
|
||||
delta: &str,
|
||||
) -> Bytes {
|
||||
sse_event(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.delta",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"delta": delta
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.function_call_arguments.done`.
|
||||
pub(crate) fn function_call_arguments_done(
|
||||
output_index: u32,
|
||||
item_id: &str,
|
||||
arguments: &str,
|
||||
) -> Bytes {
|
||||
sse_event(
|
||||
"response.function_call_arguments.done",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"arguments": arguments
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.custom_tool_call_input.delta` (Chat freeform tools only).
|
||||
pub(crate) fn custom_tool_call_input_delta(output_index: u32, item_id: &str, delta: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.custom_tool_call_input.delta",
|
||||
json!({
|
||||
"type": "response.custom_tool_call_input.delta",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"delta": delta
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// `response.custom_tool_call_input.done` (Chat freeform tools only).
|
||||
pub(crate) fn custom_tool_call_input_done(output_index: u32, item_id: &str, input: &str) -> Bytes {
|
||||
sse_event(
|
||||
"response.custom_tool_call_input.done",
|
||||
json!({
|
||||
"type": "response.custom_tool_call_input.done",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"input": input
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn body(bytes: &Bytes) -> String {
|
||||
String::from_utf8(bytes.to_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_event_framing() {
|
||||
let ev = sse_event("response.created", json!({ "a": 1 }));
|
||||
assert_eq!(body(&ev), "event: response.created\ndata: {\"a\":1}\n\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_close_shapes_match_legacy() {
|
||||
let (events, item) = message_close(2, "resp_1_msg", "hi");
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(body(&events[0]).contains("\"type\":\"response.output_text.done\""));
|
||||
assert!(body(&events[0]).contains("\"text\":\"hi\""));
|
||||
assert!(body(&events[1]).contains("\"type\":\"response.content_part.done\""));
|
||||
assert!(body(&events[2]).contains("\"type\":\"response.output_item.done\""));
|
||||
assert_eq!(item["type"], "message");
|
||||
assert_eq!(item["status"], "completed");
|
||||
assert_eq!(item["content"][0]["text"], "hi");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_close_item_has_no_status() {
|
||||
let (events, item) = reasoning_close(0, "rs_1", "because");
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(body(&events[0]).contains("\"type\":\"response.reasoning_summary_text.done\""));
|
||||
assert!(body(&events[1]).contains("\"type\":\"response.reasoning_summary_part.done\""));
|
||||
// The completed reasoning item intentionally carries no `status` field.
|
||||
assert!(item.get("status").is_none());
|
||||
assert_eq!(item["summary"][0]["text"], "because");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_item_added_is_in_progress() {
|
||||
let ev = message_item_added(0, "m1");
|
||||
let s = body(&ev);
|
||||
assert!(s.contains("\"type\":\"response.output_item.added\""));
|
||||
assert!(s.contains("\"status\":\"in_progress\""));
|
||||
assert!(s.contains("\"role\":\"assistant\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_call_argument_events() {
|
||||
assert!(body(&function_call_arguments_delta(1, "fc_x", "{\"a\":"))
|
||||
.contains("\"type\":\"response.function_call_arguments.delta\""));
|
||||
assert!(body(&function_call_arguments_done(1, "fc_x", "{\"a\":1}"))
|
||||
.contains("\"arguments\":\"{\\\"a\\\":1}\""));
|
||||
}
|
||||
}
|
||||
@@ -18,17 +18,21 @@ mod codex;
|
||||
pub(crate) mod codex_chat_common;
|
||||
pub mod codex_chat_history;
|
||||
pub mod codex_oauth_auth;
|
||||
pub(crate) mod codex_responses_sse;
|
||||
pub mod copilot_auth;
|
||||
pub mod copilot_model_map;
|
||||
mod gemini;
|
||||
pub(crate) mod gemini_schema;
|
||||
pub mod gemini_shadow;
|
||||
pub mod models;
|
||||
pub(crate) mod reasoning_bridge;
|
||||
pub mod streaming;
|
||||
pub mod streaming_codex_anthropic;
|
||||
pub mod streaming_codex_chat;
|
||||
pub mod streaming_gemini;
|
||||
pub mod streaming_responses;
|
||||
pub mod transform;
|
||||
pub mod transform_codex_anthropic;
|
||||
pub mod transform_codex_chat;
|
||||
pub mod transform_gemini;
|
||||
pub mod transform_responses;
|
||||
@@ -37,6 +41,8 @@ use crate::app_config::AppType;
|
||||
use crate::provider::Provider;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const CHATGPT_CODEX_BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
|
||||
|
||||
// 公开导出
|
||||
pub use adapter::ProviderAdapter;
|
||||
pub use auth::{AuthInfo, AuthStrategy};
|
||||
@@ -47,8 +53,10 @@ pub use claude::{
|
||||
};
|
||||
pub use codex::CodexAdapter;
|
||||
pub use codex::{
|
||||
apply_codex_chat_upstream_model, codex_provider_upstream_model,
|
||||
resolve_codex_chat_reasoning_config, should_convert_codex_responses_to_chat,
|
||||
apply_codex_chat_upstream_model, apply_codex_upstream_model, codex_provider_upstream_model,
|
||||
inject_codex_chat_prompt_cache_key, is_codex_official_provider,
|
||||
resolve_codex_catalog_tool_profile, resolve_codex_chat_reasoning_config,
|
||||
should_convert_codex_responses_to_anthropic, should_convert_codex_responses_to_chat,
|
||||
};
|
||||
pub use gemini::GeminiAdapter;
|
||||
|
||||
@@ -104,7 +112,7 @@ impl ProviderType {
|
||||
}
|
||||
ProviderType::OpenRouter => "https://openrouter.ai/api",
|
||||
ProviderType::GitHubCopilot => "https://api.githubcopilot.com",
|
||||
ProviderType::CodexOAuth => "https://chatgpt.com/backend-api/codex",
|
||||
ProviderType::CodexOAuth => CHATGPT_CODEX_BASE_URL,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Opaque reasoning transport helpers shared by the Messages ↔ Responses bridge.
|
||||
//!
|
||||
//! The Anthropic Messages protocol has no field for an OpenAI Responses
|
||||
//! `reasoning` item. To keep stateless tool loops lossless, the complete item is
|
||||
//! carried in a versioned thinking signature/redacted-thinking payload and
|
||||
//! restored when the client replays the assistant message.
|
||||
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) const OPENAI_REASONING_ITEM_PREFIX: &str = "ccswitch-openai-reasoning-v1:";
|
||||
|
||||
pub(crate) fn reasoning_summary_text(item: &Value) -> String {
|
||||
item.get("summary")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|part| {
|
||||
matches!(
|
||||
part.get("type").and_then(Value::as_str),
|
||||
Some("summary_text" | "reasoning_text")
|
||||
)
|
||||
.then(|| part.get("text").and_then(Value::as_str))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
pub(crate) fn encode_openai_reasoning_item(item: &Value) -> Option<String> {
|
||||
if item.get("type").and_then(Value::as_str) != Some("reasoning") {
|
||||
return None;
|
||||
}
|
||||
let bytes = serde_json::to_vec(item).ok()?;
|
||||
Some(format!(
|
||||
"{OPENAI_REASONING_ITEM_PREFIX}{}",
|
||||
URL_SAFE_NO_PAD.encode(bytes)
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn decode_openai_reasoning_item(encoded: &str) -> Option<Value> {
|
||||
let payload = encoded.strip_prefix(OPENAI_REASONING_ITEM_PREFIX)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
|
||||
let item: Value = serde_json::from_slice(&bytes).ok()?;
|
||||
(item.get("type").and_then(Value::as_str) == Some("reasoning")).then_some(item)
|
||||
}
|
||||
|
||||
pub(crate) fn anthropic_block_from_openai_reasoning_item(item: &Value) -> Option<Value> {
|
||||
if item.get("type").and_then(Value::as_str) != Some("reasoning") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let text = reasoning_summary_text(item);
|
||||
let has_encrypted_content = item
|
||||
.get("encrypted_content")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|value| !value.is_empty());
|
||||
|
||||
if has_encrypted_content {
|
||||
let envelope = encode_openai_reasoning_item(item)?;
|
||||
if text.is_empty() {
|
||||
return Some(json!({
|
||||
"type": "redacted_thinking",
|
||||
"data": envelope
|
||||
}));
|
||||
}
|
||||
return Some(json!({
|
||||
"type": "thinking",
|
||||
"thinking": text,
|
||||
"signature": envelope
|
||||
}));
|
||||
}
|
||||
|
||||
(!text.is_empty()).then(|| {
|
||||
json!({
|
||||
"type": "thinking",
|
||||
"thinking": text
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn openai_reasoning_item_from_anthropic_block(block: &Value) -> Option<Value> {
|
||||
match block.get("type").and_then(Value::as_str) {
|
||||
Some("thinking") => block
|
||||
.get("signature")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(decode_openai_reasoning_item),
|
||||
Some("redacted_thinking") => block
|
||||
.get("data")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(decode_openai_reasoning_item),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn openai_reasoning_item_round_trips_through_thinking_signature() {
|
||||
let item = json!({
|
||||
"id": "rs_1",
|
||||
"type": "reasoning",
|
||||
"summary": [{"type": "summary_text", "text": "Need a tool."}],
|
||||
"encrypted_content": "opaque"
|
||||
});
|
||||
let block = anthropic_block_from_openai_reasoning_item(&item).unwrap();
|
||||
assert_eq!(block["type"], "thinking");
|
||||
assert_eq!(
|
||||
openai_reasoning_item_from_anthropic_block(&block),
|
||||
Some(item)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encrypted_item_without_summary_uses_redacted_thinking() {
|
||||
let item = json!({
|
||||
"id": "rs_2",
|
||||
"type": "reasoning",
|
||||
"summary": [],
|
||||
"encrypted_content": "opaque"
|
||||
});
|
||||
let block = anthropic_block_from_openai_reasoning_item(&item).unwrap();
|
||||
assert_eq!(block["type"], "redacted_thinking");
|
||||
assert_eq!(
|
||||
openai_reasoning_item_from_anthropic_block(&block),
|
||||
Some(item)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,8 @@ struct Usage {
|
||||
struct PromptTokensDetails {
|
||||
#[serde(default)]
|
||||
cached_tokens: u32,
|
||||
#[serde(default)]
|
||||
cache_write_tokens: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -103,7 +105,7 @@ fn build_anthropic_usage_json(usage: &Usage) -> Value {
|
||||
// OpenAI prompt_tokens 含缓存,Anthropic input_tokens 不含,需减去 cache_read 与 cache_creation
|
||||
// (三桶互斥,恒等 input + cache_read + cache_creation == prompt_tokens)。
|
||||
let cached = extract_cache_read_tokens(usage).unwrap_or(0);
|
||||
let cache_creation = usage.cache_creation_input_tokens.unwrap_or(0);
|
||||
let cache_creation = extract_cache_write_tokens(usage).unwrap_or(0);
|
||||
let input_tokens = usage
|
||||
.prompt_tokens
|
||||
.saturating_sub(cached)
|
||||
@@ -233,7 +235,7 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
|
||||
if let Some(u) = &chunk.usage {
|
||||
let cached = extract_cache_read_tokens(u).unwrap_or(0);
|
||||
let cache_creation =
|
||||
u.cache_creation_input_tokens.unwrap_or(0);
|
||||
extract_cache_write_tokens(u).unwrap_or(0);
|
||||
let input = u
|
||||
.prompt_tokens
|
||||
.saturating_sub(cached)
|
||||
@@ -683,6 +685,18 @@ fn extract_cache_read_tokens(usage: &Usage) -> Option<u32> {
|
||||
.filter(|&v| v > 0)
|
||||
}
|
||||
|
||||
/// Extract cache-write tokens from direct compatibility fields or OpenAI details.
|
||||
fn extract_cache_write_tokens(usage: &Usage) -> Option<u32> {
|
||||
if let Some(value) = usage.cache_creation_input_tokens {
|
||||
return Some(value);
|
||||
}
|
||||
usage
|
||||
.prompt_tokens_details
|
||||
.as_ref()
|
||||
.map(|details| details.cache_write_tokens)
|
||||
.filter(|value| *value > 0)
|
||||
}
|
||||
|
||||
/// 映射停止原因
|
||||
fn map_stop_reason(finish_reason: Option<&str>) -> Option<String> {
|
||||
finish_reason.map(|r| {
|
||||
@@ -1061,7 +1075,7 @@ mod tests {
|
||||
let input = concat!(
|
||||
"data: {\"id\":\"chatcmpl_cc\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"tool-1\",\"type\":\"function\",\"function\":{\"name\":\"Bash\",\"arguments\":\"{\\\"command\\\":\\\"pwd\\\"}\"}}]}}]}\n\n",
|
||||
"data: {\"id\":\"chatcmpl_cc\",\"model\":\"glm-5.1\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
|
||||
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1000,\"completion_tokens\":50,\"prompt_tokens_details\":{\"cached_tokens\":600},\"cache_creation_input_tokens\":300}}\n\n",
|
||||
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1000,\"completion_tokens\":50,\"prompt_tokens_details\":{\"cached_tokens\":600,\"cache_write_tokens\":300}}}\n\n",
|
||||
"data: [DONE]\n\n"
|
||||
);
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
//! OpenAI Chat Completions SSE → OpenAI Responses SSE conversion.
|
||||
|
||||
use super::codex_responses_sse as sse;
|
||||
use super::{
|
||||
codex_chat_common::{
|
||||
extract_reasoning_field_text, split_leading_think_block, strip_leading_think_open_tag,
|
||||
@@ -270,20 +271,8 @@ impl ChatToResponsesState {
|
||||
let response = self.base_response("in_progress", Vec::new());
|
||||
|
||||
vec![
|
||||
sse_event(
|
||||
"response.created",
|
||||
json!({
|
||||
"type": "response.created",
|
||||
"response": response
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.in_progress",
|
||||
json!({
|
||||
"type": "response.in_progress",
|
||||
"response": self.base_response("in_progress", Vec::new())
|
||||
}),
|
||||
),
|
||||
sse::response_created(&response),
|
||||
sse::response_in_progress(&response),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -297,45 +286,16 @@ impl ChatToResponsesState {
|
||||
self.reasoning.item_id = item_id.clone();
|
||||
self.reasoning.added = true;
|
||||
|
||||
events.push(sse_event(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": {
|
||||
"id": item_id,
|
||||
"type": "reasoning",
|
||||
"status": "in_progress",
|
||||
"summary": []
|
||||
}
|
||||
}),
|
||||
));
|
||||
events.push(sse_event(
|
||||
"response.reasoning_summary_part.added",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.added",
|
||||
"item_id": self.reasoning.item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": {
|
||||
"type": "summary_text",
|
||||
"text": ""
|
||||
}
|
||||
}),
|
||||
));
|
||||
events.push(sse::reasoning_item_added(output_index, &item_id));
|
||||
events.push(sse::reasoning_summary_part_added(output_index, &item_id));
|
||||
}
|
||||
|
||||
self.reasoning.text.push_str(delta);
|
||||
let output_index = self.reasoning.output_index.unwrap_or(0);
|
||||
events.push(sse_event(
|
||||
"response.reasoning_summary_text.delta",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.delta",
|
||||
"item_id": self.reasoning.item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"delta": delta
|
||||
}),
|
||||
events.push(sse::reasoning_summary_text_delta(
|
||||
output_index,
|
||||
&self.reasoning.item_id,
|
||||
delta,
|
||||
));
|
||||
|
||||
events
|
||||
@@ -351,47 +311,16 @@ impl ChatToResponsesState {
|
||||
self.text.item_id = item_id.clone();
|
||||
self.text.added = true;
|
||||
|
||||
events.push(sse_event(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": output_index,
|
||||
"item": {
|
||||
"id": item_id,
|
||||
"type": "message",
|
||||
"status": "in_progress",
|
||||
"role": "assistant",
|
||||
"content": []
|
||||
}
|
||||
}),
|
||||
));
|
||||
events.push(sse_event(
|
||||
"response.content_part.added",
|
||||
json!({
|
||||
"type": "response.content_part.added",
|
||||
"item_id": self.text.item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": {
|
||||
"type": "output_text",
|
||||
"text": "",
|
||||
"annotations": []
|
||||
}
|
||||
}),
|
||||
));
|
||||
events.push(sse::message_item_added(output_index, &item_id));
|
||||
events.push(sse::message_content_part_added(output_index, &item_id));
|
||||
}
|
||||
|
||||
self.text.text.push_str(delta);
|
||||
let output_index = self.text.output_index.unwrap_or(0);
|
||||
events.push(sse_event(
|
||||
"response.output_text.delta",
|
||||
json!({
|
||||
"type": "response.output_text.delta",
|
||||
"item_id": self.text.item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"delta": delta
|
||||
}),
|
||||
events.push(sse::output_text_delta(
|
||||
output_index,
|
||||
&self.text.item_id,
|
||||
delta,
|
||||
));
|
||||
|
||||
events
|
||||
@@ -485,36 +414,21 @@ impl ChatToResponsesState {
|
||||
&self.tool_context,
|
||||
);
|
||||
|
||||
events.push(sse_event(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": assigned,
|
||||
"item": item
|
||||
}),
|
||||
));
|
||||
events.push(sse::output_item_added(assigned, &item));
|
||||
|
||||
if !pending_arguments.is_empty() && !is_custom_tool {
|
||||
events.push(sse_event(
|
||||
"response.function_call_arguments.delta",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.delta",
|
||||
"item_id": state.item_id,
|
||||
"output_index": assigned,
|
||||
"delta": pending_arguments
|
||||
}),
|
||||
events.push(sse::function_call_arguments_delta(
|
||||
assigned,
|
||||
&state.item_id,
|
||||
&pending_arguments,
|
||||
));
|
||||
}
|
||||
} 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",
|
||||
json!({
|
||||
"type": "response.function_call_arguments.delta",
|
||||
"item_id": item_id,
|
||||
"output_index": output_index,
|
||||
"delta": args_delta
|
||||
}),
|
||||
events.push(sse::function_call_arguments_delta(
|
||||
output_index,
|
||||
&item_id,
|
||||
&args_delta,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -567,13 +481,7 @@ impl ChatToResponsesState {
|
||||
response["incomplete_details"] = json!({ "reason": "max_output_tokens" });
|
||||
}
|
||||
|
||||
events.push(sse_event(
|
||||
"response.completed",
|
||||
json!({
|
||||
"type": "response.completed",
|
||||
"response": response
|
||||
}),
|
||||
));
|
||||
events.push(sse::response_completed(&response));
|
||||
self.completed = true;
|
||||
events
|
||||
}
|
||||
@@ -586,50 +494,10 @@ impl ChatToResponsesState {
|
||||
let output_index = self.reasoning.output_index.unwrap_or(0);
|
||||
let item_id = self.reasoning.item_id.clone();
|
||||
let text = self.reasoning.text.clone();
|
||||
let item = json!({
|
||||
"id": item_id,
|
||||
"type": "reasoning",
|
||||
"summary": [{
|
||||
"type": "summary_text",
|
||||
"text": text
|
||||
}]
|
||||
});
|
||||
self.output_items.push((output_index, item.clone()));
|
||||
let (events, item) = sse::reasoning_close(output_index, &item_id, &text);
|
||||
self.output_items.push((output_index, item));
|
||||
self.reasoning.done = true;
|
||||
|
||||
vec![
|
||||
sse_event(
|
||||
"response.reasoning_summary_text.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_text.done",
|
||||
"item_id": self.reasoning.item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"text": self.reasoning.text
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.reasoning_summary_part.done",
|
||||
json!({
|
||||
"type": "response.reasoning_summary_part.done",
|
||||
"item_id": self.reasoning.item_id,
|
||||
"output_index": output_index,
|
||||
"summary_index": 0,
|
||||
"part": {
|
||||
"type": "summary_text",
|
||||
"text": self.reasoning.text
|
||||
}
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": item
|
||||
}),
|
||||
),
|
||||
]
|
||||
events
|
||||
}
|
||||
|
||||
fn finalize_text(&mut self) -> Vec<Bytes> {
|
||||
@@ -638,54 +506,12 @@ impl ChatToResponsesState {
|
||||
}
|
||||
|
||||
let output_index = self.text.output_index.unwrap_or(0);
|
||||
let item = json!({
|
||||
"id": self.text.item_id,
|
||||
"type": "message",
|
||||
"status": "completed",
|
||||
"role": "assistant",
|
||||
"content": [{
|
||||
"type": "output_text",
|
||||
"text": self.text.text,
|
||||
"annotations": []
|
||||
}]
|
||||
});
|
||||
self.output_items.push((output_index, item.clone()));
|
||||
let item_id = self.text.item_id.clone();
|
||||
let text = self.text.text.clone();
|
||||
let (events, item) = sse::message_close(output_index, &item_id, &text);
|
||||
self.output_items.push((output_index, item));
|
||||
self.text.done = true;
|
||||
|
||||
vec![
|
||||
sse_event(
|
||||
"response.output_text.done",
|
||||
json!({
|
||||
"type": "response.output_text.done",
|
||||
"item_id": self.text.item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"text": self.text.text
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.content_part.done",
|
||||
json!({
|
||||
"type": "response.content_part.done",
|
||||
"item_id": self.text.item_id,
|
||||
"output_index": output_index,
|
||||
"content_index": 0,
|
||||
"part": {
|
||||
"type": "output_text",
|
||||
"text": self.text.text,
|
||||
"annotations": []
|
||||
}
|
||||
}),
|
||||
),
|
||||
sse_event(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": item
|
||||
}),
|
||||
),
|
||||
]
|
||||
events
|
||||
}
|
||||
|
||||
fn finalize_tools(&mut self) -> Vec<Bytes> {
|
||||
@@ -742,14 +568,7 @@ impl ChatToResponsesState {
|
||||
Some(&state.reasoning_content),
|
||||
&self.tool_context,
|
||||
);
|
||||
add_event = Some(sse_event(
|
||||
"response.output_item.added",
|
||||
json!({
|
||||
"type": "response.output_item.added",
|
||||
"output_index": assigned,
|
||||
"item": item
|
||||
}),
|
||||
));
|
||||
add_event = Some(sse::output_item_added(assigned, &item));
|
||||
}
|
||||
|
||||
if let Some(event) = add_event {
|
||||
@@ -777,44 +596,25 @@ impl ChatToResponsesState {
|
||||
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::custom_tool_call_input_delta(
|
||||
output_index,
|
||||
&state.item_id,
|
||||
&input,
|
||||
));
|
||||
}
|
||||
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
|
||||
}),
|
||||
events.push(sse::custom_tool_call_input_done(
|
||||
output_index,
|
||||
&state.item_id,
|
||||
&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::function_call_arguments_done(
|
||||
output_index,
|
||||
&state.item_id,
|
||||
&arguments,
|
||||
));
|
||||
}
|
||||
events.push(sse_event(
|
||||
"response.output_item.done",
|
||||
json!({
|
||||
"type": "response.output_item.done",
|
||||
"output_index": output_index,
|
||||
"item": item
|
||||
}),
|
||||
));
|
||||
events.push(sse::output_item_done(output_index, &item));
|
||||
}
|
||||
|
||||
events
|
||||
@@ -864,13 +664,7 @@ impl ChatToResponsesState {
|
||||
let mut response = self.base_response("failed", self.completed_output_items());
|
||||
response["error"] = error;
|
||||
|
||||
sse_event(
|
||||
"response.failed",
|
||||
json!({
|
||||
"type": "response.failed",
|
||||
"response": response
|
||||
}),
|
||||
)
|
||||
sse::response_failed(&response)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1030,13 +824,6 @@ fn extract_chat_sse_error(value: &Value) -> (String, Option<String>) {
|
||||
(message, error_type)
|
||||
}
|
||||
|
||||
fn sse_event(event: &str, data: Value) -> Bytes {
|
||||
Bytes::from(format!(
|
||||
"event: {event}\ndata: {}\n\n",
|
||||
serde_json::to_string(&data).unwrap_or_default()
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -490,9 +490,21 @@ fn convert_message_to_openai(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 清理 JSON schema(移除不支持的 format)
|
||||
pub fn clean_schema(mut schema: Value) -> Value {
|
||||
/// 清理工具参数的 JSON schema,并为根 schema 补齐 OpenAI 要求的 object 类型。
|
||||
pub fn clean_schema(schema: Value) -> Value {
|
||||
clean_schema_inner(schema, true)
|
||||
}
|
||||
|
||||
fn clean_schema_inner(mut schema: Value, is_root: bool) -> Value {
|
||||
if let Some(obj) = schema.as_object_mut() {
|
||||
let missing_type = is_root && !obj.contains_key("type");
|
||||
if missing_type {
|
||||
obj.insert("type".to_string(), json!("object"));
|
||||
}
|
||||
if missing_type && !obj.contains_key("properties") {
|
||||
obj.insert("properties".to_string(), json!({}));
|
||||
}
|
||||
|
||||
// 移除 "format": "uri"
|
||||
if obj.get("format").and_then(|v| v.as_str()) == Some("uri") {
|
||||
obj.remove("format");
|
||||
@@ -501,12 +513,12 @@ pub fn clean_schema(mut schema: Value) -> Value {
|
||||
// 递归清理嵌套 schema
|
||||
if let Some(properties) = obj.get_mut("properties").and_then(|v| v.as_object_mut()) {
|
||||
for (_, value) in properties.iter_mut() {
|
||||
*value = clean_schema(value.clone());
|
||||
*value = clean_schema_inner(value.clone(), false);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(items) = obj.get_mut("items") {
|
||||
*items = clean_schema(items.clone());
|
||||
*items = clean_schema_inner(items.clone(), false);
|
||||
}
|
||||
}
|
||||
schema
|
||||
@@ -653,7 +665,7 @@ pub fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
// 不再扣减),若不减则缓存会被计入 input 与各 cache 桶两次。三桶互斥,恒等:
|
||||
// input + cache_read + cache_creation == prompt_tokens(inclusive 上游)。
|
||||
// 与流式 build_anthropic_usage_json (#2774) 及 transform_gemini 的 saturating_sub 对称。
|
||||
// 最终 cache_read:直传字段优先于 nested;cache_creation 仅来自直传字段(OpenAI 无此概念)。
|
||||
// 最终 cache_read/cache_creation:直传字段优先于 OpenAI nested details。
|
||||
let cached = usage
|
||||
.get("cache_read_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
@@ -666,6 +678,12 @@ pub fn openai_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
let cache_creation = usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.or_else(|| {
|
||||
usage
|
||||
.pointer("/prompt_tokens_details/cache_write_tokens")
|
||||
.or_else(|| usage.pointer("/input_tokens_details/cache_write_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
let input_tokens = usage
|
||||
.get("prompt_tokens")
|
||||
@@ -831,6 +849,75 @@ mod tests {
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
assert_eq!(result["tools"][0]["type"], "function");
|
||||
assert_eq!(result["tools"][0]["function"]["name"], "get_weather");
|
||||
assert_eq!(
|
||||
result["tools"][0]["function"]["parameters"]["type"],
|
||||
json!("object")
|
||||
);
|
||||
assert_eq!(
|
||||
result["tools"][0]["function"]["parameters"]["properties"]["location"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_defaults_missing_tool_schema_type() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "What's the weather?"}],
|
||||
"tools": [{
|
||||
"name": "get_weather",
|
||||
"description": "Get weather info",
|
||||
"input_schema": {"properties": {"location": {"type": "string"}}}
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
let parameters = &result["tools"][0]["function"]["parameters"];
|
||||
assert_eq!(parameters["type"], json!("object"));
|
||||
assert_eq!(
|
||||
parameters["properties"]["location"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_openai_defaults_empty_tool_schema() {
|
||||
let input = json!({
|
||||
"model": "claude-3-opus",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Do work"}],
|
||||
"tools": [{"name": "do_work", "input_schema": {}}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_openai(input).unwrap();
|
||||
let parameters = &result["tools"][0]["function"]["parameters"];
|
||||
assert_eq!(parameters, &json!({"type": "object", "properties": {}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clean_schema_only_defaults_root_to_object() {
|
||||
let schema = json!({
|
||||
"properties": {
|
||||
"nullable_value": {
|
||||
"anyOf": [{"type": "string"}, {"type": "null"}]
|
||||
},
|
||||
"list": {
|
||||
"items": {"type": "string"}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let result = clean_schema(schema);
|
||||
assert_eq!(result["type"], json!("object"));
|
||||
assert_eq!(
|
||||
result["properties"]["nullable_value"],
|
||||
json!({"anyOf": [{"type": "string"}, {"type": "null"}]})
|
||||
);
|
||||
assert_eq!(
|
||||
result["properties"]["list"],
|
||||
json!({"items": {"type": "string"}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -80,7 +80,11 @@ impl CodexToolContext {
|
||||
.is_some_and(|spec| matches!(&spec.kind, CodexToolKind::Custom))
|
||||
}
|
||||
|
||||
fn chat_name_for_response_function(&self, name: &str, namespace: Option<&str>) -> String {
|
||||
pub(crate) fn chat_name_for_response_function(
|
||||
&self,
|
||||
name: &str,
|
||||
namespace: Option<&str>,
|
||||
) -> String {
|
||||
if let Some(namespace) = namespace.filter(|value| !value.is_empty()) {
|
||||
if let Some(chat_name) = self
|
||||
.namespace_name_to_chat_name
|
||||
@@ -1625,12 +1629,26 @@ pub(crate) fn chat_usage_to_responses_usage(usage: Option<&Value>) -> Value {
|
||||
"total_tokens": total_tokens
|
||||
});
|
||||
|
||||
if let Some(cached) = usage
|
||||
let cached = usage
|
||||
.pointer("/prompt_tokens_details/cached_tokens")
|
||||
.or_else(|| usage.pointer("/input_tokens_details/cached_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
{
|
||||
result["input_tokens_details"] = json!({ "cached_tokens": cached });
|
||||
.unwrap_or(0);
|
||||
let cache_write = usage
|
||||
.pointer("/prompt_tokens_details/cache_write_tokens")
|
||||
.or_else(|| usage.pointer("/input_tokens_details/cache_write_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
.or_else(|| {
|
||||
usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
})
|
||||
.unwrap_or(0);
|
||||
if cached > 0 || cache_write > 0 {
|
||||
result["input_tokens_details"] = json!({
|
||||
"cached_tokens": cached,
|
||||
"cache_write_tokens": cache_write
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(details) = usage
|
||||
@@ -1649,8 +1667,8 @@ pub(crate) fn chat_usage_to_responses_usage(usage: Option<&Value>) -> Value {
|
||||
if let Some(cache_read) = usage.get("cache_read_input_tokens") {
|
||||
result["cache_read_input_tokens"] = cache_read.clone();
|
||||
}
|
||||
if let Some(cache_creation) = usage.get("cache_creation_input_tokens") {
|
||||
result["cache_creation_input_tokens"] = cache_creation.clone();
|
||||
if cache_write > 0 {
|
||||
result["cache_creation_input_tokens"] = json!(cache_write);
|
||||
}
|
||||
|
||||
result
|
||||
@@ -2731,7 +2749,7 @@ mod tests {
|
||||
"prompt_tokens": 10,
|
||||
"completion_tokens": 5,
|
||||
"total_tokens": 15,
|
||||
"prompt_tokens_details": {"cached_tokens": 3}
|
||||
"prompt_tokens_details": {"cached_tokens": 3, "cache_write_tokens": 2}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2755,6 +2773,10 @@ mod tests {
|
||||
assert_eq!(result["usage"]["input_tokens"], 10);
|
||||
assert_eq!(result["usage"]["output_tokens"], 5);
|
||||
assert_eq!(result["usage"]["input_tokens_details"]["cached_tokens"], 3);
|
||||
assert_eq!(
|
||||
result["usage"]["input_tokens_details"]["cache_write_tokens"],
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -11,6 +11,134 @@
|
||||
use crate::proxy::{error::ProxyError, json_canonical::canonical_json_string};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::reasoning_bridge::{
|
||||
anthropic_block_from_openai_reasoning_item, openai_reasoning_item_from_anthropic_block,
|
||||
};
|
||||
|
||||
pub(crate) const TOOL_RESULT_ERROR_MARKER: &str = "[cc-switch:tool-result-error]";
|
||||
|
||||
fn anthropic_image_to_responses_part(block: &Value) -> Option<Value> {
|
||||
let source = block.get("source")?;
|
||||
match source.get("type").and_then(Value::as_str) {
|
||||
Some("url") => source
|
||||
.get("url")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|url| url.starts_with("http://") || url.starts_with("https://"))
|
||||
.map(|url| json!({"type":"input_image","image_url":url})),
|
||||
Some("base64") | None => {
|
||||
let data = source.get("data").and_then(Value::as_str)?;
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let media_type = source
|
||||
.get("media_type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("image/png");
|
||||
Some(json!({
|
||||
"type":"input_image",
|
||||
"image_url":format!("data:{media_type};base64,{data}")
|
||||
}))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn anthropic_document_to_responses_part(block: &Value) -> Option<Value> {
|
||||
let source = block.get("source")?;
|
||||
let filename = block
|
||||
.get("title")
|
||||
.or_else(|| block.get("filename"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("document.pdf");
|
||||
match source.get("type").and_then(Value::as_str) {
|
||||
Some("url") => source
|
||||
.get("url")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|url| url.starts_with("http://") || url.starts_with("https://"))
|
||||
.map(|url| json!({"type":"input_file","file_url":url,"filename":filename})),
|
||||
Some("base64") => {
|
||||
let data = source.get("data").and_then(Value::as_str)?;
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let media_type = source
|
||||
.get("media_type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("application/pdf");
|
||||
Some(json!({
|
||||
"type":"input_file",
|
||||
"file_data":format!("data:{media_type};base64,{data}"),
|
||||
"filename":filename
|
||||
}))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn anthropic_tool_result_to_responses_output(block: &Value) -> Value {
|
||||
let is_error = block.get("is_error").and_then(Value::as_bool) == Some(true);
|
||||
let content = block.get("content");
|
||||
|
||||
if !is_error {
|
||||
if let Some(Value::String(text)) = content {
|
||||
return json!(text);
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = Vec::new();
|
||||
if is_error {
|
||||
output.push(json!({"type":"input_text","text":TOOL_RESULT_ERROR_MARKER}));
|
||||
}
|
||||
|
||||
match content {
|
||||
Some(Value::String(text)) => {
|
||||
output.push(json!({"type":"input_text","text":text}));
|
||||
}
|
||||
Some(Value::Array(blocks)) => {
|
||||
for part in blocks {
|
||||
match part.get("type").and_then(Value::as_str) {
|
||||
Some("text") => {
|
||||
if let Some(text) = part.get("text").and_then(Value::as_str) {
|
||||
output.push(json!({"type":"input_text","text":text}));
|
||||
}
|
||||
}
|
||||
Some("image") => {
|
||||
if let Some(image) = anthropic_image_to_responses_part(part) {
|
||||
output.push(image);
|
||||
} else {
|
||||
output.push(json!({
|
||||
"type":"input_text",
|
||||
"text":canonical_json_string(part)
|
||||
}));
|
||||
}
|
||||
}
|
||||
Some("document") => {
|
||||
if let Some(file) = anthropic_document_to_responses_part(part) {
|
||||
output.push(file);
|
||||
} else {
|
||||
output.push(json!({
|
||||
"type":"input_text",
|
||||
"text":canonical_json_string(part)
|
||||
}));
|
||||
}
|
||||
}
|
||||
_ => output.push(json!({
|
||||
"type":"input_text",
|
||||
"text":canonical_json_string(part)
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(value) => output.push(json!({
|
||||
"type":"input_text",
|
||||
"text":canonical_json_string(value)
|
||||
})),
|
||||
None => {}
|
||||
}
|
||||
|
||||
Value::Array(output)
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_anthropic_tool_use_input(name: &str, input: Value) -> Value {
|
||||
if name != "Read" {
|
||||
return input;
|
||||
@@ -247,6 +375,37 @@ pub(crate) fn map_responses_stop_reason(
|
||||
})
|
||||
}
|
||||
|
||||
fn responses_error_message(body: &Value, fallback: &str) -> String {
|
||||
body.pointer("/error/message")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| body.get("message").and_then(Value::as_str))
|
||||
.or_else(|| body.get("error").and_then(Value::as_str))
|
||||
.filter(|message| !message.trim().is_empty())
|
||||
.unwrap_or(fallback)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn validate_responses_terminal_status(body: &Value) -> Result<(), ProxyError> {
|
||||
let status = body.get("status").and_then(Value::as_str);
|
||||
let has_error = body.get("error").is_some_and(|error| !error.is_null());
|
||||
|
||||
match status {
|
||||
Some("failed") => Err(ProxyError::TransformError(format!(
|
||||
"Responses upstream failed: {}",
|
||||
responses_error_message(body, "response generation failed")
|
||||
))),
|
||||
Some("cancelled") => Err(ProxyError::TransformError(format!(
|
||||
"Responses upstream cancelled the response: {}",
|
||||
responses_error_message(body, "response generation was cancelled")
|
||||
))),
|
||||
_ if has_error => Err(ProxyError::TransformError(format!(
|
||||
"Responses upstream returned an error envelope: {}",
|
||||
responses_error_message(body, "unknown upstream error")
|
||||
))),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build Anthropic-style usage JSON from Responses API usage, including cache tokens.
|
||||
///
|
||||
/// **Robustness Features**:
|
||||
@@ -259,10 +418,11 @@ pub(crate) fn map_responses_stop_reason(
|
||||
/// 1. input_tokens: Anthropic `input_tokens` → OpenAI `prompt_tokens` → default 0
|
||||
/// 2. output_tokens: Anthropic `output_tokens` → OpenAI `completion_tokens` → default 0
|
||||
/// 3. cache_read_input_tokens: Direct field → nested input_tokens_details.cached_tokens → prompt_tokens_details.cached_tokens
|
||||
/// 4. cache_creation_input_tokens: Direct field only
|
||||
/// 4. cache_creation_input_tokens: Direct field → nested
|
||||
/// input_tokens_details.cache_write_tokens → prompt_tokens_details.cache_write_tokens
|
||||
///
|
||||
/// **Cache Token Priority Order**:
|
||||
/// 1. OpenAI nested details (`input_tokens_details.cached_tokens`, `prompt_tokens_details.cached_tokens`) as initial value
|
||||
/// 1. OpenAI nested details (`cached_tokens`, `cache_write_tokens`) as initial values
|
||||
/// 2. Direct Anthropic-style fields (`cache_read_input_tokens`, `cache_creation_input_tokens`) override if present
|
||||
///
|
||||
/// **Logging**:
|
||||
@@ -345,6 +505,19 @@ pub(crate) fn build_anthropic_usage_from_responses(usage: Option<&Value>) -> Val
|
||||
result["cache_read_input_tokens"] = json!(cached);
|
||||
}
|
||||
}
|
||||
// GPT-5.6+ reports cache writes in the nested OpenAI token-details object.
|
||||
// Treat writes as Anthropic cache creation so the downstream client and
|
||||
// billing layer can distinguish them from fresh input.
|
||||
let nested_cache_write = u
|
||||
.pointer("/input_tokens_details/cache_write_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.or_else(|| {
|
||||
u.pointer("/prompt_tokens_details/cache_write_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
});
|
||||
if let Some(cache_write) = nested_cache_write {
|
||||
result["cache_creation_input_tokens"] = json!(cache_write);
|
||||
}
|
||||
|
||||
// Step 2: Direct Anthropic-style fields override (authoritative if present)
|
||||
// These preserve cache tokens even if input/output_tokens are missing
|
||||
@@ -354,6 +527,9 @@ pub(crate) fn build_anthropic_usage_from_responses(usage: Option<&Value>) -> Val
|
||||
if let Some(v) = u.get("cache_creation_input_tokens") {
|
||||
result["cache_creation_input_tokens"] = v.clone();
|
||||
}
|
||||
if let Some(v) = u.get("cache_creation") {
|
||||
result["cache_creation"] = v.clone();
|
||||
}
|
||||
|
||||
// OpenAI/Responses 的 input(prompt_tokens/input_tokens)含缓存命中,Anthropic input_tokens 不含
|
||||
// → 减去 cache_read 与 cache_creation,使其成为 fresh input。本函数在计量意义上是 claude 专属
|
||||
@@ -381,13 +557,15 @@ pub(crate) fn build_anthropic_usage_from_responses(usage: Option<&Value>) -> Val
|
||||
/// - user/assistant 的 text 内容 → 对应 role 的 message item
|
||||
/// - tool_use 从 assistant message 中"提升"为独立的 function_call item
|
||||
/// - tool_result 从 user message 中"提升"为独立的 function_call_output item
|
||||
/// - thinking blocks → 丢弃
|
||||
/// - bridge-owned thinking blocks → restore the original Responses reasoning item
|
||||
/// - unrelated native thinking blocks → 丢弃
|
||||
fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyError> {
|
||||
let mut input = Vec::new();
|
||||
|
||||
for msg in messages {
|
||||
let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("user");
|
||||
let content = msg.get("content");
|
||||
let message_input_start = input.len();
|
||||
|
||||
match content {
|
||||
// 字符串内容
|
||||
@@ -425,17 +603,22 @@ fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyErro
|
||||
}
|
||||
|
||||
"image" => {
|
||||
if let Some(source) = block.get("source") {
|
||||
let media_type = source
|
||||
.get("media_type")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("image/png");
|
||||
let data =
|
||||
source.get("data").and_then(|d| d.as_str()).unwrap_or("");
|
||||
message_content.push(json!({
|
||||
"type": "input_image",
|
||||
"image_url": format!("data:{media_type};base64,{data}")
|
||||
}));
|
||||
if let Some(image) = anthropic_image_to_responses_part(block) {
|
||||
message_content.push(image);
|
||||
} else {
|
||||
log::warn!(
|
||||
"[Responses] Unsupported or invalid Anthropic image block"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
"document" => {
|
||||
if let Some(file) = anthropic_document_to_responses_part(block) {
|
||||
message_content.push(file);
|
||||
} else {
|
||||
log::warn!(
|
||||
"[Responses] Unsupported or invalid Anthropic document block"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -477,11 +660,7 @@ fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyErro
|
||||
.get("tool_use_id")
|
||||
.and_then(|i| i.as_str())
|
||||
.unwrap_or("");
|
||||
let output = match block.get("content") {
|
||||
Some(Value::String(s)) => s.clone(),
|
||||
Some(v) => canonical_json_string(v),
|
||||
None => String::new(),
|
||||
};
|
||||
let output = anthropic_tool_result_to_responses_output(block);
|
||||
|
||||
input.push(json!({
|
||||
"type": "function_call_output",
|
||||
@@ -490,8 +669,19 @@ fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyErro
|
||||
}));
|
||||
}
|
||||
|
||||
"thinking" => {
|
||||
// 丢弃 thinking blocks(与 openai_chat 一致)
|
||||
"thinking" | "redacted_thinking" => {
|
||||
if let Some(reasoning_item) =
|
||||
openai_reasoning_item_from_anthropic_block(block)
|
||||
{
|
||||
if !message_content.is_empty() {
|
||||
input.push(json!({
|
||||
"role": role,
|
||||
"content": message_content.clone()
|
||||
}));
|
||||
message_content.clear();
|
||||
}
|
||||
input.push(reasoning_item);
|
||||
}
|
||||
}
|
||||
|
||||
_ => {}
|
||||
@@ -512,6 +702,26 @@ fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyErro
|
||||
input.push(json!({ "role": role }));
|
||||
}
|
||||
}
|
||||
|
||||
// A replayed reasoning item is only valid when the same assistant
|
||||
// generation also contains a following message/function call item.
|
||||
// Reasoning-only incomplete turns otherwise brick the next request with
|
||||
// "reasoning item ... without its required following item".
|
||||
if role == "assistant" {
|
||||
let mut has_generated_follower = false;
|
||||
for index in (message_input_start..input.len()).rev() {
|
||||
let item_type = input[index].get("type").and_then(Value::as_str);
|
||||
let is_assistant_message =
|
||||
input[index].get("role").and_then(Value::as_str) == Some("assistant");
|
||||
if item_type == Some("reasoning") {
|
||||
if !has_generated_follower {
|
||||
input.remove(index);
|
||||
}
|
||||
} else if item_type == Some("function_call") || is_assistant_message {
|
||||
has_generated_follower = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(input)
|
||||
@@ -519,12 +729,18 @@ fn convert_messages_to_input(messages: &[Value]) -> Result<Vec<Value>, ProxyErro
|
||||
|
||||
/// OpenAI Responses 响应 → Anthropic 响应
|
||||
pub fn responses_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
// A Responses failure can arrive inside an HTTP 2xx response object. Reject it
|
||||
// before looking at `output`; otherwise `{status:"failed", output:[]}` becomes
|
||||
// a successful empty Anthropic `end_turn` and hides the upstream error.
|
||||
validate_responses_terminal_status(&body)?;
|
||||
|
||||
let output = body
|
||||
.get("output")
|
||||
.and_then(|o| o.as_array())
|
||||
.ok_or_else(|| ProxyError::TransformError("No output in response".to_string()))?;
|
||||
|
||||
let mut content = Vec::new();
|
||||
let response_completed = body.get("status").and_then(Value::as_str) == Some("completed");
|
||||
|
||||
let mut has_tool_use = false;
|
||||
for item in output {
|
||||
@@ -559,7 +775,42 @@ pub fn responses_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
.get("arguments")
|
||||
.and_then(|a| a.as_str())
|
||||
.unwrap_or("{}");
|
||||
let input: Value = serde_json::from_str(args_str).unwrap_or(json!({}));
|
||||
let input: Value = if args_str.trim().is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
match serde_json::from_str(args_str) {
|
||||
Ok(value) => value,
|
||||
Err(error) if !response_completed => {
|
||||
log::warn!(
|
||||
"[Responses] Replacing incomplete function_call '{name}' arguments with an empty object: {error}"
|
||||
);
|
||||
json!({})
|
||||
}
|
||||
Err(error) => {
|
||||
return Err(ProxyError::TransformError(format!(
|
||||
"Invalid function_call arguments for '{name}': {error}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
};
|
||||
if !input.is_object() {
|
||||
if !response_completed {
|
||||
log::warn!(
|
||||
"[Responses] Replacing incomplete function_call '{name}' non-object arguments with an empty object"
|
||||
);
|
||||
content.push(json!({
|
||||
"type": "tool_use",
|
||||
"id": call_id,
|
||||
"name": name,
|
||||
"input": {}
|
||||
}));
|
||||
has_tool_use = true;
|
||||
continue;
|
||||
}
|
||||
return Err(ProxyError::TransformError(format!(
|
||||
"Function call arguments for '{name}' must be a JSON object"
|
||||
)));
|
||||
}
|
||||
let input = sanitize_anthropic_tool_use_input(name, input);
|
||||
|
||||
content.push(json!({
|
||||
@@ -572,26 +823,8 @@ pub fn responses_to_anthropic(body: Value) -> Result<Value, ProxyError> {
|
||||
}
|
||||
|
||||
"reasoning" => {
|
||||
// 映射 reasoning summary → thinking block
|
||||
if let Some(summary) = item.get("summary").and_then(|s| s.as_array()) {
|
||||
let thinking_text: String = summary
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
if s.get("type").and_then(|t| t.as_str()) == Some("summary_text") {
|
||||
s.get("text").and_then(|t| t.as_str())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
|
||||
if !thinking_text.is_empty() {
|
||||
content.push(json!({
|
||||
"type": "thinking",
|
||||
"thinking": thinking_text
|
||||
}));
|
||||
}
|
||||
if let Some(block) = anthropic_block_from_openai_reasoning_item(item) {
|
||||
content.push(block);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -770,10 +1003,51 @@ mod tests {
|
||||
assert_eq!(result["tools"][0]["type"], "function");
|
||||
assert_eq!(result["tools"][0]["name"], "get_weather");
|
||||
assert!(result["tools"][0].get("parameters").is_some());
|
||||
assert_eq!(result["tools"][0]["parameters"]["type"], json!("object"));
|
||||
assert_eq!(
|
||||
result["tools"][0]["parameters"]["properties"]["location"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
// input_schema should not appear
|
||||
assert!(result["tools"][0].get("input_schema").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_defaults_missing_tool_schema_type() {
|
||||
let input = json!({
|
||||
"model": "gpt-4o",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Weather?"}],
|
||||
"tools": [{
|
||||
"name": "get_weather",
|
||||
"description": "Get weather info",
|
||||
"input_schema": {"properties": {"location": {"type": "string"}}}
|
||||
}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None, false, false).unwrap();
|
||||
let parameters = &result["tools"][0]["parameters"];
|
||||
assert_eq!(parameters["type"], json!("object"));
|
||||
assert_eq!(
|
||||
parameters["properties"]["location"]["type"],
|
||||
json!("string")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_defaults_empty_tool_schema() {
|
||||
let input = json!({
|
||||
"model": "gpt-4o",
|
||||
"max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "Do work"}],
|
||||
"tools": [{"name": "do_work", "input_schema": {}}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None, false, false).unwrap();
|
||||
let parameters = &result["tools"][0]["parameters"];
|
||||
assert_eq!(parameters, &json!({"type": "object", "properties": {}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_tool_choice_any_to_required() {
|
||||
let input = json!({
|
||||
@@ -855,6 +1129,34 @@ mod tests {
|
||||
assert_eq!(input_arr[0]["output"], "Sunny, 25°C");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_tool_result_preserves_blocks_and_error() {
|
||||
let input = json!({
|
||||
"model":"gpt-5",
|
||||
"messages":[{"role":"user","content":[{
|
||||
"type":"tool_result",
|
||||
"tool_use_id":"call_1",
|
||||
"is_error":true,
|
||||
"content":[
|
||||
{"type":"text","text":"command failed"},
|
||||
{"type":"image","source":{"type":"url","url":"https://example.com/error.png"}},
|
||||
{"type":"document","title":"trace.pdf","source":{"type":"base64","media_type":"application/pdf","data":"JVBERi0="}}
|
||||
]
|
||||
}]}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None, false, false).unwrap();
|
||||
let output = result["input"][0]["output"].as_array().unwrap();
|
||||
assert_eq!(output[0]["text"], TOOL_RESULT_ERROR_MARKER);
|
||||
assert_eq!(
|
||||
output[1],
|
||||
json!({"type":"input_text","text":"command failed"})
|
||||
);
|
||||
assert_eq!(output[2]["image_url"], "https://example.com/error.png");
|
||||
assert_eq!(output[3]["type"], "input_file");
|
||||
assert_eq!(output[3]["filename"], "trace.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_thinking_discarded() {
|
||||
let input = json!({
|
||||
@@ -900,6 +1202,25 @@ mod tests {
|
||||
assert_eq!(content[1]["image_url"], "data:image/png;base64,abc123");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_anthropic_to_responses_url_image_and_document() {
|
||||
let input = json!({
|
||||
"model":"gpt-5",
|
||||
"messages":[{"role":"user","content":[
|
||||
{"type":"image","source":{"type":"url","url":"https://example.com/a.png"}},
|
||||
{"type":"document","title":"manual.pdf","source":{"type":"url","url":"https://example.com/manual.pdf"}}
|
||||
]}]
|
||||
});
|
||||
|
||||
let result = anthropic_to_responses(input, None, false, false).unwrap();
|
||||
let content = result["input"][0]["content"].as_array().unwrap();
|
||||
assert_eq!(content[0]["type"], "input_image");
|
||||
assert_eq!(content[0]["image_url"], "https://example.com/a.png");
|
||||
assert_eq!(content[1]["type"], "input_file");
|
||||
assert_eq!(content[1]["file_url"], "https://example.com/manual.pdf");
|
||||
assert_eq!(content[1]["filename"], "manual.pdf");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_to_anthropic_simple() {
|
||||
let input = json!({
|
||||
@@ -952,6 +1273,65 @@ mod tests {
|
||||
assert_eq!(result["stop_reason"], "tool_use");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_completed_function_call_empty_arguments_normalizes_to_object() {
|
||||
let input = json!({
|
||||
"id": "resp_empty_args",
|
||||
"status": "completed",
|
||||
"model": "gpt-5.6",
|
||||
"output": [{
|
||||
"type": "function_call",
|
||||
"call_id": "call_1",
|
||||
"name": "ping",
|
||||
"arguments": ""
|
||||
}],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 2}
|
||||
});
|
||||
let result = responses_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["content"][0]["input"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_incomplete_function_call_invalid_arguments_uses_empty_object() {
|
||||
let input = json!({
|
||||
"id": "resp_partial_args",
|
||||
"status": "incomplete",
|
||||
"incomplete_details": {"reason": "max_output_tokens"},
|
||||
"model": "gpt-5.6",
|
||||
"output": [{
|
||||
"type": "function_call",
|
||||
"call_id": "call_1",
|
||||
"name": "dangerous_tool",
|
||||
"arguments": "{\"path\":"
|
||||
}],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 2}
|
||||
});
|
||||
let result = responses_to_anthropic(input).unwrap();
|
||||
assert_eq!(result["content"][0]["type"], "tool_use");
|
||||
assert_eq!(result["content"][0]["input"], json!({}));
|
||||
assert_eq!(result["stop_reason"], "max_tokens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_completed_function_call_invalid_arguments_is_error() {
|
||||
let input = json!({
|
||||
"id": "resp_bad_args",
|
||||
"status": "completed",
|
||||
"model": "gpt-5.6",
|
||||
"output": [{
|
||||
"type": "function_call",
|
||||
"call_id": "call_1",
|
||||
"name": "broken_tool",
|
||||
"arguments": "{\"path\":"
|
||||
}],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 2}
|
||||
});
|
||||
assert!(matches!(
|
||||
responses_to_anthropic(input),
|
||||
Err(ProxyError::TransformError(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_to_anthropic_read_drops_empty_pages() {
|
||||
let input = json!({
|
||||
@@ -1057,6 +1437,115 @@ mod tests {
|
||||
assert_eq!(result["content"][1]["text"], "The answer is 42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypted_reasoning_round_trips_through_anthropic_history() {
|
||||
let original = json!({
|
||||
"type": "reasoning",
|
||||
"id": "rs_123",
|
||||
"summary": [{"type": "summary_text", "text": "Need a tool."}],
|
||||
"encrypted_content": "opaque-ciphertext"
|
||||
});
|
||||
let response = json!({
|
||||
"id": "resp_123",
|
||||
"status": "completed",
|
||||
"model": "gpt-5.6",
|
||||
"output": [original.clone()],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 2}
|
||||
});
|
||||
|
||||
let anthropic = responses_to_anthropic(response).unwrap();
|
||||
let thinking = anthropic["content"][0].clone();
|
||||
assert_eq!(thinking["type"], "thinking");
|
||||
assert!(thinking["signature"]
|
||||
.as_str()
|
||||
.is_some_and(|value| value.starts_with("ccswitch-openai-reasoning-v1:")));
|
||||
|
||||
let replay = anthropic_to_responses(
|
||||
json!({
|
||||
"model": "gpt-5.6",
|
||||
"messages": [{"role": "assistant", "content": [
|
||||
thinking,
|
||||
{"type": "tool_use", "id": "call_1", "name": "lookup", "input": {}}
|
||||
]}]
|
||||
}),
|
||||
None,
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(replay["input"][0], original);
|
||||
assert_eq!(replay["input"][1]["type"], "function_call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reasoning_only_assistant_turn_is_not_replayed() {
|
||||
let item = json!({
|
||||
"type": "reasoning",
|
||||
"id": "rs_orphan",
|
||||
"summary": [],
|
||||
"encrypted_content": "opaque"
|
||||
});
|
||||
let block = anthropic_block_from_openai_reasoning_item(&item).unwrap();
|
||||
let replay = anthropic_to_responses(
|
||||
json!({
|
||||
"model": "gpt-5.6",
|
||||
"messages": [
|
||||
{"role": "assistant", "content": [block]},
|
||||
{"role": "user", "content": "continue"}
|
||||
]
|
||||
}),
|
||||
None,
|
||||
true,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(replay["input"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(replay["input"][0]["role"], "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_failed_status_is_not_silent_empty_success() {
|
||||
let input = json!({
|
||||
"id": "resp_failed",
|
||||
"status": "failed",
|
||||
"error": {"type": "server_error", "message": "backend exploded"},
|
||||
"output": [],
|
||||
"usage": {"input_tokens": 10, "output_tokens": 0}
|
||||
});
|
||||
|
||||
let error = responses_to_anthropic(input).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, ProxyError::TransformError(message) if message.contains("backend exploded"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_error_envelope_preserves_upstream_message() {
|
||||
let input = json!({
|
||||
"error": {"type": "rate_limit_error", "message": "too many requests"}
|
||||
});
|
||||
|
||||
let error = responses_to_anthropic(input).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, ProxyError::TransformError(message) if message.contains("too many requests"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_cancelled_status_is_not_end_turn() {
|
||||
let input = json!({
|
||||
"id": "resp_cancelled",
|
||||
"status": "cancelled",
|
||||
"output": []
|
||||
});
|
||||
|
||||
let error = responses_to_anthropic(input).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, ProxyError::TransformError(message) if message.contains("cancelled"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_responses_to_anthropic_incomplete_status() {
|
||||
let input = json!({
|
||||
@@ -1669,6 +2158,21 @@ mod tests {
|
||||
assert_eq!(result["cache_read_input_tokens"], json!(80));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_usage_cache_write_tokens_from_nested_details() {
|
||||
let result = build_anthropic_usage_from_responses(Some(&json!({
|
||||
"input_tokens": 100,
|
||||
"output_tokens": 10,
|
||||
"input_tokens_details": {
|
||||
"cached_tokens": 30,
|
||||
"cache_write_tokens": 20
|
||||
}
|
||||
})));
|
||||
assert_eq!(result["input_tokens"], json!(50));
|
||||
assert_eq!(result["cache_read_input_tokens"], json!(30));
|
||||
assert_eq!(result["cache_creation_input_tokens"], json!(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_build_usage_cache_tokens_direct_override() {
|
||||
let result = build_anthropic_usage_from_responses(Some(&json!({
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{json, Value};
|
||||
///
|
||||
/// 三路径分发:
|
||||
/// - skip: haiku 模型直接跳过
|
||||
/// - adaptive: opus-4-8 / opus-4-7 / opus-4-6 / sonnet-4-6 使用 adaptive thinking
|
||||
/// - adaptive: current adaptive-thinking Claude models use adaptive thinking
|
||||
/// - legacy: 其他模型注入 enabled thinking + budget_tokens
|
||||
pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
if !config.thinking_optimizer {
|
||||
@@ -73,13 +73,42 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_adaptive_thinking(model: &str) -> bool {
|
||||
let normalized = model.replace('.', "-");
|
||||
["opus-4-8", "opus-4-7", "opus-4-6", "sonnet-4-6"]
|
||||
pub(crate) fn uses_adaptive_thinking(model: &str) -> bool {
|
||||
let normalized = normalize_model_name(model);
|
||||
[
|
||||
"fable-5",
|
||||
"mythos-5",
|
||||
"mythos-preview",
|
||||
"sonnet-5",
|
||||
"opus-4-8",
|
||||
"opus-4-7",
|
||||
"opus-4-6",
|
||||
"sonnet-4-6",
|
||||
]
|
||||
.iter()
|
||||
.any(|needle| normalized.contains(needle))
|
||||
}
|
||||
|
||||
/// Models where omitting `thinking` still leaves adaptive thinking enabled.
|
||||
pub(crate) fn adaptive_thinking_is_default(model: &str) -> bool {
|
||||
let normalized = normalize_model_name(model);
|
||||
["fable-5", "mythos-5", "mythos-preview", "sonnet-5"]
|
||||
.iter()
|
||||
.any(|needle| normalized.contains(needle))
|
||||
}
|
||||
|
||||
/// Models that reject `thinking: {"type":"disabled"}`.
|
||||
pub(crate) fn thinking_cannot_be_disabled(model: &str) -> bool {
|
||||
let normalized = normalize_model_name(model);
|
||||
["fable-5", "mythos-5"]
|
||||
.iter()
|
||||
.any(|needle| normalized.contains(needle))
|
||||
}
|
||||
|
||||
fn normalize_model_name(model: &str) -> String {
|
||||
model.trim().to_ascii_lowercase().replace(['.', '_'], "-")
|
||||
}
|
||||
|
||||
/// 追加 beta 标识到 anthropic_beta 数组(去重)
|
||||
fn append_beta(body: &mut Value, beta: &str) {
|
||||
match body.get_mut("anthropic_beta") {
|
||||
@@ -108,7 +137,6 @@ mod tests {
|
||||
enabled: true,
|
||||
thinking_optimizer: true,
|
||||
cache_injection: true,
|
||||
cache_ttl: "1h".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,7 +145,6 @@ mod tests {
|
||||
enabled: true,
|
||||
thinking_optimizer: false,
|
||||
cache_injection: true,
|
||||
cache_ttl: "1h".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,6 +166,21 @@ mod tests {
|
||||
assert!(betas.iter().any(|v| v == "context-1m-2025-08-07"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_generation_models_use_adaptive_thinking() {
|
||||
for model in [
|
||||
"claude-sonnet-5",
|
||||
"anthropic/claude-fable-5",
|
||||
"claude-mythos-5",
|
||||
"claude-opus-4.8",
|
||||
] {
|
||||
assert!(uses_adaptive_thinking(model), "model={model}");
|
||||
}
|
||||
assert!(adaptive_thinking_is_default("claude-sonnet-5"));
|
||||
assert!(thinking_cannot_be_disabled("claude-fable-5"));
|
||||
assert!(!thinking_cannot_be_disabled("claude-sonnet-5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adaptive_opus_4_6() {
|
||||
let mut body = json!({
|
||||
|
||||
@@ -219,11 +219,11 @@ pub struct RectifierConfig {
|
||||
/// 让对话不中断。总开关,管辖「显式声明 text-only」与「上游报错后兜底」两条事实驱动路径。
|
||||
#[serde(default = "default_true")]
|
||||
pub request_media_fallback: bool,
|
||||
/// 请求整流:启发式 text-only 模型名匹配(默认开启)
|
||||
/// 请求整流:确认纯文本注册表的发送前降级(默认开启)
|
||||
///
|
||||
/// 在模型未声明能力时,按内置模型名列表预测性地剥离图片(发送前)。
|
||||
/// 受 request_media_fallback 管辖;单独关闭后仅保留「显式声明」与「上游兜底」,
|
||||
/// 避免内置列表把多模态模型误判成 text-only 而静默剥图。
|
||||
/// 在模型未声明能力时,按内置的确认纯文本注册表预先剥离图片。
|
||||
/// 受 request_media_fallback 管辖;单独关闭只停用代理的注册表预判,
|
||||
/// 仍保留「显式声明」与「上游兜底」,且不改变 Codex 模型目录声明。
|
||||
#[serde(default = "default_true")]
|
||||
pub request_media_heuristic: bool,
|
||||
}
|
||||
@@ -264,13 +264,6 @@ pub struct OptimizerConfig {
|
||||
/// Cache 注入子开关(总开关开启后默认生效)
|
||||
#[serde(default = "default_true")]
|
||||
pub cache_injection: bool,
|
||||
/// Cache TTL: "5m" | "1h"(默认 "1h")
|
||||
#[serde(default = "default_cache_ttl")]
|
||||
pub cache_ttl: String,
|
||||
}
|
||||
|
||||
fn default_cache_ttl() -> String {
|
||||
"1h".to_string()
|
||||
}
|
||||
|
||||
impl Default for OptimizerConfig {
|
||||
@@ -279,7 +272,6 @@ impl Default for OptimizerConfig {
|
||||
enabled: false,
|
||||
thinking_optimizer: true,
|
||||
cache_injection: true,
|
||||
cache_ttl: "1h".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,10 +76,13 @@ impl CostCalculator {
|
||||
) -> CostBreakdown {
|
||||
let million = Decimal::from(1_000_000);
|
||||
|
||||
// OpenAI/Gemini 风格的 input_tokens 包含缓存命中,需要扣除后再按输入价计费;
|
||||
// OpenAI/Gemini 风格的 input_tokens 包含缓存读取和写入,需要扣除后再按输入价计费;
|
||||
// Claude/Anthropic 风格的 input_tokens 已经是 fresh input,不能再次扣减。
|
||||
let billable_input_tokens = if input_includes_cache_read {
|
||||
usage.input_tokens.saturating_sub(usage.cache_read_tokens)
|
||||
usage
|
||||
.input_tokens
|
||||
.saturating_sub(usage.cache_read_tokens)
|
||||
.saturating_sub(usage.cache_creation_tokens)
|
||||
} else {
|
||||
usage.input_tokens
|
||||
};
|
||||
@@ -197,15 +200,15 @@ mod tests {
|
||||
|
||||
let cost = CostCalculator::calculate_for_app("codex", &usage, &pricing, multiplier);
|
||||
|
||||
// Codex/OpenAI 语义:input_tokens 包含 cached_tokens,需要扣除 cache_read_tokens
|
||||
assert_eq!(cost.input_cost, Decimal::from_str("0.0024").unwrap());
|
||||
// Codex/OpenAI 语义:input_tokens 包含 cache read/write,两桶都需扣除。
|
||||
assert_eq!(cost.input_cost, Decimal::from_str("0.0021").unwrap());
|
||||
assert_eq!(cost.output_cost, Decimal::from_str("0.0075").unwrap());
|
||||
assert_eq!(cost.cache_read_cost, Decimal::from_str("0.00006").unwrap());
|
||||
assert_eq!(
|
||||
cost.cache_creation_cost,
|
||||
Decimal::from_str("0.000375").unwrap()
|
||||
);
|
||||
assert_eq!(cost.total_cost, Decimal::from_str("0.010335").unwrap());
|
||||
assert_eq!(cost.total_cost, Decimal::from_str("0.010035").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::calculator::{CostBreakdown, CostCalculator, ModelPricing};
|
||||
use super::parser::TokenUsage;
|
||||
use crate::database::{Database, PRICING_SOURCE_REQUEST, PRICING_SOURCE_RESPONSE};
|
||||
use crate::error::AppError;
|
||||
use crate::services::sql_helpers::{INPUT_TOKEN_SEMANTICS_FRESH, INPUT_TOKEN_SEMANTICS_TOTAL};
|
||||
use crate::services::usage_stats::{find_model_pricing_row, is_placeholder_pricing_model};
|
||||
use rust_decimal::Decimal;
|
||||
use std::str::FromStr;
|
||||
@@ -70,15 +71,21 @@ impl<'a> UsageLogger<'a> {
|
||||
};
|
||||
|
||||
let created_at = chrono::Utc::now().timestamp();
|
||||
let input_token_semantics = if matches!(log.app_type.as_str(), "codex" | "gemini") {
|
||||
INPUT_TOKEN_SEMANTICS_TOTAL
|
||||
} else {
|
||||
INPUT_TOKEN_SEMANTICS_FRESH
|
||||
};
|
||||
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO proxy_request_logs (
|
||||
request_id, provider_id, app_type, model, request_model, pricing_model,
|
||||
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
|
||||
input_token_semantics,
|
||||
input_cost_usd, output_cost_usd, cache_read_cost_usd, cache_creation_cost_usd, total_cost_usd,
|
||||
latency_ms, first_token_ms, status_code, error_message, session_id,
|
||||
provider_type, is_streaming, cost_multiplier, created_at
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24)",
|
||||
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, ?20, ?21, ?22, ?23, ?24, ?25)",
|
||||
rusqlite::params![
|
||||
log.request_id,
|
||||
log.provider_id,
|
||||
@@ -90,6 +97,7 @@ impl<'a> UsageLogger<'a> {
|
||||
log.usage.output_tokens,
|
||||
log.usage.cache_read_tokens,
|
||||
log.usage.cache_creation_tokens,
|
||||
input_token_semantics,
|
||||
input_cost,
|
||||
output_cost,
|
||||
cache_read_cost,
|
||||
|
||||
@@ -9,6 +9,24 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
fn openai_cache_read_tokens(usage: &Value) -> u32 {
|
||||
usage
|
||||
.get("cache_read_input_tokens")
|
||||
.or_else(|| usage.pointer("/input_tokens_details/cached_tokens"))
|
||||
.or_else(|| usage.pointer("/prompt_tokens_details/cached_tokens"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0) as u32
|
||||
}
|
||||
|
||||
fn openai_cache_write_tokens(usage: &Value) -> u32 {
|
||||
usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.or_else(|| usage.pointer("/input_tokens_details/cache_write_tokens"))
|
||||
.or_else(|| usage.pointer("/prompt_tokens_details/cache_write_tokens"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0) as u32
|
||||
}
|
||||
|
||||
/// Session 日志 request_id 前缀,与 `session_usage.rs` 中的格式保持一致
|
||||
pub const SESSION_REQUEST_ID_PREFIX: &str = "session:";
|
||||
|
||||
@@ -250,25 +268,14 @@ impl TokenUsage {
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
|
||||
let cached_tokens = usage
|
||||
.get("cache_read_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.or_else(|| {
|
||||
usage
|
||||
.get("input_tokens_details")
|
||||
.and_then(|d| d.get("cached_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
})
|
||||
.unwrap_or(0) as u32;
|
||||
let cached_tokens = openai_cache_read_tokens(usage);
|
||||
let cache_write_tokens = openai_cache_write_tokens(usage);
|
||||
|
||||
Some(Self {
|
||||
input_tokens: input_tokens? as u32,
|
||||
output_tokens: output_tokens? as u32,
|
||||
cache_read_tokens: cached_tokens,
|
||||
cache_creation_tokens: usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
cache_creation_tokens: cache_write_tokens,
|
||||
model,
|
||||
message_id: None,
|
||||
})
|
||||
@@ -285,19 +292,13 @@ impl TokenUsage {
|
||||
let output_tokens = usage.get("output_tokens")?.as_u64()? as u32;
|
||||
|
||||
// 获取 cached_tokens (可能在 cache_read_input_tokens 或 input_tokens_details 中)
|
||||
let cached_tokens = usage
|
||||
.get("cache_read_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.or_else(|| {
|
||||
usage
|
||||
.get("input_tokens_details")
|
||||
.and_then(|d| d.get("cached_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
})
|
||||
.unwrap_or(0) as u32;
|
||||
let cached_tokens = openai_cache_read_tokens(usage);
|
||||
let cache_write_tokens = openai_cache_write_tokens(usage);
|
||||
|
||||
// 调整 input_tokens: 减去 cached_tokens
|
||||
let adjusted_input = input_tokens.saturating_sub(cached_tokens);
|
||||
// 调整 input_tokens: OpenAI total input 同时包含 cache read/write 两桶。
|
||||
let adjusted_input = input_tokens
|
||||
.saturating_sub(cached_tokens)
|
||||
.saturating_sub(cache_write_tokens);
|
||||
|
||||
// 提取响应中的模型名称
|
||||
let model = body
|
||||
@@ -309,10 +310,7 @@ impl TokenUsage {
|
||||
input_tokens: adjusted_input,
|
||||
output_tokens,
|
||||
cache_read_tokens: cached_tokens,
|
||||
cache_creation_tokens: usage
|
||||
.get("cache_creation_input_tokens")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
cache_creation_tokens: cache_write_tokens,
|
||||
model,
|
||||
message_id: None,
|
||||
})
|
||||
@@ -391,11 +389,8 @@ impl TokenUsage {
|
||||
let completion_tokens = usage.get("completion_tokens").and_then(|v| v.as_u64())?;
|
||||
|
||||
// 获取 cached_tokens (可能在 prompt_tokens_details 中)
|
||||
let cached_tokens = usage
|
||||
.get("prompt_tokens_details")
|
||||
.and_then(|d| d.get("cached_tokens"))
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32;
|
||||
let cached_tokens = openai_cache_read_tokens(usage);
|
||||
let cache_write_tokens = openai_cache_write_tokens(usage);
|
||||
|
||||
// 提取响应中的模型名称
|
||||
let model = body
|
||||
@@ -407,7 +402,7 @@ impl TokenUsage {
|
||||
input_tokens: prompt_tokens as u32,
|
||||
output_tokens: completion_tokens as u32,
|
||||
cache_read_tokens: cached_tokens,
|
||||
cache_creation_tokens: 0,
|
||||
cache_creation_tokens: cache_write_tokens,
|
||||
model,
|
||||
message_id: None,
|
||||
})
|
||||
@@ -797,6 +792,30 @@ mod tests {
|
||||
assert_eq!(usage.cache_read_tokens, 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_response_parsing_cache_write_tokens_in_details() {
|
||||
let response = json!({
|
||||
"usage": {
|
||||
"input_tokens": 1000,
|
||||
"output_tokens": 500,
|
||||
"input_tokens_details": {
|
||||
"cached_tokens": 300,
|
||||
"cache_write_tokens": 200
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let usage = TokenUsage::from_codex_response(&response).unwrap();
|
||||
assert_eq!(usage.input_tokens, 1000);
|
||||
assert_eq!(usage.cache_read_tokens, 300);
|
||||
assert_eq!(usage.cache_creation_tokens, 200);
|
||||
|
||||
let adjusted = TokenUsage::from_codex_response_adjusted(&response).unwrap();
|
||||
assert_eq!(adjusted.input_tokens, 500);
|
||||
assert_eq!(adjusted.cache_read_tokens, 300);
|
||||
assert_eq!(adjusted.cache_creation_tokens, 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_codex_response_adjusted() {
|
||||
let response = json!({
|
||||
|
||||
@@ -32,7 +32,8 @@
|
||||
"effective_context_window_percent": 95,
|
||||
"experimental_supported_tools": [],
|
||||
"input_modalities": [
|
||||
"text"
|
||||
"text",
|
||||
"image"
|
||||
],
|
||||
"supports_search_tool": false
|
||||
}
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
//!
|
||||
//! 支持 DeepSeek、StepFun、SiliconFlow、OpenRouter、Novita AI 的账户余额查询。
|
||||
//! 返回 UsageResult 格式,与现有用量系统无缝对接。
|
||||
//!
|
||||
//! 错误通道语义(与 coding_plan / subscription 两个服务保持一致):
|
||||
//! - `Err(String)` = 瞬时传输失败(网络不可达/超时/读体中断)。前端 invoke reject,
|
||||
//! react-query 触发 retry 并保留上一次成功的 data(天然 keep-last-good)。
|
||||
//! - `Ok(success:false)` = 确定性失败(空 key/未知供应商/鉴权/非 2xx/响应体非法 JSON),
|
||||
//! 立即透出错误文案。判定按 reqwest 错误种类在折叠点完成,不依赖错误文案匹配。
|
||||
|
||||
use crate::provider::{UsageData, UsageResult};
|
||||
use std::time::Duration;
|
||||
@@ -65,7 +71,7 @@ fn make_auth_error(status: reqwest::StatusCode) -> UsageResult {
|
||||
// GET https://api.deepseek.com/user/balance
|
||||
// Response: { balance_infos: [{ currency, total_balance, granted_balance, topped_up_balance }], is_available }
|
||||
|
||||
async fn query_deepseek(api_key: &str) -> UsageResult {
|
||||
async fn query_deepseek(api_key: &str) -> Result<UsageResult, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -78,21 +84,27 @@ async fn query_deepseek(api_key: &str) -> UsageResult {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return make_auth_error(status);
|
||||
return Ok(make_auth_error(status));
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
let is_available = body
|
||||
@@ -126,18 +138,18 @@ async fn query_deepseek(api_key: &str) -> UsageResult {
|
||||
}
|
||||
}
|
||||
|
||||
UsageResult {
|
||||
Ok(UsageResult {
|
||||
success: true,
|
||||
data: if data.is_empty() { None } else { Some(data) },
|
||||
error: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── StepFun ─────────────────────────────────────────────────
|
||||
// GET https://api.stepfun.com/v1/accounts
|
||||
// Response: { object, type, balance, total_cash_balance, total_voucher_balance }
|
||||
|
||||
async fn query_stepfun(api_key: &str) -> UsageResult {
|
||||
async fn query_stepfun(api_key: &str) -> Result<UsageResult, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -150,26 +162,32 @@ async fn query_stepfun(api_key: &str) -> UsageResult {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return make_auth_error(status);
|
||||
return Ok(make_auth_error(status));
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
let balance = parse_f64_field(&body, "balance").unwrap_or(0.0);
|
||||
|
||||
UsageResult {
|
||||
Ok(UsageResult {
|
||||
success: true,
|
||||
data: Some(vec![UsageData {
|
||||
plan_name: Some("StepFun".to_string()),
|
||||
@@ -182,14 +200,14 @@ async fn query_stepfun(api_key: &str) -> UsageResult {
|
||||
extra: None,
|
||||
}]),
|
||||
error: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── SiliconFlow ─────────────────────────────────────────────
|
||||
// GET https://api.siliconflow.cn/v1/user/info (or .com for EN)
|
||||
// Response: { code, data: { balance, chargeBalance, totalBalance, status } }
|
||||
|
||||
async fn query_siliconflow(api_key: &str, is_cn: bool) -> UsageResult {
|
||||
async fn query_siliconflow(api_key: &str, is_cn: bool) -> Result<UsageResult, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let domain = if is_cn {
|
||||
@@ -209,26 +227,32 @@ async fn query_siliconflow(api_key: &str, is_cn: bool) -> UsageResult {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return make_auth_error(status);
|
||||
return Ok(make_auth_error(status));
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
let data = match body.get("data") {
|
||||
Some(d) => d,
|
||||
None => return make_error("Missing 'data' field in response".to_string()),
|
||||
None => return Ok(make_error("Missing 'data' field in response".to_string())),
|
||||
};
|
||||
|
||||
let total_balance = parse_f64_field(data, "totalBalance").unwrap_or(0.0);
|
||||
@@ -240,7 +264,7 @@ async fn query_siliconflow(api_key: &str, is_cn: bool) -> UsageResult {
|
||||
"SiliconFlow (EN)"
|
||||
};
|
||||
|
||||
UsageResult {
|
||||
Ok(UsageResult {
|
||||
success: true,
|
||||
data: Some(vec![UsageData {
|
||||
plan_name: Some(plan_name.to_string()),
|
||||
@@ -253,14 +277,14 @@ async fn query_siliconflow(api_key: &str, is_cn: bool) -> UsageResult {
|
||||
extra: None,
|
||||
}]),
|
||||
error: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── OpenRouter ──────────────────────────────────────────────
|
||||
// GET https://openrouter.ai/api/v1/credits
|
||||
// Response: { data: { total_credits, total_usage } }
|
||||
|
||||
async fn query_openrouter(api_key: &str) -> UsageResult {
|
||||
async fn query_openrouter(api_key: &str) -> Result<UsageResult, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -273,21 +297,27 @@ async fn query_openrouter(api_key: &str) -> UsageResult {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return make_auth_error(status);
|
||||
return Ok(make_auth_error(status));
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
let data = body.get("data").unwrap_or(&body);
|
||||
@@ -295,7 +325,7 @@ async fn query_openrouter(api_key: &str) -> UsageResult {
|
||||
let total_usage = parse_f64_field(data, "total_usage").unwrap_or(0.0);
|
||||
let remaining = total_credits - total_usage;
|
||||
|
||||
UsageResult {
|
||||
Ok(UsageResult {
|
||||
success: true,
|
||||
data: Some(vec![UsageData {
|
||||
plan_name: Some("OpenRouter".to_string()),
|
||||
@@ -312,7 +342,7 @@ async fn query_openrouter(api_key: &str) -> UsageResult {
|
||||
extra: None,
|
||||
}]),
|
||||
error: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Novita AI ───────────────────────────────────────────────
|
||||
@@ -320,7 +350,7 @@ async fn query_openrouter(api_key: &str) -> UsageResult {
|
||||
// Response: { availableBalance, cashBalance, creditLimit, outstandingInvoices }
|
||||
// 金额单位:0.0001 USD
|
||||
|
||||
async fn query_novita(api_key: &str) -> UsageResult {
|
||||
async fn query_novita(api_key: &str) -> Result<UsageResult, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -333,27 +363,33 @@ async fn query_novita(api_key: &str) -> UsageResult {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return make_auth_error(status);
|
||||
return Ok(make_auth_error(status));
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return make_error(format!("API error (HTTP {status}): {body}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
// Novita 金额单位为 0.0001 USD,需除以 10000 转为 USD
|
||||
let available = parse_f64_field(&body, "availableBalance").unwrap_or(0.0) / 10000.0;
|
||||
|
||||
UsageResult {
|
||||
Ok(UsageResult {
|
||||
success: true,
|
||||
data: Some(vec![UsageData {
|
||||
plan_name: Some("Novita AI".to_string()),
|
||||
@@ -370,7 +406,7 @@ async fn query_novita(api_key: &str) -> UsageResult {
|
||||
extra: None,
|
||||
}]),
|
||||
error: None,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── 工具函数 ────────────────────────────────────────────────
|
||||
@@ -385,6 +421,8 @@ fn parse_f64_field(obj: &serde_json::Value, field: &str) -> Option<f64> {
|
||||
|
||||
// ── 公开入口 ────────────────────────────────────────────────
|
||||
|
||||
/// 查询余额。瞬时传输失败返回 `Err`(前端 reject → retry + 保留上次成功值),
|
||||
/// 确定性失败返回 `Ok(success:false)`(见模块级文档)。
|
||||
pub async fn get_balance(base_url: &str, api_key: &str) -> Result<UsageResult, String> {
|
||||
if api_key.trim().is_empty() {
|
||||
return Ok(UsageResult {
|
||||
@@ -405,14 +443,12 @@ pub async fn get_balance(base_url: &str, api_key: &str) -> Result<UsageResult, S
|
||||
}
|
||||
};
|
||||
|
||||
let result = match provider {
|
||||
match provider {
|
||||
BalanceProvider::DeepSeek => query_deepseek(api_key).await,
|
||||
BalanceProvider::StepFun => query_stepfun(api_key).await,
|
||||
BalanceProvider::SiliconFlow => query_siliconflow(api_key, true).await,
|
||||
BalanceProvider::SiliconFlowEn => query_siliconflow(api_key, false).await,
|
||||
BalanceProvider::OpenRouter => query_openrouter(api_key).await,
|
||||
BalanceProvider::NovitaAI => query_novita(api_key).await,
|
||||
};
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ fn make_error(msg: String) -> SubscriptionQuota {
|
||||
|
||||
// ── Kimi For Coding ─────────────────────────────────────────
|
||||
|
||||
async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
async fn query_kimi(api_key: &str) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -112,12 +112,12 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
@@ -126,17 +126,23 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
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}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
let mut tiers = Vec::new();
|
||||
@@ -187,7 +193,7 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
});
|
||||
}
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
@@ -196,7 +202,7 @@ async fn query_kimi(api_key: &str) -> SubscriptionQuota {
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── 智谱 GLM ────────────────────────────────────────────────
|
||||
@@ -307,7 +313,7 @@ fn zhipu_quota_base(base_url: &str) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
async fn query_zhipu(base_url: &str, api_key: &str) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
let url = format!(
|
||||
"{}/api/monitor/usage/quota/limit",
|
||||
@@ -325,12 +331,12 @@ async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
@@ -339,19 +345,32 @@ async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
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}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
Ok(zhipu_quota_from_body(&body))
|
||||
}
|
||||
|
||||
/// 解析智谱额度响应体(个人版与团队版共用同一 shape)。
|
||||
/// 仅在 HTTP 成功、body 已完整读取并解析为 JSON 后调用——本函数不做任何网络 IO,
|
||||
/// 故无瞬时失败通道,确定性失败直接落进 `Ok(success:false)`。
|
||||
fn zhipu_quota_from_body(body: &serde_json::Value) -> SubscriptionQuota {
|
||||
// 检查业务级别错误
|
||||
if body.get("success").and_then(|v| v.as_bool()) == Some(false) {
|
||||
let msg = body
|
||||
@@ -388,7 +407,7 @@ async fn query_zhipu(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
|
||||
// ── MiniMax ─────────────────────────────────────────────────
|
||||
|
||||
async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
async fn query_minimax(api_key: &str, is_cn: bool) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let api_domain = if is_cn {
|
||||
@@ -408,12 +427,12 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
@@ -422,17 +441,23 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
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}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
// 检查业务级别错误
|
||||
@@ -446,14 +471,14 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
.get("status_msg")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return make_error(format!("API error (code {status_code}): {msg}"));
|
||||
return Ok(make_error(format!("API error (code {status_code}): {msg}")));
|
||||
}
|
||||
}
|
||||
|
||||
// 提取纯函数便于无 mock 单元测试;新接口直接给"剩余百分比",反转为已用百分比
|
||||
let tiers = parse_minimax_tiers(&body);
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
@@ -462,12 +487,12 @@ async fn query_minimax(api_key: &str, is_cn: bool) -> SubscriptionQuota {
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── ZenMux ──────────────────────────────────────────────────
|
||||
|
||||
async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
async fn query_zenmux(base_url: &str, api_key: &str) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -480,12 +505,12 @@ async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return make_error(format!("Network error: {e}")),
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota {
|
||||
return Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Expired,
|
||||
credential_message: Some("Invalid API key".to_string()),
|
||||
@@ -494,17 +519,23 @@ async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
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}"));
|
||||
return Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return make_error(format!("Failed to parse response: {e}")),
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
// 检查业务级别错误
|
||||
@@ -513,12 +544,12 @@ async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Unknown error");
|
||||
return make_error(format!("API error: {msg}"));
|
||||
return Ok(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()),
|
||||
None => return Ok(make_error("Missing 'data' field in response".to_string())),
|
||||
};
|
||||
|
||||
let mut tiers = Vec::new();
|
||||
@@ -581,7 +612,7 @@ async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
String::new()
|
||||
};
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: "coding_plan".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: if plan_info.is_empty() {
|
||||
@@ -594,7 +625,7 @@ async fn query_zenmux(base_url: &str, api_key: &str) -> SubscriptionQuota {
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// 从 `/coding_plan/remains` 响应中解析 MiniMax 编程套餐的额度 tier。
|
||||
@@ -690,8 +721,11 @@ enum VolcCall {
|
||||
/// 硬鉴权失败(HTTP 401/403 或 AccessDenied/Signature 等错误码)——两个 plan
|
||||
/// 共用凭据,命中即停。
|
||||
Auth(String),
|
||||
/// 网络 / 非鉴权 HTTP 错误 / 解析失败——记录后可继续尝试另一个 plan。
|
||||
/// 非鉴权 HTTP 错误 / 响应体非法 JSON——记录后可继续尝试另一个 plan。
|
||||
Soft(String),
|
||||
/// 瞬时传输失败(网络/超时/读体中断)——同 host 的另一个 plan 大概率同样
|
||||
/// 失败,调用方应立即以 `Err` 传播(前端 reject → retry + 保留上次成功值)。
|
||||
Transient(String),
|
||||
}
|
||||
|
||||
/// 从数据面 base_url 提取控制面 OpenAPI 所需的 Region(如
|
||||
@@ -889,7 +923,7 @@ async fn volcengine_openapi_call(
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return VolcCall::Soft(format!("Network error: {e}")),
|
||||
Err(e) => return VolcCall::Transient(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
@@ -916,7 +950,13 @@ async fn volcengine_openapi_call(
|
||||
return VolcCall::Soft(format!("API error (HTTP {status}): {raw}"));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 同 Bearer 路径:先 bytes() 再解析——读体失败是瞬时(Transient),解析失败
|
||||
// 是确定性(Soft)。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return VolcCall::Transient(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return VolcCall::Soft(format!("Failed to parse response: {e}")),
|
||||
};
|
||||
@@ -1058,7 +1098,7 @@ async fn query_volcengine(
|
||||
base_url: &str,
|
||||
access_key_id: &str,
|
||||
secret_access_key: &str,
|
||||
) -> SubscriptionQuota {
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
let region = volcengine_region(base_url);
|
||||
let mut soft_errors: Vec<String> = Vec::new();
|
||||
// 2xx + 无 Error 信封但解析不出额度时,截断原始响应用于诊断(区分"真没订阅"
|
||||
@@ -1071,7 +1111,8 @@ async fn query_volcengine(
|
||||
|
||||
// 1) Agent Plan:GetAFPUsage
|
||||
match volcengine_openapi_call(®ion, access_key_id, secret_access_key, "GetAFPUsage").await {
|
||||
VolcCall::Auth(detail) => return volcengine_auth_error(detail),
|
||||
VolcCall::Auth(detail) => return Ok(volcengine_auth_error(detail)),
|
||||
VolcCall::Transient(detail) => return Err(format!("GetAFPUsage: {detail}")),
|
||||
VolcCall::Soft(detail) => soft_errors.push(format!("GetAFPUsage: {detail}")),
|
||||
VolcCall::Body(body) => {
|
||||
let result = body.get("Result").unwrap_or(&body);
|
||||
@@ -1083,7 +1124,7 @@ async fn query_volcengine(
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| format!("Agent Plan {s}"));
|
||||
return volcengine_success(tiers, plan);
|
||||
return Ok(volcengine_success(tiers, plan));
|
||||
}
|
||||
empty_responses.push(summarize("GetAFPUsage", &body));
|
||||
}
|
||||
@@ -1098,32 +1139,33 @@ async fn query_volcengine(
|
||||
)
|
||||
.await
|
||||
{
|
||||
VolcCall::Auth(detail) => return volcengine_auth_error(detail),
|
||||
VolcCall::Auth(detail) => return Ok(volcengine_auth_error(detail)),
|
||||
VolcCall::Transient(detail) => return Err(format!("GetCodingPlanUsage: {detail}")),
|
||||
VolcCall::Soft(detail) => soft_errors.push(format!("GetCodingPlanUsage: {detail}")),
|
||||
VolcCall::Body(body) => {
|
||||
let result = body.get("Result").unwrap_or(&body);
|
||||
let tiers = parse_coding_plan_tiers(result);
|
||||
if !tiers.is_empty() {
|
||||
return volcengine_success(tiers, Some("Coding Plan".to_string()));
|
||||
return Ok(volcengine_success(tiers, Some("Coding Plan".to_string())));
|
||||
}
|
||||
empty_responses.push(summarize("GetCodingPlanUsage", &body));
|
||||
}
|
||||
}
|
||||
|
||||
if !soft_errors.is_empty() {
|
||||
make_error(soft_errors.join("; "))
|
||||
Ok(make_error(soft_errors.join("; ")))
|
||||
} else if !empty_responses.is_empty() {
|
||||
// 签名已通过、请求到达业务层,但响应里没有可解析的额度。带上原始响应,
|
||||
// 便于核对真实字段名/包裹层,或确认确实未订阅。
|
||||
make_error(format!(
|
||||
Ok(make_error(format!(
|
||||
"No active subscription found (signature OK). Raw: {}",
|
||||
empty_responses.join(" || ")
|
||||
))
|
||||
)))
|
||||
} else {
|
||||
make_error(
|
||||
Ok(make_error(
|
||||
"No active Agent Plan or Coding Plan subscription found for this credential"
|
||||
.to_string(),
|
||||
)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1143,12 +1185,115 @@ fn coding_plan_not_found(error: &str) -> SubscriptionQuota {
|
||||
}
|
||||
}
|
||||
|
||||
// ── 智谱团队套餐(Team Plan)──────────────────────────────────
|
||||
//
|
||||
// 与个人版的差异仅在请求构造(参考 token-monitor/src/shared/zaiTeamLimits.js):
|
||||
// - 固定走国内站 open.bigmodel.cn(团队版仅存在于国内站,z.ai 国际站无 team 档)
|
||||
// - 同一 quota 路径加 `?type=2`
|
||||
// - 额外请求头 bigmodel-organization / bigmodel-project(两者 + api_key 缺一不可)
|
||||
// 响应 shape 与个人版完全一致 → 复用 zhipu_quota_from_body / parse_zhipu_token_tiers。
|
||||
const ZHIPU_TEAM_QUOTA_URL: &str = "https://open.bigmodel.cn/api/monitor/usage/quota/limit";
|
||||
|
||||
async fn query_zhipu_team(
|
||||
api_key: &str,
|
||||
organization_id: &str,
|
||||
project_id: &str,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
query_zhipu_team_at(ZHIPU_TEAM_QUOTA_URL, api_key, organization_id, project_id).await
|
||||
}
|
||||
|
||||
/// 团队版额度查询。`quota_url_base` 为不含 query 的 quota 端点;团队版与个人版同路径,
|
||||
/// 靠 `?type=2` 区分(在此拼上)。拆出 url 参数便于用本地 server 测试请求形状。
|
||||
async fn query_zhipu_team_at(
|
||||
quota_url_base: &str,
|
||||
api_key: &str,
|
||||
organization_id: &str,
|
||||
project_id: &str,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
let url = format!("{quota_url_base}?type=2");
|
||||
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.header("Authorization", api_key) // 与个人版一致:智谱不加 Bearer 前缀
|
||||
.header("bigmodel-organization", organization_id)
|
||||
.header("bigmodel-project", project_id)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept-Language", "en-US,en")
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.send()
|
||||
.await;
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return Ok(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 Ok(make_error(format!("API error (HTTP {status}): {body}")));
|
||||
}
|
||||
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => return Ok(make_error(format!("Failed to parse response: {e}"))),
|
||||
};
|
||||
|
||||
Ok(zhipu_quota_from_body(&body))
|
||||
}
|
||||
|
||||
/// 查询编程套餐额度。瞬时传输失败(网络/超时/读体中断)返回 `Err`(前端 reject →
|
||||
/// retry + 保留上次成功值);确定性失败(凭据缺失/未知域名/鉴权/非 2xx/业务错误)
|
||||
/// 返回 `Ok(success:false)` 立即透出文案。判定按 reqwest 错误种类在折叠点完成。
|
||||
///
|
||||
/// `coding_plan_provider` 显式标识用于无法靠 base_url 区分的供应商(当前为智谱团队版
|
||||
/// `zhipu_team`——其 base_url 与个人版智谱相同);其余情况走 `detect_provider`。
|
||||
pub async fn get_coding_plan_quota(
|
||||
base_url: &str,
|
||||
api_key: &str,
|
||||
access_key_id: Option<&str>,
|
||||
secret_access_key: Option<&str>,
|
||||
coding_plan_provider: Option<&str>,
|
||||
team_organization_id: Option<&str>,
|
||||
team_project_id: Option<&str>,
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
// 智谱团队版:base_url 与个人版智谱(open.bigmodel.cn)相同,detect_provider 无法
|
||||
// 区分,必须靠显式 coding_plan_provider == "zhipu_team" 路由。需 api_key + 组织 ID
|
||||
// + 项目 ID 三者齐全,缺任一返回 NotFound 引导补全。
|
||||
if coding_plan_provider
|
||||
.map(|p| p.eq_ignore_ascii_case("zhipu_team"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let organization_id = team_organization_id.unwrap_or("").trim();
|
||||
let project_id = team_project_id.unwrap_or("").trim();
|
||||
if api_key.trim().is_empty() || organization_id.is_empty() || project_id.is_empty() {
|
||||
return Ok(coding_plan_not_found(
|
||||
"Zhipu team plan needs the API key + organization ID + project ID",
|
||||
));
|
||||
}
|
||||
return query_zhipu_team(api_key, organization_id, project_id).await;
|
||||
}
|
||||
|
||||
let provider = match detect_provider(base_url) {
|
||||
Some(p) => p,
|
||||
// 域名未命中已知套餐供应商(如第三方中转站):给出明确错误而非静默失败
|
||||
@@ -1165,7 +1310,7 @@ pub async fn get_coding_plan_quota(
|
||||
"Volcengine usage query needs the account AccessKey ID + Secret (not the inference API key)",
|
||||
));
|
||||
}
|
||||
return Ok(query_volcengine(base_url, ak, sk).await);
|
||||
return query_volcengine(base_url, ak, sk).await;
|
||||
}
|
||||
|
||||
// 其余供应商:数据面 Bearer api_key。
|
||||
@@ -1174,7 +1319,7 @@ pub async fn get_coding_plan_quota(
|
||||
return Ok(coding_plan_not_found("API key is empty"));
|
||||
}
|
||||
|
||||
let quota = match provider {
|
||||
match provider {
|
||||
CodingPlanProvider::Kimi => query_kimi(api_key).await,
|
||||
CodingPlanProvider::ZhipuCn | CodingPlanProvider::ZhipuEn => {
|
||||
query_zhipu(base_url, api_key).await
|
||||
@@ -1186,18 +1331,16 @@ pub async fn get_coding_plan_quota(
|
||||
CodingPlanProvider::Volcengine => {
|
||||
unreachable!("volcengine handled via AK/SK branch above")
|
||||
}
|
||||
};
|
||||
|
||||
Ok(quota)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
parse_afp_tiers, parse_coding_plan_tiers, parse_minimax_tiers, parse_zhipu_token_tiers,
|
||||
volcengine_canonical_query, volcengine_is_auth_error_code, volcengine_region,
|
||||
volcengine_response_error, volcengine_sign, zhipu_quota_base, TIER_FIVE_HOUR, TIER_MONTHLY,
|
||||
TIER_WEEKLY_LIMIT,
|
||||
query_zhipu_team_at, volcengine_canonical_query, volcengine_is_auth_error_code,
|
||||
volcengine_region, volcengine_response_error, volcengine_sign, zhipu_quota_base,
|
||||
TIER_FIVE_HOUR, TIER_MONTHLY, TIER_WEEKLY_LIMIT,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
@@ -1806,4 +1949,289 @@ mod tests {
|
||||
let ok_body = json!({ "ResponseMetadata": { "RequestId": "x" }, "Result": {} });
|
||||
assert!(volcengine_response_error(&ok_body).is_none());
|
||||
}
|
||||
|
||||
// ── 传输层错误通道语义:瞬时 → Err(前端 reject/retry),确定性 → Ok(success:false) ──
|
||||
//
|
||||
// 借 ZenMux 分支可指向任意 base_url 的特性,用本地 listener 驱动真实 HTTP
|
||||
// 路径,锁定 send 失败 / 读体中断 / 4xx / 非法 JSON 各自落在哪条通道。
|
||||
// balance / subscription 服务与本文件共用同一折叠模式,这里的用例同时充当
|
||||
// 三个服务的语义回归锚。
|
||||
|
||||
use super::get_coding_plan_quota;
|
||||
use crate::services::subscription::CredentialStatus;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
/// 测试进程内可能有其他用例临时 set_var HTTP_PROXY(http_client 的
|
||||
/// loopback 检测测试),NO_PROXY 保证本地回环请求始终直连。
|
||||
fn ensure_no_proxy_for_loopback() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
std::env::set_var("NO_PROXY", "127.0.0.1,localhost");
|
||||
std::env::set_var("no_proxy", "127.0.0.1,localhost");
|
||||
});
|
||||
}
|
||||
|
||||
/// 起一个只服务一次连接的本地 HTTP server。`response=None` 表示读完请求
|
||||
/// 直接断开(模拟响应前连接中断)。返回可命中 ZenMux 分支的 base_url。
|
||||
fn spawn_once_server(response: Option<String>) -> (String, std::thread::JoinHandle<()>) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local listener");
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
let handle = std::thread::spawn(move || {
|
||||
if let Ok((mut stream, _)) = listener.accept() {
|
||||
let mut buf = [0u8; 2048];
|
||||
let _ = stream.read(&mut buf);
|
||||
if let Some(resp) = response {
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
let _ = stream.flush();
|
||||
}
|
||||
}
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}/zenmux"), handle)
|
||||
}
|
||||
|
||||
fn http_response(status_line: &str, body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transient_connection_refused_returns_err() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
// 绑定后立刻释放端口 → 连接被拒(send 失败)
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
drop(listener);
|
||||
|
||||
let result = get_coding_plan_quota(
|
||||
&format!("http://127.0.0.1:{port}/zenmux"),
|
||||
"k",
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let err = result.expect_err("send 失败必须走 Err 通道(瞬时,前端 reject 后重试)");
|
||||
assert!(err.contains("Network error"), "err={err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transient_connection_closed_before_response_returns_err() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
let (base_url, handle) = spawn_once_server(None);
|
||||
|
||||
let result = get_coding_plan_quota(&base_url, "k", None, None, None, None, None).await;
|
||||
let err = result.expect_err("响应前连接中断必须走 Err 通道(瞬时)");
|
||||
assert!(err.contains("Network error"), "err={err}");
|
||||
handle.join().expect("server thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transient_truncated_body_returns_err() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
// 声明 content-length: 100 但只写一小段就断开 → 读体中断。
|
||||
// 锁定 bytes() 先于解析:这类失败必须走 Err(瞬时),不能因 reqwest 把
|
||||
// 读体错误包成 decode 而被误判成确定性的 "Failed to parse response"。
|
||||
let (base_url, handle) = spawn_once_server(Some(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 100\r\n\r\npartial"
|
||||
.to_string(),
|
||||
));
|
||||
|
||||
let result = get_coding_plan_quota(&base_url, "k", None, None, None, None, None).await;
|
||||
let err = result.expect_err("读体中断必须走 Err 通道(瞬时,前端 reject 后重试)");
|
||||
assert!(err.contains("Failed to read response"), "err={err}");
|
||||
handle.join().expect("server thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deterministic_http_401_stays_ok_with_auth_error() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
let (base_url, handle) = spawn_once_server(Some(http_response("401 Unauthorized", "{}")));
|
||||
|
||||
let quota = get_coding_plan_quota(&base_url, "k", None, None, None, None, None)
|
||||
.await
|
||||
.expect("鉴权失败是确定性失败,必须保持 Ok(success:false) 展示文案");
|
||||
assert!(!quota.success);
|
||||
assert!(matches!(quota.credential_status, CredentialStatus::Expired));
|
||||
let err = quota.error.expect("应有错误文案");
|
||||
assert!(err.contains("Authentication failed (HTTP 401"), "err={err}");
|
||||
handle.join().expect("server thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deterministic_http_429_stays_ok_with_status_in_error() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
let (base_url, handle) =
|
||||
spawn_once_server(Some(http_response("429 Too Many Requests", "slow down")));
|
||||
|
||||
let quota = get_coding_plan_quota(&base_url, "k", None, None, None, None, None)
|
||||
.await
|
||||
.expect("非 2xx 保持 Ok(success:false),状态码留在文案里交前端分类");
|
||||
assert!(!quota.success);
|
||||
// 前端 isTransientUsageError 靠 /http\s+(\d{3})/ 提取状态码把 429 归瞬时,
|
||||
// 文案格式是跨层契约,勿改。
|
||||
let err = quota.error.expect("应有错误文案");
|
||||
assert!(err.contains("HTTP 429"), "err={err}");
|
||||
handle.join().expect("server thread");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deterministic_invalid_json_body_stays_ok_with_parse_error() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
// 完整读到响应体但不是 JSON → is_decode → 确定性解析失败
|
||||
let (base_url, handle) = spawn_once_server(Some(http_response("200 OK", "not-json")));
|
||||
|
||||
let quota = get_coding_plan_quota(&base_url, "k", None, None, None, None, None)
|
||||
.await
|
||||
.expect("完整但非法的响应体是确定性失败,必须保持 Ok(success:false)");
|
||||
assert!(!quota.success);
|
||||
let err = quota.error.expect("应有错误文案");
|
||||
assert!(err.contains("Failed to parse response"), "err={err}");
|
||||
handle.join().expect("server thread");
|
||||
}
|
||||
|
||||
// ── 智谱团队套餐(Team Plan)──
|
||||
|
||||
/// 起一个只服务一次连接的本地 HTTP server,捕获原始请求文本(请求行 + 头),
|
||||
/// 用于断言 team 查询发出的 URL query 与组织/项目请求头。`response=None` 时只捕获不回包。
|
||||
fn spawn_request_capturing_server(
|
||||
response: Option<String>,
|
||||
) -> (
|
||||
String,
|
||||
std::sync::Arc<std::sync::Mutex<Option<String>>>,
|
||||
std::thread::JoinHandle<()>,
|
||||
) {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind local listener");
|
||||
let port = listener.local_addr().expect("local addr").port();
|
||||
let captured = std::sync::Arc::new(std::sync::Mutex::new(None::<String>));
|
||||
let captured_clone = captured.clone();
|
||||
let handle = std::thread::spawn(move || {
|
||||
if let Ok((mut stream, _)) = listener.accept() {
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let mut tmp = [0u8; 4096];
|
||||
// GET 无 body,读到 header 末尾(\r\n\r\n)即可
|
||||
while !buf.windows(4).any(|w| w == b"\r\n\r\n") {
|
||||
match stream.read(&mut tmp) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
buf.extend_from_slice(&tmp[..n]);
|
||||
if buf.len() > 16 * 1024 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*captured_clone.lock().unwrap() = Some(String::from_utf8_lossy(&buf).into_owned());
|
||||
if let Some(resp) = response {
|
||||
let _ = stream.write_all(resp.as_bytes());
|
||||
let _ = stream.flush();
|
||||
}
|
||||
}
|
||||
});
|
||||
(format!("http://127.0.0.1:{port}/team"), captured, handle)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zhipu_team_missing_creds_returns_not_found() {
|
||||
// 团队版必需 api_key + 组织 ID + 项目 ID,缺任一在触网前返回 NotFound(不联网)。
|
||||
let cases: [(&str, Option<&str>, Option<&str>); 3] = [
|
||||
("key", Some("org"), None), // 缺 project
|
||||
("key", None, Some("proj")), // 缺 organization
|
||||
(" ", Some("org"), Some("proj")), // 空 api_key
|
||||
];
|
||||
for (api_key, org, project) in cases {
|
||||
let q = get_coding_plan_quota(
|
||||
"https://open.bigmodel.cn/api/coding",
|
||||
api_key,
|
||||
None,
|
||||
None,
|
||||
Some("zhipu_team"),
|
||||
org,
|
||||
project,
|
||||
)
|
||||
.await
|
||||
.expect("凭据缺失是确定性失败,保持 Ok(success:false)");
|
||||
assert!(!q.success, "应失败: api_key={api_key:?}");
|
||||
assert!(
|
||||
matches!(q.credential_status, CredentialStatus::NotFound),
|
||||
"应为 NotFound: api_key={api_key:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// 标识大小写不敏感(eq_ignore_ascii_case),大写仍命中 team 分支并返回引导文案。
|
||||
let msg = get_coding_plan_quota(
|
||||
"https://open.bigmodel.cn/api/coding",
|
||||
"key",
|
||||
None,
|
||||
None,
|
||||
Some("Zhipu_Team"),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("ok")
|
||||
.error
|
||||
.expect("应有错误文案");
|
||||
assert!(
|
||||
msg.contains("API key + organization ID + project ID"),
|
||||
"err={msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zhipu_team_request_carries_type2_and_org_project_headers() {
|
||||
ensure_no_proxy_for_loopback();
|
||||
// 响应 shape 与个人版一致:两条 TOKENS_LIMIT(unit 3/6)→ five_hour + weekly。
|
||||
let body = serde_json::json!({
|
||||
"success": true,
|
||||
"data": {
|
||||
"level": "max",
|
||||
"limits": [
|
||||
{ "type": "TOKENS_LIMIT", "unit": 3, "number": 5, "percentage": 26.0 },
|
||||
{ "type": "TOKENS_LIMIT", "unit": 6, "number": 1, "percentage": 5.0 }
|
||||
]
|
||||
}
|
||||
});
|
||||
let body_str = body.to_string();
|
||||
let resp = format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body_str}",
|
||||
body_str.len()
|
||||
);
|
||||
let (base, captured, handle) = spawn_request_capturing_server(Some(resp));
|
||||
|
||||
let quota = query_zhipu_team_at(&base, "team-key", "org-xxx", "proj_xxx")
|
||||
.await
|
||||
.expect("2xx + 合法 body 应成功");
|
||||
handle.join().expect("server thread");
|
||||
|
||||
// 请求形状契约(与 token-monitor zaiTeamLimits 对齐):
|
||||
// 同路径加 ?type=2 + bigmodel-organization / bigmodel-project 头 + 鉴权头。
|
||||
// reqwest/hyper 发头会小写化,故整体转小写做包含匹配。
|
||||
let raw = captured.lock().unwrap().clone().expect("应捕获到请求");
|
||||
let raw_lc = raw.to_lowercase();
|
||||
assert!(raw_lc.contains("/team?type=2"), "缺 ?type=2: {raw}");
|
||||
assert!(
|
||||
raw_lc.contains("bigmodel-organization: org-xxx"),
|
||||
"缺组织头: {raw}"
|
||||
);
|
||||
assert!(
|
||||
raw_lc.contains("bigmodel-project: proj_xxx"),
|
||||
"缺项目头: {raw}"
|
||||
);
|
||||
assert!(
|
||||
raw_lc.contains("authorization: team-key"),
|
||||
"缺鉴权头: {raw}"
|
||||
);
|
||||
|
||||
// 解析复用个人版 zhipu_quota_from_body / parse_zhipu_token_tiers。
|
||||
assert!(quota.success);
|
||||
assert_eq!(quota.tiers.len(), 2);
|
||||
assert_eq!(quota.tiers[0].name, TIER_FIVE_HOUR);
|
||||
assert_eq!(quota.tiers[0].utilization, 26.0);
|
||||
assert_eq!(quota.tiers[1].name, TIER_WEEKLY_LIMIT);
|
||||
assert_eq!(quota.tiers[1].utilization, 5.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,9 +159,7 @@ impl ConfigService {
|
||||
}
|
||||
let cfg_text = settings.get("config").and_then(Value::as_str);
|
||||
|
||||
let profile = crate::codex_config::CodexCatalogToolProfile::from_api_format(
|
||||
provider.meta.as_ref().and_then(|m| m.api_format.as_deref()),
|
||||
);
|
||||
let profile = crate::proxy::providers::resolve_codex_catalog_tool_profile(provider);
|
||||
|
||||
crate::codex_config::write_codex_provider_live_with_catalog(
|
||||
&provider.settings_config,
|
||||
|
||||
@@ -176,21 +176,55 @@ impl McpService {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 手动同步所有启用的 MCP 服务器到对应的应用
|
||||
/// 手动同步所有启用的 MCP 服务器到对应的应用。
|
||||
///
|
||||
/// Best-effort:单个应用投影失败(如 ~/.claude.json 坏 JSON)不阻断
|
||||
/// 其余应用——各应用的 live 文件互相独立,一处损坏没有理由让其他
|
||||
/// 应用的 MCP 状态陈旧。全部跑完后若有失败,聚合成一个错误上报,
|
||||
/// 保留调用方的可见性。
|
||||
pub fn sync_all_enabled(state: &AppState) -> Result<(), AppError> {
|
||||
let servers = Self::get_all_servers(state)?;
|
||||
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
for app in AppType::all() {
|
||||
if matches!(app, AppType::OpenClaw | AppType::ClaudeDesktop) {
|
||||
continue;
|
||||
if let Err(err) = Self::project_servers_to_app(state, &servers, &app) {
|
||||
log::warn!("同步 MCP 到 {app:?} 失败: {err}");
|
||||
failures.push(format!("{}: {err}", app.as_str()));
|
||||
}
|
||||
}
|
||||
|
||||
for server in servers.values() {
|
||||
if server.apps.is_enabled_for(&app) {
|
||||
Self::sync_server_to_app(state, server, &app)?;
|
||||
} else {
|
||||
Self::remove_server_from_app(state, &server.id, &app)?;
|
||||
}
|
||||
if failures.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(AppError::Message(format!(
|
||||
"部分应用 MCP 同步失败: {}",
|
||||
failures.join("; ")
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 只把启用状态投影到单个应用。某个应用的 live 被整体重写后用它做
|
||||
/// 定向重投影,避免把无关应用的失败面(如 ~/.claude.json 坏 JSON)
|
||||
/// 牵连进目标应用的关键路径。
|
||||
pub fn sync_enabled_for_app(state: &AppState, app: &AppType) -> Result<(), AppError> {
|
||||
let servers = Self::get_all_servers(state)?;
|
||||
Self::project_servers_to_app(state, &servers, app)
|
||||
}
|
||||
|
||||
fn project_servers_to_app(
|
||||
state: &AppState,
|
||||
servers: &IndexMap<String, McpServer>,
|
||||
app: &AppType,
|
||||
) -> Result<(), AppError> {
|
||||
if matches!(app, AppType::OpenClaw | AppType::ClaudeDesktop) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for server in servers.values() {
|
||||
if server.apps.is_enabled_for(app) {
|
||||
Self::sync_server_to_app(state, server, app)?;
|
||||
} else {
|
||||
Self::remove_server_from_app(state, &server.id, app)?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,4 +468,41 @@ impl McpService {
|
||||
|
||||
Ok(new_count)
|
||||
}
|
||||
|
||||
/// 从所有支持 MCP 的应用导入服务器,返回新导入的数量。
|
||||
///
|
||||
/// Best-effort:单个应用导入失败(如坏 config.toml)不阻断其余应用;
|
||||
/// 全部跑完后若有失败,聚合成一个错误上报——历史实现逐应用
|
||||
/// `unwrap_or(0)` 吞错,坏文件只会表现为"导入成功 0 个",用户
|
||||
/// 无从得知哪个应用出了问题。
|
||||
pub fn import_from_all_apps(state: &AppState) -> Result<usize, AppError> {
|
||||
let mut total = 0;
|
||||
let mut failures: Vec<String> = Vec::new();
|
||||
|
||||
let results: [(&str, Result<usize, AppError>); 5] = [
|
||||
("claude", Self::import_from_claude(state)),
|
||||
("codex", Self::import_from_codex(state)),
|
||||
("gemini", Self::import_from_gemini(state)),
|
||||
("opencode", Self::import_from_opencode(state)),
|
||||
("hermes", Self::import_from_hermes(state)),
|
||||
];
|
||||
for (app, result) in results {
|
||||
match result {
|
||||
Ok(count) => total += count,
|
||||
Err(err) => {
|
||||
log::warn!("从 {app} 导入 MCP 失败: {err}");
|
||||
failures.push(format!("{app}: {err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if failures.is_empty() {
|
||||
Ok(total)
|
||||
} else {
|
||||
Err(AppError::Message(format!(
|
||||
"已导入 {total} 个,部分应用导入失败: {}",
|
||||
failures.join("; ")
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ pub mod env_manager;
|
||||
pub mod mcp;
|
||||
pub mod model_fetch;
|
||||
pub mod omo;
|
||||
pub mod profile;
|
||||
pub mod prompt;
|
||||
pub mod provider;
|
||||
pub mod proxy;
|
||||
|
||||
@@ -0,0 +1,656 @@
|
||||
//! 项目 Profile 编排服务
|
||||
//!
|
||||
//! Profile 是**全应用共享的项目实体**(用户拥有的项目就那几个),payload
|
||||
//! 按 app 分槽存配置快照(供应商 / MCP / Skills / Prompt)。快照与应用
|
||||
//! 均**按分组(scope)操作**:Claude Code 与 Codex 的工作目录往往不同
|
||||
//! (各在各的项目里),因此各组独立指向自己的当前项目、只拍/只应用组内
|
||||
//! 槽位,互不牵连;重命名/删除作用于共享实体本身。
|
||||
//! 应用(apply)时复用现有切换原语批量落地:
|
||||
//! - 供应商:`ProviderService::switch`(内建代理接管热切换与接管下禁切官方)
|
||||
//! - MCP:`McpService::toggle_app`(改标志 + 单 server 物化)
|
||||
//! - Skills:`SkillService::toggle_app`(改标志 + 单 skill 物化)
|
||||
//! - Prompt:`PromptService::enable_prompt`(互斥激活 + 原子写 live)
|
||||
//!
|
||||
//! apply 为 best-effort:单项失败收集为 warning 继续,不整体回滚。
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::app_config::AppType;
|
||||
use crate::database::Profile;
|
||||
use crate::error::AppError;
|
||||
use crate::services::{McpService, PromptService, ProviderService, SkillService};
|
||||
use crate::store::AppState;
|
||||
|
||||
/// Profile 操作的应用分组:项目实体全应用共享,但快照/应用/当前指针按组进行。
|
||||
///
|
||||
/// Claude Code 与 Claude Desktop 的供应商在 cc-switch 中是独立切换的,
|
||||
/// 因此各自拥有独立的项目分组。两者 live 文件零交集
|
||||
///(`~/.claude` / `Application Support/Claude-3p`),分组切换互不干扰。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProfileScope {
|
||||
Claude,
|
||||
#[serde(rename = "claude-desktop")]
|
||||
ClaudeDesktop,
|
||||
Codex,
|
||||
}
|
||||
|
||||
impl ProfileScope {
|
||||
/// 全部分组(扩展新分组时同步扩展 apps/for_app 与前端 scope.ts 镜像)
|
||||
pub const ALL: [ProfileScope; 3] = [
|
||||
ProfileScope::Claude,
|
||||
ProfileScope::ClaudeDesktop,
|
||||
ProfileScope::Codex,
|
||||
];
|
||||
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ProfileScope::Claude => "claude",
|
||||
ProfileScope::ClaudeDesktop => "claude-desktop",
|
||||
ProfileScope::Codex => "codex",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Result<Self, AppError> {
|
||||
match value {
|
||||
"claude" => Ok(ProfileScope::Claude),
|
||||
"claude-desktop" => Ok(ProfileScope::ClaudeDesktop),
|
||||
"codex" => Ok(ProfileScope::Codex),
|
||||
other => Err(AppError::InvalidInput(format!(
|
||||
"Unknown profile scope: {other}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// 组内受管应用(快照与 apply 只作用于这些 app 的槽位)
|
||||
pub fn apps(&self) -> &'static [AppType] {
|
||||
match self {
|
||||
ProfileScope::Claude => &[AppType::Claude],
|
||||
ProfileScope::ClaudeDesktop => &[AppType::ClaudeDesktop],
|
||||
ProfileScope::Codex => &[AppType::Codex],
|
||||
}
|
||||
}
|
||||
|
||||
/// 应用页 → 所属分组(Profile 不支持的应用返回 None)
|
||||
pub fn for_app(app: &AppType) -> Option<Self> {
|
||||
match app {
|
||||
AppType::Claude => Some(ProfileScope::Claude),
|
||||
AppType::ClaudeDesktop => Some(ProfileScope::ClaudeDesktop),
|
||||
AppType::Codex => Some(ProfileScope::Codex),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按 app 分槽的载荷容器;字段名与 AppType 的 serde 形式一致
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct PerApp<T> {
|
||||
pub claude: T,
|
||||
#[serde(rename = "claude-desktop")]
|
||||
pub claude_desktop: T,
|
||||
pub codex: T,
|
||||
}
|
||||
|
||||
impl<T> PerApp<T> {
|
||||
pub fn get(&self, app: &AppType) -> Option<&T> {
|
||||
match app {
|
||||
AppType::Claude => Some(&self.claude),
|
||||
AppType::ClaudeDesktop => Some(&self.claude_desktop),
|
||||
AppType::Codex => Some(&self.codex),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, app: &AppType) -> Option<&mut T> {
|
||||
match app {
|
||||
AppType::Claude => Some(&mut self.claude),
|
||||
AppType::ClaudeDesktop => Some(&mut self.claude_desktop),
|
||||
AppType::Codex => Some(&mut self.codex),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Profile 的 JSON 快照结构(与前端 TS 类型严格对应)
|
||||
///
|
||||
/// 所有槽位都是 Option:None = 该侧从未拍过快照(应用时不动),
|
||||
/// 与"拍到的就是空集/无激活项"(Some(空),应用时清空启用)严格区分——
|
||||
/// 在 Codex 页选中一个只在 Claude 页建过的项目不能误清 Codex 的启用状态。
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ProfilePayload {
|
||||
/// 每 app 的当前供应商 id
|
||||
pub providers: PerApp<Option<String>>,
|
||||
/// 每 app 启用的 MCP server id 集合
|
||||
pub mcp: PerApp<Option<Vec<String>>>,
|
||||
/// 每 app 启用的 Skill id 集合
|
||||
pub skills: PerApp<Option<Vec<String>>>,
|
||||
/// 每 app 激活的 prompt id
|
||||
pub prompts: PerApp<Option<String>>,
|
||||
}
|
||||
|
||||
impl ProfilePayload {
|
||||
/// 用另一份快照覆盖本载荷中某分组的槽位,其余分组原样保留
|
||||
/// ("以当前状态更新"只更新发起页所属分组,避免把别的应用
|
||||
/// 正处于其他项目的状态串进来)
|
||||
pub fn merge_scope_from(&mut self, other: &ProfilePayload, scope: ProfileScope) {
|
||||
for app in scope.apps() {
|
||||
if let (Some(dst), Some(src)) = (self.providers.get_mut(app), other.providers.get(app))
|
||||
{
|
||||
*dst = src.clone();
|
||||
}
|
||||
if let (Some(dst), Some(src)) = (self.mcp.get_mut(app), other.mcp.get(app)) {
|
||||
*dst = src.clone();
|
||||
}
|
||||
if let (Some(dst), Some(src)) = (self.skills.get_mut(app), other.skills.get(app)) {
|
||||
*dst = src.clone();
|
||||
}
|
||||
if let (Some(dst), Some(src)) = (self.prompts.get_mut(app), other.prompts.get(app)) {
|
||||
*dst = src.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 某分组是否拍过快照(任一槽位非 None 即视为拍过)
|
||||
pub fn scope_captured(&self, scope: ProfileScope) -> bool {
|
||||
scope.apps().iter().any(|app| {
|
||||
self.providers.get(app).is_some_and(|s| s.is_some())
|
||||
|| self.mcp.get(app).is_some_and(|s| s.is_some())
|
||||
|| self.skills.get(app).is_some_and(|s| s.is_some())
|
||||
|| self.prompts.get(app).is_some_and(|s| s.is_some())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 计算从当前启用状态到目标集合的最小 toggle 集
|
||||
///
|
||||
/// 返回 (需要执行的 (id, enabled) 列表, payload 中已不存在于 DB 的悬空 id 列表)
|
||||
fn plan_toggles(
|
||||
current: &[(String, bool)],
|
||||
target_ids: &[String],
|
||||
) -> (Vec<(String, bool)>, Vec<String>) {
|
||||
let existing: HashSet<&str> = current.iter().map(|(id, _)| id.as_str()).collect();
|
||||
let target: HashSet<&str> = target_ids.iter().map(|s| s.as_str()).collect();
|
||||
|
||||
let toggles = current
|
||||
.iter()
|
||||
.filter(|(id, enabled)| target.contains(id.as_str()) != *enabled)
|
||||
.map(|(id, enabled)| (id.clone(), !enabled))
|
||||
.collect();
|
||||
|
||||
let dangling = target_ids
|
||||
.iter()
|
||||
.filter(|id| !existing.contains(id.as_str()))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
(toggles, dangling)
|
||||
}
|
||||
|
||||
pub struct ProfileService;
|
||||
|
||||
impl ProfileService {
|
||||
/// 抓取分组内应用的当前配置状态生成快照(组外槽位保持默认值)
|
||||
pub fn snapshot_current(
|
||||
state: &AppState,
|
||||
scope: ProfileScope,
|
||||
) -> Result<ProfilePayload, AppError> {
|
||||
let mut payload = ProfilePayload::default();
|
||||
let mcp_servers = state.db.get_all_mcp_servers()?;
|
||||
let skills = state.db.get_all_installed_skills()?;
|
||||
|
||||
for app in scope.apps().iter() {
|
||||
if let Some(slot) = payload.providers.get_mut(app) {
|
||||
*slot = crate::settings::get_effective_current_provider(&state.db, app)?;
|
||||
}
|
||||
if let Some(slot) = payload.mcp.get_mut(app) {
|
||||
*slot = Some(
|
||||
mcp_servers
|
||||
.values()
|
||||
.filter(|s| s.apps.is_enabled_for(app))
|
||||
.map(|s| s.id.clone())
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if let Some(slot) = payload.skills.get_mut(app) {
|
||||
*slot = Some(
|
||||
skills
|
||||
.values()
|
||||
.filter(|s| s.apps.is_enabled_for(app))
|
||||
.map(|s| s.id.clone())
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if let Some(slot) = payload.prompts.get_mut(app) {
|
||||
*slot = state
|
||||
.db
|
||||
.get_prompts(app.as_str())?
|
||||
.values()
|
||||
.find(|p| p.enabled)
|
||||
.map(|p| p.id.clone());
|
||||
}
|
||||
}
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
/// 列出所有项目(项目实体全应用共享,current 标记按分组单独读取)
|
||||
pub fn list(state: &AppState) -> Result<Vec<Profile>, AppError> {
|
||||
state.db.get_all_profiles()
|
||||
}
|
||||
|
||||
/// 创建新项目:只拍发起页所属分组的当前状态,其余分组槽位留 None
|
||||
/// (其他应用可能正处于别的项目,不能替用户拍进来)
|
||||
pub fn create(state: &AppState, name: &str, scope: ProfileScope) -> Result<Profile, AppError> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(AppError::InvalidInput("Profile name is empty".to_string()));
|
||||
}
|
||||
let payload = Self::snapshot_current(state, scope)?;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let profile = Profile {
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
name: name.to_string(),
|
||||
payload: serde_json::to_string(&payload)
|
||||
.map_err(|e| AppError::Config(format!("序列化 profile payload 失败: {e}")))?,
|
||||
sort_order: None,
|
||||
created_at: Some(now),
|
||||
updated_at: Some(now),
|
||||
};
|
||||
state.db.save_profile(&profile)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
/// 更新项目:重命名(作用于共享实体)和/或以当前状态重拍快照
|
||||
/// (resnapshot 只覆盖 scope 分组的槽位,其余分组原样保留;
|
||||
/// 快照重拍仅由 [`Self::apply`] 切换前的自动保存触发,UI 不再暴露手动入口)
|
||||
pub fn update(
|
||||
state: &AppState,
|
||||
id: &str,
|
||||
name: Option<String>,
|
||||
resnapshot: bool,
|
||||
scope: Option<ProfileScope>,
|
||||
) -> Result<Profile, AppError> {
|
||||
let mut profile = state
|
||||
.db
|
||||
.get_profile(id)?
|
||||
.ok_or_else(|| AppError::InvalidInput(format!("Profile not found: {id}")))?;
|
||||
|
||||
if let Some(name) = name {
|
||||
let name = name.trim().to_string();
|
||||
if name.is_empty() {
|
||||
return Err(AppError::InvalidInput("Profile name is empty".to_string()));
|
||||
}
|
||||
profile.name = name;
|
||||
}
|
||||
if resnapshot {
|
||||
let scope = scope.ok_or_else(|| {
|
||||
AppError::InvalidInput("Resnapshot requires a profile scope".to_string())
|
||||
})?;
|
||||
let mut payload: ProfilePayload = serde_json::from_str(&profile.payload)
|
||||
.map_err(|e| AppError::Config(format!("解析 profile payload 失败: {e}")))?;
|
||||
payload.merge_scope_from(&Self::snapshot_current(state, scope)?, scope);
|
||||
profile.payload = serde_json::to_string(&payload)
|
||||
.map_err(|e| AppError::Config(format!("序列化 profile payload 失败: {e}")))?;
|
||||
}
|
||||
profile.updated_at = Some(chrono::Utc::now().timestamp());
|
||||
state.db.save_profile(&profile)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
/// 删除项目;若删除的是某分组当前激活项目,一并清除该分组的激活标记
|
||||
pub fn delete(state: &AppState, id: &str) -> Result<(), AppError> {
|
||||
state.db.delete_profile(id)?;
|
||||
for scope in ProfileScope::ALL {
|
||||
if state.db.get_current_profile_id(scope.as_str())?.as_deref() == Some(id) {
|
||||
state.db.set_current_profile_id(scope.as_str(), None)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 应用项目快照(best-effort,返回 warnings)
|
||||
///
|
||||
/// 只作用于发起页所属分组内的应用,不碰其他分组的配置与 current 标记。
|
||||
/// 该分组从未拍过快照时不改动任何配置,仅标记 current 并返回提示
|
||||
/// (下次从该项目切走时,自动保存会补拍该侧快照)。
|
||||
///
|
||||
/// **切换前会自动保存旧项目**:若当前分组已绑定到另一个项目,先把当前
|
||||
/// 状态写入那个旧项目(仅当前分组槽位),再加载目标项目。这样切走后
|
||||
/// 旧项目仍保留离开时的配置,回来时状态一致。自动保存失败时作为 warning
|
||||
/// 继续,不阻塞切换。
|
||||
///
|
||||
/// 应用指定项目的快照到当前分组内的所有应用。
|
||||
///
|
||||
/// 返回 `(warnings, should_stop_proxy)`:当当前分组内所有接管都被关闭、且
|
||||
/// 其它应用也没有接管时,建议调用者停止代理服务,以便 Claude Desktop 的
|
||||
/// "本地路由"总开关同步显示为关闭。
|
||||
pub fn apply(
|
||||
state: &AppState,
|
||||
profile_id: &str,
|
||||
scope: ProfileScope,
|
||||
) -> Result<(Vec<String>, bool), AppError> {
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
// 自动保存旧项目当前状态(仅当前分组),失败不阻塞切换
|
||||
if let Some(current_id) = state.db.get_current_profile_id(scope.as_str())? {
|
||||
if current_id != profile_id {
|
||||
if let Err(e) = Self::update(state, ¤t_id, None, true, Some(scope)) {
|
||||
warnings.push(format!(
|
||||
"autosave profile '{current_id}' before switch failed: {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let profile = state
|
||||
.db
|
||||
.get_profile(profile_id)?
|
||||
.ok_or_else(|| AppError::InvalidInput(format!("Profile not found: {profile_id}")))?;
|
||||
let payload: ProfilePayload = serde_json::from_str(&profile.payload)
|
||||
.map_err(|e| AppError::Config(format!("解析 profile payload 失败: {e}")))?;
|
||||
|
||||
if !payload.scope_captured(scope) {
|
||||
warnings.push(format!(
|
||||
"no {} configuration captured in this project yet; marked as current without changes (it will be saved automatically when you switch away)",
|
||||
scope.as_str()
|
||||
));
|
||||
}
|
||||
|
||||
for app in scope.apps().iter() {
|
||||
let app_str = app.as_str();
|
||||
|
||||
// 1. 切换项目前无条件关闭当前应用的代理接管。
|
||||
// 接管态下 live 文件属于代理;用户希望切换工作目录时总是退出当前
|
||||
// 代理环境,再按快照写入真实供应商配置。
|
||||
if let Err(e) = state.proxy_service.disable_takeover_for_app_sync(app) {
|
||||
warnings.push(format!(
|
||||
"[{app_str}] auto-disable proxy takeover before profile switch failed: {e}"
|
||||
));
|
||||
}
|
||||
|
||||
// 2. 供应商
|
||||
if let Some(Some(target_pid)) = payload.providers.get(app) {
|
||||
let providers = state.db.get_all_providers(app_str)?;
|
||||
if !providers.contains_key(target_pid) {
|
||||
warnings.push(format!(
|
||||
"[{app_str}] provider '{target_pid}' no longer exists, skipped"
|
||||
));
|
||||
} else {
|
||||
let current = crate::settings::get_effective_current_provider(&state.db, app)?;
|
||||
if current.as_deref() != Some(target_pid.as_str()) {
|
||||
match ProviderService::switch(state, app.clone(), target_pid) {
|
||||
Ok(result) => warnings.extend(result.warnings),
|
||||
Err(e) => warnings.push(format!(
|
||||
"[{app_str}] switch provider '{target_pid}' failed: {e}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. MCP diff(最小 toggle:仅动目标态≠当前态的条目;None = 该侧未拍过,不动)
|
||||
if let Some(Some(target_ids)) = payload.mcp.get(app) {
|
||||
let servers = state.db.get_all_mcp_servers()?;
|
||||
let current: Vec<(String, bool)> = servers
|
||||
.values()
|
||||
.map(|s| (s.id.clone(), s.apps.is_enabled_for(app)))
|
||||
.collect();
|
||||
let (toggles, dangling) = plan_toggles(¤t, target_ids);
|
||||
for id in dangling {
|
||||
warnings.push(format!("[{app_str}] MCP '{id}' no longer exists, skipped"));
|
||||
}
|
||||
for (id, enabled) in toggles {
|
||||
if let Err(e) = McpService::toggle_app(state, &id, app.clone(), enabled) {
|
||||
warnings.push(format!(
|
||||
"[{app_str}] toggle MCP '{id}' -> {enabled} failed: {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Skills diff(SkillService 返回 anyhow::Result,收进 warning)
|
||||
if let Some(Some(target_ids)) = payload.skills.get(app) {
|
||||
let skills = state.db.get_all_installed_skills()?;
|
||||
let current: Vec<(String, bool)> = skills
|
||||
.values()
|
||||
.map(|s| (s.id.clone(), s.apps.is_enabled_for(app)))
|
||||
.collect();
|
||||
let (toggles, dangling) = plan_toggles(¤t, target_ids);
|
||||
for id in dangling {
|
||||
warnings.push(format!(
|
||||
"[{app_str}] skill '{id}' no longer exists, skipped"
|
||||
));
|
||||
}
|
||||
for (id, enabled) in toggles {
|
||||
if let Err(e) = SkillService::toggle_app(&state.db, &id, app, enabled) {
|
||||
warnings.push(format!(
|
||||
"[{app_str}] toggle skill '{id}' -> {enabled} failed: {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Prompt(None = 不动;已激活则幂等跳过,避免无谓的文件写与备份)
|
||||
if let Some(Some(target_prompt)) = payload.prompts.get(app) {
|
||||
let prompts = state.db.get_prompts(app_str)?;
|
||||
match prompts.get(target_prompt) {
|
||||
None => warnings.push(format!(
|
||||
"[{app_str}] prompt '{target_prompt}' no longer exists, skipped"
|
||||
)),
|
||||
Some(p) if p.enabled => {}
|
||||
Some(_) => {
|
||||
if let Err(e) =
|
||||
PromptService::enable_prompt(state, app.clone(), target_prompt)
|
||||
{
|
||||
warnings.push(format!(
|
||||
"[{app_str}] enable prompt '{target_prompt}' failed: {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state
|
||||
.db
|
||||
.set_current_profile_id(scope.as_str(), Some(profile_id))?;
|
||||
|
||||
// 当前分组内所有接管已关闭;若其它应用也无接管,可停止代理服务。
|
||||
let should_stop_proxy = !state.db.is_live_takeover_active_sync();
|
||||
|
||||
Ok((warnings, should_stop_proxy))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ids(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_payload_serde_roundtrip() {
|
||||
let payload = ProfilePayload {
|
||||
providers: PerApp {
|
||||
claude: Some("p1".into()),
|
||||
claude_desktop: Some("d1".into()),
|
||||
codex: None,
|
||||
},
|
||||
mcp: PerApp {
|
||||
claude: Some(ids(&["m1", "m2"])),
|
||||
claude_desktop: Some(vec![]),
|
||||
codex: None,
|
||||
},
|
||||
skills: PerApp {
|
||||
claude: Some(vec![]),
|
||||
claude_desktop: Some(vec![]),
|
||||
codex: Some(ids(&["s1"])),
|
||||
},
|
||||
prompts: PerApp {
|
||||
claude: None,
|
||||
claude_desktop: None,
|
||||
codex: Some("pr1".into()),
|
||||
},
|
||||
};
|
||||
let json = serde_json::to_string(&payload).unwrap();
|
||||
// per-app key 必须与 AppType 的 serde 形式一致(claude-desktop 是连字符)
|
||||
assert!(json.contains("\"claude\""));
|
||||
assert!(json.contains("\"claude-desktop\""));
|
||||
assert!(json.contains("\"codex\""));
|
||||
let back: ProfilePayload = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(back, payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_payload_tolerates_missing_fields() {
|
||||
// 前向兼容:旧版/部分字段缺失时应落到 None("该侧未拍过")而不是报错,
|
||||
// 应用时对缺失槽位不做任何改动
|
||||
let back: ProfilePayload =
|
||||
serde_json::from_str(r#"{"providers":{"claude":"p1"},"mcp":{"claude":["m1"]}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(back.providers.claude, Some("p1".to_string()));
|
||||
assert_eq!(back.providers.claude_desktop, None);
|
||||
assert_eq!(back.providers.codex, None);
|
||||
assert_eq!(back.mcp.claude, Some(ids(&["m1"])));
|
||||
assert_eq!(back.mcp.claude_desktop, None);
|
||||
assert_eq!(back.mcp.codex, None, "missing slot means untouched");
|
||||
assert_eq!(back.prompts.codex, None);
|
||||
|
||||
let empty: ProfilePayload = serde_json::from_str("{}").unwrap();
|
||||
assert_eq!(empty, ProfilePayload::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_scope_from_only_touches_scope_slots() {
|
||||
// 项目 A:两侧都已拍过快照
|
||||
let mut payload = ProfilePayload {
|
||||
providers: PerApp {
|
||||
claude: Some("p1".into()),
|
||||
claude_desktop: Some("d1".into()),
|
||||
codex: Some("c1".into()),
|
||||
},
|
||||
mcp: PerApp {
|
||||
claude: Some(ids(&["m1"])),
|
||||
claude_desktop: Some(vec![]),
|
||||
codex: Some(ids(&["m9"])),
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// 在 Claude 页"以当前状态更新":只覆盖 claude 组槽位
|
||||
let fresh = ProfilePayload {
|
||||
providers: PerApp {
|
||||
claude: Some("p2".into()),
|
||||
claude_desktop: None,
|
||||
codex: Some("SHOULD-NOT-LEAK".into()),
|
||||
},
|
||||
mcp: PerApp {
|
||||
claude: Some(ids(&["m2"])),
|
||||
claude_desktop: Some(vec![]),
|
||||
codex: None,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
payload.merge_scope_from(&fresh, ProfileScope::Claude);
|
||||
|
||||
assert_eq!(payload.providers.claude, Some("p2".to_string()));
|
||||
assert_eq!(
|
||||
payload.providers.claude_desktop,
|
||||
Some("d1".to_string()),
|
||||
"claude-desktop slot is in its own scope, untouched by claude merge"
|
||||
);
|
||||
assert_eq!(payload.mcp.claude, Some(ids(&["m2"])));
|
||||
// codex 侧完好:既没被覆盖也没被 fresh 的值污染
|
||||
assert_eq!(payload.providers.codex, Some("c1".to_string()));
|
||||
assert_eq!(payload.mcp.codex, Some(ids(&["m9"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_captured_detects_per_scope_snapshot() {
|
||||
let mut payload = ProfilePayload::default();
|
||||
assert!(!payload.scope_captured(ProfileScope::Claude));
|
||||
assert!(!payload.scope_captured(ProfileScope::ClaudeDesktop));
|
||||
assert!(!payload.scope_captured(ProfileScope::Codex));
|
||||
|
||||
// 只拍过 claude 组(哪怕拍到的是空集)
|
||||
payload.mcp.claude = Some(vec![]);
|
||||
assert!(payload.scope_captured(ProfileScope::Claude));
|
||||
assert!(!payload.scope_captured(ProfileScope::ClaudeDesktop));
|
||||
assert!(!payload.scope_captured(ProfileScope::Codex));
|
||||
|
||||
// Desktop 槽位属于独立的 claude-desktop 组
|
||||
let mut desktop_only = ProfilePayload::default();
|
||||
desktop_only.providers.claude_desktop = Some("d1".into());
|
||||
assert!(desktop_only.scope_captured(ProfileScope::ClaudeDesktop));
|
||||
assert!(!desktop_only.scope_captured(ProfileScope::Claude));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_per_app_get_only_supports_profile_apps() {
|
||||
let per: PerApp<Option<String>> = PerApp::default();
|
||||
assert!(per.get(&AppType::Claude).is_some());
|
||||
assert!(per.get(&AppType::ClaudeDesktop).is_some());
|
||||
assert!(per.get(&AppType::Codex).is_some());
|
||||
assert!(per.get(&AppType::Gemini).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_serde_and_parse_roundtrip() {
|
||||
for scope in ProfileScope::ALL {
|
||||
// DB 存储字符串(as_str/parse)与 JSON 序列化必须是同一形式
|
||||
assert_eq!(
|
||||
serde_json::to_string(&scope).unwrap(),
|
||||
format!("\"{}\"", scope.as_str())
|
||||
);
|
||||
assert_eq!(ProfileScope::parse(scope.as_str()).unwrap(), scope);
|
||||
}
|
||||
assert!(ProfileScope::parse("gemini").is_err());
|
||||
assert!(ProfileScope::parse("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_scope_app_grouping() {
|
||||
// Claude Code 与 Claude Desktop 各自独立成组;
|
||||
// 组内应用与 for_app 反向映射必须一致
|
||||
assert_eq!(ProfileScope::Claude.apps(), &[AppType::Claude]);
|
||||
assert_eq!(
|
||||
ProfileScope::ClaudeDesktop.apps(),
|
||||
&[AppType::ClaudeDesktop]
|
||||
);
|
||||
assert_eq!(ProfileScope::Codex.apps(), &[AppType::Codex]);
|
||||
for scope in ProfileScope::ALL {
|
||||
for app in scope.apps() {
|
||||
assert_eq!(ProfileScope::for_app(app), Some(scope));
|
||||
}
|
||||
}
|
||||
assert_eq!(ProfileScope::for_app(&AppType::Gemini), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_plan_toggles_minimal_diff() {
|
||||
let current = vec![
|
||||
("a".to_string(), true), // 目标含 a:不动
|
||||
("b".to_string(), false), // 目标含 b:开
|
||||
("c".to_string(), true), // 目标不含 c:关
|
||||
("d".to_string(), false), // 目标不含 d:不动
|
||||
];
|
||||
let (toggles, dangling) = plan_toggles(¤t, &ids(&["a", "b", "ghost"]));
|
||||
assert_eq!(
|
||||
toggles,
|
||||
vec![("b".to_string(), true), ("c".to_string(), false)]
|
||||
);
|
||||
assert_eq!(dangling, ids(&["ghost"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_plan_toggles_empty_target_disables_all_enabled() {
|
||||
let current = vec![("a".to_string(), true), ("b".to_string(), false)];
|
||||
let (toggles, dangling) = plan_toggles(¤t, &[]);
|
||||
assert_eq!(toggles, vec![("a".to_string(), false)]);
|
||||
assert!(dangling.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,148 @@ use super::gemini_auth::{
|
||||
};
|
||||
use super::normalize_claude_models_in_value;
|
||||
|
||||
/// ChatGPT Codex catalogs gpt-5.6 at a 372K context window with a ~353K
|
||||
/// effective budget (openai/codex#31860), far below the 1.05M API spec.
|
||||
/// Declare the catalog window for both knobs: Claude Code's built-in output
|
||||
/// reserve and compact buffer already keep the actual compact trigger
|
||||
/// (~278K-339K) below the effective budget, so anything lower only wastes
|
||||
/// usable context.
|
||||
const CODEX_OAUTH_CLAUDE_MAX_CONTEXT_TOKENS: &str = "372000";
|
||||
const CODEX_OAUTH_CLAUDE_AUTO_COMPACT_WINDOW: &str = "372000";
|
||||
const KIMI_FOR_CODING_CONTEXT_TOKENS: &str = "262144";
|
||||
|
||||
/// Model env keys Claude Code may route requests through. The defaults above
|
||||
/// are calibrated against gpt-5.6's Codex catalog, so every configured model
|
||||
/// must belong to that family before they are injected — gpt-5.5's upstream
|
||||
/// catalog oscillates between 272K and 372K and must not inherit them.
|
||||
const CODEX_OAUTH_MODEL_ENV_KEYS: [&str; 6] = [
|
||||
"ANTHROPIC_MODEL",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL",
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL",
|
||||
];
|
||||
|
||||
fn provider_env_targets_gpt56(provider_env: Option<&serde_json::Map<String, Value>>) -> bool {
|
||||
let Some(env) = provider_env else {
|
||||
return false;
|
||||
};
|
||||
let mut saw_model = false;
|
||||
for key in CODEX_OAUTH_MODEL_ENV_KEYS {
|
||||
let Some(value) = env.get(key) else {
|
||||
continue;
|
||||
};
|
||||
let Some(model) = value.as_str() else {
|
||||
return false;
|
||||
};
|
||||
let model = model.trim();
|
||||
if model.is_empty() {
|
||||
continue;
|
||||
}
|
||||
saw_model = true;
|
||||
if !model.to_ascii_lowercase().starts_with("gpt-5.6") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
saw_model
|
||||
}
|
||||
|
||||
fn is_kimi_for_coding_provider(provider: &Provider) -> bool {
|
||||
provider
|
||||
.settings_config
|
||||
.pointer("/env/ANTHROPIC_BASE_URL")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.map(|url| url.trim_end_matches('/'))
|
||||
== Some("https://api.kimi.com/coding")
|
||||
}
|
||||
|
||||
/// Claude Code assigns unknown non-Claude model ids a 200K context window.
|
||||
/// Codex OAuth deliberately exposes GPT ids through Claude Code, so enrich the
|
||||
/// effective live settings for both newly-created and already-saved providers.
|
||||
/// Explicit user values always win; the defaults are only injected when every
|
||||
/// configured model targets gpt-5.6.
|
||||
fn apply_codex_oauth_claude_context_defaults(settings: &mut Value, provider: &Provider) {
|
||||
if !provider.is_codex_oauth() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Read provider-owned values before mutably borrowing the effective
|
||||
// settings. This also deliberately prevents a legacy common-config
|
||||
// snippet from overriding model-specific context limits.
|
||||
let provider_env = provider
|
||||
.settings_config
|
||||
.get("env")
|
||||
.and_then(Value::as_object);
|
||||
let Some(root) = settings.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
let env = root.entry("env".to_string()).or_insert_with(|| json!({}));
|
||||
let Some(env) = env.as_object_mut() else {
|
||||
log::warn!(
|
||||
"Cannot apply Codex OAuth Claude context defaults for '{}': env is not an object",
|
||||
provider.id
|
||||
);
|
||||
return;
|
||||
};
|
||||
|
||||
let inject_defaults = provider_env_targets_gpt56(provider_env);
|
||||
for (key, default_value) in [
|
||||
(
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS",
|
||||
CODEX_OAUTH_CLAUDE_MAX_CONTEXT_TOKENS,
|
||||
),
|
||||
(
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
|
||||
CODEX_OAUTH_CLAUDE_AUTO_COMPACT_WINDOW,
|
||||
),
|
||||
] {
|
||||
match provider_env.and_then(|provider_env| provider_env.get(key)) {
|
||||
Some(value) => {
|
||||
env.insert(key.to_string(), value.clone());
|
||||
}
|
||||
None if inject_defaults => {
|
||||
env.insert(key.to_string(), Value::String(default_value.to_string()));
|
||||
}
|
||||
// 老模型不注入默认值,同时剥掉遗留共享片段可能带进来的值
|
||||
None => {
|
||||
env.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Kimi For Coding serves a 256K window, but Claude Code caps unknown models at
|
||||
/// 200K unless `CLAUDE_CODE_MAX_CONTEXT_TOKENS` is set — and that env is ignored
|
||||
/// for `claude-`-prefixed ids, so these defaults only bite when the provider also
|
||||
/// routes the endpoint's `kimi-for-coding` alias (the preset does). Keep the
|
||||
/// defaults provider-owned so an old shared snippet cannot override them.
|
||||
fn apply_kimi_for_coding_context_defaults(settings: &mut Value, provider: &Provider) {
|
||||
if !is_kimi_for_coding_provider(provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
let provider_env = provider
|
||||
.settings_config
|
||||
.get("env")
|
||||
.and_then(Value::as_object);
|
||||
let Some(env) = settings.get_mut("env").and_then(Value::as_object_mut) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for key in [
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
|
||||
] {
|
||||
let value = provider_env
|
||||
.and_then(|provider_env| provider_env.get(key))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| Value::String(KIMI_FOR_CODING_CONTEXT_TOKENS.to_string()));
|
||||
env.insert(key.to_string(), value);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_claude_settings_for_live(settings: &Value) -> Value {
|
||||
let mut v = settings.clone();
|
||||
if let Some(obj) = v.as_object_mut() {
|
||||
@@ -306,6 +448,40 @@ fn remove_toml_table_like(target: &mut dyn TableLike, source: &dyn TableLike) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 前端表单勾选/取消"使用通用配置"时,对编辑器里的 config.toml 文本做
|
||||
/// 结构化合并/剥离。必须在后端用 toml_edit 做:前端 smol-toml 只能
|
||||
/// parse → merge → 整文档重序列化,注释全丢、键序重排,还会生成多余的
|
||||
/// 空父表头(如 `[model_providers]`)。
|
||||
pub fn update_toml_common_config_snippet(
|
||||
config_toml: &str,
|
||||
snippet_toml: &str,
|
||||
enabled: bool,
|
||||
) -> Result<String, AppError> {
|
||||
let trimmed = snippet_toml.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(config_toml.to_string());
|
||||
}
|
||||
|
||||
let mut target_doc = if config_toml.trim().is_empty() {
|
||||
DocumentMut::new()
|
||||
} else {
|
||||
config_toml
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex config.toml: {e}")))?
|
||||
};
|
||||
let source_doc = trimmed
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|e| AppError::Message(format!("Invalid Codex common config snippet: {e}")))?;
|
||||
|
||||
if enabled {
|
||||
merge_toml_table_like(target_doc.as_table_mut(), source_doc.as_table());
|
||||
} else {
|
||||
remove_toml_table_like(target_doc.as_table_mut(), source_doc.as_table());
|
||||
}
|
||||
|
||||
Ok(target_doc.to_string())
|
||||
}
|
||||
|
||||
fn settings_contain_common_config(app_type: &AppType, settings: &Value, snippet: &str) -> bool {
|
||||
let trimmed = snippet.trim();
|
||||
if trimmed.is_empty() {
|
||||
@@ -503,6 +679,11 @@ pub(crate) fn build_effective_settings_with_common_config(
|
||||
}
|
||||
}
|
||||
|
||||
if matches!(app_type, AppType::Claude) {
|
||||
apply_codex_oauth_claude_context_defaults(&mut effective_settings, provider);
|
||||
apply_kimi_for_coding_context_defaults(&mut effective_settings, provider);
|
||||
}
|
||||
|
||||
Ok(effective_settings)
|
||||
}
|
||||
|
||||
@@ -570,11 +751,80 @@ pub(crate) fn strip_common_config_from_live_settings(
|
||||
restore_live_settings_for_provider_backfill(app_type, provider, backfill_settings)
|
||||
}
|
||||
|
||||
/// 与 `apply_codex_oauth_claude_context_defaults` 严格对称:注入产物只活在
|
||||
/// live,切走回填时必须剥掉,否则程序默认值会固化成供应商的"用户显式值",
|
||||
/// 之后调整默认值或更换模型时旧值永远压住新默认。仅当"注入会发生且注入的
|
||||
/// 就是这个值、且存储配置本来没有显式值"时才剥;用户显式存储的值和手改
|
||||
/// live 成其他数字的值都保留。
|
||||
fn strip_injected_codex_oauth_context_defaults(settings: &mut Value, provider: &Provider) {
|
||||
if !provider.is_codex_oauth() {
|
||||
return;
|
||||
}
|
||||
let provider_env = provider
|
||||
.settings_config
|
||||
.get("env")
|
||||
.and_then(Value::as_object);
|
||||
if !provider_env_targets_gpt56(provider_env) {
|
||||
return;
|
||||
}
|
||||
let Some(env) = settings.get_mut("env").and_then(Value::as_object_mut) else {
|
||||
return;
|
||||
};
|
||||
for (key, default_value) in [
|
||||
(
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS",
|
||||
CODEX_OAUTH_CLAUDE_MAX_CONTEXT_TOKENS,
|
||||
),
|
||||
(
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
|
||||
CODEX_OAUTH_CLAUDE_AUTO_COMPACT_WINDOW,
|
||||
),
|
||||
] {
|
||||
let stored_explicit = provider_env.is_some_and(|e| e.contains_key(key));
|
||||
if stored_explicit {
|
||||
continue;
|
||||
}
|
||||
if env.get(key).and_then(Value::as_str) == Some(default_value) {
|
||||
env.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_injected_kimi_for_coding_context_defaults(settings: &mut Value, provider: &Provider) {
|
||||
if !is_kimi_for_coding_provider(provider) {
|
||||
return;
|
||||
}
|
||||
let provider_env = provider
|
||||
.settings_config
|
||||
.get("env")
|
||||
.and_then(Value::as_object);
|
||||
let Some(env) = settings.get_mut("env").and_then(Value::as_object_mut) else {
|
||||
return;
|
||||
};
|
||||
for key in [
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
|
||||
] {
|
||||
if provider_env.is_some_and(|provider_env| provider_env.contains_key(key)) {
|
||||
continue;
|
||||
}
|
||||
if env.get(key).and_then(Value::as_str) == Some(KIMI_FOR_CODING_CONTEXT_TOKENS) {
|
||||
env.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_live_settings_for_provider_backfill(
|
||||
app_type: &AppType,
|
||||
provider: &Provider,
|
||||
live_settings: Value,
|
||||
) -> Value {
|
||||
if matches!(app_type, AppType::Claude) {
|
||||
let mut settings = live_settings;
|
||||
strip_injected_codex_oauth_context_defaults(&mut settings, provider);
|
||||
strip_injected_kimi_for_coding_context_defaults(&mut settings, provider);
|
||||
return settings;
|
||||
}
|
||||
if !matches!(app_type, AppType::Codex) {
|
||||
return live_settings;
|
||||
}
|
||||
@@ -596,6 +846,15 @@ fn restore_live_settings_for_provider_backfill(
|
||||
);
|
||||
}
|
||||
|
||||
// MCP 服务器归 DB mcp_servers 表所有,live 里的 [mcp_servers] 是同步投影;
|
||||
// 回填时剥掉,否则已删除的服务器会随供应商快照复活(逐条 reconcile 清不掉孤儿)。
|
||||
if let Err(err) = crate::codex_config::strip_codex_mcp_servers_from_settings(&mut settings) {
|
||||
log::warn!(
|
||||
"Failed to strip mcp_servers while backfilling '{}': {err}",
|
||||
provider.id
|
||||
);
|
||||
}
|
||||
|
||||
// 统一会话开关注入的共享 `custom` 路由只属于 live 配置;切换回填时
|
||||
// 必须剥掉,否则官方供应商的存储配置被污染,关闭开关后无法还原。
|
||||
if provider.category.as_deref() == Some("official") {
|
||||
@@ -760,12 +1019,11 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
|
||||
.ok_or_else(|| AppError::Config("Codex 供应商配置缺少 'auth' 字段".to_string()))?;
|
||||
let config_str = obj.get("config").and_then(|v| v.as_str());
|
||||
|
||||
// Native (direct) Responses providers must suppress Codex's freeform
|
||||
// apply_patch custom tool via the generated catalog; chat/proxy
|
||||
// providers keep the default tool set. Keyed on provider.meta.apiFormat.
|
||||
let profile = crate::codex_config::CodexCatalogToolProfile::from_api_format(
|
||||
provider.meta.as_ref().and_then(|m| m.api_format.as_deref()),
|
||||
);
|
||||
// Native (direct) Responses and Anthropic providers must suppress Codex's
|
||||
// freeform apply_patch custom tool via the generated catalog; chat/proxy
|
||||
// providers keep the default tool set. Uses the same Anthropic detection as
|
||||
// the proxy router (apiFormat meta/settings + TOML wire_api).
|
||||
let profile = crate::proxy::providers::resolve_codex_catalog_tool_profile(provider);
|
||||
|
||||
crate::codex_config::write_codex_provider_live_with_catalog(
|
||||
&provider.settings_config,
|
||||
@@ -939,7 +1197,10 @@ pub(crate) fn sync_current_provider_for_app_to_live(
|
||||
}
|
||||
}
|
||||
|
||||
McpService::sync_all_enabled(state)?;
|
||||
// 本函数语义是"把这个应用同步到 live",MCP 重投影也只针对该应用;
|
||||
// 全量 sync_all_enabled 会把无关应用的 live 损坏牵连进来。投影失败
|
||||
// 上抛(不降级):这里没有已变更的 DB 状态需要保护,调用方重试即可。
|
||||
McpService::sync_enabled_for_app(state, app_type)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1007,8 +1268,10 @@ pub fn sync_current_to_live(state: &AppState) -> Result<(), AppError> {
|
||||
}
|
||||
}
|
||||
|
||||
// MCP sync
|
||||
McpService::sync_all_enabled(state)?;
|
||||
// MCP sync(best-effort 逐应用投影,内部已聚合失败)。错误暂存到
|
||||
// Skill 同步之后再返回:MCP 的失败不该跳过 Skill 同步,但调用方
|
||||
//(配置导入 / 云同步恢复)需要知道结果不完整。
|
||||
let mcp_result = McpService::sync_all_enabled(state);
|
||||
|
||||
// Skill sync
|
||||
for app_type in AppType::all() {
|
||||
@@ -1018,7 +1281,7 @@ pub fn sync_current_to_live(state: &AppState) -> Result<(), AppError> {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
mcp_result
|
||||
}
|
||||
|
||||
/// Read current live settings for an app type
|
||||
@@ -1404,15 +1667,10 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
}
|
||||
|
||||
let mut imported = 0;
|
||||
let mut updated = 0;
|
||||
let existing_ids = state.db.get_provider_ids("opencode")?;
|
||||
|
||||
for (id, config) in providers {
|
||||
// Skip if already exists in database
|
||||
if existing_ids.contains(&id) {
|
||||
log::debug!("OpenCode provider '{id}' already exists in database, skipping");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Convert to Value for settings_config
|
||||
let settings_config = match serde_json::to_value(&config) {
|
||||
Ok(v) => v,
|
||||
@@ -1422,13 +1680,36 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
}
|
||||
};
|
||||
|
||||
if existing_ids.contains(&id) {
|
||||
match state.db.get_provider_by_id(&id, "opencode") {
|
||||
Ok(Some(existing)) => {
|
||||
let display_name = config.name.clone().unwrap_or_else(|| existing.name.clone());
|
||||
if existing.settings_config != settings_config || existing.name != display_name
|
||||
{
|
||||
let mut provider = existing;
|
||||
provider.name = display_name;
|
||||
provider.settings_config = settings_config;
|
||||
if let Err(e) = state.db.save_provider("opencode", &provider) {
|
||||
log::warn!(
|
||||
"Failed to update OpenCode provider '{id}' from live config: {e}"
|
||||
);
|
||||
} else {
|
||||
updated += 1;
|
||||
log::info!("Updated OpenCode provider '{id}' from live config");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("OpenCode provider '{id}' disappeared while importing live config")
|
||||
}
|
||||
Err(e) => log::warn!("Failed to look up OpenCode provider '{id}': {e}"),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create provider
|
||||
let mut provider = Provider::with_id(
|
||||
id.clone(),
|
||||
config.name.clone().unwrap_or_else(|| id.clone()),
|
||||
settings_config,
|
||||
None,
|
||||
);
|
||||
let display_name = config.name.clone().unwrap_or_else(|| id.clone());
|
||||
let mut provider = Provider::with_id(id.clone(), display_name, settings_config, None);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
live_config_managed: Some(true),
|
||||
..Default::default()
|
||||
@@ -1444,7 +1725,7 @@ pub fn import_opencode_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
log::info!("Imported OpenCode provider '{id}' from live config");
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
Ok(imported + updated)
|
||||
}
|
||||
|
||||
/// Import all providers from OpenClaw live config to database
|
||||
@@ -1461,6 +1742,7 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
}
|
||||
|
||||
let mut imported = 0;
|
||||
let mut updated = 0;
|
||||
let existing_ids = state.db.get_provider_ids("openclaw")?;
|
||||
|
||||
for (id, config) in providers {
|
||||
@@ -1474,12 +1756,6 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if already exists in database
|
||||
if existing_ids.contains(&id) {
|
||||
log::debug!("OpenClaw provider '{id}' already exists in database, skipping");
|
||||
continue;
|
||||
}
|
||||
|
||||
// Convert to Value for settings_config
|
||||
let settings_config = match serde_json::to_value(&config) {
|
||||
Ok(v) => v,
|
||||
@@ -1489,6 +1765,30 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
}
|
||||
};
|
||||
|
||||
if existing_ids.contains(&id) {
|
||||
match state.db.get_provider_by_id(&id, "openclaw") {
|
||||
Ok(Some(existing)) => {
|
||||
if existing.settings_config != settings_config {
|
||||
let mut provider = existing;
|
||||
provider.settings_config = settings_config;
|
||||
if let Err(e) = state.db.save_provider("openclaw", &provider) {
|
||||
log::warn!(
|
||||
"Failed to update OpenClaw provider '{id}' from live config: {e}"
|
||||
);
|
||||
} else {
|
||||
updated += 1;
|
||||
log::info!("Updated OpenClaw provider '{id}' from live config");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("OpenClaw provider '{id}' disappeared while importing live config")
|
||||
}
|
||||
Err(e) => log::warn!("Failed to look up OpenClaw provider '{id}': {e}"),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Determine display name: use first model name if available, otherwise use id
|
||||
let display_name = config
|
||||
.models
|
||||
@@ -1513,7 +1813,7 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
|
||||
log::info!("Imported OpenClaw provider '{id}' from live config");
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
Ok(imported + updated)
|
||||
}
|
||||
|
||||
/// Import all providers from Hermes live config to database
|
||||
@@ -1530,6 +1830,7 @@ pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppE
|
||||
}
|
||||
|
||||
let mut imported = 0;
|
||||
let mut updated = 0;
|
||||
let existing_ids = state.db.get_provider_ids("hermes")?;
|
||||
|
||||
for (name, config) in providers {
|
||||
@@ -1539,9 +1840,27 @@ pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppE
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if already exists in database
|
||||
if existing_ids.contains(&name) {
|
||||
log::debug!("Hermes provider '{name}' already exists in database, skipping");
|
||||
match state.db.get_provider_by_id(&name, "hermes") {
|
||||
Ok(Some(existing)) => {
|
||||
if existing.settings_config != config {
|
||||
let mut provider = existing;
|
||||
provider.settings_config = config;
|
||||
if let Err(e) = state.db.save_provider("hermes", &provider) {
|
||||
log::warn!(
|
||||
"Failed to update Hermes provider '{name}' from live config: {e}"
|
||||
);
|
||||
} else {
|
||||
updated += 1;
|
||||
log::info!("Updated Hermes provider '{name}' from live config");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
log::warn!("Hermes provider '{name}' disappeared while importing live config")
|
||||
}
|
||||
Err(e) => log::warn!("Failed to look up Hermes provider '{name}': {e}"),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1562,7 +1881,7 @@ pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppE
|
||||
log::info!("Imported Hermes provider '{name}' from live config");
|
||||
}
|
||||
|
||||
Ok(imported)
|
||||
Ok(imported + updated)
|
||||
}
|
||||
|
||||
/// Remove a Hermes provider from live config
|
||||
@@ -1608,6 +1927,383 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn kimi_for_coding_effective_settings_backfill_256k_context() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let provider = Provider::with_id(
|
||||
"kimi-for-coding".to_string(),
|
||||
"Kimi For Coding".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.kimi.com/coding/",
|
||||
"ANTHROPIC_MODEL": "kimi-for-coding",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "262144"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("262144")
|
||||
);
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("262144")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kimi_for_coding_context_defaults_preserve_user_overrides() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let provider = Provider::with_id(
|
||||
"kimi-for-coding".to_string(),
|
||||
"Kimi For Coding".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.kimi.com/coding",
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "300000",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "250000"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("300000")
|
||||
);
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("250000")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kimi_for_coding_backfill_strips_only_injected_context_default() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let provider = Provider::with_id(
|
||||
"kimi-for-coding".to_string(),
|
||||
"Kimi For Coding".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_BASE_URL": "https://api.kimi.com/coding/",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "262144"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
let live = build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
let backfilled =
|
||||
strip_common_config_from_live_settings(&db, &AppType::Claude, &provider, live);
|
||||
assert!(backfilled["env"]
|
||||
.get("CLAUDE_CODE_MAX_CONTEXT_TOKENS")
|
||||
.is_none());
|
||||
assert_eq!(
|
||||
backfilled["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("262144")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_oauth_effective_settings_backfill_gpt_context_defaults() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "gpt-5.6"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("372000")
|
||||
);
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("372000")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_oauth_context_defaults_preserve_user_overrides() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "500000",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "350000"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("500000")
|
||||
);
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("350000")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_oauth_context_defaults_ignore_legacy_common_config_values() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
db.set_config_snippet(
|
||||
AppType::Claude.as_str(),
|
||||
Some(
|
||||
json!({
|
||||
"env": {
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "262144",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "262144"
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
)
|
||||
.expect("save legacy common config");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_MODEL": "gpt-5.6" } }),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
common_config_enabled: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("372000")
|
||||
);
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("372000")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_oauth_context_defaults_skip_non_gpt56_models() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
db.set_config_snippet(
|
||||
AppType::Claude.as_str(),
|
||||
Some(
|
||||
json!({
|
||||
"env": {
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "262144",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "262144"
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
)
|
||||
.expect("save legacy common config");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "gpt-5.5",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "300000"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
common_config_enabled: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let effective =
|
||||
build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
// 旧模型不注入 372K 默认值,遗留共享片段带进来的值也要剥掉
|
||||
assert!(effective["env"]
|
||||
.get("CLAUDE_CODE_MAX_CONTEXT_TOKENS")
|
||||
.is_none());
|
||||
// 用户显式写在供应商配置里的值仍然生效
|
||||
assert_eq!(
|
||||
effective["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("300000")
|
||||
);
|
||||
}
|
||||
|
||||
/// 往返不动点:注入产物只活在 live,切走回灌后存储配置必须与注入前一致,
|
||||
/// 否则程序默认值固化成"用户显式值",之后调默认值永远压不动。
|
||||
#[test]
|
||||
fn codex_oauth_backfill_strips_injected_context_defaults() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({ "env": { "ANTHROPIC_MODEL": "gpt-5.6" } }),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// 模拟写 live:注入了两个上下文默认值
|
||||
let live = build_effective_settings_with_common_config(&db, &AppType::Claude, &provider)
|
||||
.expect("build effective settings");
|
||||
assert_eq!(
|
||||
live["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("372000")
|
||||
);
|
||||
|
||||
// 模拟切走回灌:注入产物被剥掉,其余字段原样保留
|
||||
let backfilled =
|
||||
strip_common_config_from_live_settings(&db, &AppType::Claude, &provider, live);
|
||||
assert!(backfilled["env"]
|
||||
.get("CLAUDE_CODE_MAX_CONTEXT_TOKENS")
|
||||
.is_none());
|
||||
assert!(backfilled["env"]
|
||||
.get("CLAUDE_CODE_AUTO_COMPACT_WINDOW")
|
||||
.is_none());
|
||||
assert_eq!(backfilled["env"]["ANTHROPIC_MODEL"], json!("gpt-5.6"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_oauth_backfill_keeps_user_context_values() {
|
||||
let db = Database::memory().expect("create memory db");
|
||||
let mut provider = Provider::with_id(
|
||||
"codex-oauth".to_string(),
|
||||
"Codex".to_string(),
|
||||
json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "gpt-5.6",
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "500000"
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
provider.meta = Some(crate::provider::ProviderMeta {
|
||||
provider_type: Some("codex_oauth".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// live 里:MAX 是用户显式值;ACW 被用户手改成了非默认数字
|
||||
let live = json!({
|
||||
"env": {
|
||||
"ANTHROPIC_MODEL": "gpt-5.6",
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "500000",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "300000"
|
||||
}
|
||||
});
|
||||
let backfilled =
|
||||
strip_common_config_from_live_settings(&db, &AppType::Claude, &provider, live);
|
||||
assert_eq!(
|
||||
backfilled["env"]["CLAUDE_CODE_MAX_CONTEXT_TOKENS"],
|
||||
json!("500000")
|
||||
);
|
||||
assert_eq!(
|
||||
backfilled["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"],
|
||||
json!("300000")
|
||||
);
|
||||
}
|
||||
|
||||
/// C5 回归锁:前端表单的合并/剥离必须走 toml_edit 文档模型。
|
||||
/// smol-toml 的 parse→merge→stringify 整文档重序列化会丢注释、
|
||||
/// 按字母序重排键、并为 dotted 表生成多余的空父表头。
|
||||
#[test]
|
||||
fn update_toml_common_config_snippet_preserves_comments_and_key_order() {
|
||||
// 刻意非字母序的键序 + 注释,模拟用户手写格式
|
||||
let config = r#"# my precious comment
|
||||
model = "gpt-5.5"
|
||||
model_provider = "aprov"
|
||||
disable_response_storage = true
|
||||
|
||||
[model_providers.aprov]
|
||||
# provider comment
|
||||
name = "A Prov"
|
||||
base_url = "https://a.example/v1"
|
||||
"#;
|
||||
let snippet = "[tui]\nnotifications = true\n";
|
||||
|
||||
let merged = update_toml_common_config_snippet(config, snippet, true).unwrap();
|
||||
assert!(merged.contains("# my precious comment"));
|
||||
assert!(merged.contains("# provider comment"));
|
||||
let model_pos = merged.find("model = ").unwrap();
|
||||
let provider_pos = merged.find("model_provider = ").unwrap();
|
||||
let disable_pos = merged.find("disable_response_storage").unwrap();
|
||||
assert!(
|
||||
model_pos < provider_pos && provider_pos < disable_pos,
|
||||
"merge must not reorder user keys, got: {merged}"
|
||||
);
|
||||
assert!(merged.contains("[tui]"));
|
||||
assert!(merged.contains("notifications = true"));
|
||||
assert!(
|
||||
!merged.contains("[model_providers]\n"),
|
||||
"merge must not synthesize an empty parent table header, got: {merged}"
|
||||
);
|
||||
|
||||
let removed = update_toml_common_config_snippet(&merged, snippet, false).unwrap();
|
||||
assert!(!removed.contains("[tui]"), "snippet keys must be stripped");
|
||||
assert!(removed.contains("# my precious comment"));
|
||||
assert!(removed.contains("disable_response_storage = true"));
|
||||
}
|
||||
|
||||
/// 合并时标量=片段覆盖供应商值(与 Claude 侧 deepMerge 一致);
|
||||
/// 剥离按值匹配:用户改过的值不删(与 strip 路径的
|
||||
/// toml_value_is_subset 语义一致)。
|
||||
#[test]
|
||||
fn update_toml_common_config_snippet_scalar_override_and_value_matched_removal() {
|
||||
let snippet = "[tui]\nnotifications = true\n";
|
||||
|
||||
let merged =
|
||||
update_toml_common_config_snippet("[tui]\nnotifications = false\n", snippet, true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
merged.contains("notifications = true"),
|
||||
"snippet scalar should override provider value, got: {merged}"
|
||||
);
|
||||
|
||||
let removed =
|
||||
update_toml_common_config_snippet("[tui]\nnotifications = false\n", snippet, false)
|
||||
.unwrap();
|
||||
assert!(
|
||||
removed.contains("notifications = false"),
|
||||
"user-modified value must survive removal, got: {removed}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_common_config_apply_and_remove_roundtrip_for_non_overlapping_fields() {
|
||||
let settings = json!({
|
||||
@@ -1804,4 +2500,40 @@ mod tests {
|
||||
"backfill must keep the Live-reconstructed catalog when the DB has none"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_switch_backfill_strips_synced_mcp_servers() {
|
||||
// Live 里的 [mcp_servers] 是 MCP 同步的投影(SSOT 在 DB 表),
|
||||
// 回填进供应商存储配置会让已删除的服务器随快照复活。
|
||||
let provider = Provider::with_id(
|
||||
"prov".to_string(),
|
||||
"Prov".to_string(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-test" },
|
||||
"config": "model = \"gpt-5.5\"\n"
|
||||
}),
|
||||
None,
|
||||
);
|
||||
|
||||
let live_settings = json!({
|
||||
"auth": { "OPENAI_API_KEY": "sk-test" },
|
||||
"config": "model = \"gpt-5.5\"\n\n[mcp_servers.echo]\ntype = \"stdio\"\ncommand = \"echo\"\n"
|
||||
});
|
||||
|
||||
let result =
|
||||
restore_live_settings_for_provider_backfill(&AppType::Codex, &provider, live_settings);
|
||||
|
||||
let config_text = result
|
||||
.get("config")
|
||||
.and_then(|v| v.as_str())
|
||||
.expect("config text");
|
||||
assert!(
|
||||
!config_text.contains("mcp_servers"),
|
||||
"backfill must strip synced [mcp_servers] from the stored provider config, got: {config_text}"
|
||||
);
|
||||
assert!(
|
||||
config_text.contains("model = \"gpt-5.5\""),
|
||||
"non-MCP content must survive the strip"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ pub use live::{
|
||||
import_default_config, import_hermes_providers_from_live, import_openclaw_providers_from_live,
|
||||
import_opencode_providers_from_live, read_live_settings,
|
||||
should_import_default_config_on_startup, sync_current_to_live,
|
||||
update_toml_common_config_snippet,
|
||||
};
|
||||
|
||||
// Internal re-exports (pub(crate))
|
||||
@@ -42,6 +43,14 @@ use live::{
|
||||
};
|
||||
use usage::validate_usage_script;
|
||||
|
||||
/// The built-in Codex official provider is safe to select during takeover:
|
||||
/// Codex keeps ownership of its ChatGPT login and the proxy only forwards the
|
||||
/// authenticated request. Other official providers retain the existing block.
|
||||
pub fn official_provider_supports_proxy_takeover(app_type: &AppType, provider: &Provider) -> bool {
|
||||
matches!(app_type, AppType::Codex)
|
||||
&& crate::proxy::providers::is_codex_official_provider(provider)
|
||||
}
|
||||
|
||||
/// 统一会话开关变更后,立即按新开关状态重写当前官方 Codex 供应商的
|
||||
/// live 配置,使开关即时生效(无需等下一次切换)。
|
||||
/// 当前供应商非官方(或不存在)时为 no-op:注入只作用于官方配置,
|
||||
@@ -81,6 +90,18 @@ pub fn reapply_current_codex_official_live(state: &AppState) -> Result<bool, App
|
||||
}
|
||||
|
||||
live::write_live_with_common_config(&state.db, &AppType::Codex, provider)?;
|
||||
// 重写 live 会整体替换 config.toml(有意设计),[mcp_servers] 随之丢失,
|
||||
// 写完必须立刻从 DB 重新投影启用的 MCP。只投影 Codex 而非
|
||||
// sync_all_enabled:后者按 AppType::all() 顺序逐应用短路,排在 Codex
|
||||
// 前面的无关应用 live 损坏(如 ~/.claude.json 坏 JSON)会阻断 Codex
|
||||
// 的重投影,让刚被清掉的 [mcp_servers] 无人补回。
|
||||
// 投影失败降级为警告:走到这里 live 已按新开关状态落盘,开关事实上
|
||||
// 已生效;若把错误上抛,save_settings 会回滚开关设置,制造"设置=旧值、
|
||||
// live=新桶"的会话分裂——正是该回滚要防止的状态。MCP 投影可自愈
|
||||
// (下次切换 / 任一 MCP 启停操作都会重新投影)。
|
||||
if let Err(err) = McpService::sync_enabled_for_app(state, &AppType::Codex) {
|
||||
log::warn!("统一会话开关重写 live 后重投影 Codex MCP 失败(将在下次同步时自愈): {err}");
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -260,6 +281,8 @@ mod tests {
|
||||
coding_plan_provider: None,
|
||||
access_key_id: Some("ak-test".to_string()),
|
||||
secret_access_key: Some("sk-test".to_string()),
|
||||
team_organization_id: None,
|
||||
team_project_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +333,32 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn hermes_provider(id: &str) -> Provider {
|
||||
Provider {
|
||||
id: id.to_string(),
|
||||
name: format!("Provider {id}"),
|
||||
settings_config: json!({
|
||||
"api": "openai-chat",
|
||||
"base_url": "https://api.example.com/v1",
|
||||
"api_key": "test-key",
|
||||
"models": {
|
||||
"gpt-4o": {
|
||||
"name": "GPT-4o"
|
||||
}
|
||||
}
|
||||
}),
|
||||
website_url: None,
|
||||
category: Some("custom".to_string()),
|
||||
created_at: Some(1),
|
||||
sort_index: Some(0),
|
||||
notes: None,
|
||||
meta: None,
|
||||
icon: None,
|
||||
icon_color: None,
|
||||
in_failover_queue: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn opencode_provider(id: &str) -> Provider {
|
||||
Provider {
|
||||
id: id.to_string(),
|
||||
@@ -672,6 +721,9 @@ mod tests {
|
||||
"AWS_BEARER_TOKEN_BEDROCK": "bedrock-tok",
|
||||
"ANTHROPIC_BASE_URL": "https://example.com",
|
||||
"ANTHROPIC_MODEL": "claude-x",
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL": "gpt-5.4-mini",
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "400000",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "400000",
|
||||
// 可共享、非机密配置(复数 _TOKENS 不应被误剥)
|
||||
"ENABLE_TOOL_SEARCH": "true",
|
||||
"CLAUDE_CODE_MAX_OUTPUT_TOKENS": "8192"
|
||||
@@ -714,6 +766,15 @@ mod tests {
|
||||
// 端点/模型(provider-specific 非机密)也应剥掉
|
||||
assert!(env.and_then(|e| e.get("ANTHROPIC_BASE_URL")).is_none());
|
||||
assert!(env.and_then(|e| e.get("ANTHROPIC_MODEL")).is_none());
|
||||
assert!(env
|
||||
.and_then(|e| e.get("CLAUDE_CODE_SUBAGENT_MODEL"))
|
||||
.is_none());
|
||||
assert!(env
|
||||
.and_then(|e| e.get("CLAUDE_CODE_MAX_CONTEXT_TOKENS"))
|
||||
.is_none());
|
||||
assert!(env
|
||||
.and_then(|e| e.get("CLAUDE_CODE_AUTO_COMPACT_WINDOW"))
|
||||
.is_none());
|
||||
|
||||
// 可共享的非机密配置必须保留(含复数 _TOKENS 不被误剥)
|
||||
assert_eq!(
|
||||
@@ -730,6 +791,56 @@ mod tests {
|
||||
assert_eq!(value.get("includeCoAuthoredBy"), Some(&json!(false)));
|
||||
}
|
||||
|
||||
/// Regression for issue #4272: Fable tier env keys must not enter the shared
|
||||
/// Claude common-config snippet (same class as haiku/sonnet/opus model pins).
|
||||
#[test]
|
||||
fn extract_claude_common_config_strips_fable_model_env_keys() {
|
||||
let settings = json!({
|
||||
"env": {
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME": "Haiku Mapped",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped[1M]",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL_NAME": "Sonnet Mapped",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped[1M]",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL_NAME": "Opus Mapped",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL": "deepseek-v4-flash[1M]",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL_NAME": "deepseek-v4-flash",
|
||||
"ANTHROPIC_MODEL": "default-mapped",
|
||||
"ENABLE_TOOL_SEARCH": "true"
|
||||
},
|
||||
"theme": "dark"
|
||||
});
|
||||
|
||||
let snippet = ProviderService::extract_claude_common_config(&settings)
|
||||
.expect("extract should succeed");
|
||||
let value: Value = serde_json::from_str(&snippet).expect("snippet is valid JSON");
|
||||
let env = value.get("env");
|
||||
|
||||
for stripped in [
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
|
||||
"ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL_NAME",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL",
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL_NAME",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL_NAME",
|
||||
"ANTHROPIC_MODEL",
|
||||
] {
|
||||
assert!(
|
||||
env.and_then(|e| e.get(stripped)).is_none(),
|
||||
"provider-specific model key {stripped} must not enter common config"
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
env.and_then(|e| e.get("ENABLE_TOOL_SEARCH"))
|
||||
.and_then(|v| v.as_str()),
|
||||
Some("true")
|
||||
);
|
||||
assert_eq!(value.get("theme").and_then(|v| v.as_str()), Some("dark"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_provider_settings_rejects_negative_cost_multiplier() {
|
||||
let mut provider = Provider::with_id(
|
||||
@@ -779,10 +890,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_codex_common_config_preserves_mcp_servers_base_url() {
|
||||
fn extract_codex_common_config_strips_provider_fields_and_injected_artifacts() {
|
||||
// 顶层 experimental_bearer_token 模拟无活跃路由时的 fallback 注入;
|
||||
// web_search = "disabled" 是 cc-switch 对黑名单网关注入的哨兵;
|
||||
// 顶层 wire_api 模拟无 model_provider 时的 fallback 写法;
|
||||
// [mcp.servers] 是历史错误格式,sync_all_enabled 清不掉它。
|
||||
let config_toml = r#"model_provider = "azure"
|
||||
model = "gpt-4"
|
||||
wire_api = "chat"
|
||||
disable_response_storage = true
|
||||
experimental_bearer_token = "sk-live-secret"
|
||||
model_catalog_json = "cc-switch-model-catalog.json"
|
||||
web_search = "disabled"
|
||||
|
||||
[model_providers.azure]
|
||||
name = "Azure OpenAI"
|
||||
@@ -791,6 +910,9 @@ wire_api = "responses"
|
||||
|
||||
[mcp_servers.my_server]
|
||||
base_url = "http://localhost:8080"
|
||||
|
||||
[mcp.servers.legacy_server]
|
||||
command = "legacy-cmd"
|
||||
"#;
|
||||
|
||||
let settings = json!({ "config": config_toml });
|
||||
@@ -813,9 +935,51 @@ base_url = "http://localhost:8080"
|
||||
!extracted.contains("[model_providers"),
|
||||
"should remove entire model_providers table"
|
||||
);
|
||||
// MCP 归 DB mcp_servers 表所有,不得进共享片段(含历史错误格式 [mcp.servers])
|
||||
assert!(
|
||||
extracted.contains("http://localhost:8080"),
|
||||
"should keep mcp_servers.* base_url"
|
||||
!extracted.contains("mcp_servers") && !extracted.contains("http://localhost:8080"),
|
||||
"should strip mcp_servers from the shared snippet, got: {extracted}"
|
||||
);
|
||||
assert!(
|
||||
!extracted.contains("[mcp") && !extracted.contains("legacy-cmd"),
|
||||
"should strip the legacy [mcp.servers] form from the shared snippet, got: {extracted}"
|
||||
);
|
||||
// 顶层 wire_api 是供应商路由语义(model_providers 整表已剥,
|
||||
// 剩余任何 wire_api 都意味着泄漏)
|
||||
assert!(
|
||||
!extracted.contains("wire_api"),
|
||||
"should strip top-level wire_api from the shared snippet, got: {extracted}"
|
||||
);
|
||||
// 注入产物不得进共享片段(bearer token 泄漏为密钥级问题)
|
||||
assert!(
|
||||
!extracted.contains("experimental_bearer_token")
|
||||
&& !extracted.contains("sk-live-secret"),
|
||||
"should strip top-level fallback bearer token, got: {extracted}"
|
||||
);
|
||||
assert!(
|
||||
!extracted.contains("model_catalog_json"),
|
||||
"should strip catalog projection pointer, got: {extracted}"
|
||||
);
|
||||
assert!(
|
||||
!extracted.contains("web_search"),
|
||||
"should strip the cc-switch web_search disabled sentinel, got: {extracted}"
|
||||
);
|
||||
// 真正可共享的键保留
|
||||
assert!(
|
||||
extracted.contains("disable_response_storage = true"),
|
||||
"shareable keys must survive extraction, got: {extracted}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_codex_common_config_keeps_user_set_web_search() {
|
||||
let config_toml = "web_search = \"enabled\"\ndisable_response_storage = true\n";
|
||||
let settings = json!({ "config": config_toml });
|
||||
let extracted = ProviderService::extract_codex_common_config(&settings)
|
||||
.expect("extract should succeed");
|
||||
assert!(
|
||||
extracted.contains("web_search = \"enabled\""),
|
||||
"a user-set web_search value is a shareable preference, got: {extracted}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -944,6 +1108,135 @@ base_url = "http://localhost:8080"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn update_current_codex_provider_refreshes_and_clears_catalog_during_takeover() {
|
||||
let _home = TempHome::new();
|
||||
crate::settings::reload_settings().expect("reload settings");
|
||||
|
||||
let db = Arc::new(Database::memory().expect("init db"));
|
||||
let state = AppState::new(db.clone());
|
||||
|
||||
let mut original = Provider::with_id(
|
||||
"p1".into(),
|
||||
"Codex A".into(),
|
||||
json!({
|
||||
"auth": { "OPENAI_API_KEY": "token-a" },
|
||||
"config": r#"model_provider = "custom"
|
||||
model = "old-model"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "Codex A"
|
||||
base_url = "https://api.a.example/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = true
|
||||
"#,
|
||||
"modelCatalog": {
|
||||
"models": [{ "model": "old-model" }]
|
||||
}
|
||||
}),
|
||||
None,
|
||||
);
|
||||
original.meta = Some(ProviderMeta {
|
||||
api_format: Some("openai_responses".into()),
|
||||
..Default::default()
|
||||
});
|
||||
db.save_provider("codex", &original).expect("save provider");
|
||||
db.set_current_provider("codex", "p1")
|
||||
.expect("set current provider");
|
||||
crate::settings::set_current_provider(&AppType::Codex, Some("p1"))
|
||||
.expect("set local current provider");
|
||||
|
||||
db.update_proxy_config(ProxyConfig {
|
||||
live_takeover_active: true,
|
||||
listen_port: 0,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("update proxy config");
|
||||
{
|
||||
let mut config = db
|
||||
.get_proxy_config_for_app("codex")
|
||||
.await
|
||||
.expect("get app proxy config");
|
||||
config.enabled = true;
|
||||
db.update_proxy_config_for_app(config)
|
||||
.await
|
||||
.expect("enable Codex proxy config");
|
||||
}
|
||||
db.save_live_backup(
|
||||
"codex",
|
||||
&serde_json::to_string(&original.settings_config).expect("serialize backup"),
|
||||
)
|
||||
.await
|
||||
.expect("seed live backup");
|
||||
|
||||
state
|
||||
.proxy_service
|
||||
.start()
|
||||
.await
|
||||
.expect("start proxy service");
|
||||
state
|
||||
.proxy_service
|
||||
.sync_codex_live_from_provider_while_proxy_active(&original)
|
||||
.await
|
||||
.expect("seed taken-over Codex live config");
|
||||
assert!(
|
||||
state
|
||||
.proxy_service
|
||||
.detect_takeover_in_live_config_for_app(&AppType::Codex),
|
||||
"seeded Codex live config should be recognized as takeover-owned"
|
||||
);
|
||||
|
||||
let mut updated = original.clone();
|
||||
updated.settings_config["config"] = json!(
|
||||
r#"model_provider = "custom"
|
||||
model = "gpt-5.4"
|
||||
|
||||
[model_providers.custom]
|
||||
name = "Codex A"
|
||||
base_url = "https://api.updated.example/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = true
|
||||
"#
|
||||
);
|
||||
updated.settings_config["modelCatalog"] = json!({
|
||||
"models": [{ "model": "gpt-5.4", "displayName": "GPT 5.4" }]
|
||||
});
|
||||
|
||||
ProviderService::update(&state, AppType::Codex, None, updated.clone())
|
||||
.expect("update current Codex provider mapping");
|
||||
|
||||
let catalog_path = crate::codex_config::get_codex_model_catalog_path();
|
||||
let catalog: Value = read_json_file(&catalog_path).expect("read generated catalog");
|
||||
assert_eq!(catalog["models"][0]["slug"], "gpt-5.4");
|
||||
assert_eq!(
|
||||
catalog["models"][0]["input_modalities"],
|
||||
json!(["text", "image"]),
|
||||
"unknown/GPT models must fail open to image input"
|
||||
);
|
||||
let live_config = fs::read_to_string(crate::codex_config::get_codex_config_path())
|
||||
.expect("read Codex config.toml");
|
||||
assert!(live_config.contains("model_catalog_json"));
|
||||
|
||||
updated.settings_config["modelCatalog"] = json!({ "models": [] });
|
||||
ProviderService::update(&state, AppType::Codex, None, updated)
|
||||
.expect("remove current Codex provider mapping");
|
||||
|
||||
let live_config = fs::read_to_string(crate::codex_config::get_codex_config_path())
|
||||
.expect("read Codex config.toml after mapping removal");
|
||||
assert!(
|
||||
!live_config.contains("model_catalog_json"),
|
||||
"removing mappings during takeover must clear the stale catalog pointer"
|
||||
);
|
||||
|
||||
state
|
||||
.proxy_service
|
||||
.stop()
|
||||
.await
|
||||
.expect("stop proxy service");
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "macos", windows))]
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
@@ -1290,6 +1583,40 @@ base_url = "http://localhost:8080"
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn import_opencode_providers_from_live_updates_existing_provider_from_live() {
|
||||
with_test_home(|state, _| {
|
||||
let provider = opencode_provider("existing-opencode");
|
||||
state
|
||||
.db
|
||||
.save_provider(AppType::OpenCode.as_str(), &provider)
|
||||
.expect("seed existing opencode provider");
|
||||
|
||||
let mut live_settings = provider.settings_config.clone();
|
||||
live_settings.as_object_mut().unwrap().remove("name");
|
||||
live_settings["npm"] = Value::String("@ai-sdk/anthropic".to_string());
|
||||
live_settings["models"]["gpt-4o"]["name"] = Value::String("Claude Sonnet".to_string());
|
||||
crate::opencode_config::set_provider(&provider.id, live_settings)
|
||||
.expect("seed edited live opencode provider");
|
||||
|
||||
let updated = import_opencode_providers_from_live(state)
|
||||
.expect("import opencode providers from live");
|
||||
assert_eq!(updated, 1);
|
||||
|
||||
let saved = state
|
||||
.db
|
||||
.get_provider_by_id(&provider.id, AppType::OpenCode.as_str())
|
||||
.expect("query updated opencode provider")
|
||||
.expect("opencode provider should exist");
|
||||
assert_eq!(saved.name, provider.name);
|
||||
assert_eq!(saved.settings_config["npm"], json!("@ai-sdk/anthropic"));
|
||||
assert_eq!(
|
||||
saved.settings_config["models"]["gpt-4o"]["name"],
|
||||
json!("Claude Sonnet")
|
||||
);
|
||||
});
|
||||
}
|
||||
#[test]
|
||||
#[serial]
|
||||
fn import_openclaw_providers_from_live_marks_provider_as_live_managed() {
|
||||
@@ -1324,6 +1651,89 @@ base_url = "http://localhost:8080"
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn import_openclaw_providers_from_live_updates_existing_provider_from_live() {
|
||||
with_test_home(|state, _| {
|
||||
let mut provider = openclaw_provider("existing-openclaw");
|
||||
provider.settings_config["models"] = json!([
|
||||
{
|
||||
"id": "claude-sonnet-4",
|
||||
"name": "Claude Sonnet 4"
|
||||
}
|
||||
]);
|
||||
state
|
||||
.db
|
||||
.save_provider(AppType::OpenClaw.as_str(), &provider)
|
||||
.expect("seed existing openclaw provider");
|
||||
|
||||
let mut live_settings = provider.settings_config.clone();
|
||||
live_settings["baseUrl"] = Value::String("https://api.example.com/v1".to_string());
|
||||
live_settings["models"][0]["name"] = Value::String("Claude Sonnet 4.1".to_string());
|
||||
crate::openclaw_config::set_provider(&provider.id, live_settings)
|
||||
.expect("seed edited live openclaw provider");
|
||||
|
||||
let updated = import_openclaw_providers_from_live(state)
|
||||
.expect("import openclaw providers from live");
|
||||
assert_eq!(updated, 1);
|
||||
|
||||
let saved = state
|
||||
.db
|
||||
.get_provider_by_id(&provider.id, AppType::OpenClaw.as_str())
|
||||
.expect("query updated openclaw provider")
|
||||
.expect("openclaw provider should exist");
|
||||
assert_eq!(saved.name, provider.name);
|
||||
assert_eq!(
|
||||
saved.settings_config["baseUrl"],
|
||||
json!("https://api.example.com/v1")
|
||||
);
|
||||
assert_eq!(
|
||||
saved.settings_config["models"][0]["name"],
|
||||
json!("Claude Sonnet 4.1")
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn import_hermes_providers_from_live_updates_existing_provider_from_live() {
|
||||
with_test_home(|state, _| {
|
||||
let provider = hermes_provider("existing-hermes");
|
||||
state
|
||||
.db
|
||||
.save_provider(AppType::Hermes.as_str(), &provider)
|
||||
.expect("seed existing hermes provider");
|
||||
|
||||
let mut live_settings = provider.settings_config.clone();
|
||||
live_settings["base_url"] = Value::String("https://api.hermes.example/v1".to_string());
|
||||
live_settings["models"]["gpt-4o"]["name"] = Value::String("GPT-4o Updated".to_string());
|
||||
crate::hermes_config::set_provider(&provider.id, live_settings)
|
||||
.expect("seed edited live hermes provider");
|
||||
|
||||
let updated = import_hermes_providers_from_live(state)
|
||||
.expect("import hermes providers from live");
|
||||
assert_eq!(updated, 1);
|
||||
|
||||
let saved = state
|
||||
.db
|
||||
.get_provider_by_id(&provider.id, AppType::Hermes.as_str())
|
||||
.expect("query updated hermes provider")
|
||||
.expect("hermes provider should exist");
|
||||
assert_eq!(saved.name, provider.name);
|
||||
assert_eq!(
|
||||
saved.settings_config["base_url"],
|
||||
json!("https://api.hermes.example/v1")
|
||||
);
|
||||
// models are denormalized from YAML dict to UI-friendly array by
|
||||
// get_providers(), so access by index rather than dict key
|
||||
assert_eq!(
|
||||
saved.settings_config["models"][0]["name"],
|
||||
json!("GPT-4o Updated")
|
||||
);
|
||||
assert_eq!(saved.settings_config["models"][0]["id"], json!("gpt-4o"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn legacy_additive_provider_still_errors_on_live_config_parse_failure() {
|
||||
@@ -1910,20 +2320,41 @@ impl ProviderService {
|
||||
.map_err(|e| AppError::Message(format!("更新 Live 备份失败: {e}")))?;
|
||||
}
|
||||
|
||||
if matches!(app_type, AppType::Claude)
|
||||
&& futures::executor::block_on(state.proxy_service.is_running())
|
||||
{
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
.sync_claude_live_from_provider_while_proxy_active(&provider),
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("同步 Claude Live 配置失败: {e}")))?;
|
||||
if futures::executor::block_on(state.proxy_service.is_running()) {
|
||||
if matches!(app_type, AppType::Claude) {
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
.sync_claude_live_from_provider_while_proxy_active(&provider),
|
||||
)
|
||||
.map_err(|e| {
|
||||
AppError::Message(format!("同步 Claude Live 配置失败: {e}"))
|
||||
})?;
|
||||
} else if live_taken_over && matches!(app_type, AppType::Codex) {
|
||||
// Codex model mappings are projected into a generated
|
||||
// model_catalog_json file. Refresh takeover-owned Live
|
||||
// immediately so adding/removing mappings cannot leave
|
||||
// the previous catalog pointer and capabilities active.
|
||||
futures::executor::block_on(
|
||||
state
|
||||
.proxy_service
|
||||
.sync_codex_live_from_provider_while_proxy_active(&provider),
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("同步 Codex Live 配置失败: {e}")))?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write_live_with_common_config(state.db.as_ref(), &app_type, &provider)?;
|
||||
// Sync MCP
|
||||
McpService::sync_all_enabled(state)?;
|
||||
// 重写 live 后只重投影本应用的 MCP:全量 sync_all_enabled 会把
|
||||
// 无关应用的 live 损坏(如 ~/.claude.json 坏 JSON)牵连进保存
|
||||
// 流程。走到这里 DB 与 live 都已按新配置落盘,保存事实上已
|
||||
// 成功;投影失败降级为警告,避免制造"保存失败"假象(MCP
|
||||
// 投影可自愈:下次切换 / 任一 MCP 启停都会重新投影)。
|
||||
if let Err(err) = McpService::sync_enabled_for_app(state, &app_type) {
|
||||
log::warn!(
|
||||
"保存供应商后重投影 {app_type:?} MCP 失败(将在下次同步时自愈): {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2121,7 +2552,10 @@ impl ProviderService {
|
||||
|
||||
// Block switching to official providers when proxy takeover is active.
|
||||
// Using a proxy with official APIs (Anthropic/OpenAI/Google) may cause account bans.
|
||||
if should_hot_switch && _provider.category.as_deref() == Some("official") {
|
||||
if should_hot_switch
|
||||
&& _provider.category.as_deref() == Some("official")
|
||||
&& !official_provider_supports_proxy_takeover(&app_type, _provider)
|
||||
{
|
||||
return Err(AppError::localized(
|
||||
"switch.official_blocked_by_proxy",
|
||||
"代理接管模式下不能切换到官方供应商,使用代理访问官方 API 可能导致账号被封禁。请先关闭代理接管,或选择第三方供应商。",
|
||||
@@ -2297,8 +2731,16 @@ impl ProviderService {
|
||||
}
|
||||
}
|
||||
|
||||
// Sync MCP
|
||||
McpService::sync_all_enabled(state)?;
|
||||
// 切换重写了目标应用的 live,只重投影该应用的 MCP(Codex 的
|
||||
// [mcp_servers] 与 live 同文件,整体替换后必须补回;其余应用的
|
||||
// MCP 文件独立于 live,投影是幂等维护)。不用全量 sync_all_enabled:
|
||||
// 无关应用的 live 损坏(如 ~/.claude.json 坏 JSON)不该阻断切换。
|
||||
// 走到这里 DB is_current 与 live 都已落盘,切换事实上已成功;
|
||||
// 投影失败上抛会让前端报"切换失败"制造分裂假象,故降级为警告
|
||||
// (MCP 投影可自愈:下次切换 / 任一 MCP 启停都会重新投影)。
|
||||
if let Err(err) = McpService::sync_enabled_for_app(state, &app_type) {
|
||||
log::warn!("切换供应商后重投影 {app_type:?} MCP 失败(将在下次同步时自愈): {err}");
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
@@ -2444,9 +2886,12 @@ impl ProviderService {
|
||||
/// 读到的 live 一定是"片段 + 本地改动"的超集,重提取只会丢掉用户真正删掉的键,
|
||||
/// 不会误删其它供应商共享的内容。
|
||||
///
|
||||
/// **作用域**:仅 Claude。Codex 的 live 是 TOML 且端点藏在 `[model_providers]`
|
||||
/// 表里(现有提取器不剥),自动同步会泄漏端点并与 modelCatalog / 统一会话桶 /
|
||||
/// auth 还原逻辑冲突;Gemini 暂未纳入。两者如需支持应各自单独验证后再加。
|
||||
/// **作用域**:Claude + Codex。Codex 提取器(`extract_codex_common_config`)
|
||||
/// 已剥离全部供应商专属与 cc-switch 注入内容:`model` / `model_provider` /
|
||||
/// 顶层 `base_url` / 整张 `model_providers` 表(含端点与统一会话桶)、
|
||||
/// `mcp_servers`(SSOT 在 DB 表)、顶层 `experimental_bearer_token`
|
||||
/// fallback、`model_catalog_json`、`web_search = "disabled"` 哨兵——密钥与
|
||||
/// 注入产物不会进共享片段。Gemini 暂未纳入,如需支持应单独验证后再加。
|
||||
///
|
||||
/// 仅对**显式勾选"写入通用配置"**(`meta.common_config_enabled == Some(true)`)的
|
||||
/// 供应商生效;用户**显式清空**过片段(`_cleared`)时跳过,避免把用户主动清掉的
|
||||
@@ -2458,8 +2903,8 @@ impl ProviderService {
|
||||
live_config: &Value,
|
||||
result: &mut SwitchResult,
|
||||
) {
|
||||
// 作用域限定 Claude(见函数文档)。
|
||||
if !matches!(app_type, AppType::Claude) {
|
||||
// 作用域限定 Claude + Codex(见函数文档)。
|
||||
if !matches!(app_type, AppType::Claude | AppType::Codex) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2635,6 +3080,16 @@ impl ProviderService {
|
||||
"ANTHROPIC_DEFAULT_OPUS_MODEL_NAME",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL",
|
||||
"ANTHROPIC_DEFAULT_SONNET_MODEL_NAME",
|
||||
// Fable 是 v3.16.3 新增的第四档模型映射,与 haiku/sonnet/opus 同属供应商专属,
|
||||
// 不得进入通用配置片段,否则会污染其它供应商(issue #4272)。
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL",
|
||||
"ANTHROPIC_DEFAULT_FABLE_MODEL_NAME",
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL",
|
||||
// Context limits follow the actual upstream model. Sharing these
|
||||
// across providers can cap GPT/Kimi to the wrong window and make
|
||||
// Claude Code compact too early or miss the upstream limit.
|
||||
"CLAUDE_CODE_MAX_CONTEXT_TOKENS",
|
||||
"CLAUDE_CODE_AUTO_COMPACT_WINDOW",
|
||||
"ANTHROPIC_BASE_URL",
|
||||
];
|
||||
|
||||
@@ -2711,10 +3166,48 @@ impl ProviderService {
|
||||
root.remove("model_provider");
|
||||
// Legacy/alt formats might use a top-level base_url.
|
||||
root.remove("base_url");
|
||||
// wire_api 与 base_url 同属供应商路由语义:无 model_provider 时
|
||||
// update_codex_toml_field / 前端 setCodexWireApi 都会把它落在顶层,
|
||||
// 进了片段会改写其它供应商的协议选择(chat vs responses)。
|
||||
root.remove("wire_api");
|
||||
|
||||
// Remove entire model_providers table (provider-specific configuration)
|
||||
root.remove("model_providers");
|
||||
|
||||
// MCP 服务器归 DB mcp_servers 表所有:进了共享片段会绕过按应用的
|
||||
// 启用状态被合并进所有勾选通用配置的供应商,且在通用配置编辑框里
|
||||
// 显示为一份"重复"的 MCP 配置。
|
||||
root.remove("mcp_servers");
|
||||
// 历史错误格式 [mcp.servers] 一并剥离(与 strip_codex_mcp_servers_from_settings
|
||||
// 一致):sync_all_enabled 只管理 [mcp_servers.*],legacy 形态一旦进了
|
||||
// 片段就会被合并进所有供应商,且没有任何同步路径能清掉这个孤儿。
|
||||
if let Some(mcp_tbl) = root
|
||||
.get_mut("mcp")
|
||||
.and_then(|item| item.as_table_like_mut())
|
||||
{
|
||||
mcp_tbl.remove("servers");
|
||||
if mcp_tbl.is_empty() {
|
||||
root.remove("mcp");
|
||||
}
|
||||
}
|
||||
|
||||
// cc-switch 写 live 时注入的产物一律不进共享片段:
|
||||
// - experimental_bearer_token 正常写在 [model_providers.<id>] 内(上面
|
||||
// 整表已剥),但无活跃路由 / 内建保留 id / 路由表缺失三种 fallback
|
||||
// 会落在顶层——不剥等于把 API 密钥写进共享片段。
|
||||
root.remove("experimental_bearer_token");
|
||||
// - model_catalog_json 指向按供应商生成的 catalog 投影文件(DB 为 SSOT)。
|
||||
root.remove("model_catalog_json");
|
||||
// - web_search 只剥 cc-switch 注入的 "disabled" 哨兵;用户手设的其它值
|
||||
// 属于可共享偏好,保留。
|
||||
if root
|
||||
.get(crate::codex_config::CODEX_WEB_SEARCH_FIELD)
|
||||
.and_then(|item| item.as_str())
|
||||
== Some(crate::codex_config::CODEX_WEB_SEARCH_DISABLED)
|
||||
{
|
||||
root.remove(crate::codex_config::CODEX_WEB_SEARCH_FIELD);
|
||||
}
|
||||
|
||||
// Clean up multiple empty lines (keep at most one blank line).
|
||||
let mut cleaned = String::new();
|
||||
let mut blank_run = 0usize;
|
||||
|
||||
@@ -57,6 +57,18 @@ pub(crate) async fn execute_and_format_usage_result(
|
||||
})
|
||||
}
|
||||
Err(err) => {
|
||||
// 瞬时传输失败(send 失败/超时、读体中断)以 Err 传播,让前端 invoke
|
||||
// reject → react-query retry 并保留上次成功值;按错误 key 判定而非
|
||||
// 文案匹配。其余脚本/配置/HTTP 业务错误折叠成 success:false 展示文案。
|
||||
if let AppError::Localized { key, .. } = &err {
|
||||
if matches!(
|
||||
*key,
|
||||
"usage_script.request_failed" | "usage_script.read_response_failed"
|
||||
) {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
let lang = settings::get_settings()
|
||||
.language
|
||||
.unwrap_or_else(|| "zh".to_string());
|
||||
|
||||
+617
-182
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@
|
||||
//! ```
|
||||
//!
|
||||
//! ## 解析的事件类型
|
||||
//! - `session_meta` → 提取 session_id
|
||||
//! - `session_meta` → 提取唯一 thread_id(子代理的 session_id 指向父线程)
|
||||
//! - `turn_context` → 提取当前 model
|
||||
//! - `event_msg` (type=token_count) → 提取累计 token 用量,计算 delta
|
||||
|
||||
@@ -28,6 +28,8 @@ use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const CODEX_THREAD_REQUEST_ID_PREFIX: &str = "codex_session:thread-v1";
|
||||
|
||||
/// 累计 token 用量(跟踪 total_token_usage 字段)
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct CumulativeTokens {
|
||||
@@ -52,10 +54,162 @@ impl DeltaTokens {
|
||||
|
||||
/// 单文件解析时的运行状态
|
||||
struct FileParseState {
|
||||
session_id: Option<String>,
|
||||
thread_id: Option<String>,
|
||||
current_model: String,
|
||||
prev_total: Option<CumulativeTokens>,
|
||||
event_index: u32,
|
||||
history_replay_boundary: Option<i64>,
|
||||
}
|
||||
|
||||
/// Codex 子代理日志中的 `id` 是当前线程的唯一 ID,`session_id` 则指向父线程。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct CodexSessionIdentity {
|
||||
thread_id: String,
|
||||
carries_history_snapshot: bool,
|
||||
}
|
||||
|
||||
fn parse_codex_session_identity(payload: &serde_json::Value) -> Option<CodexSessionIdentity> {
|
||||
let thread_id = payload
|
||||
.get("id")
|
||||
.or_else(|| payload.get("thread_id"))
|
||||
.or_else(|| payload.get("threadId"))
|
||||
.or_else(|| payload.get("session_id"))
|
||||
.or_else(|| payload.get("sessionId"))
|
||||
.and_then(|value| value.as_str())?
|
||||
.to_string();
|
||||
let session_id = payload
|
||||
.get("session_id")
|
||||
.or_else(|| payload.get("sessionId"))
|
||||
.and_then(|value| value.as_str());
|
||||
let carries_history_snapshot = payload
|
||||
.get("forked_from_id")
|
||||
.and_then(|value| value.as_str())
|
||||
.is_some_and(|value| !value.is_empty())
|
||||
|| payload
|
||||
.get("source")
|
||||
.and_then(|source| source.get("subagent"))
|
||||
.is_some()
|
||||
|| session_id.is_some_and(|session_id| session_id != thread_id);
|
||||
|
||||
Some(CodexSessionIdentity {
|
||||
thread_id,
|
||||
carries_history_snapshot,
|
||||
})
|
||||
}
|
||||
|
||||
fn read_codex_session_identity(file_path: &Path) -> Option<CodexSessionIdentity> {
|
||||
let file = fs::File::open(file_path).ok()?;
|
||||
|
||||
for line in BufReader::new(file).lines() {
|
||||
let Ok(line) = line else {
|
||||
continue;
|
||||
};
|
||||
if !line.contains("\"session_meta\"") {
|
||||
continue;
|
||||
}
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else {
|
||||
continue;
|
||||
};
|
||||
if value.get("type").and_then(|value| value.as_str()) != Some("session_meta") {
|
||||
continue;
|
||||
}
|
||||
if let Some(identity) = value.get("payload").and_then(parse_codex_session_identity) {
|
||||
return Some(identity);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// fork/子代理日志会先重放父线程历史,再以接管事件开始当前线程。
|
||||
/// 返回接管事件所在行;此前的 token_count 只用于恢复累计值基线。
|
||||
fn codex_history_replay_boundary(
|
||||
file_path: &Path,
|
||||
identity: Option<&CodexSessionIdentity>,
|
||||
) -> Option<i64> {
|
||||
if !identity.is_some_and(|identity| identity.carries_history_snapshot) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let file = fs::File::open(file_path).ok()?;
|
||||
for (index, line) in BufReader::new(file).lines().enumerate() {
|
||||
let Ok(line) = line else {
|
||||
continue;
|
||||
};
|
||||
if !line.contains("\"thread_settings_applied\"")
|
||||
&& !line.contains("\"inter_agent_communication")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else {
|
||||
continue;
|
||||
};
|
||||
let Some(event_type) = value.get("type").and_then(|value| value.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let is_replay_boundary = event_type.starts_with("inter_agent_communication")
|
||||
|| (event_type == "event_msg"
|
||||
&& value
|
||||
.get("payload")
|
||||
.and_then(|payload| payload.get("type"))
|
||||
.and_then(|value| value.as_str())
|
||||
== Some("thread_settings_applied"));
|
||||
if is_replay_boundary {
|
||||
return Some(index as i64 + 1);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn is_history_snapshot_event(state: &FileParseState, line_offset: i64) -> bool {
|
||||
state
|
||||
.history_replay_boundary
|
||||
.is_some_and(|boundary| line_offset < boundary)
|
||||
}
|
||||
|
||||
fn get_codex_sync_state(db: &Database, file_path: &Path) -> Result<(i64, i64), AppError> {
|
||||
let file_path_str = file_path.to_string_lossy().to_string();
|
||||
let state = get_sync_state(db, &file_path_str)?;
|
||||
if state != (0, 0)
|
||||
|| file_path
|
||||
.parent()
|
||||
.and_then(Path::file_name)
|
||||
.and_then(|name| name.to_str())
|
||||
!= Some("archived_sessions")
|
||||
{
|
||||
return Ok(state);
|
||||
}
|
||||
|
||||
let Some(file_name) = file_path.file_name().and_then(|name| name.to_str()) else {
|
||||
return Ok(state);
|
||||
};
|
||||
let slash_suffix = format!("/{file_name}");
|
||||
let backslash_suffix = format!("\\{file_name}");
|
||||
let conn = lock_conn!(db.conn);
|
||||
let inherited = conn.query_row(
|
||||
"SELECT last_modified, last_line_offset
|
||||
FROM session_log_sync
|
||||
WHERE file_path <> ?1
|
||||
AND (substr(file_path, -length(?2)) = ?2
|
||||
OR substr(file_path, -length(?3)) = ?3)
|
||||
ORDER BY last_line_offset DESC, last_modified DESC
|
||||
LIMIT 1",
|
||||
rusqlite::params![file_path_str, slash_suffix, backslash_suffix],
|
||||
|row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)),
|
||||
);
|
||||
drop(conn);
|
||||
|
||||
match inherited {
|
||||
Ok(inherited) => {
|
||||
update_sync_state(db, &file_path_str, inherited.0, inherited.1)?;
|
||||
Ok(inherited)
|
||||
}
|
||||
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(state),
|
||||
Err(error) => Err(AppError::Database(format!(
|
||||
"查询 Codex 归档文件同步状态失败: {error}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// 归一化 Codex 模型名
|
||||
@@ -238,23 +392,27 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
|
||||
let file_modified = metadata_modified_nanos(&metadata);
|
||||
|
||||
// 检查同步状态
|
||||
let (last_modified, last_offset) = get_sync_state(db, &file_path_str)?;
|
||||
let (last_modified, last_offset) = get_codex_sync_state(db, file_path)?;
|
||||
|
||||
// 文件未变化则跳过
|
||||
if file_modified <= last_modified {
|
||||
return Ok((0, 0));
|
||||
}
|
||||
|
||||
let identity = read_codex_session_identity(file_path);
|
||||
|
||||
// 打开文件逐行解析
|
||||
let file =
|
||||
fs::File::open(file_path).map_err(|e| AppError::Config(format!("无法打开文件: {e}")))?;
|
||||
let reader = BufReader::new(file);
|
||||
let history_replay_boundary = codex_history_replay_boundary(file_path, identity.as_ref());
|
||||
|
||||
let mut state = FileParseState {
|
||||
session_id: None,
|
||||
thread_id: identity.map(|identity| identity.thread_id),
|
||||
current_model: "unknown".to_string(),
|
||||
prev_total: None,
|
||||
event_index: 0,
|
||||
history_replay_boundary,
|
||||
};
|
||||
|
||||
let mut line_offset: i64 = 0;
|
||||
@@ -296,16 +454,11 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
|
||||
};
|
||||
|
||||
match event_type {
|
||||
"session_meta" if state.session_id.is_none() => {
|
||||
let payload = value.get("payload");
|
||||
state.session_id = payload
|
||||
.and_then(|p| {
|
||||
p.get("session_id")
|
||||
.or_else(|| p.get("sessionId"))
|
||||
.or_else(|| p.get("id"))
|
||||
})
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
"session_meta" if state.thread_id.is_none() => {
|
||||
state.thread_id = value
|
||||
.get("payload")
|
||||
.and_then(parse_codex_session_identity)
|
||||
.map(|identity| identity.thread_id);
|
||||
}
|
||||
"turn_context" => {
|
||||
if let Some(payload) = value.get("payload") {
|
||||
@@ -383,16 +536,28 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
|
||||
continue; // 跳过 task 边界的零 delta 事件
|
||||
}
|
||||
|
||||
// 所有非零事件都占据稳定序号,包括已同步事件与 replay 快照。
|
||||
state.event_index += 1;
|
||||
|
||||
// replay 快照更新了 prev_total,但不是当前线程的新用量。
|
||||
if is_history_snapshot_event(&state, line_offset) {
|
||||
if line_offset > last_offset {
|
||||
skipped += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// 跳过已处理的行(但仍需解析以恢复状态)
|
||||
if line_offset <= last_offset {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 生成唯一 request_id
|
||||
let session_id_str = state.session_id.as_deref().unwrap_or("unknown");
|
||||
let request_id = format!("codex_session:{}:{}", session_id_str, state.event_index);
|
||||
let thread_id = state.thread_id.as_deref().unwrap_or("unknown");
|
||||
let request_id = format!(
|
||||
"{CODEX_THREAD_REQUEST_ID_PREFIX}:{thread_id}:{}",
|
||||
state.event_index
|
||||
);
|
||||
|
||||
// 提取时间戳
|
||||
let timestamp = value
|
||||
@@ -405,7 +570,7 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
|
||||
&request_id,
|
||||
&delta,
|
||||
&state.current_model,
|
||||
state.session_id.as_deref(),
|
||||
state.thread_id.as_deref(),
|
||||
timestamp.as_deref(),
|
||||
) {
|
||||
Ok(true) => imported += 1,
|
||||
@@ -549,6 +714,56 @@ fn find_codex_pricing(conn: &rusqlite::Connection, model_id: &str) -> Option<Mod
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_jsonl(path: &Path, values: &[serde_json::Value]) {
|
||||
let contents = values
|
||||
.iter()
|
||||
.map(serde_json::Value::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
+ "\n";
|
||||
fs::write(path, contents).unwrap();
|
||||
}
|
||||
|
||||
fn session_meta(thread_id: &str, session_id: &str) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"timestamp": "2026-07-10T03:00:00Z",
|
||||
"type": "session_meta",
|
||||
"payload": {
|
||||
"id": thread_id,
|
||||
"session_id": session_id,
|
||||
"source": if thread_id == session_id {
|
||||
serde_json::Value::String("cli".to_string())
|
||||
} else {
|
||||
serde_json::json!({ "subagent": {} })
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn turn_context() -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"timestamp": "2026-07-10T03:00:01Z",
|
||||
"type": "turn_context",
|
||||
"payload": { "model": "gpt-5.6-sol" }
|
||||
})
|
||||
}
|
||||
|
||||
fn token_count(input: u64, cached: u64, output: u64) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"timestamp": "2026-07-10T03:00:02Z",
|
||||
"type": "event_msg",
|
||||
"payload": {
|
||||
"type": "token_count",
|
||||
"info": { "total_token_usage": {
|
||||
"input_tokens": input,
|
||||
"cached_input_tokens": cached,
|
||||
"output_tokens": output
|
||||
}}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_delta_first_event() {
|
||||
@@ -659,6 +874,159 @@ mod tests {
|
||||
assert!(files.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subagent_identity_prefers_unique_thread_id() {
|
||||
let identity =
|
||||
parse_codex_session_identity(session_meta("child", "parent").get("payload").unwrap())
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(identity.thread_id, "child");
|
||||
assert!(identity.carries_history_snapshot);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subagent_replay_only_establishes_token_baseline() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
let temp = tempdir().unwrap();
|
||||
let child = temp.path().join("child.jsonl");
|
||||
write_jsonl(
|
||||
&child,
|
||||
&[
|
||||
session_meta("child", "parent"),
|
||||
turn_context(),
|
||||
token_count(1_000, 900, 100),
|
||||
token_count(1_200, 1_000, 120),
|
||||
serde_json::json!({
|
||||
"timestamp": "2026-07-10T03:00:03Z",
|
||||
"type": "event_msg",
|
||||
"payload": { "type": "thread_settings_applied" }
|
||||
}),
|
||||
token_count(1_300, 1_050, 150),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(sync_single_codex_file(&db, &child)?, (1, 2));
|
||||
|
||||
let conn = lock_conn!(db.conn);
|
||||
let usage: (i64, i64, i64) = conn.query_row(
|
||||
"SELECT input_tokens, cache_read_tokens, output_tokens
|
||||
FROM proxy_request_logs
|
||||
WHERE request_id = 'codex_session:thread-v1:child:3'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)?;
|
||||
assert_eq!(usage, (100, 50, 30));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subagents_under_same_parent_use_distinct_request_ids() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
let temp = tempdir().unwrap();
|
||||
let child_a = temp.path().join("child-a.jsonl");
|
||||
let child_b = temp.path().join("child-b.jsonl");
|
||||
write_jsonl(
|
||||
&child_a,
|
||||
&[
|
||||
session_meta("child-a", "parent"),
|
||||
turn_context(),
|
||||
token_count(100, 50, 10),
|
||||
],
|
||||
);
|
||||
write_jsonl(
|
||||
&child_b,
|
||||
&[
|
||||
session_meta("child-b", "parent"),
|
||||
turn_context(),
|
||||
token_count(200, 100, 20),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(sync_single_codex_file(&db, &child_a)?, (1, 0));
|
||||
assert_eq!(sync_single_codex_file(&db, &child_b)?, (1, 0));
|
||||
|
||||
let conn = lock_conn!(db.conn);
|
||||
let request_ids = conn
|
||||
.prepare(
|
||||
"SELECT request_id FROM proxy_request_logs
|
||||
WHERE data_source = 'codex_session' ORDER BY request_id",
|
||||
)?
|
||||
.query_map([], |row| row.get::<_, String>(0))?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
assert_eq!(
|
||||
request_ids,
|
||||
vec![
|
||||
"codex_session:thread-v1:child-a:1",
|
||||
"codex_session:thread-v1:child-b:1"
|
||||
]
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_archived_log_inherits_cursor_and_only_imports_appended_usage() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
let temp = tempdir().unwrap();
|
||||
let sessions = temp.path().join("sessions");
|
||||
let archived = temp.path().join("archived_sessions");
|
||||
fs::create_dir_all(&sessions).unwrap();
|
||||
fs::create_dir_all(&archived).unwrap();
|
||||
let source = sessions.join("rollout-parent.jsonl");
|
||||
let archived_file = archived.join("rollout-parent.jsonl");
|
||||
write_jsonl(
|
||||
&archived_file,
|
||||
&[
|
||||
session_meta("parent", "parent"),
|
||||
turn_context(),
|
||||
token_count(100, 50, 10),
|
||||
token_count(200, 100, 20),
|
||||
],
|
||||
);
|
||||
|
||||
{
|
||||
let conn = lock_conn!(db.conn);
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_request_logs (
|
||||
request_id, provider_id, app_type, model, request_model,
|
||||
input_tokens, output_tokens, cache_read_tokens,
|
||||
total_cost_usd, latency_ms, status_code, session_id,
|
||||
created_at, data_source
|
||||
) VALUES ('codex_session:parent:2', '_codex_session', 'codex',
|
||||
'gpt-5.6-sol', 'gpt-5.6-sol', 999, 99, 0, '0', 0,
|
||||
200, 'parent', 1, 'codex_session')",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
let source_path = source.to_string_lossy().to_string();
|
||||
update_sync_state(&db, &source_path, 1, 3)?;
|
||||
|
||||
assert_eq!(sync_single_codex_file(&db, &archived_file)?, (1, 0));
|
||||
assert_eq!(sync_single_codex_file(&db, &archived_file)?, (0, 0));
|
||||
|
||||
let conn = lock_conn!(db.conn);
|
||||
let old_row_count: i64 = conn.query_row(
|
||||
"SELECT COUNT(*) FROM proxy_request_logs
|
||||
WHERE request_id = 'codex_session:parent:2'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
assert_eq!(old_row_count, 1);
|
||||
let usage: (i64, i64, i64) = conn.query_row(
|
||||
"SELECT input_tokens, cache_read_tokens, output_tokens
|
||||
FROM proxy_request_logs
|
||||
WHERE request_id = 'codex_session:thread-v1:parent:2'",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
|
||||
)?;
|
||||
assert_eq!(usage, (100, 50, 10));
|
||||
drop(conn);
|
||||
assert_eq!(get_sync_state(&db, &archived_file.to_string_lossy())?.1, 4);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_insert_codex_session_skips_matching_proxy_log() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
@@ -18,13 +18,16 @@
|
||||
/// would happen with the opposite default.
|
||||
const CACHE_INCLUSIVE_APP_TYPES: &[&str] = &["codex", "gemini"];
|
||||
|
||||
pub(crate) const INPUT_TOKEN_SEMANTICS_LEGACY: i64 = 0;
|
||||
pub(crate) const INPUT_TOKEN_SEMANTICS_TOTAL: i64 = 1;
|
||||
pub(crate) const INPUT_TOKEN_SEMANTICS_FRESH: i64 = 2;
|
||||
|
||||
/// Build an SQL expression that returns the cache-normalized `input_tokens`
|
||||
/// for a single row in `proxy_request_logs` or `usage_daily_rollups`.
|
||||
///
|
||||
/// For rows whose `app_type` is in [`CACHE_INCLUSIVE_APP_TYPES`] and
|
||||
/// `input_tokens >= cache_read_tokens`, returns
|
||||
/// `input_tokens - cache_read_tokens`. For all other rows the original
|
||||
/// `input_tokens` is returned unchanged.
|
||||
/// Legacy rows subtract cache reads only. New total-inclusive rows subtract
|
||||
/// both cache reads and writes. Rollups normalized to fresh input are returned
|
||||
/// unchanged.
|
||||
///
|
||||
/// Pass an empty string to reference the columns directly (no alias),
|
||||
/// or a table alias such as `"l"` to emit `l.input_tokens` style references.
|
||||
@@ -40,7 +43,15 @@ pub fn fresh_input_sql(alias: &str) -> String {
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!(
|
||||
"CASE WHEN {prefix}app_type IN ({app_type_list}) AND {prefix}input_tokens >= {prefix}cache_read_tokens \
|
||||
"CASE \
|
||||
WHEN {prefix}input_token_semantics = {INPUT_TOKEN_SEMANTICS_FRESH} THEN {prefix}input_tokens \
|
||||
WHEN {prefix}app_type IN ({app_type_list}) \
|
||||
AND {prefix}input_token_semantics = {INPUT_TOKEN_SEMANTICS_TOTAL} \
|
||||
AND {prefix}input_tokens >= ({prefix}cache_read_tokens + {prefix}cache_creation_tokens) \
|
||||
THEN ({prefix}input_tokens - {prefix}cache_read_tokens - {prefix}cache_creation_tokens) \
|
||||
WHEN {prefix}app_type IN ({app_type_list}) \
|
||||
AND {prefix}input_token_semantics = {INPUT_TOKEN_SEMANTICS_LEGACY} \
|
||||
AND {prefix}input_tokens >= {prefix}cache_read_tokens \
|
||||
THEN ({prefix}input_tokens - {prefix}cache_read_tokens) \
|
||||
ELSE {prefix}input_tokens END"
|
||||
)
|
||||
@@ -60,7 +71,8 @@ mod tests {
|
||||
input_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
output_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_read_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
cache_creation_tokens INTEGER NOT NULL DEFAULT 0
|
||||
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
input_token_semantics INTEGER NOT NULL DEFAULT 0
|
||||
);",
|
||||
)
|
||||
.unwrap();
|
||||
@@ -131,4 +143,38 @@ mod tests {
|
||||
let value: i64 = conn.query_row(&sql, [], |r| r.get(0)).unwrap();
|
||||
assert_eq!(value, 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_input_subtracts_cache_write_for_total_semantics() {
|
||||
let conn = setup_conn();
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_request_logs (
|
||||
request_id, app_type, input_tokens, cache_read_tokens,
|
||||
cache_creation_tokens, input_token_semantics
|
||||
) VALUES ('codex-total', 'codex', 1000, 300, 200, ?1)",
|
||||
[INPUT_TOKEN_SEMANTICS_TOTAL],
|
||||
)
|
||||
.unwrap();
|
||||
let expr = fresh_input_sql("l");
|
||||
let sql = format!("SELECT {expr} FROM proxy_request_logs l");
|
||||
let value: i64 = conn.query_row(&sql, [], |row| row.get(0)).unwrap();
|
||||
assert_eq!(value, 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fresh_input_keeps_normalized_rollup_value() {
|
||||
let conn = setup_conn();
|
||||
conn.execute(
|
||||
"INSERT INTO proxy_request_logs (
|
||||
request_id, app_type, input_tokens, cache_read_tokens,
|
||||
cache_creation_tokens, input_token_semantics
|
||||
) VALUES ('codex-fresh', 'codex', 500, 300, 200, ?1)",
|
||||
[INPUT_TOKEN_SEMANTICS_FRESH],
|
||||
)
|
||||
.unwrap();
|
||||
let expr = fresh_input_sql("l");
|
||||
let sql = format!("SELECT {expr} FROM proxy_request_logs l");
|
||||
let value: i64 = conn.query_row(&sql, [], |row| row.get(0)).unwrap();
|
||||
assert_eq!(value, 500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,19 +92,12 @@ impl StreamCheckService {
|
||||
config: &StreamCheckConfig,
|
||||
base_url_override: Option<String>,
|
||||
) -> Result<StreamCheckResult, AppError> {
|
||||
let effective = Self::merge_provider_config(provider, config);
|
||||
|
||||
let mut last_result: Option<StreamCheckResult> = None;
|
||||
for attempt in 0..=effective.max_retries {
|
||||
for attempt in 0..=config.max_retries {
|
||||
let start = Instant::now();
|
||||
let result = Self::check_once(
|
||||
app_type,
|
||||
provider,
|
||||
&effective,
|
||||
base_url_override.clone(),
|
||||
start,
|
||||
)
|
||||
.await?;
|
||||
let result =
|
||||
Self::check_once(app_type, provider, config, base_url_override.clone(), start)
|
||||
.await?;
|
||||
|
||||
if result.success {
|
||||
return Ok(StreamCheckResult {
|
||||
@@ -114,7 +107,7 @@ impl StreamCheckService {
|
||||
}
|
||||
|
||||
// 仅超时 / abort 类网络抖动值得重试;连接被拒、DNS 失败等立即返回。
|
||||
if Self::should_retry(&result.message) && attempt < effective.max_retries {
|
||||
if Self::should_retry(&result.message) && attempt < config.max_retries {
|
||||
last_result = Some(result);
|
||||
continue;
|
||||
}
|
||||
@@ -132,31 +125,11 @@ impl StreamCheckService {
|
||||
http_status: None,
|
||||
model_used: String::new(),
|
||||
tested_at: chrono::Utc::now().timestamp(),
|
||||
retry_count: effective.max_retries,
|
||||
retry_count: config.max_retries,
|
||||
error_category: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// 合并供应商单独配置(`meta.testConfig`,仅当 `enabled`)与全局配置。
|
||||
fn merge_provider_config(provider: &Provider, global: &StreamCheckConfig) -> StreamCheckConfig {
|
||||
let tc = provider
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|m| m.test_config.as_ref())
|
||||
.filter(|tc| tc.enabled);
|
||||
|
||||
match tc {
|
||||
Some(tc) => StreamCheckConfig {
|
||||
timeout_secs: tc.timeout_secs.unwrap_or(global.timeout_secs),
|
||||
max_retries: tc.max_retries.unwrap_or(global.max_retries),
|
||||
degraded_threshold_ms: tc
|
||||
.degraded_threshold_ms
|
||||
.unwrap_or(global.degraded_threshold_ms),
|
||||
},
|
||||
None => global.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次连通性探测。
|
||||
async fn check_once(
|
||||
app_type: &AppType,
|
||||
@@ -193,6 +166,12 @@ impl StreamCheckService {
|
||||
/// 没有 cc-switch 能可靠探测的目标——这类供应商的连通检测按钮在前端已隐藏
|
||||
/// (见 `ProviderCard.tsx`),故此处对其提取失败直接报错即可,不做官方端点回退。
|
||||
fn resolve_base_url(app_type: &AppType, provider: &Provider) -> Result<String, AppError> {
|
||||
if provider.category.as_deref() == Some("official") {
|
||||
return Err(AppError::Message(
|
||||
"Official providers do not expose a reachability-check target".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
match app_type {
|
||||
// 累加模式应用的 settings_config 结构与 Claude/Codex/Gemini 不同,
|
||||
// 不走 adapter,直接按各自约定提取 base_url。
|
||||
@@ -474,48 +453,6 @@ mod tests {
|
||||
assert_eq!(r.status, HealthStatus::Degraded);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_merge_provider_config_override_and_default() {
|
||||
use crate::provider::{ProviderMeta, ProviderTestConfig};
|
||||
|
||||
let global = StreamCheckConfig::default();
|
||||
|
||||
// 无 testConfig → 用全局
|
||||
let p = make_provider(serde_json::json!({}));
|
||||
let merged = StreamCheckService::merge_provider_config(&p, &global);
|
||||
assert_eq!(merged.timeout_secs, global.timeout_secs);
|
||||
|
||||
// testConfig 启用并覆盖部分字段
|
||||
let mut p2 = make_provider(serde_json::json!({}));
|
||||
p2.meta = Some(ProviderMeta {
|
||||
test_config: Some(ProviderTestConfig {
|
||||
enabled: true,
|
||||
timeout_secs: Some(20),
|
||||
degraded_threshold_ms: Some(3000),
|
||||
max_retries: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let merged2 = StreamCheckService::merge_provider_config(&p2, &global);
|
||||
assert_eq!(merged2.timeout_secs, 20);
|
||||
assert_eq!(merged2.degraded_threshold_ms, 3000);
|
||||
assert_eq!(merged2.max_retries, global.max_retries); // 未覆盖 → 全局
|
||||
|
||||
// testConfig 存在但未启用 → 忽略,用全局
|
||||
let mut p3 = make_provider(serde_json::json!({}));
|
||||
p3.meta = Some(ProviderMeta {
|
||||
test_config: Some(ProviderTestConfig {
|
||||
enabled: false,
|
||||
timeout_secs: Some(99),
|
||||
degraded_threshold_ms: None,
|
||||
max_retries: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
let merged3 = StreamCheckService::merge_provider_config(&p3, &global);
|
||||
assert_eq!(merged3.timeout_secs, global.timeout_secs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resolve_opencode_base_url_explicit_wins() {
|
||||
let p = make_provider(serde_json::json!({
|
||||
@@ -579,5 +516,10 @@ mod tests {
|
||||
// 不会走到这里;不做官方端点回退(避免给忘填地址的第三方误显绿灯)。
|
||||
let empty = make_provider(serde_json::json!({ "env": {} }));
|
||||
assert!(StreamCheckService::resolve_base_url(&AppType::Claude, &empty).is_err());
|
||||
|
||||
let mut official = make_provider(serde_json::json!({ "auth": {}, "config": "" }));
|
||||
official.id = crate::database::CODEX_OFFICIAL_PROVIDER_ID.to_string();
|
||||
official.category = Some("official".to_string());
|
||||
assert!(StreamCheckService::resolve_base_url(&AppType::Codex, &official).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,7 +331,11 @@ const KNOWN_TIERS: &[&str] = &[
|
||||
];
|
||||
|
||||
/// 查询 Claude 官方订阅额度
|
||||
async fn query_claude_quota(access_token: &str) -> SubscriptionQuota {
|
||||
///
|
||||
/// 瞬时传输失败(网络/超时/读体中断)返回 `Err`(前端 reject → retry + 保留上次
|
||||
/// 成功值);确定性失败(鉴权/非 2xx/响应体非法 JSON)返回 `Ok(success:false)`。
|
||||
/// codex/gemini 两个查询函数遵守同一约定。
|
||||
async fn query_claude_quota(access_token: &str) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let resp = client
|
||||
@@ -345,42 +349,42 @@ async fn query_claude_quota(access_token: &str) -> SubscriptionQuota {
|
||||
|
||||
let resp = match resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
"claude",
|
||||
CredentialStatus::Valid,
|
||||
format!("Network error: {e}"),
|
||||
);
|
||||
}
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"claude",
|
||||
CredentialStatus::Expired,
|
||||
format!("Authentication failed (HTTP {status}). Please re-login with Claude CLI."),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"claude",
|
||||
CredentialStatus::Valid,
|
||||
format!("API error (HTTP {status}): {body}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let body: serde_json::Value = match resp.json().await {
|
||||
// 先 bytes() 再解析:读体失败(超时/连接中断)是瞬时 → Err;拿到完整响应体
|
||||
// 后解析失败才是确定性。reqwest 的 json() 把读体错误也包成 decode,无法区分。
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read API response: {e}")),
|
||||
};
|
||||
let body: serde_json::Value = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"claude",
|
||||
CredentialStatus::Valid,
|
||||
format!("Failed to parse API response: {e}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -435,7 +439,7 @@ async fn query_claude_quota(access_token: &str) -> SubscriptionQuota {
|
||||
})
|
||||
});
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: "claude".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
@@ -444,7 +448,7 @@ async fn query_claude_quota(access_token: &str) -> SubscriptionQuota {
|
||||
extra_usage,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Codex 凭据读取 ──────────────────────────────────────
|
||||
@@ -670,7 +674,7 @@ pub(crate) async fn query_codex_quota(
|
||||
account_id: Option<&str>,
|
||||
tool_label: &str,
|
||||
expired_message: &str,
|
||||
) -> SubscriptionQuota {
|
||||
) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
let mut req = client
|
||||
@@ -685,42 +689,40 @@ pub(crate) async fn query_codex_quota(
|
||||
|
||||
let resp = match req.timeout(std::time::Duration::from_secs(15)).send().await {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
tool_label,
|
||||
CredentialStatus::Valid,
|
||||
format!("Network error: {e}"),
|
||||
);
|
||||
}
|
||||
Err(e) => return Err(format!("Network error: {e}")),
|
||||
};
|
||||
|
||||
let status = resp.status();
|
||||
|
||||
if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
tool_label,
|
||||
CredentialStatus::Expired,
|
||||
format!("{expired_message} (HTTP {status})"),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
tool_label,
|
||||
CredentialStatus::Valid,
|
||||
format!("API error (HTTP {status}): {body}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let body: CodexUsageResponse = match resp.json().await {
|
||||
let raw = match resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read API response: {e}")),
|
||||
};
|
||||
let body: CodexUsageResponse = match serde_json::from_slice(&raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
tool_label,
|
||||
CredentialStatus::Valid,
|
||||
format!("Failed to parse API response: {e}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -746,7 +748,7 @@ pub(crate) async fn query_codex_quota(
|
||||
}
|
||||
}
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: tool_label.to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
@@ -755,7 +757,7 @@ pub(crate) async fn query_codex_quota(
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Gemini 凭据读取 ──────────────────────────────────────
|
||||
@@ -1049,7 +1051,7 @@ fn classify_gemini_model(model_id: &str) -> &str {
|
||||
/// 两步 API 调用:
|
||||
/// 1. loadCodeAssist → 获取 cloudaicompanionProject
|
||||
/// 2. retrieveUserQuota → 获取按模型分桶的配额数据
|
||||
async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
async fn query_gemini_quota(access_token: &str) -> Result<SubscriptionQuota, String> {
|
||||
let client = crate::proxy::http_client::get();
|
||||
|
||||
// ── Step 1: loadCodeAssist 获取项目 ID ──
|
||||
@@ -1069,42 +1071,40 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
|
||||
let load_resp = match load_resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("Network error (loadCodeAssist): {e}"),
|
||||
);
|
||||
}
|
||||
Err(e) => return Err(format!("Network error (loadCodeAssist): {e}")),
|
||||
};
|
||||
|
||||
let load_status = load_resp.status();
|
||||
if load_status == reqwest::StatusCode::UNAUTHORIZED
|
||||
|| load_status == reqwest::StatusCode::FORBIDDEN
|
||||
{
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Expired,
|
||||
format!("Authentication failed (HTTP {load_status}). Please re-login with Gemini CLI."),
|
||||
);
|
||||
));
|
||||
}
|
||||
if !load_status.is_success() {
|
||||
let body = load_resp.text().await.unwrap_or_default();
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("loadCodeAssist failed (HTTP {load_status}): {body}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let load_body: GeminiLoadCodeAssistResponse = match load_resp.json().await {
|
||||
let load_raw = match load_resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read loadCodeAssist response: {e}")),
|
||||
};
|
||||
let load_body: GeminiLoadCodeAssistResponse = match serde_json::from_slice(&load_raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("Failed to parse loadCodeAssist response: {e}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1130,42 +1130,40 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
|
||||
let quota_resp = match quota_resp {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("Network error (retrieveUserQuota): {e}"),
|
||||
);
|
||||
}
|
||||
Err(e) => return Err(format!("Network error (retrieveUserQuota): {e}")),
|
||||
};
|
||||
|
||||
let quota_status = quota_resp.status();
|
||||
if quota_status == reqwest::StatusCode::UNAUTHORIZED
|
||||
|| quota_status == reqwest::StatusCode::FORBIDDEN
|
||||
{
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Expired,
|
||||
format!("Authentication failed (HTTP {quota_status})."),
|
||||
);
|
||||
));
|
||||
}
|
||||
if !quota_status.is_success() {
|
||||
let body = quota_resp.text().await.unwrap_or_default();
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("retrieveUserQuota failed (HTTP {quota_status}): {body}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
|
||||
let quota_data: GeminiQuotaResponse = match quota_resp.json().await {
|
||||
let quota_raw = match quota_resp.bytes().await {
|
||||
Ok(b) => b,
|
||||
Err(e) => return Err(format!("Failed to read quota response: {e}")),
|
||||
};
|
||||
let quota_data: GeminiQuotaResponse = match serde_json::from_slice("a_raw) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
return SubscriptionQuota::error(
|
||||
return Ok(SubscriptionQuota::error(
|
||||
"gemini",
|
||||
CredentialStatus::Valid,
|
||||
format!("Failed to parse quota response: {e}"),
|
||||
);
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1213,7 +1211,7 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
|
||||
tiers.sort_by_key(|t| sort_order(&t.name));
|
||||
|
||||
SubscriptionQuota {
|
||||
Ok(SubscriptionQuota {
|
||||
tool: "gemini".to_string(),
|
||||
credential_status: CredentialStatus::Valid,
|
||||
credential_message: None,
|
||||
@@ -1222,12 +1220,16 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
|
||||
extra_usage: None,
|
||||
error: None,
|
||||
queried_at: Some(now_millis()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── 入口函数 ──────────────────────────────────────────────
|
||||
|
||||
/// 查询指定 CLI 工具的官方订阅额度
|
||||
///
|
||||
/// 瞬时传输失败以 `Err` 传播(前端 reject → retry + 保留上次成功值)。Expired
|
||||
/// 分支的"过期也试一把"重试同样用 `?` 传播瞬时错误——不能折叠成"已过期",
|
||||
/// 否则一次网络抖动会被误报成确定性的凭据过期。
|
||||
pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, String> {
|
||||
match tool {
|
||||
"claude" => {
|
||||
@@ -1243,7 +1245,7 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
CredentialStatus::Expired => {
|
||||
// 即使过期也尝试调用 API(token 可能实际上仍有效)
|
||||
if let Some(token) = token {
|
||||
let result = query_claude_quota(&token).await;
|
||||
let result = query_claude_quota(&token).await?;
|
||||
if result.success {
|
||||
return Ok(result);
|
||||
}
|
||||
@@ -1256,7 +1258,7 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
}
|
||||
CredentialStatus::Valid => {
|
||||
let token = token.expect("token must be Some when status is Valid");
|
||||
Ok(query_claude_quota(&token).await)
|
||||
query_claude_quota(&token).await
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1279,7 +1281,7 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
"codex",
|
||||
"Authentication failed. Please re-login with Codex CLI.",
|
||||
)
|
||||
.await;
|
||||
.await?;
|
||||
if result.success {
|
||||
return Ok(result);
|
||||
}
|
||||
@@ -1292,13 +1294,13 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
}
|
||||
CredentialStatus::Valid => {
|
||||
let token = token.expect("token must be Some when status is Valid");
|
||||
Ok(query_codex_quota(
|
||||
query_codex_quota(
|
||||
&token,
|
||||
account_id.as_deref(),
|
||||
"codex",
|
||||
"Authentication failed. Please re-login with Codex CLI.",
|
||||
)
|
||||
.await)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1316,12 +1318,12 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
// Gemini access_token 仅 ~1h 有效,尝试用 refresh_token 刷新
|
||||
if let Some(ref rt) = refresh_token {
|
||||
if let Some(new_token) = refresh_gemini_token(rt).await {
|
||||
return Ok(query_gemini_quota(&new_token).await);
|
||||
return query_gemini_quota(&new_token).await;
|
||||
}
|
||||
}
|
||||
// 刷新失败,尝试用旧 token
|
||||
if let Some(ref token) = token {
|
||||
let result = query_gemini_quota(token).await;
|
||||
let result = query_gemini_quota(token).await?;
|
||||
if result.success {
|
||||
return Ok(result);
|
||||
}
|
||||
@@ -1334,7 +1336,7 @@ pub async fn get_subscription_quota(tool: &str) -> Result<SubscriptionQuota, Str
|
||||
}
|
||||
CredentialStatus::Valid => {
|
||||
let token = token.expect("token must be Some when status is Valid");
|
||||
Ok(query_gemini_quota(&token).await)
|
||||
query_gemini_quota(&token).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
use crate::database::{lock_conn, Database};
|
||||
use crate::error::AppError;
|
||||
use crate::proxy::usage::calculator::ModelPricing;
|
||||
use crate::services::sql_helpers::fresh_input_sql;
|
||||
use crate::services::sql_helpers::{
|
||||
fresh_input_sql, INPUT_TOKEN_SEMANTICS_FRESH, INPUT_TOKEN_SEMANTICS_TOTAL,
|
||||
};
|
||||
use chrono::{Local, NaiveDate, TimeZone, Timelike};
|
||||
use rusqlite::{params, Connection, OptionalExtension};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -135,6 +137,9 @@ pub struct RequestLogDetail {
|
||||
pub output_tokens: u32,
|
||||
pub cache_read_tokens: u32,
|
||||
pub cache_creation_tokens: u32,
|
||||
/// Internal storage semantics; omitted from the UI/API payload.
|
||||
#[serde(skip)]
|
||||
pub input_token_semantics: i64,
|
||||
pub input_cost_usd: String,
|
||||
pub output_cost_usd: String,
|
||||
pub cache_read_cost_usd: String,
|
||||
@@ -154,15 +159,15 @@ pub struct RequestLogDetail {
|
||||
pub pricing_model: Option<String>,
|
||||
}
|
||||
|
||||
/// 把 25 列的查询结果映射为 `RequestLogDetail`。
|
||||
/// 把 26 列的查询结果映射为 `RequestLogDetail`。
|
||||
///
|
||||
/// 调用方的 SELECT **必须**按以下顺序返回 25 列:
|
||||
/// 调用方的 SELECT **必须**按以下顺序返回 26 列:
|
||||
/// `request_id, provider_id, provider_name, app_type, model, request_model,
|
||||
/// cost_multiplier, input_tokens, output_tokens, cache_read_tokens,
|
||||
/// cache_creation_tokens, input_cost_usd, output_cost_usd, cache_read_cost_usd,
|
||||
/// cache_creation_cost_usd, total_cost_usd, is_streaming, latency_ms,
|
||||
/// first_token_ms, duration_ms, status_code, error_message, created_at,
|
||||
/// data_source, pricing_model`
|
||||
/// data_source, pricing_model, input_token_semantics`
|
||||
///
|
||||
/// 不需要 provider_name 时(如 backfill)SELECT `NULL AS provider_name` 占位即可。
|
||||
fn row_to_request_log_detail(row: &rusqlite::Row<'_>) -> rusqlite::Result<RequestLogDetail> {
|
||||
@@ -194,6 +199,7 @@ fn row_to_request_log_detail(row: &rusqlite::Row<'_>) -> rusqlite::Result<Reques
|
||||
created_at: row.get(22)?,
|
||||
data_source: row.get(23)?,
|
||||
pricing_model: row.get(24)?,
|
||||
input_token_semantics: row.get::<_, i64>(25)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1526,7 +1532,8 @@ impl Database {
|
||||
l.input_tokens, l.output_tokens, l.cache_read_tokens, l.cache_creation_tokens,
|
||||
l.input_cost_usd, l.output_cost_usd, l.cache_read_cost_usd, l.cache_creation_cost_usd, l.total_cost_usd,
|
||||
l.is_streaming, l.latency_ms, l.first_token_ms, l.duration_ms,
|
||||
l.status_code, l.error_message, l.created_at, l.data_source, l.pricing_model
|
||||
l.status_code, l.error_message, l.created_at, l.data_source, l.pricing_model,
|
||||
l.input_token_semantics
|
||||
FROM proxy_request_logs l
|
||||
LEFT JOIN providers p ON l.provider_id = p.id AND l.app_type = p.app_type
|
||||
{where_clause}
|
||||
@@ -1569,7 +1576,8 @@ impl Database {
|
||||
input_tokens, output_tokens, cache_read_tokens, cache_creation_tokens,
|
||||
input_cost_usd, output_cost_usd, cache_read_cost_usd, cache_creation_cost_usd, total_cost_usd,
|
||||
is_streaming, latency_ms, first_token_ms, duration_ms,
|
||||
status_code, error_message, created_at, l.data_source, l.pricing_model
|
||||
status_code, error_message, created_at, l.data_source, l.pricing_model,
|
||||
l.input_token_semantics
|
||||
FROM proxy_request_logs l
|
||||
LEFT JOIN providers p ON l.provider_id = p.id AND l.app_type = p.app_type
|
||||
WHERE l.request_id = ?"
|
||||
@@ -1725,7 +1733,7 @@ impl Database {
|
||||
input_cost_usd, output_cost_usd, cache_read_cost_usd,
|
||||
cache_creation_cost_usd, total_cost_usd, is_streaming, latency_ms,
|
||||
first_token_ms, duration_ms, status_code, error_message, created_at,
|
||||
data_source, pricing_model
|
||||
data_source, pricing_model, input_token_semantics
|
||||
FROM proxy_request_logs
|
||||
WHERE CAST(total_cost_usd AS REAL) <= 0
|
||||
AND (input_tokens > 0 OR output_tokens > 0
|
||||
@@ -1806,15 +1814,21 @@ impl Database {
|
||||
let million = rust_decimal::Decimal::from(1_000_000u64);
|
||||
|
||||
// 与 CostCalculator::calculate_for_app 保持一致的计算逻辑:
|
||||
// 1. Codex/Gemini 的 input_tokens 包含 cache_read_tokens,需要扣除后按输入价计费
|
||||
// 1. 历史 Codex/Gemini 行只包含 cache read;新 total 行还包含 cache write。
|
||||
// 2. Claude/Anthropic 的 input_tokens 已经是 fresh input,不能再次扣减
|
||||
// 3. 各项成本是基础成本(不含倍率),倍率只作用于最终总价
|
||||
let input_includes_cache_read = matches!(log.app_type.as_str(), "codex" | "gemini");
|
||||
let billable_input_tokens = if input_includes_cache_read {
|
||||
(log.input_tokens as u64).saturating_sub(log.cache_read_tokens as u64)
|
||||
} else {
|
||||
log.input_tokens as u64
|
||||
};
|
||||
let cache_inclusive_app = matches!(log.app_type.as_str(), "codex" | "gemini");
|
||||
let billable_input_tokens =
|
||||
if !cache_inclusive_app || log.input_token_semantics == INPUT_TOKEN_SEMANTICS_FRESH {
|
||||
log.input_tokens as u64
|
||||
} else if log.input_token_semantics == INPUT_TOKEN_SEMANTICS_TOTAL {
|
||||
(log.input_tokens as u64)
|
||||
.saturating_sub(log.cache_read_tokens as u64)
|
||||
.saturating_sub(log.cache_creation_tokens as u64)
|
||||
} else {
|
||||
// v12 and earlier: input included cache reads but excluded cache writes.
|
||||
(log.input_tokens as u64).saturating_sub(log.cache_read_tokens as u64)
|
||||
};
|
||||
let input_cost =
|
||||
rust_decimal::Decimal::from(billable_input_tokens) * pricing.input / million;
|
||||
let output_cost =
|
||||
@@ -2492,6 +2506,77 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backfill_distinguishes_legacy_and_total_cache_semantics() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
{
|
||||
let conn = lock_conn!(db.conn);
|
||||
// v12 mirror row: input = fresh + read; creation was reported separately.
|
||||
insert_usage_log(
|
||||
&conn,
|
||||
"legacy-cache-semantics",
|
||||
"codex",
|
||||
"p1",
|
||||
"gpt-5.5",
|
||||
"proxy",
|
||||
1000,
|
||||
800_000,
|
||||
0,
|
||||
600_000,
|
||||
200_000,
|
||||
200,
|
||||
"0",
|
||||
)?;
|
||||
// v13 proxy row: input = fresh + read + creation.
|
||||
insert_usage_log(
|
||||
&conn,
|
||||
"total-cache-semantics",
|
||||
"codex",
|
||||
"p1",
|
||||
"gpt-5.5",
|
||||
"proxy",
|
||||
1001,
|
||||
1_000_000,
|
||||
0,
|
||||
600_000,
|
||||
200_000,
|
||||
200,
|
||||
"0",
|
||||
)?;
|
||||
conn.execute(
|
||||
"UPDATE proxy_request_logs
|
||||
SET input_token_semantics = ?1
|
||||
WHERE request_id = 'total-cache-semantics'",
|
||||
[INPUT_TOKEN_SEMANTICS_TOTAL],
|
||||
)?;
|
||||
}
|
||||
|
||||
assert_eq!(db.backfill_missing_usage_costs()?, 2);
|
||||
|
||||
let conn = lock_conn!(db.conn);
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT request_id, input_cost_usd
|
||||
FROM proxy_request_logs
|
||||
WHERE request_id IN ('legacy-cache-semantics', 'total-cache-semantics')
|
||||
ORDER BY request_id",
|
||||
)?;
|
||||
let rows = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
|
||||
})?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
assert_eq!(
|
||||
rows,
|
||||
vec![
|
||||
("legacy-cache-semantics".to_string(), "1.000000".to_string()),
|
||||
("total-cache-semantics".to_string(), "1.000000".to_string()),
|
||||
]
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_backfill_missing_usage_costs_uses_stored_multiplier() -> Result<(), AppError> {
|
||||
let db = Database::memory()?;
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::LazyLock;
|
||||
use std::time::Duration;
|
||||
|
||||
use regex::Regex;
|
||||
use rusqlite::Connection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::codex_config::get_codex_config_dir;
|
||||
use crate::codex_config::{get_codex_config_dir, read_codex_config_text};
|
||||
use crate::codex_state_db::codex_state_db_paths;
|
||||
use crate::session_manager::{SessionMessage, SessionMeta};
|
||||
|
||||
use super::utils::{
|
||||
@@ -15,6 +20,7 @@ use super::utils::{
|
||||
};
|
||||
|
||||
const PROVIDER_ID: &str = "codex";
|
||||
const CODEX_SESSION_INDEX_FILENAME: &str = "session_index.jsonl";
|
||||
const VSCODE_CONTEXT_PREFIX: &str = "# Context from my IDE setup:";
|
||||
const CODEX_REQUEST_MARKER: &str = "my request for codex";
|
||||
|
||||
@@ -23,6 +29,12 @@ static UUID_RE: LazyLock<Regex> = LazyLock::new(|| {
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct SessionIndexEntry {
|
||||
id: String,
|
||||
thread_name: String,
|
||||
}
|
||||
|
||||
pub fn scan_sessions() -> Vec<SessionMeta> {
|
||||
let roots = session_roots();
|
||||
scan_sessions_in_roots(&roots)
|
||||
@@ -37,6 +49,14 @@ pub fn session_roots() -> Vec<PathBuf> {
|
||||
}
|
||||
|
||||
fn scan_sessions_in_roots(roots: &[PathBuf]) -> Vec<SessionMeta> {
|
||||
let thread_titles = load_thread_titles();
|
||||
scan_sessions_in_roots_with_titles(roots, &thread_titles)
|
||||
}
|
||||
|
||||
fn scan_sessions_in_roots_with_titles(
|
||||
roots: &[PathBuf],
|
||||
thread_titles: &HashMap<String, String>,
|
||||
) -> Vec<SessionMeta> {
|
||||
let mut files = Vec::new();
|
||||
for root in roots {
|
||||
collect_jsonl_files(root, &mut files);
|
||||
@@ -44,7 +64,7 @@ fn scan_sessions_in_roots(roots: &[PathBuf]) -> Vec<SessionMeta> {
|
||||
|
||||
let mut sessions = Vec::new();
|
||||
for path in files {
|
||||
if let Some(meta) = parse_session(&path) {
|
||||
if let Some(meta) = parse_session_with_titles(&path, thread_titles) {
|
||||
sessions.push(meta);
|
||||
}
|
||||
}
|
||||
@@ -52,6 +72,135 @@ fn scan_sessions_in_roots(roots: &[PathBuf]) -> Vec<SessionMeta> {
|
||||
sessions
|
||||
}
|
||||
|
||||
fn load_thread_titles() -> HashMap<String, String> {
|
||||
let config_dir = get_codex_config_dir();
|
||||
let config_text = read_codex_config_text().unwrap_or_default();
|
||||
let db_paths = codex_state_db_paths(&config_dir, &config_text);
|
||||
load_thread_titles_from_paths(&config_dir.join(CODEX_SESSION_INDEX_FILENAME), &db_paths)
|
||||
}
|
||||
|
||||
fn load_thread_titles_from_paths(
|
||||
session_index_path: &Path,
|
||||
db_paths: &[PathBuf],
|
||||
) -> HashMap<String, String> {
|
||||
let mut titles = load_thread_titles_from_session_index(session_index_path);
|
||||
for db_path in db_paths {
|
||||
titles.extend(load_thread_titles_from_db(db_path));
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
fn load_thread_titles_from_session_index(index_path: &Path) -> HashMap<String, String> {
|
||||
if !index_path.exists() {
|
||||
return HashMap::new();
|
||||
}
|
||||
|
||||
let file = match File::open(index_path) {
|
||||
Ok(file) => file,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to open Codex session index {}: {err}",
|
||||
index_path.display()
|
||||
);
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
let reader = BufReader::new(file);
|
||||
let mut titles = HashMap::new();
|
||||
for line in reader.lines() {
|
||||
let line = match line {
|
||||
Ok(line) => line,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let Ok(entry) = serde_json::from_str::<SessionIndexEntry>(line.trim()) else {
|
||||
continue;
|
||||
};
|
||||
let id = entry.id.trim();
|
||||
let title = entry.thread_name.trim();
|
||||
if !id.is_empty() && !title.is_empty() {
|
||||
titles.insert(id.to_string(), title.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
titles
|
||||
}
|
||||
|
||||
fn load_thread_titles_from_db(db_path: &Path) -> HashMap<String, String> {
|
||||
if !db_path.exists() {
|
||||
return HashMap::new();
|
||||
}
|
||||
|
||||
let conn = match Connection::open_with_flags(
|
||||
db_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
) {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to open Codex state database {}: {err}",
|
||||
db_path.display()
|
||||
);
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
// Codex keeps this DB open and write-locked while running; without a busy
|
||||
// timeout a read during a write fails immediately and titles silently drop.
|
||||
if let Err(err) = conn.busy_timeout(Duration::from_secs(2)) {
|
||||
log::warn!(
|
||||
"Failed to set Codex state database busy timeout for {}: {err}",
|
||||
db_path.display()
|
||||
);
|
||||
return HashMap::new();
|
||||
}
|
||||
|
||||
// Mirror Codex's own `distinct_thread_metadata_title`: keep a title only
|
||||
// when it differs from the first user message. Push the comparison into SQL
|
||||
// (NULL-safe) so we never SELECT the unbounded `first_user_message` blob —
|
||||
// it can grow large enough to OOM (openai/codex#29007).
|
||||
let mut stmt = match conn.prepare(
|
||||
"SELECT id, title FROM threads \
|
||||
WHERE title <> '' \
|
||||
AND (first_user_message IS NULL OR TRIM(title) <> TRIM(first_user_message))",
|
||||
) {
|
||||
Ok(stmt) => stmt,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to prepare Codex thread title query for {}: {err}",
|
||||
db_path.display()
|
||||
);
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
let rows = match stmt.query_map([], |row| {
|
||||
let id: String = row.get(0)?;
|
||||
let title: String = row.get(1)?;
|
||||
Ok((id, title))
|
||||
}) {
|
||||
Ok(rows) => rows,
|
||||
Err(err) => {
|
||||
log::warn!(
|
||||
"Failed to query Codex thread titles from {}: {err}",
|
||||
db_path.display()
|
||||
);
|
||||
return HashMap::new();
|
||||
}
|
||||
};
|
||||
|
||||
rows.flatten()
|
||||
.filter_map(|(id, title)| {
|
||||
let id = id.trim();
|
||||
let title = title.trim();
|
||||
if id.is_empty() || title.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some((id.to_string(), title.to_string()))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
|
||||
let file = File::open(path).map_err(|e| format!("Failed to open session file: {e}"))?;
|
||||
let reader = BufReader::new(file);
|
||||
@@ -141,6 +290,13 @@ pub fn delete_session(_root: &Path, path: &Path, session_id: &str) -> Result<boo
|
||||
}
|
||||
|
||||
fn parse_session(path: &Path) -> Option<SessionMeta> {
|
||||
parse_session_with_titles(path, &HashMap::new())
|
||||
}
|
||||
|
||||
fn parse_session_with_titles(
|
||||
path: &Path,
|
||||
thread_titles: &HashMap<String, String>,
|
||||
) -> Option<SessionMeta> {
|
||||
let (head, tail) = read_head_tail_lines(path, 10, 30).ok()?;
|
||||
|
||||
let mut session_id: Option<String> = None;
|
||||
@@ -233,8 +389,10 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
|
||||
let session_id = session_id.or_else(|| infer_session_id_from_filename(path));
|
||||
let session_id = session_id?;
|
||||
|
||||
let title = first_user_message
|
||||
.map(|t| truncate_summary(&t, TITLE_MAX_CHARS))
|
||||
let title = thread_titles
|
||||
.get(&session_id)
|
||||
.map(|t| truncate_summary(t, TITLE_MAX_CHARS))
|
||||
.or_else(|| first_user_message.map(|t| truncate_summary(&t, TITLE_MAX_CHARS)))
|
||||
.or_else(|| {
|
||||
project_dir
|
||||
.as_deref()
|
||||
@@ -366,6 +524,7 @@ fn collect_jsonl_files(root: &Path, files: &mut Vec<PathBuf>) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::codex_state_db::CODEX_STATE_DB_FILENAME;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn write_codex_session(path: &Path, session_id: &str, message: &str) {
|
||||
@@ -443,6 +602,166 @@ mod tests {
|
||||
assert_eq!(meta.title.as_deref(), Some("How do I deploy?"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_session_prefers_thread_title() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let path = temp.path().join("session.jsonl");
|
||||
std::fs::write(
|
||||
&path,
|
||||
concat!(
|
||||
"{\"timestamp\":\"2026-03-06T21:50:12Z\",\"type\":\"session_meta\",\"payload\":{\"id\":\"test-id\",\"cwd\":\"/tmp/project\"}}\n",
|
||||
"{\"timestamp\":\"2026-03-06T21:50:13Z\",\"type\":\"response_item\",\"payload\":{\"type\":\"message\",\"role\":\"user\",\"content\":\"How do I deploy?\"}}\n"
|
||||
),
|
||||
)
|
||||
.expect("write");
|
||||
|
||||
let mut thread_titles = HashMap::new();
|
||||
thread_titles.insert(
|
||||
"test-id".to_string(),
|
||||
"Renamed deployment thread".to_string(),
|
||||
);
|
||||
|
||||
let meta = parse_session_with_titles(&path, &thread_titles).unwrap();
|
||||
assert_eq!(meta.title.as_deref(), Some("Renamed deployment thread"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_thread_titles_from_state_db_trims_and_filters_titles() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let db_path = temp.path().join(CODEX_STATE_DB_FILENAME);
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
conn.execute(
|
||||
"CREATE TABLE threads (id TEXT PRIMARY KEY, title TEXT NOT NULL, first_user_message TEXT NOT NULL)",
|
||||
[],
|
||||
)
|
||||
.expect("create threads table");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-1", " Renamed Codex thread ", "First prompt"),
|
||||
)
|
||||
.expect("insert renamed thread");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-2", " ", "First prompt"),
|
||||
)
|
||||
.expect("insert blank thread");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-3", " First prompt ", "First prompt"),
|
||||
)
|
||||
.expect("insert first-message title");
|
||||
drop(conn);
|
||||
|
||||
let titles = load_thread_titles_from_db(&db_path);
|
||||
|
||||
assert_eq!(
|
||||
titles.get("thread-1").map(String::as_str),
|
||||
Some("Renamed Codex thread")
|
||||
);
|
||||
assert!(!titles.contains_key("thread-2"));
|
||||
assert!(!titles.contains_key("thread-3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_thread_titles_from_state_db_keeps_title_when_first_user_message_null() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let db_path = temp.path().join(CODEX_STATE_DB_FILENAME);
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
// Codex stores first_user_message as a nullable column (Option<String>);
|
||||
// a renamed thread can have a title before any first message is synced.
|
||||
conn.execute(
|
||||
"CREATE TABLE threads (id TEXT PRIMARY KEY, title TEXT NOT NULL, first_user_message TEXT)",
|
||||
[],
|
||||
)
|
||||
.expect("create threads table");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, NULL)",
|
||||
("thread-1", "Renamed thread"),
|
||||
)
|
||||
.expect("insert renamed thread without first message");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-2", "First prompt", "First prompt"),
|
||||
)
|
||||
.expect("insert first-message title");
|
||||
drop(conn);
|
||||
|
||||
let titles = load_thread_titles_from_db(&db_path);
|
||||
|
||||
// Kept: title present and no first message to compare against.
|
||||
assert_eq!(
|
||||
titles.get("thread-1").map(String::as_str),
|
||||
Some("Renamed thread")
|
||||
);
|
||||
// Filtered: title equals the first user message.
|
||||
assert!(!titles.contains_key("thread-2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_thread_titles_from_session_index_uses_latest_name() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let index_path = temp.path().join(CODEX_SESSION_INDEX_FILENAME);
|
||||
std::fs::write(
|
||||
&index_path,
|
||||
concat!(
|
||||
"{\"id\":\"thread-1\",\"thread_name\":\"Old name\",\"updated_at\":\"2026-07-01T00:00:00Z\"}\n",
|
||||
"{\"id\":\"thread-2\",\"thread_name\":\" \",\"updated_at\":\"2026-07-01T00:00:00Z\"}\n",
|
||||
"not json\n",
|
||||
"{\"id\":\"thread-1\",\"thread_name\":\" New name \",\"updated_at\":\"2026-07-02T00:00:00Z\"}\n"
|
||||
),
|
||||
)
|
||||
.expect("write session index");
|
||||
|
||||
let titles = load_thread_titles_from_session_index(&index_path);
|
||||
|
||||
assert_eq!(titles.get("thread-1").map(String::as_str), Some("New name"));
|
||||
assert!(!titles.contains_key("thread-2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_thread_titles_prefers_state_db_explicit_title_over_session_index() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
let index_path = temp.path().join(CODEX_SESSION_INDEX_FILENAME);
|
||||
std::fs::write(
|
||||
&index_path,
|
||||
concat!(
|
||||
"{\"id\":\"thread-1\",\"thread_name\":\"Legacy name\",\"updated_at\":\"2026-07-01T00:00:00Z\"}\n",
|
||||
"{\"id\":\"thread-2\",\"thread_name\":\"Legacy fallback\",\"updated_at\":\"2026-07-01T00:00:00Z\"}\n"
|
||||
),
|
||||
)
|
||||
.expect("write session index");
|
||||
|
||||
let db_path = temp.path().join(CODEX_STATE_DB_FILENAME);
|
||||
let conn = Connection::open(&db_path).expect("open sqlite db");
|
||||
conn.execute(
|
||||
"CREATE TABLE threads (id TEXT PRIMARY KEY, title TEXT NOT NULL, first_user_message TEXT NOT NULL)",
|
||||
[],
|
||||
)
|
||||
.expect("create threads table");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-1", "SQLite name", "First prompt"),
|
||||
)
|
||||
.expect("insert sqlite title");
|
||||
conn.execute(
|
||||
"INSERT INTO threads (id, title, first_user_message) VALUES (?1, ?2, ?3)",
|
||||
("thread-2", "First prompt", "First prompt"),
|
||||
)
|
||||
.expect("insert first-message sqlite title");
|
||||
drop(conn);
|
||||
|
||||
let titles = load_thread_titles_from_paths(&index_path, &[db_path]);
|
||||
|
||||
assert_eq!(
|
||||
titles.get("thread-1").map(String::as_str),
|
||||
Some("SQLite name")
|
||||
);
|
||||
assert_eq!(
|
||||
titles.get("thread-2").map(String::as_str),
|
||||
Some("Legacy fallback")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_session_skips_agents_md_injection() {
|
||||
let temp = tempdir().expect("tempdir");
|
||||
|
||||
@@ -149,7 +149,7 @@ fn scan_sessions_sqlite() -> Vec<SessionMeta> {
|
||||
created_at: Some(created),
|
||||
last_active_at: Some(updated),
|
||||
source_path: Some(format!("sqlite:{db_display}:{session_id}")),
|
||||
resume_command: Some(format!("opencode session resume {session_id}")),
|
||||
resume_command: Some(format!("opencode -s {session_id}")),
|
||||
});
|
||||
}
|
||||
sessions
|
||||
@@ -473,7 +473,7 @@ fn parse_session(storage: &Path, path: &Path) -> Option<SessionMeta> {
|
||||
created_at,
|
||||
last_active_at: updated_at.or(created_at),
|
||||
source_path: Some(source_path),
|
||||
resume_command: Some(format!("opencode session resume {session_id}")),
|
||||
resume_command: Some(format!("opencode -s {session_id}")),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -825,6 +825,10 @@ mod tests {
|
||||
sessions[1].source_path.as_deref(),
|
||||
Some(expected_source.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
sessions[1].resume_command.as_deref(),
|
||||
Some("opencode -s ses_1")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -366,12 +366,14 @@ pub struct AppSettings {
|
||||
/// User has confirmed the usage query first-run notice
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage_confirmed: Option<bool>,
|
||||
/// User has confirmed the stream check first-run notice
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub stream_check_confirmed: Option<bool>,
|
||||
pub usage_dashboard_refresh_interval_ms: Option<u32>,
|
||||
/// Whether to show the failover toggle independently on the main page
|
||||
#[serde(default)]
|
||||
pub enable_failover_toggle: bool,
|
||||
/// Whether to show the project profile switcher on the main page header
|
||||
#[serde(default = "default_show_profile_switcher")]
|
||||
pub show_profile_switcher: bool,
|
||||
/// Keep Codex ChatGPT login material in auth.json when switching to third-party providers.
|
||||
/// Opt-in: defaults to false so third-party switches cleanly overwrite auth.json.
|
||||
#[serde(default)]
|
||||
@@ -488,6 +490,10 @@ fn default_minimize_to_tray_on_close() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn default_show_profile_switcher() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for AppSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -501,8 +507,9 @@ impl Default for AppSettings {
|
||||
enable_local_proxy: false,
|
||||
proxy_confirmed: None,
|
||||
usage_confirmed: None,
|
||||
stream_check_confirmed: None,
|
||||
usage_dashboard_refresh_interval_ms: None,
|
||||
enable_failover_toggle: false,
|
||||
show_profile_switcher: true,
|
||||
preserve_codex_official_auth_on_switch: false,
|
||||
unify_codex_session_history: false,
|
||||
unify_codex_migrate_existing: None,
|
||||
|
||||
+192
-2
@@ -54,6 +54,8 @@ pub struct TrayTexts {
|
||||
pub lightweight_mode: &'static str,
|
||||
pub quit: &'static str,
|
||||
pub _auto_label: &'static str,
|
||||
pub projects_label: &'static str,
|
||||
pub no_project_label: &'static str,
|
||||
}
|
||||
|
||||
impl TrayTexts {
|
||||
@@ -66,6 +68,8 @@ impl TrayTexts {
|
||||
lightweight_mode: "Lightweight Mode",
|
||||
quit: "Quit",
|
||||
_auto_label: "Auto (Failover)",
|
||||
projects_label: "Projects",
|
||||
no_project_label: "No project",
|
||||
},
|
||||
"ja" => Self {
|
||||
show_main: "メインウィンドウを開く",
|
||||
@@ -74,6 +78,8 @@ impl TrayTexts {
|
||||
lightweight_mode: "軽量モード",
|
||||
quit: "終了",
|
||||
_auto_label: "自動 (フェイルオーバー)",
|
||||
projects_label: "プロジェクト",
|
||||
no_project_label: "プロジェクトを使用しない",
|
||||
},
|
||||
"zh-TW" => Self {
|
||||
show_main: "開啟主介面",
|
||||
@@ -82,6 +88,8 @@ impl TrayTexts {
|
||||
lightweight_mode: "輕量模式",
|
||||
quit: "退出",
|
||||
_auto_label: "自動 (故障轉移)",
|
||||
projects_label: "專案",
|
||||
no_project_label: "不使用專案",
|
||||
},
|
||||
_ => Self {
|
||||
show_main: "打开主界面",
|
||||
@@ -90,6 +98,8 @@ impl TrayTexts {
|
||||
lightweight_mode: "轻量模式",
|
||||
quit: "退出",
|
||||
_auto_label: "自动 (故障转移)",
|
||||
projects_label: "项目",
|
||||
no_project_label: "不使用项目",
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -326,6 +336,95 @@ fn sort_providers(
|
||||
sorted
|
||||
}
|
||||
|
||||
/// 处理项目 Profile 托盘事件,返回是否已处理
|
||||
///
|
||||
/// 事件 id 形如 `profile_<scope>_<uuid>`(同一项目在各分组子菜单里各有一项,
|
||||
/// 应用时只作用于该分组);`profile_none_<scope>` 表示某分组"不使用项目"
|
||||
/// (只清该分组标记,不动配置)。
|
||||
pub fn handle_profile_tray_event(app: &tauri::AppHandle, event_id: &str) -> bool {
|
||||
let Some(suffix) = event_id.strip_prefix("profile_") else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if let Some(scope_str) = suffix.strip_prefix("none_") {
|
||||
let Ok(scope) = crate::services::profile::ProfileScope::parse(scope_str) else {
|
||||
log::error!("未知的项目分组托盘事件: {event_id}");
|
||||
return true;
|
||||
};
|
||||
if let Some(app_state) = app.try_state::<AppState>() {
|
||||
if let Err(e) = app_state.db.set_current_profile_id(scope.as_str(), None) {
|
||||
log::error!("清除当前项目失败: {e}");
|
||||
}
|
||||
}
|
||||
// 通知主窗口刷新(profileId=null 表示该分组已清除当前项目)
|
||||
if let Err(e) = app.emit(
|
||||
"profile-applied",
|
||||
serde_json::json!({ "profileId": null, "scope": scope.as_str() }),
|
||||
) {
|
||||
log::error!("发射 profile-applied 事件失败: {e}");
|
||||
}
|
||||
refresh_tray_menu(app);
|
||||
return true;
|
||||
}
|
||||
|
||||
// scope 是固定枚举字符串(不含下划线),uuid 只含连字符,首个下划线即分界
|
||||
let Some((scope_str, profile_id)) = suffix.split_once('_') else {
|
||||
log::error!("无法解析项目托盘事件: {event_id}");
|
||||
return true;
|
||||
};
|
||||
let Ok(scope) = crate::services::profile::ProfileScope::parse(scope_str) else {
|
||||
log::error!("未知的项目分组托盘事件: {event_id}");
|
||||
return true;
|
||||
};
|
||||
|
||||
log::info!("应用项目: {profile_id}({scope_str} 组)");
|
||||
let app_handle = app.clone();
|
||||
let profile_id = profile_id.to_string();
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let Some(app_state) = app_handle.try_state::<AppState>() else {
|
||||
return;
|
||||
};
|
||||
match crate::services::profile::ProfileService::apply(app_state.inner(), &profile_id, scope)
|
||||
{
|
||||
Ok((warnings, should_stop_proxy)) => {
|
||||
for warning in &warnings {
|
||||
log::warn!("[Profile] 应用项目 {profile_id} 警告: {warning}");
|
||||
}
|
||||
|
||||
if should_stop_proxy {
|
||||
let app_handle2 = app_handle.clone();
|
||||
let proxy_service = app_state.proxy_service.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = proxy_service.stop().await {
|
||||
log::warn!("托盘切换项目后停止代理服务失败: {e}");
|
||||
}
|
||||
if let Some(state) = app_handle2.try_state::<AppState>() {
|
||||
crate::commands::emit_profile_apply_events(
|
||||
&app_handle2,
|
||||
state.inner(),
|
||||
&profile_id,
|
||||
scope,
|
||||
);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
crate::commands::emit_profile_apply_events(
|
||||
&app_handle,
|
||||
app_state.inner(),
|
||||
&profile_id,
|
||||
scope,
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("应用项目 {profile_id} 失败: {e}");
|
||||
refresh_tray_menu(&app_handle);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// 处理供应商托盘事件
|
||||
pub fn handle_provider_tray_event(app: &tauri::AppHandle, event_id: &str) -> bool {
|
||||
for section in TRAY_SECTIONS.iter() {
|
||||
@@ -574,8 +673,12 @@ pub fn create_tray_menu(
|
||||
|
||||
for (id, provider) in sort_providers(&providers) {
|
||||
let is_current = current_id == *id;
|
||||
let is_official_blocked =
|
||||
is_app_taken_over && provider.category.as_deref() == Some("official");
|
||||
let is_official_blocked = is_app_taken_over
|
||||
&& provider.category.as_deref() == Some("official")
|
||||
&& !crate::services::provider::official_provider_supports_proxy_takeover(
|
||||
§ion.app_type,
|
||||
provider,
|
||||
);
|
||||
let label = if is_official_blocked {
|
||||
format!("{} \u{26D4}", &provider.name) // ⛔ emoji
|
||||
} else {
|
||||
@@ -605,6 +708,90 @@ pub fn create_tray_menu(
|
||||
menu_builder = menu_builder.separator();
|
||||
}
|
||||
|
||||
// 项目 Profile 子菜单:项目列表全应用共享,按分组嵌套子菜单各自勾选/应用
|
||||
// (组内应用可见且存在项目时才显示该组)
|
||||
{
|
||||
use crate::services::profile::ProfileScope;
|
||||
|
||||
let any_scope_visible = ProfileScope::ALL.iter().any(|scope| {
|
||||
scope
|
||||
.apps()
|
||||
.iter()
|
||||
.any(|app_type| visible_apps.is_visible(app_type))
|
||||
});
|
||||
let profiles = if any_scope_visible {
|
||||
app_state.db.get_all_profiles()?
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let mut scope_submenus = Vec::new();
|
||||
for scope in ProfileScope::ALL {
|
||||
if profiles.is_empty()
|
||||
|| !scope
|
||||
.apps()
|
||||
.iter()
|
||||
.any(|app_type| visible_apps.is_visible(app_type))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let current_profile_id = app_state
|
||||
.db
|
||||
.get_current_profile_id(scope.as_str())?
|
||||
.unwrap_or_default();
|
||||
// 分组标签用产品名,不进 i18n
|
||||
let scope_label = match scope {
|
||||
ProfileScope::Claude => "Claude Code",
|
||||
ProfileScope::ClaudeDesktop => "Claude Desktop",
|
||||
ProfileScope::Codex => "Codex",
|
||||
};
|
||||
let mut scope_builder = SubmenuBuilder::with_id(
|
||||
app,
|
||||
format!("submenu_profiles_{}", scope.as_str()),
|
||||
scope_label,
|
||||
);
|
||||
for profile in &profiles {
|
||||
let item = CheckMenuItem::with_id(
|
||||
app,
|
||||
format!("profile_{}_{}", scope.as_str(), profile.id),
|
||||
&profile.name,
|
||||
true,
|
||||
current_profile_id == profile.id,
|
||||
None::<&str>,
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("创建项目菜单项失败: {e}")))?;
|
||||
scope_builder = scope_builder.item(&item);
|
||||
}
|
||||
let none_item = CheckMenuItem::with_id(
|
||||
app,
|
||||
format!("profile_none_{}", scope.as_str()),
|
||||
tray_texts.no_project_label,
|
||||
true,
|
||||
current_profile_id.is_empty(),
|
||||
None::<&str>,
|
||||
)
|
||||
.map_err(|e| AppError::Message(format!("创建不使用项目菜单项失败: {e}")))?;
|
||||
let scope_submenu = scope_builder
|
||||
.separator()
|
||||
.item(&none_item)
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("构建项目分组子菜单失败: {e}")))?;
|
||||
scope_submenus.push(scope_submenu);
|
||||
}
|
||||
|
||||
if !scope_submenus.is_empty() {
|
||||
let mut profiles_builder =
|
||||
SubmenuBuilder::with_id(app, "submenu_profiles", tray_texts.projects_label);
|
||||
for scope_submenu in &scope_submenus {
|
||||
profiles_builder = profiles_builder.item(scope_submenu);
|
||||
}
|
||||
let profiles_submenu = profiles_builder
|
||||
.build()
|
||||
.map_err(|e| AppError::Message(format!("构建项目子菜单失败: {e}")))?;
|
||||
menu_builder = menu_builder.item(&profiles_submenu).separator();
|
||||
}
|
||||
}
|
||||
|
||||
let lightweight_item = CheckMenuItem::with_id(
|
||||
app,
|
||||
"lightweight_mode",
|
||||
@@ -750,6 +937,9 @@ pub fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
|
||||
app.exit(0);
|
||||
}
|
||||
_ => {
|
||||
if handle_profile_tray_event(app, event_id) {
|
||||
return;
|
||||
}
|
||||
if handle_provider_tray_event(app, event_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "CC Switch",
|
||||
"version": "3.16.5",
|
||||
"version": "3.17.0",
|
||||
"identifier": "com.ccswitch.desktop",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -497,6 +497,42 @@ fn sync_enabled_to_codex_returns_error_on_invalid_toml() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_single_server_to_codex_fails_closed_on_invalid_toml() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let path = cc_switch_lib::get_codex_config_path();
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("create codex dir");
|
||||
}
|
||||
// 含用户内容 + 语法错误的 config.toml:同步必须报错且不得覆盖文件
|
||||
let broken = "model = \"gpt-5.5\"\ninvalid = [\n";
|
||||
fs::write(&path, broken).expect("write invalid config");
|
||||
|
||||
let config = MultiAppConfig::default();
|
||||
let err = cc_switch_lib::sync_single_server_to_codex(
|
||||
&config,
|
||||
"srv",
|
||||
&json!({ "type": "stdio", "command": "echo" }),
|
||||
)
|
||||
.expect_err("sync should fail instead of wiping the file");
|
||||
match err {
|
||||
cc_switch_lib::AppError::McpValidation(msg) => {
|
||||
assert!(
|
||||
msg.contains("config.toml"),
|
||||
"error message should mention config.toml"
|
||||
);
|
||||
}
|
||||
other => panic!("unexpected error: {other:?}"),
|
||||
}
|
||||
|
||||
let text = fs::read_to_string(&path).expect("read config.toml");
|
||||
assert_eq!(
|
||||
text, broken,
|
||||
"invalid config.toml must be left untouched on sync failure"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_codex_provider_missing_auth_returns_error() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
|
||||
@@ -287,6 +287,56 @@ fn import_mcp_from_claude_invalid_json_preserves_state() {
|
||||
);
|
||||
}
|
||||
|
||||
/// "从应用导入"是 best-effort:单个应用的坏配置文件不阻断其余应用的
|
||||
/// 导入,但失败必须聚合上报——历史实现逐应用 `unwrap_or(0)` 吞错,
|
||||
/// 坏 config.toml 只会表现为"导入成功 0 个",用户无从得知出了什么问题。
|
||||
#[test]
|
||||
fn import_from_all_apps_reports_broken_app_but_imports_the_rest() {
|
||||
use support::create_test_state;
|
||||
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
reset_test_fs();
|
||||
let home = ensure_test_home();
|
||||
|
||||
// 好的 ~/.claude.json:应正常导入
|
||||
let claude_json = json!({
|
||||
"mcpServers": {
|
||||
"alpha": { "type": "stdio", "command": "echo" }
|
||||
}
|
||||
});
|
||||
fs::write(
|
||||
get_claude_mcp_path(),
|
||||
serde_json::to_string_pretty(&claude_json).expect("serialize claude mcp"),
|
||||
)
|
||||
.expect("seed ~/.claude.json");
|
||||
|
||||
// 坏的 ~/.codex/config.toml:解析必然失败
|
||||
let codex_dir = home.join(".codex");
|
||||
fs::create_dir_all(&codex_dir).expect("create codex dir");
|
||||
fs::write(codex_dir.join("config.toml"), "not = = valid toml")
|
||||
.expect("seed broken codex config");
|
||||
|
||||
let state = create_test_state().expect("create test state");
|
||||
|
||||
let err = McpService::import_from_all_apps(&state)
|
||||
.expect_err("broken codex config must surface, not be swallowed as zero imports");
|
||||
let message = err.to_string();
|
||||
assert!(
|
||||
message.contains("codex"),
|
||||
"aggregated error should name the failing app, got: {message}"
|
||||
);
|
||||
|
||||
// Codex 的失败不阻断 Claude:alpha 应已入库并启用 Claude
|
||||
let servers = state.db.get_all_mcp_servers().expect("get all mcp servers");
|
||||
let entry = servers
|
||||
.get("alpha")
|
||||
.expect("claude server imported despite codex failure");
|
||||
assert!(
|
||||
entry.apps.claude,
|
||||
"imported server should have Claude app enabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_mcp_enabled_for_codex_writes_live_config() {
|
||||
let _guard = test_mutex().lock().expect("acquire test mutex");
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user