Compare commits

...

110 Commits

Author SHA1 Message Date
Jason 3d176b98cc docs(release): add v3.17.0 release notes 2026-07-13 23:41:54 +08:00
Jason c154d30b7a chore(release): v3.17.0 2026-07-13 21:24:58 +08:00
Jason 6eb217b242 revert(proxy): drop the 1-hour cache TTL option and TTL-bucketed write accounting
The forced 1-hour cache_control TTL (schema v14) was a mistake. Injected
breakpoints return to Anthropic's standard 5-minute TTL, caller-owned
markers are preserved verbatim instead of having their TTLs rewritten,
and the 5m/1h cache-write buckets are removed from usage parsing and
pricing (back to the single aggregate cache-creation rate). The cache
TTL selector is removed from the rectifier settings panel along with its
i18n keys in all four locales.

SCHEMA_VERSION returns to 13: the unreleased cache_creation_1h_tokens
column and the v13->v14 migration are removed. The feature never shipped
in a release and the introducing commit was never pushed, so no
databases were stamped v14 outside this machine (local DB verified at
user_version 13).
2026-07-13 17:55:33 +08:00
Jason ac52c851bf fix(codex): infer image capability for generated catalogs and resync takeover live on save
Mapped GPT models were rejected by Codex clients with "model does not
support image inputs". Two root causes:

- Catalog entries for native-Responses/Anthropic providers cloned a
  template whose input_modalities defaulted to ["text"], so every mapped
  model was advertised text-only. model_catalog_json replaces Codex's
  built-in model table wholesale, and both the TUI and the IDE extension
  block images pre-send when the current model is found without "image".
- Editing the current Codex provider during proxy takeover only refreshed
  the DB backup, so removing the mapping left a stale model_catalog_json
  pointer (and its text-only catalog file) active in live config.

Changes:

- New shared model_capabilities module: explicit row declaration first,
  then a confirmed text-only registry (exact tail match only — prefix
  matching removed, variants enumerated so future -vl/-vision models fail
  open), everything else unknown.
- Catalog generation writes input_modalities from that inference for all
  tool profiles: unknown models fail open to ["text","image"]; only
  confirmed text-only models are advertised as ["text"], giving users a
  clear client-side prompt instead of silent image stripping.
- Live catalog reverse-import collapses modalities that match current
  inference, so registry corrections are not frozen into hidden row
  overrides and the rectifier's heuristic opt-out keeps working.
- Saving the current Codex provider while takeover owns live now
  re-projects the live config (mirrors the hot-switch path), so mapping
  edits and removals take effect immediately.
- Media rectifier delegates to the shared module; its preflight toggle is
  documented (4 locales) as proxy-request-only, never affecting catalog
  capability declarations.
2026-07-13 16:48:22 +08:00
Jason 618723b42f feat(presets): promote SudoCode to paid sponsor across six clients
Replace the legacy sudocode.us provider (a name collision) with the new
paid sponsor SudoCode on sudocode.chat, updated in place across six
clients: Claude Code, Codex, Claude Desktop, OpenCode, OpenClaw, Hermes.

- Switch endpoints to api.sudocode.chat, add isPartner +
  partnerPromotionKey, and add four-locale partnerPromotion copy
- Claude Code / Desktop use direct passthrough (no model mapping)
- Codex / OpenCode / OpenClaw / Hermes use gpt-5.6-sol
- Remove the Gemini entry (outside sponsor scope)
- Replace the provider icon with the new brand PNG
2026-07-13 16:48:22 +08:00
Jason af58740bcd fix(proxy): align Codex OAuth client identity
ChatGPT's Codex backend routes model availability by the originator and version header pair. Requests identifying as cc-switch without a version were assigned to a cohort where gpt-5.6-luna resolved to an unavailable internal engine, resulting in a misleading 404 Model not found response.

Identify takeover requests as codex_cli_rs and send version 0.144.1, satisfying luna's minimal_client_version requirement of 0.144.0. A direct HTTP A/B test confirmed the existing headers returned 404 while the aligned identity completed successfully, so no WebSocket transport workaround is required.
2026-07-13 16:48:22 +08:00
Jason 99573d2242 refactor(presets): pin context window values instead of form fields
Drop the Max Context Tokens / Auto Compact Window template inputs from
the Codex and Kimi For Coding presets and hardcode the values in the
preset env (372000 / 262144). The rare user who wants different numbers
can edit them directly in the JSON editor.

Both keys stay on purpose: the compact window resolves as
min(model window, value), so matching the window is behavior-neutral
today, but the explicit env pins compaction locally against
remote-config experiments dialing it down.
2026-07-13 16:48:21 +08:00
Jason 940ddd332b feat(kimi): declare the 256K context window for Kimi For Coding
Claude Code caps unknown model ids at 200K, so the preset's standalone
CLAUDE_CODE_AUTO_COMPACT_WINDOW=262144 was clamped by min(window, value)
and never took effect. Pair it with CLAUDE_CODE_MAX_CONTEXT_TOKENS and
route the endpoint's kimi-for-coding alias on every tier, since both
context envs are ignored for claude-* prefixed model ids.

Saved providers get the same context defaults injected into effective
live settings at switch time, with a mirror-inverse strip on backfill so
injected values never harden into provider config. Explicit user values
always win over the injected defaults.
2026-07-13 16:48:21 +08:00
Jason 31ee42854a feat(pricing): seed gpt-5.6 alias rows and 1.25x cache-write rates
- Add the bare gpt-5.6 row (official Sol alias) plus effort-suffix variants
  mirroring the gpt-5.5 accounting shape, priced at Sol rates
- The GPT-5.6 family charges cache writes at 1.25x the uncached input rate
  (new for OpenAI; earlier GPT models keep their correct zero): set
  6.25 / 3.125 / 1.25 for Sol / Terra / Luna across seed rows
- Repair earlier zero-value gpt-5.6 tier seeds in existing databases,
  matching only untouched rows so user-customized prices survive
2026-07-13 16:48:21 +08:00
Jason 5c39dfbfbe feat(codex): declare gpt-5.6 context window for Claude Code takeover
- Update Codex OAuth presets to the gpt-5.6 family (haiku -> gpt-5.6-luna)
  and bump the custom Codex template default model
- Inject CLAUDE_CODE_MAX_CONTEXT_TOKENS / CLAUDE_CODE_AUTO_COMPACT_WINDOW
  (372000, the ChatGPT Codex catalog window with a ~353K effective budget,
  openai/codex#31860) into effective live settings so Claude Code stops
  assuming a 200K window and compacts before the upstream rejects the prompt
- Gate the injected defaults on every configured model being gpt-5.6*:
  gpt-5.5's upstream catalog oscillates between 272K and 372K and must not
  inherit them; explicit user values always win
- Strip the injected values on switch-away backfill (mirror-inverse of the
  injection conditions) so program defaults never harden into per-provider
  explicit values, and keep both keys out of the shared common-config snippet
2026-07-13 16:48:21 +08:00
Jason f15184edb0 feat(codex): expose official routing and restore the built-in provider
Let users switch between the built-in OpenAI provider and third-party Codex providers directly from the provider panel while takeover mode remains active.

Centralize the frontend capability predicate so only the fixed codex-official seed receives native-login routing support, and keep copied UUID-based official entries clearly marked as unsupported.

Add an idempotent backend command that recreates the deleted official seed, wire it into the add-provider flow, refresh localized guidance, and add mutation and provider-action regression coverage.
2026-07-13 16:48:21 +08:00
Jason f2c6d48e19 fix(providers): skip reachability probes for official OAuth entries
Do not derive unauthenticated health-check targets from runtime adapter defaults for official providers. Batch checks now skip official entries, and direct base-URL resolution fails explicitly instead of probing first-party endpoints without credentials.

Cover the Codex official provider in the stream-check regression tests so future adapter changes cannot silently reintroduce these probes.
2026-07-13 16:48:21 +08:00
Jason 51d6c458ff feat(codex): route native ChatGPT sessions through proxy takeover
Allow the built-in Codex official provider to participate in takeover mode while preserving Codex's native OAuth or API-key credentials instead of persisting them into provider records.

Project official routing into a dedicated TOML provider, normalize inline tables, clean stale managed placeholders, and fail closed when the live configuration cannot be transformed safely.

Validate forwarded authorization, make official 401/403 responses non-retryable, avoid circuit-breaker pollution, and share the first-party ChatGPT endpoint across the Codex and Claude adapters.
2026-07-13 16:48:21 +08:00
Jason 13e7c1fcc4 fix(usage): account for Anthropic cache write TTLs
Parse and retain Anthropic's ephemeral 5-minute and 1-hour cache-creation token buckets while preserving the existing aggregate cache-write metric for compatibility.

Price 1-hour writes at the documented premium relative to the configured 5-minute write rate, clamp inconsistent provider details safely, and include TTL buckets in usage diagnostics.

Persist 1-hour cache-write tokens with schema version 14 so zero-cost backfills and later pricing updates retain the original TTL semantics. Keep session import paths compatible through zero-valued detail fields.
2026-07-13 16:48:21 +08:00
Jason b9263a8040 fix(cache): strengthen prompt cache breakpoint injection
Honor both the optimizer master switch and the cache-injection sub-switch before mutating native optimizer requests.

Use the available four-breakpoint budget across tools, system content, the latest cacheable message, and an older user anchor for long tool-heavy conversations.

Preserve caller-owned breakpoint limits, avoid thinking blocks as cache targets, normalize configured TTLs, and add regression coverage for disabled optimization and long histories.
2026-07-13 16:48:21 +08:00
Jason 650905af2c fix(proxy): harden Responses and Anthropic protocol bridges
Fail closed on HTTP 2xx failure envelopes and pre-output SSE failures so semantic upstream errors can trigger failover instead of becoming empty successful replies.

Finalize incomplete and truncated streams explicitly, handle clean EOF and whole JSON responses, and keep tool-call stop reasons and terminal event ordering consistent.

Preserve structured tool results, URL images, documents, system roles, and signed thinking across both conversion directions. Drop incomplete historical tool calls safely and classify malformed completed arguments as non-retryable client requests.

Keep Codex-to-Anthropic prompt caching enabled by default while honoring the dedicated cache-injection switch.
2026-07-13 16:48:21 +08:00
Jason a078b4b207 feat(proxy): session-based prompt_cache_key routing for Codex Chat bridge
Codex always sends prompt_cache_key in its Responses requests, but the
Responses -> Chat Completions conversion dropped it, breaking session
cache affinity on upstreams that route by key (e.g. Kimi Coding).

- Re-inject prompt_cache_key after conversion in the forwarder: an
  explicit client key wins, otherwise a client-provided session ID;
  generated per-request UUIDs are never sent upstream.
- Provider-aware gating: "auto" enables only known-compatible upstreams
  (api.openai.com, api.kimi.com/coding) because strict gateways reject
  unknown fields with HTTP 400 (e.g. Fireworks); an advanced
  Auto/Enabled/Disabled override is available on the Codex form in all
  four locales.
- Kimi For Coding preset opts in explicitly.
2026-07-13 16:48:21 +08:00
Jason 0e563b50c5 fix(cache): surface unsupported breakpoint counts
Warn when caller-provided cache breakpoints already exceed the supported total of four while preserving the original markers and upgrading their TTLs.

Clarify that automatic injection is governed by the remaining breakpoint budget, and add regression coverage proving excess caller markers are never deleted or reordered.
2026-07-13 16:48:21 +08:00
Jason 27ce0a519c fix(proxy): harden Responses reasoning and tool-call conversion
Round-trip encrypted Responses reasoning items through bridge-owned Anthropic thinking blocks, discard orphaned reasoning-only history, and consume the official reasoning text event vocabulary.

Track concurrent streaming items by stable IDs and output indexes, reuse a dedicated fallback block for keyless legacy reasoning, recover tool arguments from done events, and close blocks in protocol order.

Normalize empty or incomplete non-streaming tool arguments, reject malformed completed calls, and persist upstream usage before returning terminal conversion errors.
2026-07-13 16:48:21 +08:00
Jason f991726ff0 fix(usage): account for cache-write tokens across schema versions
Parse cache_write_tokens from OpenAI usage details and preserve cache creation data across Chat, Responses, and Anthropic conversion paths.

Add explicit input-token semantics to request logs and rollups so legacy rows subtract cache reads only while new total-inclusive rows subtract both cache reads and writes. Migrate v12 databases, normalize rollups to fresh input, and cover historical backfill behavior with regression tests.
2026-07-13 16:48:21 +08:00
Jason 06039540ff refactor(health-check): remove per-provider test config 2026-07-13 16:48:21 +08:00
Jason 442799879d feat(profiles): add setting to toggle project switcher on main page
Add a show/hide toggle for the header project profile switcher under
the Homepage Display section in settings. Defaults to visible so
existing users keep the current behavior.
2026-07-13 16:48:21 +08:00
Jason 7479d10db7 feat(codex): add default model field to provider form
Expose the top-level `model` key of config.toml as an editable field in
the Codex provider form, so users can switch to newly released models
(e.g. gpt-5.6) without waiting for a preset update — preset updates only
affect newly added providers, 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 plus the
provider's /models endpoint, and offers a one-click "add to mapping"
action when the value is outside a non-empty catalog. Hidden for
official providers.

Details:

- Save-time catalog sync now only backfills the first mapping row into
  the top-level model when the field was left empty, so the explicit
  field wins over the implicit row-0 sync
- Escape model names (and base_url) with TOML basic-string escaping and
  strip control characters from field input: /models ids are remote
  data and unescaped interpolation could inject config.toml lines
  (e.g. a forged [mcp_servers.*] command)
- The strict model-line matcher now recognizes escaped output, empty
  strings and single-quoted literals, keeping extract/set round-trips
  stable; deliberately no key-only loose matching (it would misfire on
  assignment-looking text inside multiline strings)
- Invalidate the fetched model list whenever the request identity
  changes (base URL, full-URL toggle, API key, custom UA) and discard
  in-flight responses via a sequence guard, so the dropdown never shows
  a previous provider's models
- i18n for zh/en/ja/zh-TW
2026-07-13 16:48:21 +08:00
Jason 62e44c4838 feat(pricing): seed Tencent Hunyuan Hy3 pricing
Add Hunyuan Hy3 (released 2026-07-06, 256K context) to seed_model_pricing
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 come from Tencent's launch-day list price (CNY 1 / 4 / 0.25 per 1M
input / output / cache-hit), converted at 1 USD ~= 7.14: 0.14 / 0.56 / 0.035.
cache_write is "0" (no published write rate). Hy3 actually uses input-length
tiered billing (<16K / 16-32K / >=32K); the single-price table holds the
lowest tier, so long-context requests are under-billed until this is revisited
against the official billing page. New model, so seed only.
2026-07-13 16:48:21 +08:00
Jason a7b4dd9405 feat(pricing): seed GPT-5.6 Sol/Terra/Luna pricing
Add the three GPT-5.6 tiers to seed_model_pricing, cross-checked against
OpenAI's official pricing page and OpenRouter:

  gpt-5.6-sol    5 / 30 / 0.50 (cache read)
  gpt-5.6-terra  2.50 / 15 / 0.25
  gpt-5.6-luna   1 / 6 / 0.10

cache_write is "0": OpenAI publishes only a cached-input (read) rate and no
separate cache-write price, matching the gpt-5.x family convention. Base ids
only for now — effort-suffix variants are deferred until the upstream logging
suffix set for 5.6 is confirmed. New model, so seed only (no repair branch,
no SCHEMA_VERSION bump).
2026-07-13 16:48:21 +08:00
风少1227 c6197ae324 fix(proxy): inject a single auth placeholder on managed Claude takeover (#5095)
Switching the Claude provider from a third-party (DeepSeek/MiMo/...) to a
managed Codex provider wrote both ANTHROPIC_API_KEY and
ANTHROPIC_AUTH_TOKEN as PROXY_MANAGED into ~/.claude/settings.json,
making Claude Code warn "Both ANTHROPIC_AUTH_TOKEN and ANTHROPIC_API_KEY
set - auth may not work as expected" on every run.

The double key is an accretion artifact: the ManagedAccount takeover
policy originally injected only ANTHROPIC_API_KEY (Copilot, #1049), and
the Codex fix that preserved ANTHROPIC_AUTH_TOKEN to avoid the login
prompt (#3784 / PR #3789) added the token on top without removing the
API key insert.

Inject exactly one placeholder instead: AUTH_TOKEN for Codex-managed
providers (keeps the #3784 fix), API_KEY for Copilot (keeps the #1049
behavior). Local-proxy auth is unaffected - the forwarder resolves the
PROXY_MANAGED placeholder from either header.

Updates the three Codex takeover tests to assert API_KEY is absent and
adds a regression test for the exact third-party -> Codex switch from
the report.

Fixes #4919
2026-07-12 21:47:45 +08:00
白喵喵喵喵 f39d463c44 fix(usage): 修复 Codex 子代理使用量未计入统计 (#5187)
* fix(usage): count Codex subagent session tokens

* fix(usage): address Codex subagent review feedback

* fix(usage): preserve Codex migration history

* fix(usage): harden Codex subagent migration

* fix(usage): reimport late Codex subagents

* fix(usage): guard late Codex rollup reimport

* refactor(usage): simplify Codex subagent accounting fix
2026-07-11 20:11:14 +08:00
Komi ded0b63a8e fix: handle missing provider keys and tool schema types (#5069)
* fix: handle missing api keys and tool schema types

* fix: preserve nested tool schemas

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-07-11 16:57:46 +08:00
v2v 6245caa6c5 Fix/opencode known field editors (#2907)
* fix: add opencode model limit editor

* fix: add opencode headers editor

* style: refine opencode advanced field layout

* fix: preserve valid opencode headers

* fix: preserve opencode extra options and sync translations

---------

Co-authored-by: wzk <wx13571681304@outlook.com>
Co-authored-by: Jason Young <44939412+farion1231@users.noreply.github.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-11 16:38:00 +08:00
Dawn 50270d5e42 fix: exclude Fable model env from Claude common config (#4272) (#5206)
* Add test for Fable model env key exclusion

Add regression test to ensure Fable model env keys are excluded from common config.

* Add Fable model to CLAUDE_MODEL_OVERRIDE_ENV_KEYS

* Add files via upload

* Delete .github/workflows/build-windows-unsigned.yml
2026-07-11 10:11:57 +08:00
Yeeyzy 99e11e0851 feat(codex): support native Anthropic Messages protocol as upstream (#5071)
* feat(codex): support native Anthropic Messages protocol as upstream

Allow gateways that only expose the native Anthropic Messages protocol
(/v1/messages) to be used by Codex: the local proxy performs bidirectional
request/response/streaming conversion between Responses and Anthropic.

Backend:
- Add two conversion modules: transform_codex_anthropic / streaming_codex_anthropic
- codex.rs: add routing detection and auth: ANTHROPIC_AUTH_TOKEN→Bearer (default),
  ANTHROPIC_API_KEY→x-api-key, mutually exclusive
- handlers.rs: add handle_codex_anthropic_to_responses_transform
- forwarder.rs: support optional Claude Code client fingerprint impersonation
  (User-Agent / anthropic-beta / x-app / system prompt first-line injection)
  and /responses→/v1/messages rewriting
- codex_config: the anthropic format reuses the NativeResponses profile to strip
  custom tools
- ProviderMeta: add impersonateClaudeCode

Frontend:
- CodexApiFormat: add "anthropic"; the form adds auth field selection and an
  impersonation toggle
- Add en/ja/zh/zh-TW copy

Robustness:
- Downgrade when tool history / forced tool_choice conflicts with extended
  thinking, avoiding upstream 400s
- Emit cache_creation_input_tokens in usage and use saturating_add to guard
  against overflow
- Append a unique suffix to non-streaming/streaming output-item ids to avoid
  multi-segment text/thinking overwriting each other

* fix(codex): harden Anthropic bridge against empty text blocks and truncated streams

- Drop empty/whitespace-only text content blocks when rebuilding Anthropic
  messages from Responses history; Anthropic 400s on empty text blocks (e.g. an
  empty assistant text emitted alongside a tool_use), which broke follow-up and
  tool-result requests. Also drop messages left without content.
- Do not report a truncated Anthropic stream as completed: when the SSE
  connection ends before message_stop with no stop_reason, emit an incomplete
  response if partial output exists, or a failed (stream_truncated) response
  otherwise, mirroring the chat converter's EOF handling.

* fix(codex): resolve Anthropic-bridge review findings

Blocking:
1. Defer stripping the [1m] long-context marker until after catalog matching and model write-back, re-stripping it on the final Codex→Anthropic body and setting a flag to emit the context-1m-2025-08-07 beta header, so the marker is no longer lost or overridden by the default model.
2. Gate Anthropic thinking on the trailing turn only (via trailing_turn_allows_thinking) instead of scanning full history, so a Codex session that resends history each round no longer permanently loses thinking after the first tool call.
3. Inject 5m ephemeral cache_control on the Codex→Anthropic body by reusing cache_injector (handling the system string→array conversion), so system/tools/history are cached instead of re-sent at full price every round.
4. Add a shared base_url_is_full_endpoint helper (normalizing whitespace/query/fragment/trailing slash) used by both the Anthropic and Chat paths, so a base URL already ending in /v1/messages is treated as a full endpoint instead of double-appending to /v1/messages/v1/messages.
5. Align the catalog tool-profile predicate with the routing predicate so resolve_codex_catalog_tool_profile returns the Anthropic profile whenever the request converts to Anthropic, preventing freeform tools like apply_patch from being silently filtered by a ProxyChat catalog.
6. Explicitly disable native web_search for the Anthropic profile (including the no-catalog branch) via set_codex_native_web_search_field, so Codex no longer treats it as available while the transform silently drops it.
7. Only forward tool_choice when tools survive filtering, dropping it otherwise, to avoid a non-retryable 400 from upstream when tool_choice is sent with no tools.
8. Lower the fallback default to max_tokens=8192 (only when max_output_tokens is omitted) and clamp the thinking budget to max_tokens/2, disabling thinking below the 1024 floor, to avoid hard 400s on low-output-ceiling models/gateways.

Minor:
9. Centralize the Codex/OpenAI fingerprint-header denylist in is_codex_client_fingerprint_header so impersonating Claude Code uniformly drops originator/session_id/conversation_id/chatgpt-account-id/x-client-request-id/openai-* and the x-stainless-*/x-codex-* prefixes.
10. Retain content_block_start.input as start_input and fall back to it at block close when no input_json_delta arrived, so a gateway that carries the full tool input on the start event no longer yields empty tool arguments.
11. Extract a shared codex_responses_sse module as the single Responses SSE envelope builder that both the chat and anthropic streaming emitters delegate to, with byte-for-byte-unchanged wire output, so future event-format fixes touch one place instead of two.

* fix(codex): add per-provider max_output_tokens override for Codex→Anthropic path

Codex does not forward model_max_output_tokens in the request body,
causing the proxy to fall back to a conservative 8192 default. This
truncates long or thinking-heavy responses (stop_reason=max_tokens).

- Add maxOutputTokens field to ProviderMeta (Rust + TypeScript)
- Inject the value into the Anthropic request body before transform,
  taking precedence over request-supplied and default values
- Add numeric input in Codex form fields (Anthropic format only)
- Add i18n entries for label, placeholder, and hint (en/zh/zh-TW/ja)
- Include roundtrip and omission unit tests for the new field

* fix(codex): harden Anthropic protocol bridge

* fix(codex): address Anthropic bridge review

* fix(codex): preserve flattened Anthropic inputs

* fix(codex): harden Anthropic recovery paths

* fix(ci): satisfy Rust clippy

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-07-10 23:06:30 +08:00
makoMakoGo 98ccde0050 fix(usage): persist dashboard refresh interval (#5057) 2026-07-09 10:02:23 +08:00
zhanxin.xu 95c917b337 feat(provider): add Zhipu team plan quota query support (#5128)
智谱团队套餐(Team Plan)的额度查询与个人版不同:同一 quota 端点加
`?type=2`,需额外 `bigmodel-organization` / `bigmodel-project` 请求头
(api_key + 组织 ID + 项目 ID 三者缺一不可),且仅存在于国内站
open.bigmodel.cn。参考 token-monitor/src/shared/zaiTeamLimits.js 实现。

- Backend (services/coding_plan.rs): 新增 query_zhipu_team(固定 CN 站、
  ?type=2、org/project 头);抽出 zhipu_quota_from_body 与个人版共用解析;
  入口 get_coding_plan_quota 靠显式 coding_plan_provider == "zhipu_team"
  路由(base_url 与个人版智谱相同,detect_provider 无法区分)。新字段经
  UsageScript、IPC 命令、后台查询路径(query_provider_usage_inner)透传。
- Frontend: UsageScriptModal 新增「Zhipu GLM Team」选项 + 组织/项目 ID
  输入;模板切换时保留 team 字段;测试与保存逻辑按 team 传参。
- i18n: en/zh/zh-TW/ja 四个 locale 更新。
- Tests: 凭据校验/路由(缺任一凭据 → NotFound,标识大小写不敏感)+ 本地
  server 验证 ?type=2 与 org/project 请求头形状。

Co-authored-by: XuZhanXin <1239576606@qq.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 09:21:10 +08:00
Salar 3538b39246 feat(claude): add 1M checkbox to fallback model field (#5124)
The fallback model (ANTHROPIC_MODEL) field was missing the 1M checkbox
that the role-specific model rows already have. Added the checkbox with
the same strip/set marker logic used by role rows.

Fixes #3679
2026-07-09 08:36:54 +08:00
Jason ba531ca222 docs(readme): add new-api as a sponsor
Add the open-source AI infrastructure project new-api as the latest
sponsor entry, appended to the end of the sponsor table across all four
localized READMEs (en/zh/ja/de). Includes the banner asset.
2026-07-08 22:46:09 +08:00
Jason 88d5ffba44 fix(codex): move common-config TOML merge off smol-toml to backend toml_edit
updateTomlCommonConfigSnippet re-serialized the whole document through
smol-toml (parse -> deepMerge -> stringify): comments dropped, keys
reordered, and empty parent table headers synthesized -- the
long-standing "config.toml keeps getting reordered" symptom (audit C5,
introduced in 083e48bf).

Replace it with a backend command backed by the same
merge_toml_table_like / remove_toml_table_like used when writing live
configs, so the form preview and the live write share one merge
semantic and user formatting survives edit-time merges. The frontend
sync helper is deleted outright to keep the pattern from coming back.

Making the form operations async exposes them to interleaving, so a
result is discarded unless it is still current when it lands:

- a per-hook sequence number (last operation wins) covers rapid
  toggle/save races where an earlier merge resolves after a later
  removal and would flip the switch back;
- a config-baseline check covers the user hand-editing the TOML while
  a merge is in flight -- the stale result must not clobber their edit.
  The checkbox state self-heals via the existing inference effect.

Regression tests pin both by resolving a suspended merge after a newer
operation / an external edit, plus backend tests locking comment and
key-order preservation, scalar override, and value-matched removal.
2026-07-08 22:46:09 +08:00
Jason 94fc1cc064 fix(mcp): surface per-app failures when importing MCP servers from apps
import_mcp_from_apps swallowed every importer error with unwrap_or(0),
so a corrupt config.toml surfaced as "imported 0 servers" with no hint
that anything went wrong.

Move the aggregation into McpService::import_from_all_apps: each app
imports best-effort (one bad file doesn't block the rest), and failures
are collected into a single error naming the failing apps alongside the
count that did import. The frontend now refreshes the server list on
settle rather than success, since a partial failure still means new
servers were persisted.
2026-07-08 22:46:09 +08:00
Jason 11c173c730 fix(mcp): stop cross-app failures from blocking MCP re-projection
sync_all_enabled iterated AppType::all() with `?`, so one app's corrupt
live file (e.g. a broken ~/.claude.json, which passes the existence
gate but fails to parse) blocked every app behind it in the iteration
order -- and bubbled the error into whatever operation triggered the
sync:

- switch/save had just rewritten only the target app's live file, yet a
  broken unrelated file failed the whole operation after DB and live
  were already updated, reporting a false "switch failed" to the user.
  Both now project only the target app (sync_enabled_for_app) and
  degrade projection failure to a warning: the primary operation has
  already taken effect, and the projection self-heals on the next
  switch or MCP toggle.
- sync_current_provider_for_app_to_live syncs a single app; it now
  projects that app only, keeping failures (which can only concern the
  target app) as errors.
- sync_current_to_live (config import / cloud-sync restore) keeps the
  all-apps sweep, but sync_all_enabled is now best-effort: it projects
  every app, collects failures, and reports them aggregated. Its error
  is held until after skill sync so an MCP failure no longer skips it.
2026-07-08 22:46:09 +08:00
Jason 1f36f0cfed feat(provider): extend switch-time common-config autosync to Codex
Claude already re-extracts the live config into the shared common-config
snippet right before switching away, so shared tweaks (plugins,
preferences) made in live propagate to all opted-in providers. Codex was
gated out because its TOML pipeline leaked provider-specific and
injected content into the snippet.

With the extractor now stripping all injection artifacts and routing
fields, and backfill stripping the MCP projection, open the gate to
Claude + Codex. The autosync-before-strip ordering also self-heals
stale snippet values previously baked into provider snapshots: the
re-extracted snippet matches the live values, so the value-match strip
removes them on the same switch.

End-to-end tests cover: new shared keys captured, deletions synced,
secrets/injected artifacts never entering the snippet, and provider A's
key not leaking into provider B's live.
2026-07-08 22:46:09 +08:00
Jason 6d2ee2472f fix(provider): re-project Codex MCP after unified-session toggle rewrites live config
Toggling unify_codex_session_history rewrites the current official
provider's live config.toml in full (intended design), which drops the
[mcp_servers] projection -- and nothing put it back, so enabled MCP
servers silently vanished until the next provider switch (#C2).

Re-project after the rewrite, with two deliberate choices:

- Project Codex only (new McpService::sync_enabled_for_app) instead of
  sync_all_enabled: the all-apps sync short-circuits in AppType::all()
  order, so a corrupt ~/.claude.json would error before Codex is ever
  reached and the freshly wiped [mcp_servers] would stay missing. Only
  Codex's live file was rewritten here, so only Codex needs
  re-projection.
- Degrade projection failure to a warning: by this point the live file
  already carries the new bucket state, so the toggle has taken effect.
  Propagating the error would make save_settings roll back the setting,
  creating the exact "setting=old, live=new bucket" session split the
  rollback exists to prevent. The projection self-heals on the next
  switch or any MCP toggle.
2026-07-08 22:46:09 +08:00
Jason 473c2aaa9f fix(provider): exclude injected artifacts and routing fields from Codex common-config extraction
extract_codex_common_config kept several fields in the shared snippet
that must never cross providers:

- [mcp_servers] and the legacy [mcp.servers] form: owned by the DB
  mcp_servers table; once in the snippet they get merged into every
  opted-in provider and no sync path can ever clean them up.
- top-level experimental_bearer_token: normally lives inside
  [model_providers.<id>] (stripped with the whole table), but three
  fallbacks write it at top level -- leaking the API key into the
  shared snippet.
- model_catalog_json: per-provider catalog projection pointer.
- web_search, only when it equals the injected "disabled" sentinel;
  a user-set value remains a shareable preference.
- top-level wire_api: same provider-routing semantics as top-level
  base_url (the fallback target when no model_provider is set); leaking
  it would rewrite the next provider's protocol selection.

This makes the extractor safe as the source for switch-time
common-config autosync.
2026-07-08 22:46:09 +08:00
Jason 93f56198da fix(codex): strip synced [mcp_servers] from provider snapshots on backfill
MCP servers are owned by the DB mcp_servers table; the [mcp_servers]
section in live config.toml is only a projection re-synced after every
live write. When switching away baked that projection into the stored
provider snapshot, servers deleted in the app were resurrected the next
time that provider was activated -- per-entry reconcile only knows rows
that still exist in the DB, so it can never clean up such orphans.

Strip [mcp_servers] (and the legacy [mcp.servers] form) from the live
settings during switch-away backfill. Previously polluted snapshots
self-heal the next time the user switches away from them.
2026-07-08 22:46:09 +08:00
Jason 8b1ce764f1 fix(mcp): fail closed when Codex config.toml is unparseable during MCP sync
sync_single_server_to_codex silently fell back to an empty DocumentMut
when the existing config.toml failed to parse, then wrote the whole file
back -- wiping every other section (model, model_providers, comments)
and leaving only the single synced [mcp_servers.<id>] entry. Introduced
by 3a548152, which fixed the removal path but left the destructive
fallback on the sync path.

Now the sync path returns an McpValidation error and leaves the file
untouched, matching the fail-closed behavior of the read/validate path.
2026-07-08 22:46:09 +08:00
Jason fad5b4c094 Revert "fix(presets): point Volcengine/Doubao/BytePlus website links to official sites"
The websiteUrl for 火山Agentplan, DouBaoSeed and BytePlus is intentionally the ccswitch-attributed apiKeyUrl link, per the Volcengine partner's request. Restore the invite/attribution links across all six app preset files.

This reverts the websiteUrl changes from 56248087; apiKeyUrl was already left intact there.
2026-07-08 22:46:09 +08:00
Jason bad3610d93 refactor(presets): drop redundant 'OpenAI Compatible' preset
Remove the 'OpenAI Compatible' custom-template preset from the OpenCode
and OpenClaw preset lists. 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) produces a
byte-identical starting config. Having both left two list items pointing
to the same place.

Existing providers are unaffected — presets only seed form defaults on
creation; saved providers store concrete npm/baseUrl/apiKey/models values.

The '@ai-sdk/openai-compatible' dropdown label is intentionally kept; it
is the format option users pick in the custom flow, not the deleted preset.
2026-07-08 22:46:09 +08:00
Allen Xu e78aa8a7c3 fix: sync openclaw and hermes live provider updates (#5098)
* fix: sync openclaw live provider updates

* fix: sync hermes live provider updates

* fix test: hermes live import stores models as array after denormalize

The test import_hermes_providers_from_live_updates_existing_provider_from_live
seeded models as a dict, but import_hermes_providers_from_live reads via
get_providers() which calls denormalize_provider_models_for_read(), converting
models from YAML dict to UI-friendly array. The test assertion accessed models
as dict -> Null -> assertion failure.

Fix: access models as array by index, matching the actual storage format after
live import. Also verify the id field is preserved in the denormalized output.
2026-07-08 12:09:56 +08:00
Allen Xu e191af4aa1 fix: OpenCode live provider import updates (#4712)
* fix: sync existing opencode providers from live config

* fix: preserve OpenCode provider display names

* docs: update comments and log messages to reflect new update behavior

- fix stale comment in lib.rs that said existing providers are skipped
- change log message from 'Imported' to 'Synced' since count now
  includes both new imports and updates
2026-07-08 10:34:49 +08:00
Jason d271d60cf9 docs: add Codex Kimi routing guides 2026-07-08 00:00:56 +08:00
Jason 358bf1e2b7 chore(pnpm): settle build-script approvals for esbuild and msw
pnpm 10.13+ appends "set this to true or false" allowBuilds
placeholders to pnpm-workspace.yaml on every install for unreviewed
dependencies with lifecycle scripts. Approve esbuild (postinstall
ensures the platform binary) and ignore msw (postinstall only prints
an integration notice) so the file stops mutating itself.
2026-07-07 21:03:20 +08:00
Jason 2df2212ceb fix(usage): reject transient transport failures so retry and keep-last-good work
Usage/quota queries frequently showed spurious "query failed" states that
manual refresh could not clear (#3820). Root cause: all transport-level
failures were folded into Ok(success:false), so react-query's retry never
fired and the failure body poisoned the cache as regular data.

Backend:
- balance/coding_plan/subscription services now return Err for send
  failures and body-read failures (read body via bytes() before
  serde_json::from_slice; reqwest's json() wraps read errors as Decode,
  making error-kind checks on it dead code). Auth/4xx/parse errors stay
  Ok(success:false) and surface immediately.
- Script path maps transient AppError keys (request_failed /
  read_response_failed) to Err; Volcengine adds a Transient call variant.
- Command layer skips snapshot persistence, usage-cache-updated emit and
  tray refresh on Err so the cache bridge cannot overwrite retained data.
- Expired-credential retry propagates transient errors instead of
  rewriting them as "OAuth token has expired".

Frontend:
- resolveDisplayUsage generalized to subscription quotas; 5th param is now
  an options object with a `rejected` flag: stale success data retained by
  react-query across rejections is re-anchored to dataUpdatedAt and expires
  through the same 10-minute keep-last-good window instead of being shown
  indefinitely (a total outage used to mask longer than a single 5xx).
- 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
  footers keep rendering a retry entry point.
- HTTP 429 is classified transient (retry-later) alongside 5xx.
- UsageScriptModal surfaces string rejections via extractErrorMessage.

Tests: 6 backend behavior tests drive real HTTP against a local listener
to pin the Err/Ok channel semantics; frontend suite extends
keepLastGoodUsage coverage (405 passing).
2026-07-07 20:05:29 +08:00
Jason 468c93d409 ci: harden release supply chain
- Add CODEOWNERS so PRs to main require owner review (closes the gap
  where two collaborators could approve each other's changes).
- Gate the release job behind a 'release' environment, so signing
  secrets are only unlocked after manual approval.
- Stop ignoring the whole .github directory; this had been silently
  swallowing labeler.yml and workflows/labeler.yml, which are now tracked.

Paired with a tag ruleset (created out-of-band) that restricts creation
of v* tags to admins, this prevents a write collaborator from pushing a
tag to trigger a signed release build.
2026-07-07 16:02:16 +08:00
Jason 525346188b fix(proxy): close media fallback gaps for Volcano GLM 5.2 image 400s
Fixes #5025. The rectifier's media fallback missed Volcano Coding Plan's
GLM 5.2 on both paths:

- Preventive: known_text_only_model had glm-5.1 but not glm-5.2, so image
  blocks were forwarded verbatim. Added glm-5.2 as an exact tail match
  (not a prefix, to avoid stripping images from a future glm-5.2v
  multimodal variant following Zhipu's 4v/5v naming).
- Reactive: the upstream error "Model only support text input" never
  mentions image/media, so the mentions_image gate rejected it before
  hints ran; and the existing "only supports text" hint misses the
  gateway's missing third-person "s". Added a self-evident phrase list
  ("only support text" / "only supports text") that asserts a modality
  rejection on its own and bypasses the image-mention gate.

Includes regression tests using the verbatim #5025 error body and the
glm-5.2[1M] mapped-model form, plus a glm-5.2v negative assertion.
2026-07-07 12:57:11 +08:00
Jason afabe80167 test(profiles): gate desktop-scope assertion by platform in profile roundtrip
The desktop switch to d2 is cfg-gated to macOS/Windows, but the assertion
expecting d2 was not, so on Linux CI the desktop provider stays at the seeded
d1 and the assertion panics — poisoning the shared test mutex and cascading
into two more failures. Expect d1 on non-desktop platforms.
2026-07-07 11:57:26 +08:00
Jason 7fada72dd4 chore(code0): update partner invite link to agent register URL
Replace the ?source=ccswitch referral with the new agent register invite
link (https://code0.ai/agent/register/B2XHxGjGmRvqgznY) on code0's
apiKeyUrl across all seven presets and the sponsor rows in all four
READMEs. API endpoints stay bare per the referral red-line.
2026-07-07 10:49:32 +08:00
Jason 9f7642e29c refactor(profiles): drop manual snapshot update now that switching autosaves
Since switching projects automatically saves the current configuration
back to the project being left, the per-project "update from current"
button is redundant and even harmful: it allowed overwriting another
project's snapshot with the current state, breaking the invariant that
a project holds the state you last left it in.

- Remove the resnapshot button and confirm dialog from the manage
  dialog; drop the now-unused scope prop and PROFILE_SCOPE_LABELS
- Add a footer Close button to the manage dialog (overlay click is
  disabled app-wide, so it previously could only be closed via Esc)
- Update manageDescription in all four locales to describe the
  autosave behavior; remove the two dead i18n keys
- Fix a shadowed `warnings` vec in ProfileService::apply that silently
  dropped autosave-failure warnings before they reached the frontend
- Mention auto-capture on next switch in the "no snapshot for this
  scope yet" warning and doc comments

The backend update command keeps its resnapshot parameter; it is now
only exercised by the pre-switch autosave path.
2026-07-07 10:49:32 +08:00
Jason 22159430c6 fix(profiles): use camelCase keys for current profile ids in frontend 2026-07-07 10:49:32 +08:00
Jason 754af2cc31 feat(profiles): split Claude Desktop into independent profile scope 2026-07-07 10:49:32 +08:00
Jason 3ec83578f6 fix(profiles): stop proxy server when profile switch leaves no takeovers active 2026-07-07 10:49:32 +08:00
Jason f05ed3dbac fix(ui): invalidate proxy takeover status after profile switch 2026-07-07 10:49:32 +08:00
Jason 4f45601f9f feat(profiles): unconditionally disable proxy takeover before applying profile 2026-07-07 10:49:32 +08:00
Jason 4cf6f175a7 feat(profiles): autosave previous profile state on switch
When switching to a different project, the current configuration of the
previously active project is automatically captured into that project's
snapshot before the target project's snapshot is applied. Scope is limited
to the active group (Claude/Codex); autosave failures are collected as
warnings and do not block the switch.

- Move autosave logic into ProfileService::apply for consistent behavior
  across UI, tray, and tests
- Add integration test covering bidirectional autosave roundtrip

Refs: profile switch B方案
2026-07-07 10:49:32 +08:00
Jason dbb5999d1e refactor(profiles): shared project entity with per-scope switching
Projects are now global shared entities; Claude and Codex groups switch
independently via scoped current pointers and scoped payload slots.

- Remove scope column from profiles; keep current_profile_id_<scope>
- Use Option<Vec<String>> for mcp/skills to distinguish 'never captured'
  from 'captured empty', preventing cross-side accidental disable
- Update/apply operations scoped to the active group via merge_scope_from
- Tray menu nests same shared list under Claude Code/Codex groups
- Add i18n for per-scope tooltips and 'not saved for this side' hint

Refs: profile P1 shared-entity redesign
2026-07-07 10:49:32 +08:00
Jason 65a5464fcc feat(profiles): include Claude Desktop provider in project profiles
Claude Desktop's only dimension managed by cc-switch is its provider
(MCP/Skills are hardcoded unsupported and prompts have no live file),
so snapshots capture just the current desktop provider while the empty
MCP/Skills sets and None prompt make apply a natural no-op for the
other dimensions - no per-dimension special casing needed.

- Add claude-desktop slot to PROFILE_APPS and PerApp (serde key uses
  the hyphenated app id); old payloads without the key deserialize to
  None and leave Claude Desktop untouched on apply
- Gate the tray Projects submenu by iterating PROFILE_APPS instead of
  hardcoding Claude/Codex visibility
- Show the profile switcher on the Claude Desktop tab, mirror the
  PerApp type, invalidate the claude-desktop providers cache on apply,
  and extend the switcher tooltip in all four locales
- Extend the roundtrip integration test with the desktop provider
  dimension; the desktop switch is cfg-gated to macOS/Windows because
  desktop live writes error on Linux where CI runs cargo test
2026-07-07 10:49:32 +08:00
Jason 6179c18805 fix(profiles): scope switcher to supported app tabs and relocate it
- Render the profile switcher only when the active tab is Claude or
  Codex (frontend mirror of backend PROFILE_APPS), so viewing an
  unsupported app no longer suggests its config was switched
- Move the switcher from beside the logo to the right of the route
  toggles, where the flexible spacer absorbs its appearance and other
  header controls no longer shift when switching tabs
2026-07-07 10:49:32 +08:00
Jason 8f018a2d45 feat: add project profiles for snapshot-based config switching
Add a profile feature that captures the current provider, MCP,
skills and prompt state for Claude Code and Codex as a named
snapshot, and re-applies it in one click from the header switcher
or the tray Projects submenu.

- New profiles table (schema v12) with current marker in settings
- ProfileService orchestrates the four existing switch primitives
  (provider first, then MCP diff, skills diff, prompt enable)
- Best-effort apply: dangling references become warnings, no rollback
- Header combobox switcher + snapshot-style manage dialog
- Tray Projects submenu shared with the UI apply/event pipeline
- i18n for zh/en/ja/zh-TW under the new profiles domain
- Integration tests covering roundtrip, dangling refs and clear
2026-07-07 10:49:32 +08:00
秋澪Akimio b3e5e32c89 feat: add Claude subagent model config (#4830)
* feat: add Claude subagent takeover config

* feat: add Claude subagent model field

* i18n: add Claude subagent model labels

* fix(proxy): preserve configured subagent model mapping

* fix(providers): exclude subagent model from Claude common config

* style: format rust code
2026-07-07 10:28:36 +08:00
makoMakoGo e606adfae7 fix(codex): display renamed session titles (#4927)
* fix(codex): display renamed session titles

* fix(codex): resolve custom state db for titles

* refactor(codex): dedupe state-db resolution and harden title lookup

- Extract a shared `codex_state_db` module for `state_5.sqlite` path
  resolution (config `sqlite_home` / `CODEX_SQLITE_HOME`), previously
  copy-pasted verbatim between codex_history_migration and the codex
  session provider. `state_5.sqlite` is now a single source of truth.
- Add `busy_timeout` to the read-only title query; without it a read
  during a concurrent Codex write fails immediately (SQLITE_BUSY) and
  renamed titles silently fall back to the first user message.
- Push the `title == first_user_message` comparison into the SQL WHERE
  clause (NULL-safe, aligning with Codex's `distinct_thread_metadata_title`
  semantics) and stop SELECTing `first_user_message`, which can hold
  large values (openai/codex#29007) — the comparison belongs in SQL
  anyway, so the column no longer needs to cross into Rust.
2026-07-06 09:11:55 +08:00
SaladDay 7a7d41c873 fix(subscription): display Codex free-plan 30-day quota window (#3651) (#4886)
* fix(subscription): display Codex free-plan 30-day quota window (#3651)

Codex free accounts are metered on a rolling 30-day secondary window
(limit_window_seconds = 2,592,000) instead of the weekly window used by
paid plans. The backend already maps this correctly to the tier name
"30_day", but the frontend TIER_I18N_KEYS whitelist had no entry for it,
so SubscriptionQuotaView filtered the tier out. When that was the only
surviving tier (as happens for free accounts), the whole quota footer
rendered nothing — free accounts showed no remaining quota or reset time
while paid accounts worked.

- Add "30_day" -> subscription.thirtyDay to TIER_I18N_KEYS
- Add the thirtyDay label to all four locales (zh/en/ja/zh-TW)
- Add a unit test locking in window_seconds_to_tier_name mappings,
  including the 30-day case

Fixes #3651

* fix(tray): render Codex free-plan 30-day window in tray menu

The tray keeps its own tier-name whitelist (TIER_LABEL_GROUPS) independent
of the frontend TIER_I18N_KEYS. Its month group only listed "monthly", so a
free Codex account whose only tier is "30_day" produced empty labeled parts
→ format_subscription_summary returned None → the tray showed no quota, even
though the footer now does. That breaks the invariant the existing
gemini_summary_lite_only_still_renders test guards: any tier visible in the
footer must not leave the tray blank.

- Add TIER_THIRTY_DAY ("30_day") constant so the string is single-sourced
  across backend mapping, tray grouping, and the frontend whitelist
- Map 2_592_000s explicitly to it in window_seconds_to_tier_name
- Add TIER_THIRTY_DAY to the tray month ("m") group
- Add codex_summary_thirty_day_only_still_renders regression test

Follow-up to the review on #3651 / PR for the 30-day footer fix.
2026-07-05 22:54:20 +08:00
Butui Hu ffc22ea714 feat(universal-provider): Auto-sync after adding and drop unused addSuccess i18n key (#2811)
* feat(universal-provider): Auto-sync after adding and drop unused addSuccess i18n key

Signed-off-by: Hu Butui <hot123tea123@gmail.com>

* fix(i18n): sync zh-TW universal provider strings

---------

Signed-off-by: Hu Butui <hot123tea123@gmail.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-05 22:41:05 +08:00
Cheng Zi Feng 7a8b956253 Update Longcat presets to LongCat-2.0 (#4838)
* Update Longcat presets to LongCat-2.0

* fix(proxy): classify LongCat-2.0 as text-only for media sanitizer

The Longcat presets now use LongCat-2.0, but the known_text_only_model
allowlist still only matched the retired longcat-flash-chat tail. Without
this, images pasted into a text-only LongCat-2.0 session are forwarded
upstream instead of being replaced with the unsupported-image marker,
causing a hard rejection. Add longcat-2.0 (keeping the retired name for
saved configs) and a regression test.

---------

Co-authored-by: chengzifeng <chengzifeng@meituan.com>
Co-authored-by: Jason <farion1231@gmail.com>
2026-07-04 16:38:35 +08:00
makoMakoGo 0cda8d46c7 fix: 更新 OpenCode 会话恢复命令 (#2359) 2026-07-02 22:14:43 +08:00
Jason 8d1b3306d0 chore(release): v3.16.5 2026-07-01 23:55:55 +08:00
Jason 6d84082d27 docs(release-notes): add v3.16.5 notes (zh/en/ja) 2026-07-01 23:55:55 +08:00
Jason 76b8620ffe fix(tests): align Sonnet tier expectations with claude-sonnet-5
The default Sonnet tier was bumped to claude-sonnet-5, but the TheRouter preset tests and ClaudeDesktopProviderForm tests still asserted claude-sonnet-4.6/4-6. Update the expected values to match the presets; input fixtures are left as-is to keep exercising legacy-route migration.
2026-07-01 23:55:55 +08:00
Jason 9079935d72 feat(presets): add NekoCode partner preset for 6 apps
Partner aggregator (New API gateway) across Claude Code, Claude Desktop,
Codex, OpenCode, OpenClaw, and Hermes -- no Gemini, since its /v1beta
surface falls through to the web app. Claude Code and Claude Desktop use
the bare host https://nekocode.ai; Codex, OpenCode, OpenClaw, and Hermes
use /v1 with gpt-5.5.

Marks isPartner with the ?aff=CCSWITCH referral on apiKeyUrl only (the
website URL and every API endpoint stay bare, so the attribution param
never rides on a real request). Adds the partnerPromotion blurb in all
four locales and a sponsor row appended to the end of all four READMEs,
surfacing the CC Switch offer: 10% off top-ups with promo code cc-switch.
Registers the logo-derived nekocode-icon.png via URL import; the README
banner is normalized to the standard 1920x798 aspect ratio.
2026-07-01 22:27:10 +08:00
Jason a8657d229a feat(presets): add Code0.ai partner preset for 7 apps
Partner aggregator (New API gateway) across Claude Code, Claude Desktop,
Codex, Gemini, OpenCode, OpenClaw, and Hermes. Claude Code, Claude
Desktop, and Gemini use the bare host (gemini-3.1-pro-preview for
Gemini); Codex, OpenCode, OpenClaw, and Hermes use /v1 with gpt-5.5.

Marks isPartner with ?source=ccswitch attribution on apiKeyUrl only
(website URL stays clean). Adds the partnerPromotion blurb in all four
locales and a sponsor row in all four READMEs. Positioned after
ClaudeAPI in the Claude Code and Claude Desktop lists (the two apps
that carry a ClaudeAPI preset). Registers the favicon-derived code0.png
icon via URL import; the README banner is normalized to the standard
1920x798 aspect ratio.
2026-07-01 22:27:10 +08:00
Jason cd9e025b5a feat(presets): switch Claude Sonnet tier default to Sonnet 5
Bump every claude-sonnet-4-6/claude-sonnet-4.6 default pin to claude-sonnet-5 across all provider presets (claude, claudeDesktop, hermes, openclaw, opencode, universal NEWAPI_DEFAULT_MODELS) and the Claude Desktop DEFAULT_PROXY_ROUTES sonnet route id. Update route-derivation test expectations accordingly. Non-Anthropic pins (gpt/gemini/glm/sonnet-4-5) left untouched.
2026-07-01 22:27:10 +08:00
Jason 778d5b9268 feat(pricing): add Claude Sonnet 5 model pricing
Seed claude-sonnet-5 at Anthropic list price ($3/$15 in/out, $0.30/$3.75 cache read/write per Mtok, matching Sonnet 4.6). The introductory $2/$10 promo through 2026-08-31 is intentionally not seeded. Applied on next app start via ensure_model_pricing_seeded; no SCHEMA_VERSION bump.
2026-07-01 22:27:10 +08:00
Jason 97512cabbd docs: document CC_SWITCH_GDK_BACKEND Linux Wayland escape hatch
Document the opt-in CC_SWITCH_GDK_BACKEND environment variable (added in
#4351) that overrides the AppImage's hardcoded GDK_BACKEND=x11, letting
Wayland+NVIDIA users switch back to native Wayland when the webview goes
click-dead and black-screens on resize. The override is generic, so
tiling-Wayland users can set it to x11 for the inverse input bug.

- CHANGELOG.md: new Unreleased/Fixed entry (#4351, fixes #4350)
- README.md / README_ZH / README_JA / README_DE: FAQ entry across all locales
- docs/user-manual/{zh,en,ja}/5-faq/5.2-questions.md: Linux troubleshooting entry
2026-07-01 22:27:10 +08:00
Jason 332a3c16a8 feat(presets): add Amux provider preset for 6 apps
Non-partner aggregator across Claude Code, Claude Desktop, Codex,
OpenCode, OpenClaw, and Hermes. Claude Code uses bare host
api.amux.ai; Codex uses /v1 native Responses; the other three apps
default to gpt-5.5. No Gemini preset. Registers the amux inline icon
(currentColor) in the icon index and metadata.
2026-07-01 22:27:10 +08:00
SaladDay 586fb46b10 fix(usage): keep date-range picker calendar on-screen in narrow popovers (#4860)
The custom date-range picker switched to its two-column layout (date
fields | calendar) based on the viewport width via Tailwind `sm:`
(640px). But the popover is clamped to `100vw - 2rem` and anchored to
its trigger with `align="end"`, so its actual available width is not the
viewport width. On narrow windows the wide two-column layout could
activate while the popover only had room for one column, pushing the
calendar column off the right edge of the window where it was clipped
and unusable (month header and 4 of 7 weekday columns cut off).

Gate the two-column layout on the popover's own inline size via a CSS
container query instead of the viewport, and let the popover width
shrink to fit the viewport. When the popover is genuinely wide it shows
two columns; when it is clamped narrow it stacks vertically so the
calendar stays fully visible. The base stacked layout is the safe
fallback for engines without container-query support.

Closes #4669
2026-07-01 16:33:07 +08:00
Nothing 251b13e5d2 feat(sessions): 新增会话分类视图与分组管理 (#4776)
* feat(sessions): 新增会话分类查看方式

* test(sessions): 补充会话分类视图覆盖

* feat(sessions): 适配分类视图批量管理

* test(sessions): 补充分类批量选择覆盖

* feat(sessions): 新增分类视图收起状态控制

* test(sessions): 补充分类收起状态覆盖
2026-07-01 12:23:46 +08:00
Arc f21d6f7a42 fix(i18n): rename "Write Common Config" checkbox to "Apply Common Config" (#4829)
* fix(i18n): rename "Write Common Config" checkbox to "Apply Common Config"

The original label "Write Common Config" (写入通用配置) was ambiguous
about data flow direction — it read as "write current config INTO the
common config" when the actual behavior is the reverse: merge the
saved common config snippet INTO this provider's config.

Rename to "Apply Common Config" across zh/zh-TW/en/ja, including all
hint/guide/notice references and component defaultValue fallbacks, to
make the action unambiguous. Also aligns the Gemini hint wording with
the claude/codex "when checked" phrasing.

* docs(ja): sync Japanese docs with renamed 'Apply Common Config' label

Codex review on #4829 pointed out the Japanese user manual and README
still referenced the old checkbox label after the rename.

- docs/user-manual/ja/2-providers/2.1-add.md: 共通設定を書き込み → 共通設定を適用
- README_JA.md: 共有設定を書き込む → 共有設定を適用
2026-07-01 11:58:31 +08:00
ayxwi ab3e628bad Fix scroll bounds for long select dropdowns (#4798)
Co-authored-by: Xvvln <180168103+Xvvln@users.noreply.github.com>
2026-07-01 11:57:17 +08:00
迷渡 8f484c54ce fix(detect): dedupe Windows Codex npm shims (#4782) 2026-07-01 11:33:40 +08:00
Bone 5546815441 fix(linux): allow overriding AppImage's forced GDK_BACKEND=x11 via CC_SWITCH_GDK_BACKEND (#4351)
The AppImage GTK hook (linuxdeploy-plugin-gtk.sh) hardcodes
`export GDK_BACKEND=x11`, forcing XWayland to avoid a historical Wayland crash
(tauri-apps/tauri#8541). On modern Wayland + NVIDIA setups this forced XWayland
instead makes the WebKitGTK webview unable to receive pointer events (GTK
titlebar clickable, web content completely dead) and black-screens on resize.

Read an opt-in CC_SWITCH_GDK_BACKEND var before GTK init (the hook does not
touch it) so affected users can switch back to native Wayland without unpacking
the AppImage. Default behavior is unchanged when the var is unset.

Refs #4350

Co-authored-by: BoneLiu <bone_liu@sina.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-30 23:26:51 +08:00
Jason 01bf003783 feat(presets): add TeamoRouter provider preset for 6 apps
Add TeamoRouter (enterprise Agentic LLM gateway) as a sponsor partner
across Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw and Hermes.

- Claude Code uses bare host https://api.teamorouter.com; Codex uses
  https://api.teamorouter.com/v1 (native Responses); OpenCode/OpenClaw/
  Hermes use gpt-5.5 over the OpenAI-compatible /v1 endpoint. No Gemini.
- apiKeyUrl uses the English referral link with UTM params (in-app stays
  English; README links are per-language).
- Add localized in-app promo blurb (zh/en/ja/zh-TW).
- Add README sponsor rows below PatewayAI in all four READMEs.
- Register the teamorouter provider icon and pad the README banner to the
  standard 2.40 aspect ratio.
2026-06-30 23:01:49 +08:00
Jason e1e3dadf89 chore(icons): remove unused dds.svg orphan
dds.svg (1.4MB genuine vector, 2222 paths) was not imported in index.ts
nor referenced anywhere in src/, so it never shipped in the app or
appeared in the icon system — it only bloated the repo. Remove it.
2026-06-30 17:02:19 +08:00
Jason ba87e8f69d perf(icons): downscale hermes, claudecn and atlascloud icons to 256px
All three shipped well above their ~32px render size (hermes/claudecn at
512x512, atlascloud at 3525x3300). Downscale to a 256px max dimension:
hermes 125KB->38KB, claudecn 109KB->46KB, atlascloud 105KB->9KB. Same
filenames, no code change.
2026-06-30 17:02:19 +08:00
Jason 37f2e248dc perf(icons): shrink ccsub and shengsuanyun embedded-image SVGs
Both were "fake vector" SVGs wrapping a single oversized base64 PNG
(ccsub embedded 1446x1328 / 1.16MB, shengsuanyun 720x720 / 212KB),
rendered at ~32px. Downscale the embedded bitmap to a 256px max dimension
and re-embed, keeping the SVG wrapper, filename, and import unchanged
(no code change). Result: ccsub 1.16MB -> 60KB, shengsuanyun 212KB -> 51KB.
2026-06-30 17:00:53 +08:00
Jason 6f8e12a1ac perf(icons): downscale relaxcode and sudocode icons to 256px
Both shipped far larger than their on-screen render size: relaxcode was
1462x1076 / 1.16MB and sudocode 2048x2048 / 432KB. Downscale to a 256px
max dimension (aspect ratio preserved; ProviderIcon renders via <img>
object-contain), cutting them to ~41KB and ~36KB. Same filenames.
2026-06-30 16:50:38 +08:00
Jason 8fb6ebb6bd perf(icons): downscale ZetaAPI provider icon to 256px
The ZetaAPI icon shipped as a 1254x1254 / 940KB PNG, roughly 30x larger
than its on-screen render size (~32px in ProviderIcon). Downscale to
256x256, cutting it to ~40KB (-96%) so it no longer bloats the bundle.
Same filename, so no import/code change.
2026-06-30 16:49:35 +08:00
Jason e54a342301 feat(presets): add ZetaAPI provider preset for 6 apps
Add ZetaAPI (api.zetaapi.ai) as a partner aggregator preset across Claude
Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes (Gemini not
supported). ZetaAPI relays native Claude/GPT, so Claude Code/Codex pass
through native models; the OpenAI-compatible apps default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host (api.zetaapi.ai)
- Codex: native Responses at api.zetaapi.ai/v1, gpt-5.5
- OpenCode / OpenClaw / Hermes: gpt-5.5 over api.zetaapi.ai/v1
- Partner referral link (zetaapi.ai/go/ccs) as apiKeyUrl + short
  partner-promotion blurb in zh/en/ja/zh-TW
- Add ZetaAPI sponsor entry to all four READMEs (zetaapi-banner.png),
  first-recharge 10% off with promo code CC-SWITCH
- Register zetaapi-icon.png icon (URL import + iconUrls + metadata)
2026-06-30 16:39:32 +08:00
Jason 997bad94f0 docs(kimi): point overseas READMEs to platform.kimi.ai and add Coding Plan link 2026-06-30 09:53:02 +08:00
Jason d4feaa4e53 chore(kimi): update referral links to new platform.kimi.com domain
Moonshot rebranded its console to Kimi, so refresh all Kimi sponsor
referral links across provider presets and READMEs:

- API (domestic): platform.moonshot.cn/console -> platform.kimi.com
- API key page: platform.moonshot.cn/console/api-keys -> platform.kimi.com/console/api-keys
- Coding Plan: www.kimi.com/code/docs/ -> www.kimi.com/code/

Also add the missing ?aff=cc-switch param to the codex and openclaw
entries that previously had no referral attribution. API endpoints
(api.moonshot.cn, api.kimi.com/coding) are intentionally left unchanged.
The overseas link (platform.kimi.ai) is not wired up yet since there is
no overseas API preset.
2026-06-30 09:15:04 +08:00
Jason 16f988bd1a feat(providers): auto-sync Claude common config from live on switch
When switching away from a Claude provider that opted into common config, re-extract the shareable portion of its live settings.json and replace the stored snippet. This captures config the user added directly in the app (plugins/hooks/shared prefs) so it isn't lost on switch, and propagates deletions so a removed key isn't re-injected on the next switch.

Scoped to Claude providers with common_config_enabled, skipped when the snippet was explicitly cleared. All failures are non-fatal (warn only) and never block the switch.

Also harden extract_claude_common_config to strip ALL credential-like keys via pattern match (*_API_KEY / *_AUTH_TOKEN / secret / token / etc.), not just ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN. Claude providers legitimately use OPENROUTER_API_KEY / GOOGLE_API_KEY (and may carry OpenAI/Gemini/AWS Bedrock/Vertex creds), which previously could leak into the shared snippet and be injected into other providers. This also fixes the pre-existing leak in the manual Extract and one-time auto-extract paths. Plural _TOKENS (e.g. MAX_OUTPUT_TOKENS) is preserved as shareable.

Tests: 4 integration (capture / delete-sync / opt-out / cleared) + 1 unit (credential stripping).
2026-06-29 23:30:58 +08:00
Jason 36e0378e78 feat(providers): show API key link in Claude Desktop, OpenClaw and Hermes forms
The "Get API Key" link (and partner promotion) below the API key input was
only wired for claude/codex/gemini/opencode. Claude Desktop uses a separate
form that never rendered it, and OpenClaw/Hermes were blocked by two gaps:

- useApiKeyLink whitelisted only 4 app ids, so the link was suppressed for
  claude-desktop/openclaw/hermes even when a preset carried apiKeyUrl.
- useProviderCategory only parsed claude/codex/gemini/opencode preset ids, so
  OpenClaw/Hermes category stayed undefined and the link condition
  (cn_official/aggregator/third_party) never held.

Changes:
- ClaudeDesktopProviderForm: call useApiKeyLink and replace the bare API key
  Input with the shared ApiKeySection.
- useApiKeyLink: add claude-desktop/openclaw/hermes to the whitelist and add
  ClaudeDesktopProviderPreset to the PresetEntry union.
- useProviderCategory: parse and resolve openclaw/hermes preset categories.
- Hermes/OpenClaw form fields: don't let an "official" category disable the
  API key input, since these apps have no OAuth-only official providers
  (e.g. Hermes' Nous Research is "official" but still needs a user key).
2026-06-29 23:30:58 +08:00
Jason 238cd5d7c9 feat(presets): add FennoAI provider preset for 6 apps
Add FennoAI (api.fenno.ai) as a partner aggregator preset across Claude
Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes (Gemini not
supported). FennoAI relays native Claude/GPT, so Claude Code/Codex pass
through native models; the OpenAI-compatible apps default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host (api.fenno.ai)
- Codex: native Responses at api.fenno.ai, gpt-5.5
- OpenCode / OpenClaw / Hermes: gpt-5.5 over api.fenno.ai/v1
- Partner referral link as apiKeyUrl + short partner-promotion blurb in
  zh/en/ja/zh-TW
- Add FennoAI sponsor entry to all four READMEs (fenno-banner.png)
- Register fenno-icon.webp icon (URL import + iconUrls + metadata)
2026-06-29 23:30:58 +08:00
Jason 3476707321 feat(presets): add Qiniu (七牛云) provider preset for all apps
Add the Qiniu Cloud AI gateway (api.qnaigc.com primary, api.modelink.ai
overseas mirror) as a partner aggregator preset across Claude Code, Claude
Desktop, Codex, Gemini, OpenCode, OpenClaw, and Hermes.

Qiniu relays native Claude/GPT/Gemini, so Claude Code/Codex pass through
native models (no domestic-model pinning); the OpenAI-compatible apps
default to gpt-5.5.

- Claude / Claude Desktop: Anthropic-compatible bare host, native passthrough
- Codex: native Responses at /bypass/openai/v1, gpt-5.5
- Gemini: gemini-3.1-pro-preview via /bypass/vertex
- OpenCode / OpenClaw / Hermes: gpt-5.5 over OpenAI-compatible /v1
- Localized display name via nameKey + partner promotion blurb in zh/en/ja/zh-TW
- Register qiniu.png icon (URL import + iconUrls + metadata)
2026-06-29 23:30:58 +08:00
Jason 64a94ba3f7 chore(presets): update SiliconFlow referral link
Replace the SiliconFlow invite code drGuwc9k with YflgU2Ve across all
README locales and provider presets (claude, claude-desktop, codex,
hermes, openclaw).
2026-06-29 23:30:58 +08:00
Jason d916b4e12d fix(openclaw): sync Doubao context window to 262144
The OpenClaw DouBaoSeed preset hard-coded contextWindow 128000 while the
Codex preset/catalog uses 262144 for the same model, giving OpenClaw users
a too-small window that could compress or truncate long context early.
Align to 262144 and add a cross-preset consistency test asserting the
OpenClaw and Codex Doubao context windows stay equal, so neither side can
drift again.
2026-06-29 23:30:58 +08:00
Jason 7f83feb222 fix(presets): use dated Doubao model id and price 6-digit dated models
Volcengine Ark rejects the bare model name doubao-seed-2-1-pro with a 404
("model does not exist or you do not have access to it") even after the
model is activated; the API requires the full dated id
doubao-seed-2-1-pro-260628. Update the Doubao preset model id across all
apps (config default, generated catalog, and OpenClaw namespaced refs).

Pricing lookup only stripped 8-digit (YYYYMMDD) and ISO date suffixes, not
the 6-digit YYMMDD format Volcengine uses (-260628, -250615), so real
Doubao usage never matched the bare-name pricing seed and showed $0 cost.
Extend strip_model_date_suffix to also strip 6-digit YYMMDD (with
month/day validation to avoid eating non-date version suffixes), keeping
the bare-name pricing seed as the canonical identity. This also fixes
pricing for every other Volcengine Doubao model. Add unit and end-to-end
regression tests.
2026-06-29 23:30:58 +08:00
Jason 562480870d fix(presets): point Volcengine/Doubao/BytePlus website links to official sites
The websiteUrl for the 火山Agentplan, BytePlus and DouBaoSeed presets was
accidentally set to the same invite/console link as apiKeyUrl, so the
"visit official site" button took users to the referral/API-key page
instead of the product homepage. Restore clean official homepages across
all six app preset files; the apiKeyUrl referral links are kept intact.

- 火山Agentplan -> https://www.volcengine.com/product/ark
- DouBaoSeed    -> https://www.volcengine.com/product/doubao
- BytePlus      -> https://www.byteplus.com/en/product/modelark (drop utm)
2026-06-29 23:30:58 +08:00
Jason 85b38c1bed refactor(codex): decouple model mapping from local-routing toggle
Align the Codex provider form with Claude Code. Model mapping (the
catalog) is independent from route takeover: native Responses providers
(MiMo, Doubao, MiniMax) need it for direct connect with no proxy, while
Chat providers use the proxy regardless of any per-provider flag.

- Remove the "Needs Local Routing" toggle. It had no backend field and
  only gated catalog/reasoning persistence, which is equivalent to
  "is the mapping filled".
- Always show model mapping for non-official providers; persist when the
  list is non-empty (backend already keys off modelCatalog.models).
- Gate reasoning visibility/persistence on Chat format, not the toggle.
- Mark the Chat upstream-format option "routing required" and refresh the
  advanced-section hint (zh/en/ja/zh-TW); drop dead localRouting* keys.
- Move the model-mapping block above the custom User-Agent block.

fix(codex): preserve native-profile hidden catalog fields on edit

useCodexConfigState dropped supportsParallelToolCalls / inputModalities /
baseInstructions when loading a saved provider, so editing and saving a
native Responses provider lost parallel tools, image input and the
official base instructions from the generated catalog. Preserve them on
load (camelCase + snake_case) and compare them in the row sync. Add a
regression test.
2026-06-29 23:30:58 +08:00
Jason 26f0d221c0 fix(codex): reject web_search for Qwen3-Coder and correct LongCat context window
- Add `qwen3-coder` to the web_search reject model-prefix blacklist so the
  native qwen3-coder-plus direct-connect preset suppresses the built-in tool
  (百炼 rejects it for the coder series), while general Qwen models sharing the
  DashScope host keep web_search enabled. Matched on the model axis, not host.
- Correct LongCat-2.0-Preview context window from 128K to its real 1M
  (1048576), aligning with the MiMo/Qwen 2^20 convention.
- Tighten native Responses preset tests to assert exact model→contextWindow
  catalogs instead of only checking catalog presence.
2026-06-29 23:30:58 +08:00
Jason d380b410af fix(codex): disable web_search for native gateways that reject it
Some native /responses gateways whose first-party models lack OpenAI's
hosted web_search tool (MiMo, LongCat, MiniMax) reject a web_search tool
with "tool type 'web_search' is not supported by this gateway phase".
Codex sends the tool by default (config-driven, not gated by the catalog's
supports_search_tool), so cc-switch now writes the top-level
`web_search = "disabled"` line per those vendors' official Codex docs.

Scope is a blacklist (default-on): only providers matched by base_url host
or model brand prefix are disabled; relays serving real GPT, DouBao, Qwen,
and any unknown provider keep Codex's default. Matching by model brand (not
just host) also catches aggregators (e.g. SiliconFlow) fronting a reject
vendor's model. The field is injected alongside model_catalog_json at
switch time and removed via an ownership sentinel, so existing providers
need no re-save and switching back re-enables web search.
2026-06-29 23:30:58 +08:00
Jason 15e712e779 feat(codex): support native Responses direct-connect with generated model catalog
Codex providers can now run in two modes per provider:

- Proxy-Chat (route takeover): apiFormat=openai_chat, existing Responses<->Chat conversion. Unchanged.

- Native-Responses (direct): apiFormat=openai_responses, no proxy. cc-switch generates ~/.codex/cc-switch-model-catalog.json so Codex shows the custom models and tools work without the freeform apply_patch (type=custom) tool that native gateways like MiMo reject; editing falls back to shell_command.

Catalog generation is keyed on apiFormat (CodexCatalogToolProfile), decoupled from the takeover toggle, so native providers persist a catalog without enabling local route mapping.

Codex's catalog parser requires base_instructions on every entry; the native template carries a neutral default and per-vendor official text overrides it (MiMo, MiniMax). Synthesized catalogs for Qwen/Doubao/LongCat use the neutral default.

Existing native providers must be re-saved once to regenerate a valid catalog (no DB migration).
2026-06-29 23:30:58 +08:00
thisTom 61d7ac01fb fix(hermes): Windows 上 Hermes 供应商配置不生效 (#4680)
* fix(hermes): resolve config dir via HERMES_HOME and platform defaults

On Windows, CC Switch hardcoded `~/.hermes` as the Hermes config directory,
but Hermes resolves it through `get_hermes_home()`: `HERMES_HOME` env var,
then a platform default (Windows `%LOCALAPPDATA%\hermes`, mac/Linux
`~/.hermes`). So CC Switch wrote configs where Hermes never reads them and
provider changes had no effect (refs #3178).

`get_hermes_dir()` now mirrors Hermes' own resolution order:
  1. `settings.hermes_config_dir` — CC Switch explicit override
  2. `HERMES_HOME` env var — trimmed, non-empty, taken as-is (no `~`
     expansion, matching Hermes' `Path(val)`)
  3. platform default — Windows reads the `LOCALAPPDATA` env var (the exact
     value Hermes reads, not a re-derived Known-Folder path) and falls back
     to `~\AppData\Local\hermes`; mac/Linux keep `~/.hermes`

Relation to #3470: that PR dropped `HERMES_HOME` for "consistency with
Codex/Claude". But unlike those tools Hermes treats `HERMES_HOME` as a
first-class mechanism (its own Windows installer sets it), so ignoring it
reintroduces the same mismatch for relocated installs. This keeps it.

Tests cover HERMES_HOME precedence, settings-override > HERMES_HOME, blank
HERMES_HOME fall-through, the platform-correct default, and a pure
`windows_local_hermes_dir` helper exercising the LOCALAPPDATA-set and
LOCALAPPDATA-empty fallback paths on every host.

* test(hermes): isolate config-dir tests from ambient HERMES_HOME/LOCALAPPDATA

`get_hermes_dir()` now consults `HERMES_HOME` (all platforms) and `LOCALAPPDATA`
(Windows). The `with_test_home` helper only neutralized `CC_SWITCH_TEST_HOME`,
so an ambient `HERMES_HOME` — which Hermes' own Windows installer sets — would
make tests that write `get_hermes_config_path()` escape the temp home and touch
a real Hermes config (and the same hazard exists via `LOCALAPPDATA` on Windows).

Clear and restore both env vars in `with_test_home`. This is safe: only this
module reads those env vars, and `dirs` uses the Known-Folder API rather than the
env var. Adds a test asserting both are neutralized inside `with_test_home`.

Addresses the Codex review comment on #4680.

* fix(hermes): trim LOCALAPPDATA to match Hermes' .strip()

`windows_local_hermes_dir` checked `OsStr::is_empty()` on the raw value, but
Hermes does `os.environ.get("LOCALAPPDATA", "").strip()`. A whitespace/padded
`LOCALAPPDATA` would make CC Switch write under the literal padded path while
Hermes trims and falls back, hiding the config from Hermes. Trim before the
empty check, matching the existing `HERMES_HOME` handling. Adds
`windows_local_hermes_dir_trims_localappdata`.

Addresses the Codex review comment on #4680.

---------

Co-authored-by: thisTom <19346741+thisTom@users.noreply.github.com>
2026-06-28 17:49:52 +08:00
yyhhyyyyyy d1f6c74be8 fix(usage): treat usage_script credentials as explicit overrides (#4654)
* fix(usage): treat usage_script credentials as explicit overrides

* fix: treat usage script credentials as explicit overrides
2026-06-28 17:37:58 +08:00
Jason eb847642d0 docs(release-notes): add GitHub global top-100 milestone banner to v3.16.4 notes 2026-06-27 13:32:18 +08:00
242 changed files with 28650 additions and 5147 deletions
+14
View File
@@ -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
+74
View File
@@ -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"
+17
View File
@@ -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
+1
View File
@@ -15,6 +15,7 @@ concurrency:
jobs:
release:
runs-on: ${{ matrix.os }}
environment: release
strategy:
fail-fast: false
matrix:
-1
View File
@@ -28,5 +28,4 @@ flatpak-repo/
copilot-api
.history
CODEBUDDY.md
.github
mainWindow.js
+118
View File
@@ -5,6 +5,124 @@ 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.
**Stats**: 36 commits | 93 files changed | +5,678 insertions | -2,804 deletions
### Added
- **Codex Native Responses Direct-Connect Regenerates a Model Catalog**: Reverses the v3.16.4 direction that dropped the catalog — Codex providers now run in two explicit modes, and native direct-connect once again ships a catalog file. Providers with `apiFormat: "openai_responses"` run with no proxy, and cc-switch generates `~/.codex/cc-switch-model-catalog.json` (`CC_SWITCH_CODEX_MODEL_CATALOG_FILENAME`, provider id `custom`) so Codex Desktop actually shows the custom models and tools work without the freeform `apply_patch` (`type=custom`) tool that native gateways like MiMo reject — editing falls back to `shell_command`. Catalog generation is keyed on `apiFormat` via `CodexCatalogToolProfile` and decoupled from the route-takeover toggle, so a native provider persists a catalog without enabling local route mapping, while `openai_chat` keeps the existing Responses↔Chat proxy conversion unchanged. Codex's parser requires `base_instructions` on every entry, so the native template (`codex_native_responses_template.json`, slug `gpt-5.5`) carries a neutral default that per-vendor official text overrides (MiMo, MiniMax); synthesized catalogs for Qwen/Doubao/LongCat use the neutral default. Existing native providers must be re-saved once to regenerate a valid catalog (no DB migration).
- **Categorized Session View With Two-Level Grouping**: The Session Manager gains a grouped view mode alongside the flat list, toggled via a List/ListTree Select in the toolbar and persisted to `localStorage` under `cc-switch.sessionManager.listViewMode`. The new `groupSessionsByProviderAndDirectory` helper builds a two-level hierarchy (provider group → project-directory group): directory groups are keyed by `getSessionDirectoryGroupKey(providerId, projectDir)` and labeled with `getBaseName(projectDir)`, and sessions lacking a `projectDir` fall into an "unknown directory" bucket (`UNKNOWN_PROJECT_DIR_KEY = __unknown_project_dir__`). Both levels are Radix Collapsible sections whose expansion state is serialized to `cc-switch.sessionManager.groupExpansionState` (pruned to valid keys after load), with a "collapse all" button; in batch mode each group header gains a tri-state checkbox that selects/deselects every selectable session (those with a `sourcePath`) at once, backed by a `Minus`-glyph indeterminate state added to `ui/checkbox.tsx` and a selected/selectable count badge. New keys were added across all four locales (zh/en/ja/zh-TW). The change is entirely frontend — no Tauri commands or DAO changes. (#4776)
- **Qiniu (七牛云) Provider Preset Across All Seven Apps**: Added the Qiniu Cloud AI gateway as a partner aggregator spanning Claude Code, Claude Desktop, Codex, Gemini, OpenCode, OpenClaw, and Hermes — the widest coverage of the batch and the only one carrying a Gemini preset. Because Qiniu relays native Claude/GPT/Gemini rather than remapping to domestic models, Claude Code/Desktop use the Anthropic-compatible bare host with native passthrough (no model pinning), Codex hits native Responses at `https://api.qnaigc.com/bypass/openai/v1` defaulting to `gpt-5.5`, and Gemini uses `gemini-3.1-pro-preview` via `https://api.qnaigc.com/bypass/vertex`; OpenCode/OpenClaw/Hermes default to `gpt-5.5` over the OpenAI-compatible `/v1`. Each type carries `endpointCandidates` listing the `api.qnaigc.com` primary plus the `api.modelink.ai` overseas mirror for failover. It is marked `isPartner` with referral `https://s.qiniu.com/nMvAvy`, a localized display name via `nameKey` (`providerForm.presets.qiniu`) and a partner-promotion blurb in all four locales (zh/en/ja/zh-TW), and registers the `qiniu.png` icon through URL import plus `iconUrls` and metadata.
- **FennoAI, ZetaAPI, and TeamoRouter Partner Presets**: Added three partner aggregators — FennoAI (`api.fenno.ai`), ZetaAPI (`api.zetaapi.ai`), and TeamoRouter (`api.teamorouter.com`) — each covering Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes with no Gemini preset, since these relay native Claude/GPT only. In every case Claude Code/Desktop use the Anthropic-compatible bare host with native passthrough, Codex uses native Responses (FennoAI at `api.fenno.ai`, ZetaAPI and TeamoRouter at their `/v1` paths) defaulting to `gpt-5.5`, and OpenCode/OpenClaw/Hermes default to `gpt-5.5` over the OpenAI-compatible `/v1`. All three are `isPartner` with referral `apiKeyUrls` (FennoAI's ¥9.9 Coding Plan link, ZetaAPI's `zetaapi.ai/go/ccs`, TeamoRouter's `teamorouter.com` with `utm_source=cc_switch` — its in-app link stays English while README links are per-language), each ships a localized promo blurb in zh/en/ja/zh-TW plus a sponsor row in all four READMEs, and each registers its own icon (`fenno-icon.webp`, `zetaapi-icon.png`, `teamorouter`). Two carry surfaced discount codes: ZetaAPI gives a first-recharge 10% discount with promo code `CC-SWITCH`, and TeamoRouter gives new users 10% off their first top-up.
- **Amux Aggregator Preset**: Added Amux (`api.amux.ai`) as a non-partner aggregator across Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes, with no Gemini preset. Claude Code/Desktop use the bare Anthropic-compatible host, Codex uses native Responses over the `/v1` path, and the remaining three apps default to `gpt-5.5` over the OpenAI-compatible endpoint. Unlike the partner presets in this batch it carries no `isPartner` flag, referral link, or promo copy; the `amuxapi-icon.svg` is registered as an inline `currentColor` icon in `src/icons/extracted/index.ts` and `metadata.ts` rather than a raster URL import.
- **Code0.ai Partner Preset Across All Seven Apps**: Added Code0.ai (`code0.ai`) as a partner aggregator spanning all seven apps — Claude Code, Claude Desktop, Codex, Gemini, OpenCode, OpenClaw, and Hermes. Claude Code, Claude Desktop, and Gemini use the bare `https://code0.ai` host (Anthropic-native passthrough with no model pinning for the two Claude apps, `gemini-3.1-pro-preview` for Gemini), Codex hits native Responses at `https://code0.ai/v1`, and OpenCode/OpenClaw/Hermes default to `gpt-5.5` over the OpenAI-compatible `/v1`. It is marked `isPartner` with a `?source=ccswitch` referral on the API-key signup link, a partner-promotion blurb surfacing the CC Switch test-credit offer in all four locales (zh/en/ja/zh-TW), a sponsor row in all four READMEs, and the `code0.png` icon registered via URL import.
- **NekoCode Partner Preset Across Six Apps**: Added NekoCode (`nekocode.ai`) as a partner aggregator spanning six apps — Claude Code, Claude Desktop, Codex, OpenCode, OpenClaw, and Hermes (no Gemini preset). Claude Code and Claude Desktop use the bare `https://nekocode.ai` host (Anthropic-native passthrough with no model pinning), Codex hits native Responses at `https://nekocode.ai/v1`, and OpenCode/OpenClaw/Hermes default to `gpt-5.5` over the OpenAI-compatible `/v1`. It is marked `isPartner` with a `?aff=CCSWITCH` referral on the API-key signup link (kept off the actual request endpoints), a partner-promotion blurb in all four locales (zh/en/ja/zh-TW), and a sponsor row in all four READMEs, both surfacing the CC Switch offer — 10% off top-ups with promo code `cc-switch` at recharge. The `nekocode-icon.png` icon is registered via URL import.
- **Claude Sonnet 5 Model Pricing**: Seeded a `claude-sonnet-5` pricing row in `schema.rs` at Anthropic list price — $3/$15 per Mtok input/output and $0.30/$3.75 cache read/write, identical to the Sonnet 4.6 rates. The introductory $2/$10 promo (valid through 2026-08-31) is deliberately not seeded, so accounting reflects steady-state list pricing rather than a temporary discount. The row is applied on next app start via `ensure_model_pricing_seeded` and requires no `SCHEMA_VERSION` bump.
### Changed
- **Decoupled Codex Model Mapping From the Local-Routing Toggle**: Aligns the Codex provider form with Claude Code — the model-mapping catalog is now independent of route takeover, since native Responses providers (MiMo, Doubao, MiniMax) need it for proxy-less direct connect while Chat providers use the proxy regardless of any per-provider flag. The "Needs Local Routing" toggle is removed: it had no backend field and only gated catalog/reasoning persistence, which is equivalent to whether the mapping is filled. Model mapping is now always shown for non-official providers and persisted whenever the list is non-empty (the backend already keys off `modelCatalog.models`), while reasoning visibility/persistence is gated on the Chat format instead of the toggle. The Chat upstream-format option is marked "routing required" with a refreshed advanced-section hint across all four locales (zh/en/ja/zh-TW), dead `localRouting*` keys are dropped, and the model-mapping block moves above the custom User-Agent block. Also fixes `useCodexConfigState` dropping `supportsParallelToolCalls`/`inputModalities`/`baseInstructions` when loading a saved provider — which silently lost parallel tools, image input, and the official base instructions on edit — by preserving them on load (camelCase and snake_case) and comparing them in the row sync.
- **Auto-Sync Claude Common Config From Live settings.json on Switch**: When switching away from a Claude provider that has `common_config_enabled`, the service now re-extracts the shareable portion of its live `settings.json` and replaces the stored common-config snippet, instead of only writing the snippet one way. This captures config the user added directly in the running app (`enabledPlugins`, `hooks`, `env`, `theme`, shared prefs) so it isn't silently lost on the next switch, and it propagates deletions so a removed key isn't re-injected later. The sync in `services/provider/mod.rs` is scoped strictly to Claude providers with `common_config_enabled`, is skipped when the snippet was explicitly cleared, and all failures are non-fatal (warn-only) and never block the switch. Four integration tests cover capture / delete-sync / opt-out / cleared.
- **Default Sonnet Tier Now Pins to Claude Sonnet 5**: Bumped every default Sonnet pin from `claude-sonnet-4-6`/`claude-sonnet-4.6` to `claude-sonnet-5` across all provider presets (`claudeProviderPresets`, `claudeDesktopProviderPresets`, `hermesProviderPresets`, `openclawProviderPresets`, `opencodeProviderPresets`, and universal `NEWAPI_DEFAULT_MODELS`), covering the `ANTHROPIC_MODEL` / `ANTHROPIC_DEFAULT_SONNET_MODEL` / `ANTHROPIC_DEFAULT_OPUS_MODEL` env keys and prefixed variants like `anthropic/claude-sonnet-5` and `global.anthropic.claude-sonnet-5`. The Claude Desktop `DEFAULT_PROXY_ROUTES` sonnet `route_id` in `claude_desktop_config.rs` also moves to `claude-sonnet-5` (`supports_1m` preserved), and the route-derivation test expectations were updated to match. Non-Anthropic pins (gpt/gemini/glm/sonnet-4-5) were left untouched.
- **Doubao Dated Model Id and YYMMDD Pricing Normalization**: Switched the Doubao (DouBaoSeed) preset model id to the dated form `doubao-seed-2-1-pro-260628` across every app surface (config default, generated Codex catalog, and OpenClaw namespaced refs), because Volcengine Ark rejects the bare `doubao-seed-2-1-pro` with a 404 ("model does not exist or you do not have access to it") even after activation and only accepts the full dated id. Because real usage now arrives with a date suffix, `strip_model_date_suffix` in `usage_stats.rs` was extended to also strip Volcengine's 6-digit YYMMDD form (`-260628`, `-250615`) in addition to the existing 8-digit YYYYMMDD/ISO handling; the 6-digit branch validates month 01-12 and day 01-31 to avoid eating non-date version suffixes like `-123456`, then falls back to `None` for exact matching. This keeps the bare-name seed row as the canonical pricing identity, fixing the $0-cost display for every Volcengine Doubao model. Unit and end-to-end regression tests were added.
- **"Write Common Config" Renamed to "Apply Common Config"**: The original label "Write Common Config" (写入通用配置) was ambiguous about data-flow direction, reading as "write the current config INTO the common config" when the actual behavior is the reverse — the saved common-config snippet is merged INTO this provider's config. The checkbox is renamed to "Apply Common Config" across all four locales (zh/en/ja/zh-TW), including every hint/guide/notice reference and the `CommonConfigEditor` / `GeminiConfigSections` defaultValue fallbacks, and the Gemini hint wording is aligned with the claude/codex "when checked" phrasing. The Japanese user manual (`docs/user-manual/ja/2-providers/2.1-add.md`) and `README_JA.md` were also synced to 共通設定を適用 / 共有設定を適用. (#4829)
- **OpenClaw Doubao Context Window Aligned to 262144**: The OpenClaw DouBaoSeed preset hard-coded `contextWindow` 128000 while the Codex preset/catalog used 262144 for the same model, giving OpenClaw users a too-small window that could compress or truncate long context prematurely. Bumped `openclawProviderPresets.ts` to 262144 and added a cross-preset consistency test asserting the OpenClaw and Codex Doubao context windows stay equal so the two sides cannot silently drift apart again.
- **Volcengine/Doubao/BytePlus Website Links Restored to Official Homepages**: The `websiteUrl` for the 火山Agentplan, BytePlus, and DouBaoSeed presets had accidentally been set to the same invite/console link as `apiKeyUrl`, so the "visit official site" button routed users to the referral/API-key page instead of the product homepage. Restored clean official homepages across all six app preset files — 火山Agentplan to `https://www.volcengine.com/product/ark`, DouBaoSeed to `https://www.volcengine.com/product/doubao`, and BytePlus to `https://www.byteplus.com/en/product/modelark` (dropping the utm params) — while leaving the `apiKeyUrl` referral links intact.
- **Kimi and SiliconFlow Referral Links Refreshed**: Updated two sponsor referral sets across presets and READMEs. Following Moonshot's console rebrand to Kimi, the Kimi preset referral links and the domestic (ZH) README banner moved to the new `platform.kimi.com` domain — the domestic console `platform.moonshot.cn/console``platform.kimi.com`, the API-key page → `platform.kimi.com/console/api-keys`, and the Coding Plan link `www.kimi.com/code/docs/``www.kimi.com/code/` — and the missing `?aff=cc-switch` attribution param was added to the codex and openclaw entries. API endpoints (`api.moonshot.cn`, `api.kimi.com/coding`) were left unchanged, and the presets have no overseas variant (the separate EN/DE/JA README switch to `platform.kimi.ai` is covered under Docs below). Separately, the SiliconFlow invite code was rotated from `drGuwc9k` to `YflgU2Ve` across all README locales and the claude, claude-desktop, codex, hermes, and openclaw presets.
- **Downscaled Oversized Provider Icons to 256px**: Shrank a batch of bundled provider icons that shipped far larger than their ~32px on-screen render size in `ProviderIcon`, cutting bundle weight with no code, filename, or import changes (aspect ratio preserved, rendered via `<img>` object-contain). Raster PNGs: ZetaAPI 1254×1254/940KB→40KB, relaxcode 1462×1076/1.16MB→42KB, sudocode 2048×2048/432KB→37KB, hermes 512×512/125KB→38KB, claudecn 512×512/109KB→46KB, atlascloud 3525×3300/105KB→9KB. Two "fake vector" SVGs wrapping a single oversized base64 PNG were re-embedded at a 256px max dimension keeping the SVG wrapper: ccsub 1.16MB→60KB and shengsuanyun 212KB→51KB. Also removed `dds.svg`, a 1.4MB genuine 2222-path vector that was never imported in `index.ts` nor referenced under `src/`, so it only bloated the repo without ever shipping.
### Fixed
- **Disable web_search for Native Codex Gateways That Reject It**: Some native `/responses` gateways whose first-party models lack OpenAI's hosted `web_search` tool reject it with "tool type 'web_search' is not supported by this gateway phase" (`responses_feature_not_supported`), and Codex sends the tool by default (config-driven, not gated by the catalog's `supports_search_tool`), producing hard 400s. cc-switch now writes the top-level TOML line `web_search = "disabled"` for those vendors via `set_codex_native_web_search_field`, injected alongside `model_catalog_json` at switch time. Scope is a blacklist (default-on): only providers matched by `base_url` host — `CODEX_WEB_SEARCH_REJECT_HOSTS = xiaomimimo.com, longcat.chat, minimax.io, minimaxi.com` — or by model brand prefix — `CODEX_WEB_SEARCH_REJECT_MODEL_PREFIXES = mimo, longcat, minimax, qwen3-coder` — are disabled, so relays serving real GPT, DouBao, general Qwen, and any unknown provider keep Codex's default. The `qwen3-coder` prefix suppresses the tool for the native `qwen3-coder-plus` direct-connect preset (百炼/DashScope marks built-in tools unsupported for the coder series) while general Qwen models sharing the DashScope host stay enabled — matching is on the model axis (after stripping any aggregator `vendor/` path segment like `MiniMaxAI/MiniMax-M3` or `qwen/qwen3-coder-plus`), so it also catches aggregators such as SiliconFlow fronting a reject vendor's model. A blacklist was chosen over a fuzzy "is this GPT?" whitelist because wrongly keeping `web_search` ON fails with a hard 400, and an ownership sentinel means cc-switch only ever removes a `web_search` key whose value equals its own `disabled`, so existing providers need no re-save and switching back re-enables web search. Also corrects the LongCat-2.0-Preview preset context window from 131072 (128K) to its real 1048576 (1M), aligning with the MiMo/Qwen 2^20 convention, and tightens the native Responses preset tests to assert exact model→contextWindow catalogs instead of only checking catalog presence.
- **Strip All Credential-Like Keys From the Shared Claude Common-Config Snippet**: `extract_claude_common_config` previously only redacted `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN`, but Claude providers legitimately carry other credentials (`OPENROUTER_API_KEY`, `GOOGLE_API_KEY`, and possibly OpenAI/Gemini/AWS Bedrock/Vertex secrets), which could leak into the shared snippet and then be injected into other providers. Extraction now pattern-matches and strips any credential-shaped env key (`*_API_KEY` / `*_AUTH_TOKEN` / `*secret*` / `*token*`, etc.), while preserving plural `*_TOKENS` values like `MAX_OUTPUT_TOKENS` as legitimately shareable. This also closes the same pre-existing leak in the manual Extract and one-time auto-extract paths, and is covered by a dedicated credential-stripping unit test.
- **Usage-Script Credentials Persisted Only as Explicit Overrides**: Provider usage scripts store optional `api_key`/`base_url` fields that override the provider's live credentials when querying quota, but these were silently mirroring the provider's own credentials — so copying a provider or editing its main API key/base URL left the usage script pinned to the old endpoint and key, and quota queries kept hitting the stale target. `ProviderService::add`/`update` now run `normalize_usage_script_credential_overrides` before persisting: if the script's trimmed `api_key` or slash-normalized `base_url` matches the provider's resolved usage credentials (or is blank) it is cleared to `None` so the query falls back to `resolve_usage_credentials` from the live config, while genuinely distinct overrides are kept and `template_type == "token_plan"` scripts are left untouched. The deeplink import path gained matching `normalize_deeplink_api_key`/`base_url` helpers, and the frontend now invalidates `usageKeys.script(id, appId)` (including the `originalId` when a provider is renamed) on update so the homepage re-queries with the corrected config instead of the test-time cache. (#4654)
- **Hermes Config Dir Now Resolves Correctly on Windows**: CC Switch hardcoded `~/.hermes` as the Hermes config directory, but Hermes itself resolves it via `get_hermes_home()` — the `HERMES_HOME` env var, then a platform default of `%LOCALAPPDATA%\hermes` on Windows (`~/.hermes` on mac/Linux). On Windows this meant CC Switch wrote provider configs to a path Hermes never reads, so provider switches had no effect. `get_hermes_dir()` now mirrors Hermes' own resolution order — `settings.hermes_config_dir` explicit override, then `HERMES_HOME` taken verbatim (trimmed, non-empty, no `~` expansion, matching Hermes' `Path(val)`), then the platform default reading the actual `LOCALAPPDATA` env var (falling back to `~\AppData\Local\hermes`) on Windows and `~/.hermes` elsewhere. This deliberately re-honors the `HERMES_HOME` that #3470 had dropped, since unlike Codex/Claude the Hermes Windows installer sets `HERMES_HOME` as a first-class mechanism for relocated installs. Config-dir tests were also isolated from ambient `HERMES_HOME`/`LOCALAPPDATA`. (#4680, refs #3178, #3470)
- **Linux Wayland: Override the AppImage's Forced `GDK_BACKEND=x11`**: The AppImage's GTK launch hook (`linuxdeploy-plugin-gtk.sh`) unconditionally exports `GDK_BACKEND=x11` to dodge a historical native-Wayland crash (tauri-apps/tauri#8541). On newer Wayland + NVIDIA setups this forced XWayland leaves the WebKitGTK web content unable to receive pointer events — the GTK title bar stays clickable but the page is dead — and black-screens on resize; the existing `WEBKIT_DISABLE_*` mitigations don't help because the root cause is the forced window backend, not rendering. Since the hook also overrides any user-set `GDK_BACKEND`, there was no way to switch back without unpacking the AppImage. `main.rs` now reads an opt-in `CC_SWITCH_GDK_BACKEND` escape hatch (which the hook never touches) before GTK init: leaving it unset keeps the current x11 behavior unchanged (zero regression), while `CC_SWITCH_GDK_BACKEND=wayland` forces native Wayland. The override is generic, so users on tiling Wayland compositors hitting the inverse input bug can set `CC_SWITCH_GDK_BACKEND=x11`. (#4351, fixes #4350)
- **Get API Key Link Now Shows in Claude Desktop, OpenClaw, and Hermes Forms**: The "Get API Key" link and partner-promotion block below the API key input was only wired for claude/codex/gemini/opencode. Claude Desktop rendered a bare Input that never showed it, and OpenClaw/Hermes were blocked by two gaps: `useApiKeyLink` whitelisted only those four appIds (so the link was suppressed even when a preset carried `apiKeyUrl`), and `useProviderCategory` only parsed the `/^(claude|codex|gemini|opencode)-(\d+)$/` preset-id pattern (so OpenClaw/Hermes category stayed undefined and the cn_official/aggregator/third_party link condition never held). `ClaudeDesktopProviderForm` now calls `useApiKeyLink` and uses the shared `ApiKeySection`; the `useApiKeyLink` whitelist and its `PresetEntry` union add claude-desktop/openclaw/hermes; and `useProviderCategory` now resolves openclaw/hermes preset categories. Additionally, `HermesFormFields` and `OpenClawFormFields` no longer let an "official" category disable the key input, since these apps have no OAuth-only official providers (e.g. Hermes' Nous Research is official but still needs a user-supplied key).
- **Deduplicated Windows Codex npm Shims in Tool Detection**: On Windows, npm installs a tool as three sibling files — `codex.cmd`, `codex.exe`, and an extensionless Unix shim named `codex` — and CC Switch's `tool_executable_candidates` listed all three, so the extensionless shim (which Windows cannot execute directly) was probed as a redundant/failing candidate. `tool_executable_candidates` now appends the extensionless path only when `windows_runnable_sibling_for_extensionless_tool` finds no adjacent `.cmd`/`.exe` sibling, and `resolve_path_default` likewise prefers a runnable `.cmd`/`.exe` sibling before canonicalizing a bare extensionless PATH hit. This keeps version detection and launching anchored to the actually-runnable Windows shim instead of the shadowed Unix one. (#4782)
- **Scroll Bounds for Long Select Dropdowns**: The `SelectContent` popover used `overflow-hidden` with no height cap, so dropdowns with many options (e.g. long model or provider lists) rendered taller than the viewport and clipped their overflowing items with no way to reach them. It now sets `max-h-[min(24rem,var(--radix-select-content-available-height))]` and `overflow-y-auto overflow-x-hidden`, bounding the content to 24rem or the Radix-computed available height and letting the list scroll vertically while still clipping horizontally. (#4798)
- **Date-Range Picker Calendar Stays On-Screen in Narrow Popovers**: The custom date-range picker switched to its two-column layout (date fields | calendar) based on the viewport width via Tailwind's `sm:` (640px) breakpoint, but the popover is clamped to `100vw - 2rem` and anchored to its trigger with `align="end"`, so its real available width is narrower than the viewport. On narrow windows the two-column layout could activate while the popover only had room for one column, pushing the calendar column off the right edge where it was clipped — the month header and 4 of 7 weekday columns cut off and unreachable. The layout now keys off the popover's own inline size via a CSS container query (`w-[620px] max-w-[calc(100vw-2rem)]`) instead of the viewport, so it collapses to one column exactly when the popover itself is narrow, keeping the calendar fully visible at any window width. (#4860)
### Docs
- **Documented the `CC_SWITCH_GDK_BACKEND` Escape Hatch in README and User Manual**: Added an FAQ entry for the opt-in `CC_SWITCH_GDK_BACKEND` environment variable (see the corresponding Fixed entry) across all four README locales (`README.md`, `README_ZH.md`, `README_JA.md`, `README_DE.md`) and the zh/en/ja user-manual troubleshooting pages (`docs/user-manual/{zh,en,ja}/5-faq/5.2-questions.md`), explaining how Wayland + NVIDIA users can switch back to native Wayland when the webview goes click-dead and black-screens on resize, and how tiling-Wayland users can set it to `x11` for the inverse input bug.
- **Overseas Kimi READMEs Point to platform.kimi.ai With a Coding Plan Link**: Updated the Kimi K2.7 Code partner section across the English, German, and Japanese READMEs so the banner image and both inline CTAs point to `https://platform.kimi.ai?aff=cc-switch` instead of the old `platform.kimi.com` host, keeping the `aff=cc-switch` referral tag intact. All four localized READMEs (`README.md`, `README_DE.md`, `README_JA.md`, `README_ZH.md`) also gained a new line promoting the Kimi For Coding subscription plan linked to `https://www.kimi.com/code/?aff=cc-switch`; note the ZH README kept its existing `platform.kimi.com` link and only received the Coding Plan addition.
- **GitHub Global Top-100 Milestone Banner in v3.16.4 Release Notes**: Prepended a celebratory callout blockquote to all three localized v3.16.4 release notes (`docs/release-notes/v3.16.4-en.md`, `-ja.md`, `-zh.md`) announcing that CC Switch has entered the global top 100 GitHub projects by star count, thanking users, contributors, and stargazers. This is a docs-only addition to the release-notes header and does not change any product behavior.
## [3.16.4] - 2026-06-27
Development since v3.16.3 focuses on tightening the Codex proxy path — native OpenAI Responses migration for the major Chinese providers, a decoupled upstream-format selector, zstd request/error-body decompression, and a run of tool-call and OAuth-over-proxy fixes — alongside richer usage and pricing tooling (models.dev pricing import, Volcengine Ark coding/agent-plan quotas, live-tracking date ranges, GLM-5.2/Doubao Seed 2.1 pricing), new proxy and resilience capabilities (custom request header/body overrides, an in-app recovery screen for too-new databases, native Windows ARM64 builds), and a broad wave of preset and branding updates (the SubRouter and OpenCode Go subscriptions, the CTok→ETok rename, Kimi rebranding and prime-partner badges, and a Kimi K2.7 Code sponsor banner).
+51 -4
View File
@@ -25,9 +25,11 @@ English | [中文](README_ZH.md) | [日本語](README_JA.md) | [Deutsch](README_
<details open>
<summary>Click to collapse</summary>
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.moonshot.cn/console?aff=cc-switch)
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.kimi.ai?aff=cc-switch)
Kimi K2.7 Code is an open-source, coding-focused agentic model developed by Moonshot AI. It delivers stronger coding and agent performance, with substantial improvements in real-world long-horizon coding tasks. These gains translate into higher end-to-end task success rates across complex software engineering workflows. K2.7 Code also improves reasoning efficiency, reducing thinking-token usage by approximately 30% compared with K2.6. **[Click here to start using Kimi](https://platform.moonshot.cn/console?aff=cc-switch)**
Kimi K2.7 Code is an open-source, coding-focused agentic model developed by Moonshot AI. It delivers stronger coding and agent performance, with substantial improvements in real-world long-horizon coding tasks. These gains translate into higher end-to-end task success rates across complex software engineering workflows. K2.7 Code also improves reasoning efficiency, reducing thinking-token usage by approximately 30% compared with K2.6. **[Click here to start using Kimi](https://platform.kimi.ai?aff=cc-switch)**
Doing mostly coding work? Try the **[Kimi For Coding plan](https://www.kimi.com/code/?aff=cc-switch)** — a subscription service built for coding!
---
@@ -60,14 +62,21 @@ It also supports enterprise-grade concurrency and provides a dedicated managemen
Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this link</a> to receive $3 in trial credit. Top-ups go as low as 60% of the original price, with a two-way referral bonus of up to $150!</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>Thanks to TeamoRouter for sponsoring this project! TeamoRouter is an enterprise-grade Agentic LLM gateway built for developers, AI teams, and businesses. Without requiring any subscriptions, it lets you access Claude Code, Codex, Gemini CLI, OpenAI Codex, and other popular AI agents through a single unified API, while offering API pricing at discounts of up to 90%.
Unlike typical API relay services, TeamoRouter aggregates hundreds of official model providers and trusted infrastructure partners, including OpenAI, Anthropic, Vertex, Azure, and AWS bedrock. Every provider is verified for 100% Agent protocol compatibility, cache performance, and request traceability, ensuring stable quality instead of reverse-engineered or diluted endpoints. The platform delivers near-official TTFT, 99.6% SLA, enterprise-scale throughput up to 5,000 QPM, and industry-leading cache hit rates that dramatically reduce token costs for long-running agent workflows.
TeamoRouter also offers enterprise features including centralized billing, team management, BYOK, smart routing, usage analytics, dynamic provider optimization, and dedicated support. For an even simpler experience, Teamo Desktop lets you use Claude Code, Codex, Gemini CLI, and other popular AI agents with one-click setup—no API key management or manual gateway configuration required. Register via <a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">this link</a> as a new user to receive 10% off your first top-up.</td>
</tr>
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Thanks to Dola seed for sponsoring this project! Dola Seed 2.0 is a fullmodal general large model independently developed by ByteDance for the global market. Built on a unified multimodal architecture, it supports joint understanding and generation of text, images, audio, and video. It natively enables agent collaboration, with strong reasoning, longtask execution, tool integration, and coding capabilities. It is widely applicable to smart cockpits, personal assistants, education, customer support, marketing, retail, and other scenarios. It excels in multimodal perception, endtoend complex task delivery, stable interaction, and data security, and is readily accessible and deployable via the ModelArk platform.Register via <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">this link</a> to get 500,000 tokens of free inference quota per model.<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥16 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/YflgU2Ve">this link</a> and complete real-name verification to receive ¥16 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
</tr>
<tr>
@@ -115,6 +124,11 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
<td>This project is sponsored by <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a>. Direct Claude API access — connect Claude Code and Agent apps in 3 minutes. New users can claim a free trial credit.Powered by official Anthropic API keys + AWS Bedrock official channels. No reverse engineering, no model degradation. Full support for Opus / Sonnet / Haiku model lineup, with official capabilities preserved including Tool Use, 1M context window, and more. Built for Claude Code power users, Agent engineers, and enterprise engineering teams. Invoicing and dedicated team support available. Click <a href="https://console.claudeapi.com/register?aff=pCLD">here</a> to register!</td>
</tr>
<tr>
<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>
<td width="180"><a href="https://claudecn.top"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>Thanks to ClaudeCN for sponsoring this project! ClaudeCN is an enterprise-grade AI gateway platform operated by a registered company. It delivers high-availability commercial API access to popular models including Claude, GPT, and DeepSeek, and is built around formal enterprise procurement workflows — corporate bank transfers, signed contracts, and full compliance. Register via <a href="https://claudecn.top">this link</a>!</td>
@@ -150,6 +164,26 @@ Register now via <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">this lin
<td>Thanks to Unity2.ai for sponsoring this project! Unity2.ai is a high-performance AI model API relay platform for individual developers, teams, and enterprises. Long trusted by leading companies in China, it serves over 30 billion tokens per day and supports high concurrency at the 5,000 RPM level. It offers balance-based billing, first top-up bonuses, bundle subscriptions, corporate invoicing, and dedicated support. Register via <a href="https://unity2.ai/register?source=ccs">this link</a> to get $2 in credits, plus another $10 for joining the official group — up to $12 in free credits!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Thanks to Fenno.ai for sponsoring this project! Fenno.ai is a stable and efficient API relay service provider, currently focused on Codex relay. It is compatible with the OpenAI and Anthropic protocols and can be flexibly used from Codex, Claude Code, OpenCode, and other mainstream coding tools. It reliably supports enterprise-grade workloads of hundreds of billions of tokens per day, with corporate (B2B) settlement and invoicing for both domestic and overseas entities. Fenno.ai offers an exclusive benefit for CC Switch users: subscribe via <a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">this link</a> to the incredible ¥9.9 Coding Plan worth $150 in credits, and earn up to 20% in referral rewards — invite more, earn more!</td>
</tr>
<tr>
<td width="180"><a href="https://zetaapi.ai/go/ccs"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>Thanks to ZetaAPI for sponsoring this project! ZetaAPI focuses on real model fidelity, no watered-down responses, no quality degradation, and pricing as low as 35% of official rates. The platform does not mix traffic, secretly replace models with lower-quality alternatives, or use fake model routing. It supports Claude Code, Codex, Gemini, ChatGPT, and other mainstream AI models, helping users significantly reduce API costs while maintaining reliable model quality. At the same time, ZetaAPI provides enterprise-grade SLA-backed stability, standard API compatibility, one API key for multiple models, fast integration, and pay-as-you-go billing, making it suitable for AI products, coding agents, internal business tools, customer service systems, content generation, and automation workflows. If any model is verified to be inconsistent with its stated quality, ZetaAPI backs it with a 10x compensation guarantee, giving users a more stable, transparent, and trustworthy experience. Register via <a href="https://zetaapi.ai/go/ccs">this link</a> and use the promo code CC-SWITCH during your first recharge to enjoy an exclusive 10% discount on your first top-up, just for CC Switch users!</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<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>
@@ -265,6 +299,19 @@ Add an official provider from the preset list. After switching to it, run the Lo
</details>
<details>
<summary><strong>Linux (Wayland + NVIDIA): clicks don't register and the window black-screens on resize</strong></summary>
The AppImage forces `GDK_BACKEND=x11` (XWayland) to avoid a historical native-Wayland crash. On newer Wayland + NVIDIA setups this can leave the web content area unclickable (the title-bar buttons still work) and black-screen on resize. Launch with the opt-in escape hatch to switch back to native Wayland:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
If you launch from a desktop icon, add it to the `.desktop` `Exec=` line (e.g. `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`) or set it in your session environment. The variable is generic: on tiling Wayland compositors (sway/Hyprland) where clicks don't register, try `CC_SWITCH_GDK_BACKEND=x11` instead. Leaving it unset keeps the default behavior.
</details>
## Documentation
For detailed guides on every feature, check out the **[User Manual](docs/user-manual/en/README.md)** — covering provider management, MCP/Prompts/Skills, proxy & failover, and more.
+51 -4
View File
@@ -25,9 +25,11 @@
<details open>
<summary>Zum Einklappen klicken</summary>
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.moonshot.cn/console?aff=cc-switch)
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.kimi.ai?aff=cc-switch)
Kimi K2.7 Code ist ein quelloffenes, auf Programmierung spezialisiertes Agenten-Modell von Moonshot AI. Es bietet eine stärkere Programmier- und Agentenleistung mit erheblichen Verbesserungen bei realen, langfristigen Programmieraufgaben. Diese Fortschritte führen zu höheren End-to-End-Erfolgsraten in komplexen Software-Engineering-Workflows. Zudem verbessert K2.7 Code die Reasoning-Effizienz und reduziert den Verbrauch an Thinking-Tokens um rund 30 % gegenüber K2.6. **[Hier klicken, um Kimi auszuprobieren](https://platform.moonshot.cn/console?aff=cc-switch)**
Kimi K2.7 Code ist ein quelloffenes, auf Programmierung spezialisiertes Agenten-Modell von Moonshot AI. Es bietet eine stärkere Programmier- und Agentenleistung mit erheblichen Verbesserungen bei realen, langfristigen Programmieraufgaben. Diese Fortschritte führen zu höheren End-to-End-Erfolgsraten in komplexen Software-Engineering-Workflows. Zudem verbessert K2.7 Code die Reasoning-Effizienz und reduziert den Verbrauch an Thinking-Tokens um rund 30 % gegenüber K2.6. **[Hier klicken, um Kimi auszuprobieren](https://platform.kimi.ai?aff=cc-switch)**
Hauptsächlich mit Programmierung beschäftigt? Probieren Sie den **[Kimi-For-Coding-Plan](https://www.kimi.com/code/?aff=cc-switch)** ein Abo, das speziell fürs Programmieren entwickelt wurde!
---
@@ -60,14 +62,21 @@ Er unterstützt zudem unternehmensgerechte Nebenläufigkeit und stellt Unternehm
Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">diesen Link</a> und erhalten Sie ein Testguthaben von 3 $. Aufladungen sind ab 60 % des Originalpreises möglich, mit einem beidseitigen Empfehlungsbonus von bis zu 150 $!</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>Danke an TeamoRouter für die Unterstützung dieses Projekts! TeamoRouter ist ein Agentic-LLM-Gateway in Enterprise-Qualität, das für Entwickler, KI-Teams und Unternehmen entwickelt wurde. Ganz ohne Abonnement können Sie über eine einzige einheitliche API auf Claude Code, Codex, Gemini CLI, OpenAI Codex und weitere beliebte KI-Agenten zugreifen — bei API-Preisen mit Rabatten von bis zu 90 %.
Anders als typische API-Relay-Dienste bündelt TeamoRouter Hunderte offizieller Modellanbieter und vertrauenswürdiger Infrastrukturpartner, darunter OpenAI, Anthropic, Vertex, Azure und AWS Bedrock. Jeder Anbieter wird auf 100%ige Kompatibilität mit dem Agent-Protokoll, Cache-Performance und Nachverfolgbarkeit von Anfragen geprüft und liefert so stabile Qualität statt reverse-engineerter oder verwässerter Endpunkte. Die Plattform bietet nahezu offizielle TTFT, 99,6 % SLA, Durchsatz in Unternehmensgröße von bis zu 5.000 QPM und branchenführende Cache-Trefferquoten, die die Token-Kosten für langlaufende Agent-Workflows drastisch senken.
TeamoRouter bietet außerdem Enterprise-Funktionen wie zentrale Abrechnung, Team-Verwaltung, BYOK, intelligentes Routing, Nutzungsanalysen, dynamische Anbieter-Optimierung und dedizierten Support. Für ein noch einfacheres Erlebnis können Sie mit Teamo Desktop Claude Code, Codex, Gemini CLI und weitere beliebte KI-Agenten per Ein-Klick-Einrichtung nutzen — ohne Verwaltung von API-Schlüsseln oder manuelle Gateway-Konfiguration. Registrieren Sie sich als neuer Nutzer über <a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">diesen Link</a> und erhalten Sie 10 % Rabatt auf Ihre erste Aufladung.</td>
</tr>
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Danke an Dola seed für die Unterstützung dieses Projekts! Dola Seed 2.0 ist ein voll-modales Allzweck-Großmodell, das von ByteDance eigenständig für den globalen Markt entwickelt wurde. Aufbauend auf einer einheitlichen multimodalen Architektur unterstützt es das gemeinsame Verstehen und Generieren von Text, Bildern, Audio und Video. Es ermöglicht von Haus aus die Zusammenarbeit von Agenten und verfügt über starke Fähigkeiten in den Bereichen Schlussfolgern, Ausführung langer Aufgaben, Werkzeugintegration und Programmierung. Es ist breit einsetzbar — etwa für intelligente Cockpits, persönliche Assistenten, Bildung, Kundensupport, Marketing, Einzelhandel und weitere Szenarien. Es überzeugt bei multimodaler Wahrnehmung, der Ende-zu-Ende-Bewältigung komplexer Aufgaben, stabiler Interaktion und Datensicherheit und ist über die ModelArk-Plattform einfach zugänglich und bereitstellbar. Registrieren Sie sich über <a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">diesen Link</a> und erhalten Sie pro Modell ein kostenloses Inferenzkontingent von 500.000 Token.<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Danke an SiliconFlow für die Unterstützung dieses Projekts! SiliconFlow ist eine leistungsstarke KI-Infrastruktur- und Modell-API-Plattform, die schnellen und zuverlässigen Zugriff auf Sprach-, Audio-, Bild- und Videomodelle an einem Ort bietet. Mit nutzungsbasierter Abrechnung, breiter Unterstützung multimodaler Modelle, Hochgeschwindigkeitsinferenz und unternehmensgerechter Stabilität hilft SiliconFlow Entwicklern und Teams, KI-Anwendungen effizienter zu erstellen und zu skalieren. Registrieren Sie sich über <a href="https://cloud.siliconflow.cn/i/drGuwc9k">diesen Link</a> und schließen Sie die Identitätsverifizierung ab, um ein Bonusguthaben von ¥16 zu erhalten, das für alle Modelle der Plattform nutzbar ist. SiliconFlow ist zudem nun mit OpenClaw kompatibel, sodass Nutzer einen SiliconFlow-API-Schlüssel verbinden und große KI-Modelle kostenlos aufrufen können.</td>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Danke an SiliconFlow für die Unterstützung dieses Projekts! SiliconFlow ist eine leistungsstarke KI-Infrastruktur- und Modell-API-Plattform, die schnellen und zuverlässigen Zugriff auf Sprach-, Audio-, Bild- und Videomodelle an einem Ort bietet. Mit nutzungsbasierter Abrechnung, breiter Unterstützung multimodaler Modelle, Hochgeschwindigkeitsinferenz und unternehmensgerechter Stabilität hilft SiliconFlow Entwicklern und Teams, KI-Anwendungen effizienter zu erstellen und zu skalieren. Registrieren Sie sich über <a href="https://cloud.siliconflow.cn/i/YflgU2Ve">diesen Link</a> und schließen Sie die Identitätsverifizierung ab, um ein Bonusguthaben von ¥16 zu erhalten, das für alle Modelle der Plattform nutzbar ist. SiliconFlow ist zudem nun mit OpenClaw kompatibel, sodass Nutzer einen SiliconFlow-API-Schlüssel verbinden und große KI-Modelle kostenlos aufrufen können.</td>
</tr>
<tr>
@@ -115,6 +124,11 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
<td>Dieses Projekt wird von <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> gesponsert. Direkter Claude-API-Zugriff — verbinden Sie Claude Code und Agent-Apps in 3 Minuten. Neukunden können ein kostenloses Testguthaben einlösen. Betrieben mit offiziellen Anthropic-API-Schlüsseln + offiziellen AWS-Bedrock-Kanälen. Kein Reverse Engineering, keine Modellverschlechterung. Volle Unterstützung der Modellreihe Opus / Sonnet / Haiku, mit erhaltenen offiziellen Fähigkeiten einschließlich Tool Use, 1M-Kontextfenster und mehr. Entwickelt für Claude-Code-Power-User, Agent-Ingenieure und technische Unternehmensteams. Rechnungsstellung und dedizierter Team-Support verfügbar. Klicken Sie <a href="https://console.claudeapi.com/register?aff=pCLD">hier</a>, um sich zu registrieren!</td>
</tr>
<tr>
<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>
<td width="180"><a href="https://claudecn.top"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>Danke an ClaudeCN für die Unterstützung dieses Projekts! ClaudeCN ist eine unternehmensgerechte KI-Gateway-Plattform, die von einem eingetragenen Unternehmen betrieben wird. Sie bietet hochverfügbaren kommerziellen API-Zugriff auf beliebte Modelle wie Claude, GPT und DeepSeek und ist auf formelle Unternehmensbeschaffungsprozesse ausgerichtet — Banküberweisungen von Firmen, unterzeichnete Verträge und volle Compliance. Registrieren Sie sich über <a href="https://claudecn.top">diesen Link</a>!</td>
@@ -150,6 +164,26 @@ Registrieren Sie sich jetzt über <a href="https://pateway.ai/?ch=etzpm8&aff=WB6
<td>Danke an Unity2.ai für die Unterstützung dieses Projekts! Unity2.ai ist eine leistungsstarke AI-Modell-API-Relay-Plattform für Einzelentwickler, Teams und Unternehmen. Sie wird seit Langem von führenden Unternehmen in China genutzt, verarbeitet täglich über 30 Milliarden Tokens und unterstützt hohe Parallelität auf 5.000-RPM-Niveau. Geboten werden Guthaben-Abrechnung, Ersteinzahlungsbonus, Kombi-Abonnements, Firmenrechnungen und persönliche Betreuung. Registrieren Sie sich über <a href="https://unity2.ai/register?source=ccs">diesen Link</a> und erhalten Sie $2 Guthaben, plus weitere $10 für den Beitritt zur offiziellen Gruppe — bis zu $12 Gratis-Guthaben!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Danke an Fenno.ai für die Unterstützung dieses Projekts! Fenno.ai ist ein stabiler und effizienter API-Relay-Dienstleister, der sich derzeit hauptsächlich auf Codex-Relay konzentriert. Er ist mit den OpenAI- und Anthropic-Protokollen kompatibel und lässt sich flexibel mit Codex, Claude Code, OpenCode und anderen gängigen Coding-Tools nutzen. Er unterstützt zuverlässig Workloads auf Unternehmensniveau von Hunderten Milliarden Tokens pro Tag und bietet B2B-Abrechnung sowie Rechnungsstellung für Unternehmen im In- und Ausland. Fenno.ai bietet einen exklusiven Vorteil für CC-Switch-Nutzer: Abonnieren Sie über <a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">diesen Link</a> den unschlagbaren ¥9,9-Coding-Plan im Wert von $150 Guthaben und erhalten Sie bis zu 20% Empfehlungsprämien — je mehr Einladungen, desto mehr Belohnung!</td>
</tr>
<tr>
<td width="180"><a href="https://zetaapi.ai/go/ccs"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>Danke an ZetaAPI für die Unterstützung dieses Projekts! ZetaAPI legt den Fokus auf echte Modelltreue — keine verwässerten Antworten, keine Qualitätsminderung — und Preise von nur 35 % der offiziellen Tarife. Die Plattform mischt keinen Traffic, ersetzt Modelle nicht heimlich durch minderwertige Alternativen und nutzt kein gefälschtes Modell-Routing. Sie unterstützt Claude Code, Codex, Gemini, ChatGPT und weitere gängige KI-Modelle und hilft Nutzern, die API-Kosten deutlich zu senken und gleichzeitig eine zuverlässige Modellqualität zu gewährleisten. Gleichzeitig bietet ZetaAPI eine SLA-gestützte Stabilität auf Unternehmensniveau, Standard-API-Kompatibilität, einen API-Key für mehrere Modelle, schnelle Integration und nutzungsbasierte Abrechnung — geeignet für KI-Produkte, Coding-Agents, interne Unternehmenstools, Kundenservice-Systeme, Content-Erstellung und Automatisierungs-Workflows. Falls bei einem Modell nachgewiesen wird, dass es nicht der angegebenen Qualität entspricht, sichert ZetaAPI dies mit einer 10-fachen Entschädigungsgarantie ab und bietet Nutzern ein stabileres, transparenteres und vertrauenswürdigeres Erlebnis. Registrieren Sie sich über <a href="https://zetaapi.ai/go/ccs">diesen Link</a> und verwenden Sie bei Ihrer ersten Aufladung den Promo-Code CC-SWITCH, um als CC-Switch-Nutzer einen exklusiven Rabatt von 10 % auf Ihre erste Aufladung zu erhalten!</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<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>
@@ -265,6 +299,19 @@ Fügen Sie einen offiziellen Anbieter aus der Preset-Liste hinzu. Führen Sie na
</details>
<details>
<summary><strong>Linux (Wayland + NVIDIA): Klicks im Webinhalt reagieren nicht, schwarzer Bildschirm beim Größenändern</strong></summary>
Das AppImage erzwingt `GDK_BACKEND=x11` (XWayland), um einen historischen nativen Wayland-Absturz zu vermeiden. Auf neueren Wayland-+-NVIDIA-Systemen kann das dazu führen, dass der Webinhalt nicht anklickbar ist (die Titelleisten-Schaltflächen funktionieren weiterhin) und das Fenster beim Größenändern schwarz wird. Starten Sie mit dem optionalen Notausgang, um zu nativem Wayland zu wechseln:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
Wenn Sie über ein Desktop-Symbol starten, fügen Sie es der `Exec=`-Zeile der `.desktop`-Datei hinzu (z. B. `env CC_SWITCH_GDK_BACKEND=wayland /pfad/zum/AppImage`) oder setzen Sie es in Ihrer Sitzungsumgebung. Die Variable ist generisch: Auf Tiling-Wayland-Compositors (sway/Hyprland), bei denen Klicks nicht reagieren, versuchen Sie umgekehrt `CC_SWITCH_GDK_BACKEND=x11`. Bleibt sie ungesetzt, bleibt das Standardverhalten erhalten.
</details>
## Dokumentation
Ausführliche Anleitungen zu jeder Funktion finden Sie im **[Benutzerhandbuch](docs/user-manual/en/README.md)** — es deckt Anbieterverwaltung, MCP/Prompts/Skills, Proxy & Failover und mehr ab.
+52 -5
View File
@@ -25,9 +25,11 @@
<details open>
<summary>クリックで折りたたむ</summary>
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.moonshot.cn/console?aff=cc-switch)
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-en.png)](https://platform.kimi.ai?aff=cc-switch)
Kimi K2.7 Code は Moonshot AI が開発した、コーディングに特化したオープンソースのエージェントモデルです。コーディング能力とエージェント性能が全面的に強化され、実世界の長程コーディングタスクで大幅な向上を実現し、複雑なソフトウェアエンジニアリングのワークフロー全体でエンドツーエンドのタスク成功率を高めます。さらに K2.7 Code は推論効率を改善し、K2.6 と比べて推論トークンの消費を約 30% 削減します。**[ここをクリックして Kimi を体験する](https://platform.moonshot.cn/console?aff=cc-switch)**
Kimi K2.7 Code は Moonshot AI が開発した、コーディングに特化したオープンソースのエージェントモデルです。コーディング能力とエージェント性能が全面的に強化され、実世界の長程コーディングタスクで大幅な向上を実現し、複雑なソフトウェアエンジニアリングのワークフロー全体でエンドツーエンドのタスク成功率を高めます。さらに K2.7 Code は推論効率を改善し、K2.6 と比べて推論トークンの消費を約 30% 削減します。**[ここをクリックして Kimi を体験する](https://platform.kimi.ai?aff=cc-switch)**
コーディング作業がメインですか?コーディングのために作られたサブスクリプション、**[Kimi For Coding プラン](https://www.kimi.com/code/?aff=cc-switch)** をぜひお試しください!
---
@@ -60,14 +62,21 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
現在、<a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">このリンク</a>からご登録いただくと $3 のトライアルクレジットを進呈。チャージは最安で元価格の 60%、友達紹介は双方にボーナスが付与され、紹介報酬は最大 $150!</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>このプロジェクトをご支援いただいている TeamoRouter に感謝します!TeamoRouter は、開発者、AI チーム、企業向けに構築されたエンタープライズグレードの Agentic LLM ゲートウェイです。サブスクリプション不要で、単一の統合 API を通じて Claude Code、Codex、Gemini CLI、OpenAI Codex、その他の人気 AI エージェントにアクセスでき、API 料金は最大 90% オフで利用できます。
一般的な API リレーサービスとは異なり、TeamoRouter は OpenAI、Anthropic、Vertex、Azure、AWS Bedrock など、数百の公式モデルプロバイダーと信頼できるインフラパートナーを集約しています。各プロバイダーは、Agent プロトコルとの 100% 互換性、キャッシュ性能、リクエストの追跡可能性について検証されており、リバースエンジニアリングされたものや品質が薄められたエンドポイントではなく、安定した品質を提供します。プラットフォームは公式に近い TTFT、99.6% の SLA、最大 5,000 QPM のエンタープライズ規模のスループット、そして業界トップクラスのキャッシュヒット率を提供し、長時間稼働するエージェントワークフローのトークンコストを大幅に削減します。
TeamoRouter は、集中請求、チーム管理、BYOK、スマートルーティング、利用状況分析、動的なプロバイダー最適化、専任サポートなどのエンタープライズ機能も提供しています。さらにシンプルな体験を求める場合は、Teamo Desktop を使うことで、Claude Code、Codex、Gemini CLI、その他の人気 AI エージェントをワンクリックで利用できます。API キー管理や手動のゲートウェイ設定は不要です。新規ユーザーとして<a href="https://teamorouter.com/?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">こちらのリンク</a>から登録すると、初回チャージが 10% オフになります。</td>
</tr>
<tr>
<td width="180"><a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/byteplus.png" alt="BytePlus" width="150"></a></td>
<td>Dola seed のご支援に感謝します!Dola Seed 2.0 は ByteDance がグローバル市場向けに独自開発したフルモーダル汎用大規模モデルです。統一されたマルチモーダルアーキテクチャを基盤に、テキスト・画像・音声・動画の統合的な理解と生成をサポートします。エージェント連携をネイティブに実現し、強力な推論、長時間タスクの実行、ツール統合、コーディング能力を備えています。スマートコックピット、パーソナルアシスタント、教育、カスタマーサポート、マーケティング、リテールなど幅広いシナリオに適用可能で、マルチモーダル認識、エンドツーエンドの複雑なタスク遂行、安定したインタラクション、データセキュリティに優れ、ModelArk プラットフォームを通じて手軽に利用・デプロイできます。<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">このリンク</a>からご登録いただくと、モデルごとに 500,000 トークンの無料推論クォータを進呈します。<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"> >>中国大陆地区的开发者请点击这里</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/YflgU2Ve">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
</tr>
<tr>
@@ -115,6 +124,11 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td>本プロジェクトは <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> がスポンサーです。Claude API 直結 — わずか 3 分で Claude Code や Agent アプリに接続可能。新規ユーザーにはテストクレジットを提供しています。Anthropic 公式キーおよび AWS Bedrock 公式チャネルに基づいており、リバースエンジニアリングや性能劣化はありません。Opus / Sonnet / Haiku の全モデルラインナップをサポートし、Tool Use や 1M コンテキストなどの公式機能をすべて保持しています。Claude Code ヘビーユーザー、Agent エンジニア、企業技術チームに最適です。請求書発行およびチーム対応が可能です。<a href="https://console.claudeapi.com/register?aff=pCLD">こちら</a>から登録してください!</td>
</tr>
<tr>
<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>
<td width="180"><a href="https://claudecn.top"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>本プロジェクトのスポンサーである ClaudeCN に感謝いたします!ClaudeCN は、実体のある企業によって運営されるエンタープライズ向け AI ゲートウェイプラットフォームです。Claude、GPT、DeepSeek など主要モデルへの高可用な商用 API アクセスを提供し、企業の調達プロセスにも対応 — 法人振込や正式契約に対応し、コンプライアンス面でも安心してご利用いただけます。<a href="https://claudecn.top">こちら</a>からご登録ください!</td>
@@ -150,6 +164,26 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td>Unity2.ai のご支援に感謝します!Unity2.ai は個人開発者・チーム・企業向けの高性能 AI モデル API リレープラットフォームです。中国の大手企業に長年利用されており、1 日 300 億トークン以上を処理し、5000 RPM クラスの高並列に対応しています。残高課金、初回チャージボーナス、組み合わせサブスクリプション、企業向け請求書発行、専任サポートを提供。<a href="https://unity2.ai/register?source=ccs">こちらのリンク</a>から登録すると $2 のクレジット、公式グループへの参加でさらに $10、最大 $12 の無料クレジットがもらえます!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>Fenno.ai のご支援に感謝します!Fenno.ai は安定かつ高効率な API 中継サービスプロバイダーで、現在は主に Codex の中継を提供しています。OpenAI および Anthropic プロトコルに対応し、Codex・Claude Code・OpenCode などの主要なコーディングツールから柔軟に利用できます。1 日あたり数千億トークンというエンタープライズ級の呼び出し需要を安定して支え、国内外の法人による B2B 決済・請求書発行に対応しています。Fenno.ai は CC Switch 利用者限定の特典を用意しています:<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">こちらのリンク</a>から 9.9 元(150 ドル相当)のお得な Coding Plan を購入でき、友達紹介で最大 20% の特典がもらえます。紹介すればするほどお得です!</td>
</tr>
<tr>
<td width="180"><a href="https://zetaapi.ai/go/ccs"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>本プロジェクトをご支援いただいている ZetaAPI に感謝します!ZetaAPI は、モデル品質の忠実性、水増しなし、性能劣化なし、公式価格の 35% から利用できる低価格を主な特徴としています。プラットフォームはトラフィックの混在、低品質モデルへの密かな切り替え、虚偽のモデルルーティングを行わず、Claude Code、Codex、Gemini、ChatGPT などの主要 AI モデルに対応しており、モデル品質を維持しながら API 利用コストを大幅に削減できます。同時に、ZetaAPI はエンタープライズ級の SLA 安定性保証、標準 API 互換、1つの Key による複数モデル接続、迅速な導入、従量課金などの機能を提供し、AI プロダクト、コード生成、企業内ツール、カスタマーサポート、コンテンツ生成、自動化ワークフローなどの用途に適しています。万が一、モデル品質が表記内容と一致しないことが確認された場合、ZetaAPI は 10 倍補償保証を提供し、ユーザーがより安定して、透明性高く、安心して利用できる環境を実現します。<a href="https://zetaapi.ai/go/ccs">こちらのリンク</a>から登録し、初回チャージ時にプロモコード CC-SWITCH を使用すると、CC Switch ユーザー限定の初回チャージ 10% オフ特典をご利用いただけます!</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<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>
@@ -229,7 +263,7 @@ CC Switch は **Claude Code**、**Claude Desktop**、**Codex**、**Gemini CLI**
<details>
<summary><strong>プロバイダを切り替えた後、プラグイン設定が消えてしまいました。どうすればよいですか?</strong></summary>
CC Switch には「共有設定スニペット」機能があり、APIキーやエンドポイント以外の共通データをプロバイダ間で引き継ぐことができます。「プロバイダ編集」→「共有設定パネル」→「現在のプロバイダから抽出」をクリックして、すべての共通データを保存してください。新しいプロバイダを作成する際に「共有設定を書き込む」にチェック(デフォルトで有効)を入れれば、プラグインなどのデータが新しいプロバイダ設定に含まれます。すべての設定項目は、アプリ初回起動時にインポートされたデフォルトプロバイダに保存されており、失われることはありません。
CC Switch には「共有設定スニペット」機能があり、APIキーやエンドポイント以外の共通データをプロバイダ間で引き継ぐことができます。「プロバイダ編集」→「共有設定パネル」→「現在のプロバイダから抽出」をクリックして、すべての共通データを保存してください。新しいプロバイダを作成する際に「共有設定を適用」にチェック(デフォルトで有効)を入れれば、プラグインなどのデータが新しいプロバイダ設定に含まれます。すべての設定項目は、アプリ初回起動時にインポートされたデフォルトプロバイダに保存されており、失われることはありません。
</details>
@@ -265,6 +299,19 @@ CC Switch は「最小限の介入」という設計原則に従っています
</details>
<details>
<summary><strong>LinuxWayland + NVIDIA):Web コンテンツがクリックできない・リサイズで黒画面になる</strong></summary>
AppImage は過去のネイティブ Wayland クラッシュを避けるため `GDK_BACKEND=x11`(XWayland)を強制します。新しい Wayland + NVIDIA 環境ではこれが原因で Web コンテンツ領域がクリックできなくなり(タイトルバーのボタンは動作します)、リサイズ時に黒画面になることがあります。内蔵のエスケープハッチでネイティブ Wayland に戻せます:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
デスクトップアイコンから起動する場合は、`.desktop``Exec=` 行に追記するか(例:`env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`)、セッション環境で設定してください。この変数は汎用です:タイル型 Wayland コンポジタ(sway/Hyprland)でクリックが効かない場合は、逆に `CC_SWITCH_GDK_BACKEND=x11` を試してください。未設定の場合は既定の動作のままです。
</details>
## ドキュメント
各機能の詳しい使い方については、**[ユーザーマニュアル](docs/user-manual/ja/README.md)** をご覧ください。プロバイダ管理、MCP/Prompts/Skills、プロキシとフェイルオーバーなど、すべての機能を網羅しています。
+52 -5
View File
@@ -25,9 +25,11 @@
<details open>
<summary>点击折叠</summary>
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-zh.png)](https://platform.moonshot.cn/console?aff=cc-switch)
[![Kimi K2.7 Code](assets/partners/banners/kimi-banner-zh.png)](https://platform.kimi.com?aff=cc-switch)
Kimi K2.7 Code 是 Moonshot AI 开发的编程专用开源智能体模型。它在编程与智能体执行能力上全面增强,在真实长程编程任务中实现显著提升,带来复杂软件工程工作流中更高的端到端任务成功率。同时,K2.7 Code 优化了推理效率,相较 K2.6 平均减少约 30% 的推理 token 消耗。**[点击此处开启 Kimi 使用体验](https://platform.moonshot.cn/console?aff=cc-switch)**
Kimi K2.7 Code 是 Moonshot AI 开发的编程专用开源智能体模型。它在编程与智能体执行能力上全面增强,在真实长程编程任务中实现显著提升,带来复杂软件工程工作流中更高的端到端任务成功率。同时,K2.7 Code 优化了推理效率,相较 K2.6 平均减少约 30% 的推理 token 消耗。**[点击此处开启 Kimi 使用体验](https://platform.kimi.com?aff=cc-switch)**
主要做编程工作?可以试试 **[Kimi For Coding 编程套餐](https://www.kimi.com/code/?aff=cc-switch)**,专为编程打造的订阅服务!
---
@@ -60,14 +62,21 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
现在通过<a href="https://pateway.ai/?ch=etzpm8&aff=WB6M6F67#/">此链接</a>注册即送 $3 试用额度,用户充值低至 6 折,邀请好友双向赠送,邀请奖励可达 $150!</td>
</tr>
<tr>
<td width="180"><a href="https://teamorouter.com/zh?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory"><img src="assets/partners/logos/TeamoRouter-banner.png" alt="TeamoRouter" width="150"></a></td>
<td>感谢 TeamoRouter 赞助本项目!TeamoRouter 是一款面向开发者、AI 团队和企业的企业级 Agentic LLM 网关。无需任何订阅,你就可以通过一个统一 API 访问 Claude Code、Codex、Gemini CLI、OpenAI Codex 以及其他热门 AI Agent,同时享受最高可达 90% 折扣的 API 价格。
不同于常见的 API 中转服务,TeamoRouter 聚合了数百家官方模型提供商和可信基础设施合作伙伴,包括 OpenAI、Anthropic、Vertex、Azure 和 AWS Bedrock。每个提供商都经过验证,确保 100% 兼容 Agent 协议,并具备可靠的缓存性能和请求可追踪性,从而提供稳定质量,而不是反向工程或缩水后的接口。平台提供接近官方水平的 TTFT、99.6% SLA、最高 5,000 QPM 的企业级吞吐量,以及行业领先的缓存命中率,可大幅降低长时间运行的 Agent 工作流中的 token 成本。
TeamoRouter 还提供企业级功能,包括集中账单、团队管理、BYOK、智能路由、用量分析、动态提供商优化和专属支持。为了获得更简单的使用体验,Teamo Desktop 支持你一键使用 Claude Code、Codex、Gemini CLI 和其他热门 AI Agent,无需管理 API Key,也无需手动配置网关。新用户通过<a href="https://teamorouter.com/zh?utm_source=cc_switch&utm_medium=referral&utm_campaign=ai_directory">此链接</a>注册,首次充值可享受 10% 折扣。</td>
</tr>
<tr>
<td width="180"><a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch"><img src="assets/partners/logos/huoshan.png" alt="HuoShan" width="150"></a></td>
<td>感谢火山方舟 Agent Plan 模型赞助了本项目!方舟 Agent Plan 模型订阅套餐集成了包含 Doubao-Seed、Doubao-Seedance、Doubao-Seedream 等在内的字节跳动自研 SOTA 级模型,覆盖文本、代码、图像、视频等多模态任务。最新支持 MiniMax-M3、DeepSeek-V4 系列、GLM-5.1、Doubao-Seed-2.0 系列、Kimi-K2.6 等模型,工具不限。超全模态模型与 Harness 升级一步到位,深度支持 Agent 框架与 AI 编程工具。一次订阅,可以为不同任务切换合适的 AI 引擎。方舟 Coding Plan 为 CC Switch 的用户提供了专属福利:通过<a href="https://www.volcengine.com/activity/ai618?utm_campaign=hw&utm_content=hw&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">此链接</a>订阅方舟 Coding Plan,新客户首两个月享 2.5 折优惠,再用专属邀请码 6J6FV5N2 领取奖励叠加 9.5 折,低至 9.4 元/月!<a href="https://www.byteplus.com/en/product/modelark?utm_campaign=hw&utm_content=ccswitch&utm_medium=devrel_tool_web&utm_source=OWO&utm_term=ccswitch">>>For developers outside Mainland China, please click here</a></td>
</tr>
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
<td width="180"><a href="https://cloud.siliconflow.cn/i/YflgU2Ve"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/YflgU2Ve">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
</tr>
<tr>
@@ -116,6 +125,11 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>本项目由 <a href="https://console.claudeapi.com/register?aff=pCLD">Claude API</a> 赞助。Claude API 直连,三分钟接入 Claude Code 与 Agent 应用 新用户可领取测试额度。基于 Anthropic 官方 Key + AWS Bedrock 官方渠道,非逆向、非降智,支持 Opus / Sonnet / Haiku 全系列模型,保留 Tool Use、1M 上下文等官方能力。适合 Claude Code 深度用户、Agent 工程师与企业技术团队,支持开票和团队对接。点击<a href="https://console.claudeapi.com/register?aff=pCLD">这里</a>注册!</td>
</tr>
<tr>
<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>
<td width="180"><a href="https://claudecn.top"><img src="assets/partners/logos/claudecn.jpg" alt="ClaudeCN" width="150"></a></td>
<td>感谢 ClaudeCN 赞助本项目!ClaudeCN 由是一家实体企业运营的企业级AI中转平台。平台可提供高可用性的商用API服务,提供Claude、GPT、Deepseek等热门模型,支持企业采购流程,可对公打款、签约,服务合规有保障。点击<a href="https://claudecn.top">此链接</a>注册!</td>
@@ -151,6 +165,26 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>感谢 Unity2.ai 赞助了本项目!Unity2.ai 是面向个人开发者、团队和企业的高性能 AI 模型 API 中转平台,长期服务国内头部企业,日均承载超 300 亿 token 调用,支持 5000 RPM 级高并发。支持余额计费、首充赠额、组合订阅、企业开票和专属对接。通过<a href="https://unity2.ai/register?source=ccs">此链接</a>注册可领取 $2 余额,加入官方群再送 $10 余额,最高可领 $12 免费额度!</td>
</tr>
<tr>
<td width="180"><a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL"><img src="assets/partners/logos/fenno-banner.png" alt="Fenno.ai" width="150"></a></td>
<td>感谢 Fenno.ai 赞助了本项目!Fenno.ai 是一家稳定、高效的 API 中转服务商,目前主要提供 Codex 中转服务,兼容 OpenAI 及 Anthropic 协议,可灵活接入 Codex、Claude Code、OpenCode 等主流编程工具,可稳定支撑千亿 Token/日的企业级调用需求,支持国内及海外主体公对公结算、开票。Fenno.ai 为 CC Switch 的用户提供了专属福利:通过<a href="https://api.fenno.ai/register?redirect=/purchase?tab=subscription%26group=16&aff=P9MR3D3PLCNL">此链接</a>即可订阅 9.9 元/150 刀额度的超值 Coding Plan,邀请好友最高可享 20% 奖励,多邀多得!</td>
</tr>
<tr>
<td width="180"><a href="https://zetaapi.ai/go/ccs"><img src="assets/partners/logos/zetaapi-banner.png" alt="ZetaAPI" width="150"></a></td>
<td>感谢 ZetaAPI 赞助本项目!ZetaAPI 主打模型不掺水、保真不降智、价格低至官方价 35 折,平台不混量、不暗中替换低质量模型、不做虚假路由,支持 Claude Code、Codex、Gemini、ChatGPT 等主流模型接入,帮助用户在保证模型质量的同时大幅降低 API 使用成本。同时,ZetaAPI 提供企业级 SLA 稳定性保障、标准接口兼容、一个 Key 接入多模型、快速集成、按量计费等能力,适用于 AI 产品、代码生成、企业内部工具、客服系统、内容生产和自动化流程等场景。若经验证发现模型质量与标称不符,ZetaAPI 承诺假一赔十,让用户用得更稳定、更透明、更放心。通过<a href="https://zetaapi.ai/go/ccs">此链接</a>注册,并在首次充值时使用优惠码 CC-SWITCH,即可享受 CC Switch 用户专属的首次充值九折优惠!</td>
</tr>
<tr>
<td width="180"><a href="https://nekocode.ai?aff=CCSWITCH"><img src="assets/partners/logos/nekocode-banner.png" alt="NekoCode" width="150"></a></td>
<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>
@@ -230,7 +264,7 @@ CC Switch 支持七个工具:**Claude Code**、**Claude Desktop**、**Codex**
<details>
<summary><strong>切换供应商之后我的插件配置怎么不见了?</strong></summary>
CC Switch 使用“通用配置片段”功能,在不同的供应商之间传递 Key 和请求地址之外的通用数据,您可以在“编辑供应商”菜单的“通用配置面板”里,点击“从当前供应商提取”,把所有的通用数据提取到通用配置中,之后在新建“供应商”的时候,只要勾选“写入通用配置”(默认勾选),就会把插件等数据写入到新的供应商配置中。您的所有配置项都会保存在运行本软件的时候,第一次导入的默认供应商里面,不会丢失。
CC Switch 使用“通用配置片段”功能,在不同的供应商之间传递 Key 和请求地址之外的通用数据,您可以在“编辑供应商”菜单的“通用配置面板”里,点击“从当前供应商提取”,把所有的通用数据提取到通用配置中,之后在新建“供应商”的时候,只要勾选“应用通用配置”(默认勾选),就会把插件等数据写入到新的供应商配置中。您的所有配置项都会保存在运行本软件的时候,第一次导入的默认供应商里面,不会丢失。
</details>
@@ -268,6 +302,19 @@ CC Switch macOS 版本已通过 Apple 代码签名和公证,可直接下载安
</details>
<details>
<summary><strong>LinuxWayland + NVIDIA):网页内容点不动、缩放后黑屏</strong></summary>
AppImage 会强制 `GDK_BACKEND=x11`(走 XWayland)以规避历史上的原生 Wayland 崩溃。但在较新的 Wayland + NVIDIA 环境下,这会导致网页内容区点不动(标题栏按钮仍可点)、窗口缩放后黑屏。可用内置的逃生开关切回原生 Wayland:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
如果你是从桌面图标启动的,请把它写进 `.desktop``Exec=` 行(如 `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`),或在会话环境中设置。该变量是通用的:在 tiling Wayland 合成器(sway/Hyprland)下若出现点击失效,可反过来设 `CC_SWITCH_GDK_BACKEND=x11`。不设置则保持默认行为。
</details>
## 文档
如需了解各项功能的详细使用方法,请查阅 **[用户手册](docs/user-manual/zh/README.md)** — 涵盖供应商管理、MCP/Prompts/Skills、代理与故障转移等全部功能。
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 424 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+112
View File
@@ -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.
![Needs routing marker in the Codex provider list](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
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.
![Upstream format in the Kimi Codex provider form](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
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.
![Enabling Codex routing on the local routing page](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
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)
+112
View File
@@ -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 形式へ戻します。
![Codex プロバイダー一覧のローカルルーティング必須マーク](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
この経路は主に 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 Codex プロバイダーフォームの上流フォーマット設定](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
プリセットには 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 はオフのままで構いません。
![ローカルルーティング画面で Codex ルーティングを有効化](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
ルーティングを有効にすると、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)
+112
View File
@@ -0,0 +1,112 @@
# 在 Codex 中用 KimiCC 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。
![Codex 供应商列表里的需要路由标记](../images/codex-kimi-routing/01-codex-providers-require-routing.png)
这条链路主要分成四步:
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 Codex 供应商表单中的上游格式设置](../images/codex-kimi-routing/02-kimi-codex-routing-form.png)
预设已经内置 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 关闭。
![本地路由页面中启用 Codex 接管](../images/codex-kimi-routing/03-local-route-codex-takeover.png)
接管后,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

+3
View File
@@ -1,5 +1,8 @@
# CC Switch v3.16.4
> 🎉 **CC Switch is now in the global top 100 on GitHub by stars!**
> Thank you to every user, contributor, and Star — you brought it here. 🙏
> After v3.16.3 made usage billing accurate, this release shifts the focus to polishing the Codex proxy chain and enriching the usage / pricing tooling — migrating Chinese providers to native Responses, decoupling the upstream-format selector from model mapping, decompressing zstd request / error bodies, and a batch of tool-call and OAuth-through-proxy fixes — while also adding local proxy request overrides, an in-app recovery screen when the database version is too new, native Windows ARM64 builds, and a wave of preset and branding updates (SubRouter, OpenCode Go, the CTok→ETok rename, the Kimi brand refresh, and a prime-partner badge).
**[中文版 →](v3.16.4-zh.md) | [日本語版 →](v3.16.4-ja.md)**
+3
View File
@@ -1,5 +1,8 @@
# CC Switch v3.16.4
> 🎉 **CC Switch が GitHub の全世界 Star ランキングでトップ 100 入り!**
> ここまで支えてくださったすべてのユーザー、コントリビューター、そして Star に感謝します。🙏
> v3.16.3 で「使用量の課金を正確にする」ことに取り組んだのに続き、本リリースは Codex プロキシ経路の磨き込みと、使用量 / 価格ツールの拡充に重きを置いています——国産プロバイダーのネイティブ Responses への移行、上流の形式セレクタとモデルマッピングの分離、zstd リクエスト / エラーボディの展開、そしてツール呼び出しと OAuth がプロキシを経由するようにする一連の修正です。あわせて、ローカルプロキシのリクエストオーバーライド、データベースのバージョンが新しすぎる場合のアプリ内リカバリ画面、ネイティブ Windows ARM64 ビルドを新設し、一連のプリセットとブランドの更新(SubRouter、OpenCode Go、CTok→ETok の改名、Kimi のブランド刷新と prime-partner バッジ)を届けます。
**[English →](v3.16.4-en.md) | [中文版 →](v3.16.4-zh.md)**
+3
View File
@@ -1,5 +1,8 @@
# CC Switch v3.16.4
> 🎉 **CC Switch 跻身 GitHub 全球 Star 排行榜前 100**
> 感谢每一位用户、贡献者与 Star —— 是你们让它走到这里。🙏
> 继 v3.16.3 把「用量计费做准」之后,这一版把重心放在打磨 Codex 代理链路与丰富用量 / 定价工具上——国产供应商原生 Responses 迁移、上游格式选择器与模型映射解耦、zstd 请求 / 错误体解压,以及一批工具调用与 OAuth 走代理的修复;同时新增本地代理请求覆盖、数据库版本过新时的应用内恢复屏、原生 Windows ARM64 构建,并带来一波预设与品牌更新(SubRouter、OpenCode Go、CTok→ETok 改名、Kimi 品牌刷新与 prime-partner 徽标)。
**[English →](v3.16.4-en.md) | [日本語版 →](v3.16.4-ja.md)**
+278
View File
@@ -0,0 +1,278 @@
# CC Switch v3.16.5
> The centerpiece of this release is **getting native-Responses direct-connect properly adapted for domestic (Chinese) model providers** — generating Codex model catalogs for providers with native Responses endpoints (Xiaomi MiMo, Volcengine Doubao, Qwen3-Coder, Meituan LongCat, MiniMax) so the Codex desktop app can actually see these models and their built-in tools work, and automatically disabling `web_search` for the few domestic gateways that reject it so requests are no longer hard-rejected. Two other important improvements: when you switch providers, the plugins, environment variables, etc. you added inside the app are **automatically written back to the common config and carried over to the next provider**; and Linux (Wayland + NVIDIA) users hitting the "title bar clicks, page is dead, black screen on resize" problem now have an environment-variable escape hatch. This release also brings Claude Sonnet 5 pricing and a default-tier bump, a two-level grouped session view, and a batch of credential-safety and platform-compatibility fixes.
**[中文版 →](v3.16.5-zh.md) | [日本語版 →](v3.16.5-ja.md)**
---
## Usage Guides
The new capabilities in this release land mainly in the Codex provider form, the session panel, and usage / common config. The following docs are worth reading alongside it:
- **[Can't see custom models in the Codex desktop app?](../guides/codex-desktop-custom-model-visibility-en.md)**: this release reworks **model-catalog generation for native direct-connect** — when a Codex provider connects directly via native Responses (`openai_responses`), CC Switch generates `~/.codex/cc-switch-model-catalog.json` so the Codex desktop app can display the configured custom models and their tools work. If you previously configured a native Codex provider, **re-save it once** to regenerate the catalog (see "Upgrade Notes" 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 adds Claude Sonnet 5 pricing and fixes usage-script credentials being persisted as "explicit overrides".
- **[Settings](../user-manual/en/1-getting-started/1.5-settings.md)**: the Codex upstream-format selector and local routing toggle, and Claude's common config (now renamed "Apply Common Config" and auto-synced on switch) all live in the provider form's advanced options.
---
> [!WARNING]
>
> ## Only Official Channels (Please Read)
>
> CC Switch is a **fully free and open-source** desktop app, and we **do not charge users any fees**. Please only obtain the software through the official channels listed below:
>
> | Channel | Only Official |
> | ------------------ | ------------------------------------------------------------------------------ |
> | Website | **[ccswitch.io](https://ccswitch.io)** |
> | Source | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | Downloads | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | Author | **[@farion1231](https://github.com/farion1231)** |
> | Report an Imposter | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **Any "CC Switch" website or client that asks you for payment, top-ups, or login credentials is fake.** If you have been tricked into paying, stop the transaction immediately and file a report through GitHub Issues.
---
## Overview
CC Switch v3.16.5 is a maintenance update following v3.16.4, centered on **making native Codex direct-connect work end-to-end for domestic model providers**. v3.16.4 already switched Qwen / DashScope, Xiaomi MiMo, Volcengine Doubao, Meituan LongCat, and MiniMax to native Responses endpoints; this release goes a step further and generates the **model catalog** Codex needs (`~/.codex/cc-switch-model-catalog.json`), so the Codex desktop app can really see these custom models and invoke their built-in tools, and it fully decouples model mapping from the "local routing" toggle. For the few domestic gateways whose first-party models don't support OpenAI's built-in `web_search` (MiMo, LongCat, MiniMax, Qwen3-Coder), this release also disables that tool automatically, so Codex's default doesn't trigger a hard 400.
For everyday use, this release makes Claude's **common config auto-sync and carry over when you switch providers** — the plugins, environment variables, theme, etc. you added inside the running app are first written back to the common config and then handed to the next provider, so they're not lost on switch; it adds an escape-hatch environment variable for Linux (Wayland + NVIDIA) users hitting click-dead / black-screen issues; it adds Claude Sonnet 5 pricing and bumps the default Sonnet tier to it; it brings a two-level "provider → project directory" grouped session view; and it fixes a string of credential-safety (the common-config snippet now strips all secrets, usage-script credentials are only kept as explicit overrides), platform-compatibility (Hermes Windows config directory, Windows Codex npm shims), and UI (long dropdown scrolling, narrow-window date-range picker) issues. It also adds several new provider presets, ready to pick out of the box.
**Release date**: 2026-07-01
**Stats**: 36 commits | 93 files changed | +5,678 / -2,804 lines
---
## Highlights
- **Native Codex direct-connect actually works for domestic model providers**: CC Switch generates a Codex model catalog (`~/.codex/cc-switch-model-catalog.json`) for domestic providers like Xiaomi MiMo, Volcengine Doubao, Qwen3-Coder, Meituan LongCat, and MiniMax, so the Codex desktop app can see these models and their built-in tools work; and it auto-disables `web_search` for the domestic gateways that reject it (MiMo, LongCat, MiniMax, Qwen3-Coder) to avoid hard 400s. **Existing native providers need a one-time re-save** to regenerate the catalog.
- **Common config auto-synced and carried over on switch**: when you switch away from a Claude provider that has the common config enabled, the plugins, environment variables, theme, and hooks you added inside the app are first written back to the common config and then handed to the next provider — no longer overwritten and lost on switch.
- **Escape hatch for Linux Wayland click-dead / black-screen**: when you hit "title bar clicks, page doesn't, black screen on resize" on Wayland + NVIDIA, launch with `CC_SWITCH_GDK_BACKEND=wayland` to switch back to native Wayland (set it to `x11` for the inverse problem on tiling compositors).
- **Claude Sonnet 5**: adds Sonnet 5 pricing and bumps each preset's default Sonnet tier to `claude-sonnet-5`.
- **Categorized session view with grouping**: the session panel gains a two-level "provider → project directory" grouped view, with a tri-state checkbox on each group header for one-click batch selection.
- **New provider presets**: adds Qiniu, FennoAI, ZetaAPI, TeamoRouter, NekoCode, Code0.ai, and Amux presets across the managed apps, ready to pick out of the box.
---
## Added
### Native Codex Direct-Connect for Domestic Model Providers (Generated Model Catalog)
This release makes native Codex direct-connect work for domestic providers. After v3.16.4 switched Xiaomi MiMo, Volcengine Doubao, Qwen3-Coder, Meituan LongCat, and MiniMax to native Responses (`apiFormat: "openai_responses"`), this release reverses the then-current "drop the model catalog on native direct-connect" approach: when these providers connect directly without the local proxy, CC Switch generates `~/.codex/cc-switch-model-catalog.json` for them, so the Codex desktop app really shows these custom models and their built-in tools work — without triggering the freeform `apply_patch` (`type=custom`) tool that native gateways like MiMo reject (editing falls back to `shell_command`). Catalog generation is keyed on `apiFormat` and decoupled from the "local routing" toggle, so a native provider persists a catalog without turning on local route mapping, while `openai_chat` keeps the existing Responses↔Chat proxy conversion unchanged. Because Codex's parser requires `base_instructions` on every entry, the native template carries a neutral default that each vendor's official copy overrides (MiMo, MiniMax). **Existing native providers need a one-time re-save to generate a valid catalog** (no database migration).
Alongside that, for the few domestic gateways whose first-party models don't support OpenAI's built-in `web_search` tool (MiMo, LongCat, MiniMax, Qwen3-Coder), this release auto-disables the tool on switch, so Codex's default doesn't include it and get hard-rejected with a 400 (see "Fixed" below).
### Categorized Session View with Grouping
The Session Manager panel gains a grouped view alongside the existing flat list, toggled via a List / ListTree selector in the toolbar, with view mode and expansion state persisted to `localStorage`. Grouping builds a two-level "provider → project directory" hierarchy: sessions are grouped by project directory name, and sessions with no project directory fall into an "unknown directory" bucket. Both levels are collapsible sections, with a "collapse all" button; in batch mode, each group header shows a tri-state checkbox that selects / deselects every selectable session in that group at once, along with a selected / selectable count badge. Copy across all four locales (zh / en / ja / zh-TW) is in sync. The change is entirely front-end, with no backend commands or data-access changes. ([#4776](https://github.com/farion1231/cc-switch/pull/4776))
### Claude Sonnet 5 Model Pricing
Added a `claude-sonnet-5` pricing row in `schema.rs` at Anthropic list pricing — \$3 / \$15 per million input / output tokens and \$0.30 / \$3.75 cache read / write, matching Sonnet 4.6. The introductory \$2 / \$10 promotion (valid through 2026-08-31) is deliberately not seeded, so accounting reflects steady-state list pricing rather than a temporary discount. The row is applied on the app's next start via `ensure_model_pricing_seeded`, with no `SCHEMA_VERSION` bump.
### New Provider Presets
This release adds a batch of provider presets; pick one and fill in your own API key to use it:
- **Qiniu**: covers all seven managed apps (including Gemini), relaying native Claude / GPT / Gemini.
- **FennoAI / ZetaAPI / TeamoRouter / NekoCode**: each covers six apps (Claude, Claude Desktop, Codex, OpenCode, OpenClaw, Hermes).
- **Code0.ai**: covers all seven apps (including Gemini).
- **Amux**: covers six apps.
Each preset's endpoints and default models are configured for the corresponding app — the Claude family connects directly to an Anthropic-compatible host, Codex uses native Responses, and the rest use the OpenAI-compatible `/v1`.
---
## Changed
### Common Config Auto-Synced and Carried Over on Provider Switch
This is a very practical change in this release: when you switch away from a Claude provider that has the common config enabled, the service first **re-extracts the shareable portion from its live `settings.json` and updates the common config**, then hands it to the next provider, instead of only writing one way. As a result, the plugins (`enabledPlugins`), hooks, environment variables (`env`), theme (`theme`), and other shared config you added directly in the running app are not silently lost on switch, but automatically follow along to the next provider; deletions sync too (a removed key is not re-injected). This sync is strictly scoped to Claude providers that have the common config enabled, is skipped when it was explicitly cleared, and all failures are non-fatal (warn only) and never block the switch.
### Codex Model Mapping Decoupled from the "Local Routing" Toggle
The Codex provider form aligns with Claude Code — the model-mapping catalog is now independent of route takeover, because native Responses providers (MiMo, Doubao, MiniMax) need it for proxy-less direct-connect, while Chat providers go through the proxy regardless. The "needs local routing" toggle is removed (it had no backend field and only gated catalog / reasoning persistence, which is equivalent to whether the mapping is filled in). Model mapping is now always shown for non-official providers and persisted whenever it's non-empty, while reasoning visibility / persistence is gated on the Chat format instead. Copy across all four locales (zh / en / ja / zh-TW) was rewritten accordingly. As a side fix, `useCodexConfigState` no longer drops `supportsParallelToolCalls` / `inputModalities` / `baseInstructions` when loading a saved provider (which used to silently lose parallel tools, image input, and the official base instructions on edit).
### Default Sonnet Tier Bumped to Claude Sonnet 5
Bumped the default Sonnet tier in each provider preset from `claude-sonnet-4-6` to `claude-sonnet-5` (across the claude / claude-desktop / hermes / openclaw / opencode presets and the universal `NEWAPI_DEFAULT_MODELS`), covering keys like `ANTHROPIC_MODEL` / `ANTHROPIC_DEFAULT_SONNET_MODEL` / `ANTHROPIC_DEFAULT_OPUS_MODEL` and their prefixed variants. Claude Desktop's default-route sonnet `route_id` also migrates to `claude-sonnet-5`. Non-Anthropic pins (gpt / gemini / glm / sonnet-4-5) are left unchanged.
### Doubao Dated Model Id and Pricing Normalization
The Doubao (DouBaoSeed) preset's model id switches to the dated form `doubao-seed-2-1-pro-260628` (across all apps), because Volcengine Ark rejects the bare `doubao-seed-2-1-pro` with a 404 and only accepts the full dated id. Since real usage now carries a date suffix, `strip_model_date_suffix` was extended to also strip Volcengine's 6-digit YYMMDD form (validating month 01-12 and day 01-31 to avoid eating non-date version suffixes like `-123456`), so it normalizes back to hit the bare-name seed row in the pricing table, fixing the \$0-cost display for Doubao models.
### "Write Common Config" Renamed to "Apply Common Config"
The original label "Write Common Config" was ambiguous about data-flow direction (it read like "write the current config into the common config"), whereas the actual behavior is the reverse — it merges the saved common-config snippet into this provider's config. The checkbox is renamed to "Apply Common Config" across all four locales (zh / en / ja / zh-TW), including every hint / guide / notice reference, with the Japanese user manual and `README_JA.md` synced too. ([#4829](https://github.com/farion1231/cc-switch/pull/4829))
### Other Preset and Asset Adjustments
- **OpenClaw Doubao context aligned to 262144**: OpenClaw's DouBaoSeed preset previously hardcoded 128000 while the Codex side used 262144 for the same model, giving OpenClaw users too small a window; the two are now aligned, with a cross-preset consistency test to prevent drift.
- **Volcengine / Doubao / BytePlus website links corrected**: the "visit website" links on these three presets had been mistakenly set to console / signup links, and are restored to clean product homepages.
- **Downscale oversized provider icons to 256px**: a batch of bundled icons were far larger than their ~32px on-screen render size; downscaling significantly reduces their size with no code / filename / import changes (e.g. ZetaAPI 940KB→40KB, relaxcode 1.16MB→42KB), and the never-referenced 1.4MB `dds.svg` orphan was removed.
---
## Fixed
### Disable web_search for Native Codex Gateways That Reject It
Some native `/responses` gateways whose first-party models lack OpenAI's hosted `web_search` tool reject it with "tool type 'web_search' is not supported", and Codex sends the tool by default, producing a hard 400. CC Switch now writes the top-level TOML line `web_search = "disabled"` for those vendors on switch. The scope is a blacklist (default-on): only providers matched by `base_url` host (`xiaomimimo.com`, `longcat.chat`, `minimax.io`, `minimaxi.com`) or by model brand prefix (`mimo`, `longcat`, `minimax`, `qwen3-coder`) are disabled, so relays serving real GPT, Doubao, general Qwen, and any unknown provider keep Codex's default. The `qwen3-coder` prefix only suppresses native `qwen3-coder-plus` (Bailian / DashScope marks built-in tools unsupported for the coder series), while general Qwen sharing the same host stays enabled; matching is on the model axis (stripping any aggregator `vendor/` path segment), so it also catches cases like SiliconFlow fronting a reject vendor's model. A blacklist was chosen over a fuzzy "is this GPT?" whitelist because wrongly keeping `web_search` on fails with a hard 400; an ownership sentinel ensures CC Switch only ever removes a `disabled` value it wrote itself, so existing providers need no re-save and switching back re-enables it. As a side fix, the LongCat-2.0-Preview preset's context window is corrected from 131072 (128K) to the real 1048576 (1M).
### Strip All Credential-Like Keys from the Shared Claude Common-Config Snippet
`extract_claude_common_config` previously only redacted `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN`, but Claude providers legitimately carry other credentials (`OPENROUTER_API_KEY`, `GOOGLE_API_KEY`, and possibly OpenAI / Gemini / AWS Bedrock / Vertex secrets), which could leak into the shared snippet and then be injected into other providers. Extraction now pattern-matches and strips any credential-shaped env key (`*_API_KEY` / `*_AUTH_TOKEN` / `*secret*` / `*token*`, etc.), while preserving legitimately shareable plural `*_TOKENS` values like `MAX_OUTPUT_TOKENS`. This also closes the same leak on the manual "Extract" and one-time auto-extract paths.
### Usage-Script Credentials Persisted Only as Explicit Overrides
Provider usage scripts store optional `api_key` / `base_url` fields that override the live credentials when querying quota, but they used to silently mirror the provider's own credentials — so copying a provider or editing its main API key / base URL left the usage script pinned to the old endpoint and key, and quota queries kept hitting a stale target. `ProviderService` now normalizes before persisting: if the script's `api_key` or `base_url` matches the provider's resolved usage credentials (or is blank), it is cleared to `None` so queries fall back to the live config; genuinely different overrides are kept (`token_plan` scripts are left alone). The deeplink import path gets matching normalization too, and the front-end invalidates the relevant cache keys on update so the home page re-queries with the corrected config. ([#4654](https://github.com/farion1231/cc-switch/pull/4654))
### Hermes Config Directory Resolves Correctly on Windows
CC Switch hardcoded `~/.hermes` as the Hermes config directory, but Hermes itself resolves it via the `HERMES_HOME` environment variable, then a platform default (`%LOCALAPPDATA%\hermes` on Windows). On Windows this meant CC Switch wrote provider configs to a path Hermes never reads, so provider switches had no effect. `get_hermes_dir()` now mirrors Hermes' own resolution order — explicit override, then `HERMES_HOME` (taken verbatim, no `~` expansion), then the platform default — re-honoring the `HERMES_HOME` that #3470 had dropped (Hermes' Windows installer sets it as the first-class mechanism for relocated installs). ([#4680](https://github.com/farion1231/cc-switch/pull/4680), see #3178, #3470)
### Linux Wayland: Override the AppImage's Forced `GDK_BACKEND=x11`
The AppImage's GTK launch hook unconditionally exports `GDK_BACKEND=x11` to dodge a historical native-Wayland crash. On newer Wayland + NVIDIA setups, this forced XWayland leaves the WebKitGTK web content unable to receive pointer events (the title bar clicks, the page is dead) and black-screens on resize, and the existing `WEBKIT_DISABLE_*` mitigations don't help because the root cause is the forced window backend, not rendering. `main.rs` now reads an optional `CC_SWITCH_GDK_BACKEND` escape hatch before GTK init (the AppImage's launch hook never touches it): leaving it unset keeps current behavior (zero regression). When you hit the problem above, launch with it set to switch back to native Wayland:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
The override is generic — if you're on a tiling Wayland compositor hitting the inverse input problem, set `CC_SWITCH_GDK_BACKEND=x11` instead. ([#4351](https://github.com/farion1231/cc-switch/pull/4351), fixes #4350)
### "Get API Key" Link Now Shows in Claude Desktop, OpenClaw, and Hermes Forms
The "Get API Key" link and partner-promotion block below the API key input was only wired for claude / codex / gemini / opencode. Claude Desktop rendered a bare input that never showed it, and OpenClaw / Hermes were blocked by two gaps (the whitelist only listed those four appIds, and category parsing only recognized those four preset-id patterns). Claude Desktop now uses the shared `ApiKeySection`, and both the whitelist and category parsing were extended to claude-desktop / openclaw / hermes; additionally, the Hermes / OpenClaw forms no longer let an "official" category disable the key input (these apps have no OAuth-only official providers — e.g. Hermes' Nous Research is official but still needs a user-supplied key).
### Deduplicate Windows Codex npm Shims
On Windows, npm installs a tool as three sibling files — `codex.cmd`, `codex.exe`, and an extensionless Unix shim `codex` — and CC Switch previously listed all three as candidates, so the non-executable extensionless shim was probed as a redundant / failing candidate. It now appends the extensionless path only when there's no runnable `.cmd` / `.exe` sibling adjacent, and path resolution prefers the runnable `.cmd` / `.exe`, anchoring version detection and launch to the actually-runnable Windows shim. ([#4782](https://github.com/farion1231/cc-switch/pull/4782))
### Scroll Bounds for Long Select Dropdowns
`SelectContent` previously used `overflow-hidden` with no height cap, so dropdowns with many options (e.g. long model / provider lists) rendered taller than the viewport and clipped their overflow with no way to reach it. It now sets `max-h-[min(24rem,var(--radix-select-content-available-height))]` and `overflow-y-auto`, bounding the content to 24rem or the Radix-computed available height and allowing vertical scrolling. ([#4798](https://github.com/farion1231/cc-switch/pull/4798))
### Date-Range Picker Calendar Stays On-Screen in Narrow Popovers
The custom date-range picker previously switched to its two-column layout (date fields | calendar) based on the **viewport** width (Tailwind's `sm:` 640px breakpoint), but the popover is clamped to `100vw - 2rem` and anchored to its trigger, so its real available width is narrower than the viewport. On narrow windows the two-column layout could activate while the popover only had room for one column, pushing the calendar column off the right edge where it was clipped (the month header and 4 of 7 weekday columns cut off and unreachable). The layout now keys off the popover's own inline size via a CSS container query, so it collapses to one column exactly when the popover itself is narrow, keeping the calendar fully visible at any window width. ([#4860](https://github.com/farion1231/cc-switch/pull/4860))
---
## Documentation
### `CC_SWITCH_GDK_BACKEND` Escape Hatch Documented
Added an FAQ entry for the optional `CC_SWITCH_GDK_BACKEND` environment variable across all four README languages and the zh / en / ja user-manual troubleshooting pages, explaining how Wayland + NVIDIA users can switch back to native Wayland when the web content goes "click-dead + black screen on resize", and how tiling-Wayland users can set it to `x11` for the inverse input problem.
### Overseas Kimi READMEs Point to platform.kimi.ai
The Kimi K2.7 Code partner section in the English, German, and Japanese READMEs now points its banner and inline calls to action at `https://platform.kimi.ai?aff=cc-switch` (keeping the referral tag), and all four READMEs gained a line promoting the Kimi For Coding subscription linked to `https://www.kimi.com/code/?aff=cc-switch`.
---
## Upgrade Notes
### Existing Native Codex Providers Need a One-Time Re-Save
This release reworks model-catalog generation for native Responses direct-connect. If you previously configured a Codex provider using native Responses (`openai_responses`), **re-pick the preset or open the provider and save it once** to generate the new `~/.codex/cc-switch-model-catalog.json` — that's what lets the Codex desktop app show the custom models and makes the tools work. This requires no database migration and does not affect providers on the `openai_chat` format.
### web_search Blacklist Is Default Behavior
For known-to-reject-`web_search` domestic native gateways (Xiaomi MiMo, Meituan LongCat, MiniMax, Qwen3-Coder), this release automatically writes `web_search = "disabled"` on switch. Relays serving real GPT, Doubao, general Qwen, and unknown providers are unaffected and keep Codex's default. The switch is managed by CC Switch with an ownership sentinel, so switching back to a provider not on the blacklist restores it automatically, with no manual intervention.
### Default Sonnet Tier Change
Claude-family providers newly created from a preset now have their default Sonnet tier pointing to `claude-sonnet-5`. Existing configured providers are unaffected and keep their configuration as-is; to switch to Sonnet 5, re-pick the preset and save.
---
## Risk Notice
This release continues the risk notices from previous versions for reverse-proxy-style features.
**Codex OAuth reverse proxy**: using a ChatGPT subscription's Codex OAuth through a reverse proxy may violate OpenAI's terms of service. See the [v3.13.0 release notes](v3.13.0-en.md#-risk-notice) for details.
**Codex third-party provider Chat routing**: when CC Switch local proxy converts and forwards Codex requests to third-party providers, each provider may have different requirements for billing, compliance, and data retention. Read the target provider's terms before use.
**Claude Desktop third-party provider proxy switching**: when CC Switch's built-in proxy gateway forwards Claude Desktop requests to third-party providers, you must also follow the target provider's billing, compliance, and data-retention terms.
By enabling these features, users accept the related risks. CC Switch is not responsible for account restrictions, warnings, or service suspensions caused by using these features.
---
## Thanks
Thanks to the following contributors for the features and fixes in v3.16.5:
- [#4776](https://github.com/farion1231/cc-switch/pull/4776): add the categorized session view and group management, thanks @alkaid616.
- [#4829](https://github.com/farion1231/cc-switch/pull/4829): rename "Write Common Config" to "Apply Common Config", thanks @arichyx.
- [#4654](https://github.com/farion1231/cc-switch/pull/4654): persist usage-script credentials only as explicit overrides, thanks @yyhhyyyyyy.
- [#4680](https://github.com/farion1231/cc-switch/pull/4680): fix Hermes provider config not taking effect on Windows, thanks @thisTom.
- [#4782](https://github.com/farion1231/cc-switch/pull/4782): deduplicate Windows Codex npm shims, thanks @justjavac.
- [#4798](https://github.com/farion1231/cc-switch/pull/4798): fix long dropdown lists not being scrollable, thanks @xwil1.
- [#4351](https://github.com/farion1231/cc-switch/pull/4351): allow overriding the AppImage's forced `GDK_BACKEND=x11` via `CC_SWITCH_GDK_BACKEND`, thanks @BoneLiu.
- [#4860](https://github.com/farion1231/cc-switch/pull/4860): keep the date-range picker calendar on-screen in narrow popovers, thanks @SaladDay.
Thanks also to everyone who reported native Codex direct-connect, common config, credential reuse, and platform compatibility issues after the v3.16.4 release. Many of these patches came directly from real-world reproduction clues.
---
## 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.16.5-Windows.msi` | **Recommended** - MSI installer with auto-update |
| `CC-Switch-v3.16.5-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.16.5-macOS.dmg` | **Recommended** - DMG installer, drag to Applications |
| `CC-Switch-v3.16.5-macOS.zip` | Unzip and drag to Applications, Universal Binary |
| `CC-Switch-v3.16.5-macOS.tar.gz` | For Homebrew install and auto-update |
Homebrew install:
```bash
brew install --cask cc-switch
```
Upgrade:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux assets are available for both **x86_64** and **ARM64** (`aarch64`). Choose the file whose architecture tag matches your machine's `uname -m` output:
- `CC-Switch-v3.16.5-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.5-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` |
+278
View File
@@ -0,0 +1,278 @@
# CC Switch v3.16.5
> 本リリースの目玉は、**ネイティブ Responses 形式の国産モデルプロバイダーをきちんと適合させたこと**です——ネイティブ Responses endpoint を備えるプロバイダー(小米 MiMo、火山 Doubao、Qwen3-Coder、美団 LongCat、MiniMax)向けに Codex モデルカタログを生成し、Codex デスクトップがこれらのモデルを表示でき、内蔵ツールも正しく動くようにしました。また、`web_search` を拒否する一部の国産ゲートウェイに対しては、そのツールを自動で無効化し、リクエストがハード拒否されないようにします。ほかに 2 つの重要な改善があります: プロバイダーを切り替えるとき、アプリ内で追加したプラグインや環境変数などが**自動的に共通設定へ書き戻され、次のプロバイダーへ引き継がれます**。そして LinuxWayland + NVIDIA)で「タイトルバーは押せるのにページが反応しない、リサイズで黒画面」になる問題も、環境変数のスイッチで自力回避できるようになりました。本リリースはさらに Claude Sonnet 5 の価格と既定階層の引き上げ、2 段階グルーピングのセッションビュー、そして一連の認証情報の安全性とプラットフォーム互換性の修正を届けます。
**[English →](v3.16.5-en.md) | [中文版 →](v3.16.5-zh.md)**
---
## 利用ガイド
本リリースの新機能は、主に Codex プロバイダーフォーム、セッションパネル、使用量 / 共通設定に収まっています。以下のドキュメントとあわせてご覧ください:
- **[Codex デスクトップでカスタムモデルが見えない?](../guides/codex-desktop-custom-model-visibility-ja.md)**: 本リリースは**ネイティブ直結時のモデルカタログ生成**を作り直しました——Codex プロバイダーがネイティブ Responses(`openai_responses`)で直結するとき、CC Switch が `~/.codex/cc-switch-model-catalog.json` を生成し、Codex デスクトップが設定済みのカスタムモデルを表示でき、ツールも動くようにします。以前にネイティブ Codex プロバイダーを設定していた場合は、新しいカタログを生成するために**一度保存し直して**ください(下記「アップグレード時の注意」を参照)。
- **[使用量統計](../user-manual/ja/4-proxy/4.4-usage.md)**: 使用量ダッシュボードのデータソースと集計の仕組みを確認できます。本リリースでは Claude Sonnet 5 の価格を追加し、使用量スクリプトの認証情報が「明示的なオーバーライド」として永続化される問題を修正しました。
- **[設定](../user-manual/ja/1-getting-started/1.5-settings.md)**: Codex の上流形式セレクタとローカルルーティングのトグル、Claude の共通設定(「共通設定を適用」に改名され、切り替え時に自動同期)は、いずれもプロバイダーフォームの高度なオプションにあります。
---
> [!WARNING]
>
> ## 唯一の公式チャネル(必ずお読みください)
>
> CC Switch は**完全に無料・オープンソース**のデスクトップアプリで、**ユーザーから料金を徴収することはありません**。本ソフトウェアは下記の公式チャネルからのみ入手してください:
>
> | チャネル | 唯一の公式 |
> | ------------ | ------------------------------------------------------------------------------ |
> | 公式サイト | **[ccswitch.io](https://ccswitch.io)** |
> | ソースコード | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | ダウンロード | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 偽サイト通報 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **料金請求・チャージ・認証情報の提供を求める「CC Switch」サイトやクライアントはすべて偽物です。** 支払いを誘導された場合は直ちに操作を中止し、GitHub Issues からご報告ください。
---
## 概要
CC Switch v3.16.5 は v3.16.4 に続くメンテナンスアップデートで、その中心は**国産モデルプロバイダーの Codex ネイティブ直結をエンドツーエンドで通すこと**です。v3.16.4 ですでに千問 / DashScope 百炼、小米 MiMo、火山 Doubao、美団 LongCat、MiniMax をネイティブ Responses endpoint へ切り替えていましたが、本リリースはさらに Codex が必要とする**モデルカタログ**(`~/.codex/cc-switch-model-catalog.json`)を生成し、Codex デスクトップがこれらのカスタムモデルを本当に表示でき、内蔵ツールも呼び出せるようにし、モデルマッピングを「ローカルルーティング」トグルから完全に分離しました。第一方モデルが OpenAI 内蔵の `web_search` に対応しない一部の国産ゲートウェイ(MiMo、LongCat、MiniMax、Qwen3-Coder)については、本リリースがそのツールを自動で無効化し、Codex の既定でそれが付いてハード 400 を招くことを避けます。
日々の使い勝手の面では、本リリースは Claude の**共通設定をプロバイダー切り替え時に自動で同期・引き継ぐ**ようにしました——アプリ内で直接追加したプラグイン、環境変数、テーマなどが、まず共通設定へ書き戻され、次のプロバイダーへ渡されるため、切り替え時に失われません。Linux(Wayland + NVIDIA)でクリック無反応 / 黒画面になるユーザー向けに、自力回避できる環境変数を追加し、Claude Sonnet 5 の価格を補って既定の Sonnet 階層をそれへ引き上げ、「プロバイダー → プロジェクトディレクトリ」の 2 段階グルーピングのセッションビューを届け、一連の認証情報の安全性(共通設定スニペットからすべての秘密情報を除去、使用量スクリプトの認証情報は明示的なオーバーライドとしてのみ保持)、プラットフォーム互換性(Hermes の Windows 設定ディレクトリ、Windows の Codex npm シム)、UI(長いドロップダウンのスクロール、狭いウィンドウの日付範囲セレクタ)の問題を修正しました。あわせて、いくつかのプロバイダープリセットも追加し、そのまますぐ選べます。
**リリース日**: 2026-07-01
**Stats**: 36 commits | 93 files changed | +5,678 / -2,804 lines
---
## ハイライト
- **国産モデルプロバイダーの Codex ネイティブ直結が本当に使える**: 小米 MiMo、火山 Doubao、Qwen3-Coder、美団 LongCat、MiniMax などの国産プロバイダー向けに Codex モデルカタログ(`~/.codex/cc-switch-model-catalog.json`)を生成し、Codex デスクトップがこれらのモデルを表示でき、内蔵ツールが動くようにします。あわせて `web_search` を拒否する国産ゲートウェイ(MiMo、LongCat、MiniMax、Qwen3-Coder)に対してはそのツールを自動で無効化し、ハード 400 を避けます。**既存のネイティブプロバイダーは、新しいカタログ生成のために一度保存し直す必要があります。**
- **共通設定を切り替え時に自動同期・引き継ぎ**: 共通設定を有効にした Claude プロバイダーから切り替えるとき、アプリ内で追加したプラグイン、環境変数、テーマ、hooks が、まず共通設定へ書き戻され、次のプロバイダーへ渡されます——切り替え時に上書きで失われることがなくなりました。
- **Linux Wayland のクリック無反応 / 黒画面の回避スイッチ**: Wayland + NVIDIA で「タイトルバーは押せるのにページが反応しない、リサイズで黒画面」に遭遇したら、`CC_SWITCH_GDK_BACKEND=wayland` で起動すればネイティブ Wayland へ切り替えられます(タイリング系コンポジタで逆の問題に遭遇する場合は `x11` に設定)。
- **Claude Sonnet 5**: Sonnet 5 の価格を追加し、各プリセットの既定 Sonnet 階層を `claude-sonnet-5` へ引き上げます。
- **セッションの分類ビューとグルーピング**: セッションパネルに「プロバイダー → プロジェクトディレクトリ」の 2 段階グルーピングビューを新設し、グループヘッダーの 3 状態チェックボックスでワンクリックの一括選択に対応します。
- **新しいプロバイダープリセット**: 七牛云、FennoAI、ZetaAPI、TeamoRouter、NekoCode、Code0.ai、Amux などのプロバイダープリセットを、管理対象アプリ全体に追加し、そのまますぐ選べます。
---
## 追加機能
### 国産モデルプロバイダーの Codex ネイティブ直結(モデルカタログの生成)
本リリースは、国産プロバイダーの Codex ネイティブ直結を通しました。v3.16.4 で小米 MiMo、火山 Doubao、Qwen3-Coder、美団 LongCat、MiniMax をネイティブ Responses`apiFormat: "openai_responses"`)へ切り替えたのに続き、本リリースは当時の「ネイティブ直結ならモデルカタログを削除する」やり方を覆しました: これらのプロバイダーがローカルプロキシを経由せず直結するとき、CC Switch が `~/.codex/cc-switch-model-catalog.json` を生成し、Codex デスクトップがこれらのカスタムモデルを本当に表示でき、内蔵ツールも動くようにします——MiMo のようなネイティブゲートウェイが拒否する freeform `apply_patch``type=custom`)ツールを発生させません(編集は `shell_command` へフォールバック)。カタログ生成は `apiFormat` で判定され、「ローカルルーティング」トグルから分離されているため、ネイティブプロバイダーはローカルルートマッピングを有効にしなくてもカタログを永続化します。一方 `openai_chat` 形式は、既存の Responses↔Chat プロキシ変換をそのまま保ちます。Codex のパーサーは各項目に `base_instructions` を要求するため、ネイティブテンプレートは中立の既定値を携え、各ベンダーの公式文面がそれを上書きします(MiMo、MiniMax)。**既存のネイティブプロバイダーは、有効なカタログを生成するために一度保存し直す必要があります**(データベース移行は不要)。
あわせて、第一方モデルが OpenAI 内蔵の `web_search` ツールに対応しない一部の国産ゲートウェイ(MiMo、LongCat、MiniMax、Qwen3-Coder)については、本リリースが切り替え時にそのツールを自動で無効化し、Codex の既定でそれが付いてハード 400 で拒否されるのを避けます(下記「修正」を参照)。
### セッションの分類ビューとグルーピング
セッション管理パネルに、既存のフラットなリストに加えてグルーピングビューを新設し、ツールバーの List / ListTree セレクタで切り替え、ビューモードと展開状態を `localStorage` に永続化します。グルーピングは「プロバイダー → プロジェクトディレクトリ」の 2 段階階層を構築します: プロジェクトディレクトリ名でグループ化し、プロジェクトディレクトリを持たないセッションは「不明なディレクトリ」バケットに入ります。両方の段階が折りたたみ可能な区画で、「すべて折りたたむ」ボタンを備えます。バッチモードでは、各グループヘッダーに 3 状態チェックボックスが現れ、そのグループ内の選択可能なセッションをすべて一括で選択 / 解除でき、選択数 / 選択可能数のバッジも表示します。4 言語(zh / en / ja / zh-TW)の文言は同期済みです。この変更は完全にフロントエンドで、バックエンドのコマンドやデータアクセス層には手を加えていません。([#4776](https://github.com/farion1231/cc-switch/pull/4776)
### Claude Sonnet 5 のモデル価格
`schema.rs``claude-sonnet-5` の価格行を Anthropic の定価で追加しました——入力 / 出力が 100 万 token あたり \$3 / \$15、キャッシュ読み書きが \$0.30 / \$3.75 で、Sonnet 4.6 と同一です。導入期の \$2 / \$10 プロモーション(2026-08-31 まで有効)は意図的にシードせず、記帳が一時的な割引ではなく定常の定価を反映するようにしています。この行はアプリの次回起動時に `ensure_model_pricing_seeded` 経由で適用され、`SCHEMA_VERSION` の引き上げは不要です。
### 新しいプロバイダープリセット
本リリースは一連のプロバイダープリセットを追加しました。選択して自分の API key を入力すればすぐ使えます:
- **七牛云(Qiniu**: 管理対象の 7 アプリすべて(Gemini を含む)をカバーし、ネイティブ Claude / GPT / Gemini を中継します。
- **FennoAI / ZetaAPI / TeamoRouter / NekoCode**: それぞれ 6 アプリ(Claude、Claude Desktop、Codex、OpenCode、OpenClaw、Hermes)をカバーします。
- **Code0.ai**: 7 アプリすべて(Gemini を含む)をカバーします。
- **Amux**: 6 アプリをカバーします。
各プリセットの endpoint と既定モデルは対応するアプリに合わせて設定済みです——Claude 系は Anthropic 互換ホストへ直結、Codex はネイティブ Responses、その他は OpenAI 互換の `/v1` を使います。
---
## 変更
### プロバイダー切り替え時に共通設定を自動同期・引き継ぎ
これは本リリースのとても実用的な変更です: 共通設定を有効にした Claude プロバイダーから切り替えるとき、サービスはまずその live の `settings.json` から**共有可能な部分を再抽出して共通設定を更新し**、次のプロバイダーへ渡します。以前のような一方向の書き込みだけではありません。これにより、実行中のアプリで直接追加したプラグイン(`enabledPlugins`)、hooks、環境変数(`env`)、テーマ(`theme`)などの共有設定が、切り替え時に静かに失われることなく、自動的に次のプロバイダーへ引き継がれます。削除も同期されます(削除されたキーは再注入されません)。この同期は共通設定を有効にした Claude プロバイダーに厳密に限定され、明示的にクリアされた場合はスキップされ、すべての失敗は非致命的(警告のみ)で、切り替えを妨げることは決してありません。
### Codex のモデルマッピングと「ローカルルーティング」トグルの分離
Codex プロバイダーフォームが Claude Code に揃いました——モデルマッピングカタログがルーティングテイクオーバーから独立しました。ネイティブ Responses プロバイダー(MiMo、Doubao、MiniMax)はプロキシなし直結のためにそれを必要とする一方、Chat プロバイダーはいずれにせよプロキシを経由するためです。「ローカルルーティングが必要」トグルは削除されました(バックエンドのフィールドを持たず、カタログ / 推論の永続化を制御していただけで、これはマッピングが記入されているかどうかと等価です)。モデルマッピングは非公式プロバイダーに対して常に表示され、空でなければ永続化されます。一方、推論能力の表示 / 永続化は Chat 形式で制御されるようになりました。4 言語(zh / en / ja / zh-TW)の文言もあわせて書き直しました。副次的な修正として、`useCodexConfigState` が保存済みプロバイダーを読み込むときに `supportsParallelToolCalls` / `inputModalities` / `baseInstructions` を落とす問題(編集時に並列ツール、画像入力、公式の base instructions を静かに失っていた)も修正しました。
### 既定の Sonnet 階層を Claude Sonnet 5 へ引き上げ
各プロバイダープリセットの既定 Sonnet 階層を `claude-sonnet-4-6` から `claude-sonnet-5` へ引き上げました(claude / claude-desktop / hermes / openclaw / opencode のプリセットとユニバーサルの `NEWAPI_DEFAULT_MODELS` をカバー)。`ANTHROPIC_MODEL` / `ANTHROPIC_DEFAULT_SONNET_MODEL` / `ANTHROPIC_DEFAULT_OPUS_MODEL` などのキーとそのプレフィックス付き変種が対象です。Claude Desktop の既定ルートの sonnet `route_id` もあわせて `claude-sonnet-5` へ移行しました。非 Anthropic の pingpt / gemini / glm / sonnet-4-5)はそのままです。
### Doubao の日付付き model id と価格の正規化
DoubaoDouBaoSeed)プリセットの model id を日付付きの `doubao-seed-2-1-pro-260628` へ切り替えました(各アプリをカバー)。火山方舟が素の `doubao-seed-2-1-pro` を 404 で拒否し、完全な日付付き id のみを受け付けるためです。実際の使用量が日付サフィックスを伴うようになったため、`strip_model_date_suffix` を火山の 6 桁 YYMMDD 形式も剥がせるように拡張し(`-123456` のような非日付のバージョンサフィックスを誤って食わないよう、月 01-12・日 01-31 を検証)、価格表の素の名前のシード行にマッチするよう正規化して、Doubao モデルが \$0 コストで表示される問題を修正しました。
###「共通設定を書き込む」を「共通設定を適用」へ改名
元のラベル「共通設定を書き込む」はデータの流れの方向が曖昧でした(「現在の設定を共通設定へ書き込む」と読めた)。実際の挙動は逆で——保存済みの共通設定スニペットをこのプロバイダーの設定へマージするものです。チェックボックスを 4 言語(zh / en / ja / zh-TW)で「共通設定を適用」へ改名し、すべてのヒント / ガイド / 説明の参照を含め、日本語ユーザーマニュアルと `README_JA.md` もあわせて同期しました。([#4829](https://github.com/farion1231/cc-switch/pull/4829)
### その他のプリセットと素材の調整
- **OpenClaw の Doubao コンテキストを 262144 へ整合**: OpenClaw の DouBaoSeed プリセットは以前 128000 をハードコードしていましたが、Codex 側は同モデルで 262144 を使っており、OpenClaw ユーザーのウィンドウが小さすぎました。両者を整合させ、再びずれないようクロスプリセットの一貫性テストを追加しました。
- **火山 / Doubao / BytePlus の公式サイトリンクを訂正**: これら 3 つのプリセットの「公式サイトを訪問」リンクが、誤ってコンソール / 登録リンクに設定されていたため、クリーンな製品トップページへ戻しました。
- **過大なプロバイダーアイコンを 256px へダウンスケール**: 一連のバンドルアイコンが、実際の描画サイズ(~32px)よりはるかに大きかったため、ダウンスケールで大幅に容量を削減しました(コード / ファイル名 / インポートの変更なし。例: ZetaAPI 940KB→40KB、relaxcode 1.16MB→42KB)。また、一度も参照されていない 1.4MB の `dds.svg` 孤立ファイルを削除しました。
---
## 修正
### `web_search` を拒否するネイティブ Codex ゲートウェイでは無効化
一部のネイティブ `/responses` ゲートウェイは、第一方モデルが OpenAI のホスト型 `web_search` ツールを備えないため、それを「tool type 'web_search' is not supported」で拒否します。そして Codex は既定でそのツールを送るため、ハード 400 を招きます。CC Switch は現在、これらのベンダーに対して切り替え時にトップレベルの TOML 行 `web_search = "disabled"` を書き込みます。スコープはブラックリスト(既定オン)で、`base_url` ホスト(`xiaomimimo.com``longcat.chat``minimax.io``minimaxi.com`)または model のブランドプレフィックス(`mimo``longcat``minimax``qwen3-coder`)に一致するプロバイダーだけが無効化されるため、本物の GPT、Doubao、一般の Qwen、そして未知のプロバイダーはいずれも Codex の既定を保ちます。`qwen3-coder` プレフィックスはネイティブの `qwen3-coder-plus` だけを抑制し(百炼 / DashScope は coder 系で内蔵ツールを非対応と示します)、同じホストを共有する一般の Qwen は有効のままです。マッチングは model 軸で行われ(アグリゲーターの `vendor/` パスセグメントを剥がす)、SiliconFlow が拒否ベンダーのモデルを前面に立てるようなケースも捕捉します。曖昧な「これは GPT か?」というホワイトリストではなくブラックリストを選んだのは、`web_search` を誤ってオンのままにするとハード 400 で失敗するためです。所有権のセンチネルにより、CC Switch は自らが書いた `disabled` 値だけを削除するため、既存プロバイダーは保存し直す必要がなく、切り替えて戻せば再び有効になります。副次的な修正として、LongCat-2.0-Preview プリセットのコンテキストウィンドウを 131072(128K)から本来の 1048576(1M)へ訂正しました。
### 共有される Claude 共通設定スニペットからすべての認証情報系キーを除去
`extract_claude_common_config` は以前 `ANTHROPIC_API_KEY``ANTHROPIC_AUTH_TOKEN` だけをマスクしていましたが、Claude プロバイダーは正当に他の認証情報(`OPENROUTER_API_KEY``GOOGLE_API_KEY`、場合によっては OpenAI / Gemini / AWS Bedrock / Vertex の秘密情報)を携えることがあり、それらが共有スニペットへ漏れ、他のプロバイダーへ注入されるおそれがありました。抽出は現在、認証情報の形をした環境変数キー(`*_API_KEY` / `*_AUTH_TOKEN` / `*secret*` / `*token*` など)をパターンマッチで除去し、`MAX_OUTPUT_TOKENS` のような正当に共有可能な複数形 `*_TOKENS` の値は保持します。手動の「抽出」と一度きりの自動抽出の経路にあった同じ漏れも、あわせて塞ぎました。
### 使用量スクリプトの認証情報は明示的なオーバーライドとしてのみ永続化
プロバイダーの使用量スクリプトは、クォータ照会時に live の認証情報を上書きする任意の `api_key` / `base_url` フィールドを保持しますが、これらが以前はプロバイダー自身の認証情報を静かにミラーしていました——そのため、プロバイダーを複製したり、メインの API key / base URL を編集したりすると、使用量スクリプトが古い endpoint と key に固定されたまま残り、クォータ照会が古い対象を叩き続けていました。`ProviderService` は現在、永続化の前に正規化します: スクリプトの `api_key` または `base_url` がプロバイダーの解決済み使用量認証情報と一致する(または空の)場合は `None` にクリアして、照会が live 設定へフォールバックするようにします。本当に異なるオーバーライドは保持されます(`token_plan` スクリプトはそのまま)。deeplink インポート経路にも同様の正規化を加え、フロントエンドは更新時に関連するキャッシュキーを無効化して、ホームページが訂正済みの設定で再照会するようにします。([#4654](https://github.com/farion1231/cc-switch/pull/4654)
### Hermes 設定ディレクトリが Windows で正しく解決されるように
CC Switch は Hermes の設定ディレクトリとして `~/.hermes` をハードコードしていましたが、Hermes 自身は `HERMES_HOME` 環境変数、次にプラットフォーム既定(Windows では `%LOCALAPPDATA%\hermes`)で解決します。Windows ではこれにより、CC Switch がプロバイダー設定を Hermes が決して読まないパスへ書いていたため、プロバイダーの切り替えが効きませんでした。`get_hermes_dir()` は現在、Hermes 自身の解決順序——明示的なオーバーライド、次に `HERMES_HOME`(そのまま使用、`~` 展開なし)、次にプラットフォーム既定——をミラーし、#3470 が落としていた `HERMES_HOME` を再び尊重します(Hermes の Windows インストーラーは、再配置されたインストールの第一級の仕組みとしてそれを設定します)。([#4680](https://github.com/farion1231/cc-switch/pull/4680)、#3178#3470 を参照)
### Linux Wayland: AppImage が強制する `GDK_BACKEND=x11` を上書き可能に
AppImage の GTK 起動フックは、歴史的なネイティブ Wayland のクラッシュを避けるために `GDK_BACKEND=x11` を無条件でエクスポートします。新しめの Wayland + NVIDIA 環境では、この強制された XWayland により WebKitGTK のウェブコンテンツがポインタイベントを受け取れなくなり(タイトルバーは押せてもページは反応しない)、リサイズで黒画面になります。既存の `WEBKIT_DISABLE_*` の緩和策は効きません。根本原因が描画ではなく、強制されたウィンドウバックエンドだからです。`main.rs` は現在、GTK の初期化前に任意の `CC_SWITCH_GDK_BACKEND` 回避スイッチを読みます(AppImage の起動フックはそれに触れません): 未設定なら現状のまま(回帰ゼロ)。上記の問題に遭遇したら、これを設定してネイティブ Wayland へ切り替えて起動できます:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
この上書きは汎用です——タイリング系 Wayland コンポジタで逆の入力問題に遭遇する場合は、代わりに `CC_SWITCH_GDK_BACKEND=x11` に設定してください。([#4351](https://github.com/farion1231/cc-switch/pull/4351)、#4350 を修正)
###「API Key を取得」リンクが Claude Desktop / OpenClaw / Hermes フォームでも表示されるように
API key 入力欄の下の「API Key を取得」リンクとパートナー宣伝ブロックは、以前 claude / codex / gemini / opencode にしか配線されていませんでした。Claude Desktop はそれを表示しない素の入力欄を描画し、OpenClaw / Hermes は 2 つの欠落(ホワイトリストがその 4 つの appId しか列挙しておらず、カテゴリ解析もその 4 つのプリセット id パターンしか認識しなかった)にブロックされていました。Claude Desktop は現在、共有の `ApiKeySection` を使い、ホワイトリストとカテゴリ解析の両方を claude-desktop / openclaw / hermes へ拡張しました。さらに、Hermes / OpenClaw のフォームは「公式」カテゴリで key 入力欄を無効化しなくなりました(これらのアプリには OAuth 専用の公式プロバイダーが存在しません——例えば Hermes の Nous Research は公式ですが、それでもユーザー入力の key が必要です)。
### Windows の Codex npm シムの重複排除
Windows では、npm がツールを 3 つの兄弟ファイル——`codex.cmd``codex.exe`、拡張子なしの Unix シム `codex`——としてインストールし、CC Switch は以前この 3 つすべてを候補に列挙していたため、実行できない拡張子なしシムが冗長 / 失敗する候補としてプローブされていました。現在は、隣接する実行可能な `.cmd` / `.exe` の兄弟が見つからない場合にのみ拡張子なしパスを追加し、パス解決も実行可能な `.cmd` / `.exe` を優先して、バージョン検出と起動を実際に実行可能な Windows シムに固定します。([#4782](https://github.com/farion1231/cc-switch/pull/4782)
### 長い Select ドロップダウンのスクロール境界
`SelectContent` は以前、高さの上限なしで `overflow-hidden` を使っていたため、選択肢の多いドロップダウン(長いモデル / プロバイダーのリストなど)がビューポートより高く描画され、あふれた項目が切り取られて届かなくなっていました。現在は `max-h-[min(24rem,var(--radix-select-content-available-height))]``overflow-y-auto` を設定し、内容を 24rem または Radix が計算した利用可能高さに収め、縦方向のスクロールを許可します。([#4798](https://github.com/farion1231/cc-switch/pull/4798)
### 日付範囲セレクタのカレンダーが狭いポップオーバーでも画面内に収まるように
カスタム日付範囲セレクタは以前、2 列レイアウト(日付フィールド | カレンダー)への切り替えを**ビューポート**幅(Tailwind の `sm:` 640px ブレークポイント)で判定していましたが、ポップオーバーは `100vw - 2rem` に制限され、トリガーにアンカーされているため、実際に使える幅はビューポートより狭くなります。狭いウィンドウでは、ポップオーバーに 1 列分しか収まらないのに 2 列レイアウトが有効化されることがあり、カレンダー列が右端の外へ押し出されて切り取られていました(月ヘッダーと 7 列中 4 列の曜日が切れて届かない)。レイアウトは現在、CSS コンテナクエリでポップオーバー自身のインラインサイズに基づいて切り替わるため、ポップオーバー自体が狭いときにちょうど 1 列へ折りたたまれ、どのウィンドウ幅でもカレンダーが完全に見えるようになりました。([#4860](https://github.com/farion1231/cc-switch/pull/4860)
---
## ドキュメント
### `CC_SWITCH_GDK_BACKEND` 回避スイッチのドキュメント化
任意の `CC_SWITCH_GDK_BACKEND` 環境変数について、4 言語すべての README と zh / en / ja のユーザーマニュアルのトラブルシューティングページに FAQ 項目を追加し、Wayland + NVIDIA ユーザーがウェブコンテンツの「クリック無反応 + リサイズで黒画面」時にネイティブ Wayland へ切り替える方法、そしてタイリング系 Wayland ユーザーが逆の入力問題で `x11` に設定する方法を解説しました。
### 海外向け Kimi README が platform.kimi.ai を指すように
英語・ドイツ語・日本語の README の Kimi K2.7 Code パートナー段落で、バナーとインラインの行動喚起を `https://platform.kimi.ai?aff=cc-switch` へ向け(紹介タグは維持)、4 言語すべての README に `https://www.kimi.com/code/?aff=cc-switch` へリンクした Kimi For Coding サブスクリプションの宣伝行を追加しました。
---
## アップグレード時の注意
### 既存のネイティブ Codex プロバイダーは一度保存し直しが必要
本リリースは、ネイティブ Responses 直結のモデルカタログ生成を作り直しました。以前にネイティブ Responses(`openai_responses`)を使う Codex プロバイダーを設定していた場合は、新しい `~/.codex/cc-switch-model-catalog.json` を生成するために、**プリセットから選び直すか、プロバイダーを開いて一度保存し直して**ください——それが、Codex デスクトップにカスタムモデルを表示させ、ツールを動かすための鍵です。これはデータベース移行を必要とせず、`openai_chat` 形式のプロバイダーには影響しません。
### `web_search` ブラックリストは既定の挙動
`web_search` を拒否することが分かっている国産ネイティブゲートウェイ(小米 MiMo、美団 LongCat、MiniMax、Qwen3-Coder)に対しては、本リリースが切り替え時に自動で `web_search = "disabled"` を書き込みます。本物の GPT、Doubao、一般の Qwen、そして未知のプロバイダーは影響を受けず、Codex の既定を保ちます。このスイッチは CC Switch が所有権のセンチネルで管理するため、ブラックリストにないプロバイダーへ切り替えて戻せば自動的に復元され、手動の介入は不要です。
### 既定の Sonnet 階層の変化
プリセットから新規作成した Claude 系プロバイダーは、既定の Sonnet 階層が `claude-sonnet-5` を指すようになりました。設定済みの既存プロバイダーは影響を受けず、設定はそのまま保たれます。Sonnet 5 へ切り替えたい場合は、プリセットから選び直して保存してください。
---
## リスク通知
本リリースは、リバースプロキシ系機能に関する以前のリスク通知を引き続き適用します。
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションの Codex OAuth をリバースプロキシ経由で使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 release notes](v3.13.0-ja.md#-リスクに関する注意事項) を参照してください。
**Codex サードパーティプロバイダー Chat ルーティング**: CC Switch ローカルプロキシで Codex リクエストを変換し、サードパーティプロバイダーへ転送する場合、課金・コンプライアンス・データ保持に関する制約はプロバイダーごとに異なります。利用前に対象プロバイダーの利用規約を確認してください。
**Claude Desktop サードパーティプロバイダープロキシ切り替え**: CC Switch 内蔵のプロキシゲートウェイで Claude Desktop のリクエストをサードパーティプロバイダーへ転送する場合も、対象プロバイダーの課金・コンプライアンス・データ保持に関する規約に従う必要があります。
上記機能を有効化したユーザーは、関連するリスクを自ら負うものとします。CC Switch は、これらの機能の利用によって発生したアカウント制限、警告、サービス停止について責任を負いません。
---
## 謝辞
v3.16.5 で機能と修正を届けてくださった以下のコントリビューターに感謝します:
- [#4776](https://github.com/farion1231/cc-switch/pull/4776): セッションの分類ビューとグループ管理を追加、@alkaid616 に感謝。
- [#4829](https://github.com/farion1231/cc-switch/pull/4829):「共通設定を書き込む」を「共通設定を適用」へ改名、@arichyx に感謝。
- [#4654](https://github.com/farion1231/cc-switch/pull/4654): 使用量スクリプトの認証情報を明示的なオーバーライドとしてのみ永続化、@yyhhyyyyyy に感謝。
- [#4680](https://github.com/farion1231/cc-switch/pull/4680): Windows で Hermes プロバイダー設定が効かない問題を修正、@thisTom に感謝。
- [#4782](https://github.com/farion1231/cc-switch/pull/4782): Windows の Codex npm シムを重複排除、@justjavac に感謝。
- [#4798](https://github.com/farion1231/cc-switch/pull/4798): 長いドロップダウンリストがスクロールできない問題を修正、@xwil1 に感謝。
- [#4351](https://github.com/farion1231/cc-switch/pull/4351): AppImage が強制する `GDK_BACKEND=x11``CC_SWITCH_GDK_BACKEND` で上書き可能に、@BoneLiu に感謝。
- [#4860](https://github.com/farion1231/cc-switch/pull/4860): 日付範囲セレクタのカレンダーが狭いポップオーバーでも画面内に収まるように、@SaladDay に感謝。
v3.16.4 リリース後に Codex ネイティブ直結、共通設定、認証情報の再利用、プラットフォーム互換性の問題を報告してくださったすべてのユーザーにも感謝します。今回の多くのパッチは、こうした実際の利用シーンから得られた再現の手がかりに基づいています。
---
## ダウンロードとインストール
[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.16.5-Windows.msi` | **推奨** - 自動更新対応の MSI インストーラー |
| `CC-Switch-v3.16.5-Windows-Portable.zip` | ポータブル版、展開してそのまま実行できます |
Windows ARM64 デバイスをお使いの場合は、ファイル名に `arm64` 識別子が含まれる対応する制品を選択してください。
### macOS
| ファイル | 説明 |
| -------------------------------- | ------------------------------------------------------ |
| `CC-Switch-v3.16.5-macOS.dmg` | **推奨** - DMG インストーラー、Applications へドラッグ |
| `CC-Switch-v3.16.5-macOS.zip` | 展開して Applications へドラッグ、Universal Binary |
| `CC-Switch-v3.16.5-macOS.tar.gz` | Homebrew インストールと自動更新用 |
Homebrew インストール:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux アセットは **x86_64****ARM64**`aarch64`)の両方を提供します。ファイル名にアーキテクチャ識別子が含まれているため、マシンの `uname -m` 出力に合わせて選択してください:
- `CC-Switch-v3.16.5-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.5-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` |
+278
View File
@@ -0,0 +1,278 @@
# CC Switch v3.16.5
> 这一版的重头戏是**让原生 Responses 格式的国产模型供应商真正适配到位**——为小米 MiMo、火山豆包、千问 Qwen3-Coder、美团 LongCat、MiniMax 等具备原生 Responses 端点的供应商生成 Codex 模型目录,让 Codex 桌面能看到这些模型、内置工具也能正常工作,并对少数拒收 `web_search` 的国产网关自动禁用该工具、避免请求被硬性拒绝。另有两处重要改进:切换供应商时,你在应用内新增的插件、环境变量等会**自动回写到通用配置并带给下一个供应商**;LinuxWayland + NVIDIA)上「标题栏能点、页面点不动、缩放黑屏」的问题,现在也能用一个环境变量开关自救。本版还带来 Claude Sonnet 5 定价与默认档升级、两级分组的会话视图,以及一批凭据安全与平台兼容修复。
**[English →](v3.16.5-en.md) | [日本語版 →](v3.16.5-ja.md)**
---
## 使用攻略
本版的新能力主要落在 Codex 供应商表单、会话面板与用量 / 通用配置里,建议结合以下文档了解:
- **[Codex 桌面看不到自定义模型?](../guides/codex-desktop-custom-model-visibility-zh.md)**:本版重做了**原生直连时的模型目录生成**——当 Codex 供应商使用原生 Responses`openai_responses`)直连时,CC Switch 会生成 `~/.codex/cc-switch-model-catalog.json`,让 Codex 桌面能显示配置的自定义模型、工具也可用。若你此前配过原生 Codex 供应商,请**重新保存一次**以生成新目录(详见下方「升级提醒」)。
- **[用量统计](../user-manual/zh/4-proxy/4.4-usage.md)**:了解用量看板的数据来源与统计口径。本版新增了 Claude Sonnet 5 定价,并修复了用量脚本凭据被当作「显式覆盖」持久化的问题。
- **[设置](../user-manual/zh/1-getting-started/1.5-settings.md)**:Codex 上游格式选择器与本地路由开关、Claude 通用配置(现更名为「应用通用配置」并支持切换时自动同步)都在供应商表单的高级选项里。
---
> [!WARNING]
>
> ## 唯一官方渠道声明(请务必阅读)
>
> CC Switch 是**完全免费、开源**的桌面应用,**不会向用户收取任何费用**。请仅通过下列官方渠道获取本软件:
>
> | 类别 | 唯一官方 |
> | -------- | ------------------------------------------------------------------------------ |
> | 官网 | **[ccswitch.io](https://ccswitch.io)** |
> | 源码 | **[github.com/farion1231/cc-switch](https://github.com/farion1231/cc-switch)** |
> | 下载 | **[GitHub Releases](https://github.com/farion1231/cc-switch/releases)** |
> | 作者 | **[@farion1231](https://github.com/farion1231)** |
> | 举报山寨 | **[GitHub Issues](https://github.com/farion1231/cc-switch/issues)** |
>
> **任何向你收费、要求充值、或索取登录凭据的"CC Switch"网站或客户端均为假冒**。如果你被诱导支付了费用,请立即停止操作并通过 GitHub Issues 反馈。
---
## 概览
CC Switch v3.16.5 是 v3.16.4 之后的一版维护更新,核心是把**国产模型供应商的 Codex 原生直连做通**。v3.16.4 已经把千问 / 百炼、小米 MiMo、火山豆包、美团 LongCat、MiniMax 等供应商切到了原生 Responses 端点,本版进一步为它们生成 Codex 所需的**模型目录**(`~/.codex/cc-switch-model-catalog.json`),让 Codex 桌面真正能看到这些自定义模型、内置工具也能正常调用,并把模型映射从「本地路由」开关里彻底解耦。针对少数第一方模型不支持 OpenAI 内置 `web_search` 的国产网关(MiMo、LongCat、MiniMax、Qwen3-Coder),本版还会自动禁用该工具,避免 Codex 默认带上它触发硬 400。
围绕日常使用体验,本版让 Claude 的**通用配置在切换供应商时自动同步并传递**——你在应用内新增的插件、环境变量、主题等会先回写到通用配置、再带给下一个供应商,不会在切换时丢失;给 LinuxWayland + NVIDIA)上点击失灵 / 黑屏的用户加了一个可自救的环境变量开关;补上 Claude Sonnet 5 定价并把默认 Sonnet 档升级到它;带来「供应商 → 项目目录」两级分组的会话视图;并修了一串凭据安全(通用配置片段剥离全部密钥、用量脚本凭据仅作显式覆盖)、平台兼容(Hermes Windows 配置目录、Windows Codex npm 影子命令)与界面(长下拉滚动、窄窗口日期选择器)的问题。此外也新增了若干供应商预设,开箱即可选用。
**发布日期**2026-07-01
**更新规模**36 commits | 93 files changed | +5,678 / -2,804 lines
---
## 重点内容
- **让国产模型供应商的 Codex 原生直连真正可用**:为小米 MiMo、火山豆包、千问 Qwen3-Coder、美团 LongCat、MiniMax 等国产供应商生成 Codex 模型目录(`~/.codex/cc-switch-model-catalog.json`),让 Codex 桌面能看到这些模型、内置工具可用;并对拒收 `web_search` 的国产网关(MiMo、LongCat、MiniMax、Qwen3-Coder)自动禁用该工具、避免硬 400。**存量原生供应商需重存一次**以生成新目录。
- **通用配置切换时自动同步并传递**:切走一个启用了通用配置的 Claude 供应商时,你在应用内新增的插件、环境变量、主题、hooks 会先自动回写到通用配置,再带给下一个供应商——不再在切换时被覆盖丢失。
- **Linux Wayland 点击失灵 / 黑屏的自救开关**:遇到 Wayland + NVIDIA 上「标题栏能点、页面点不动、缩放黑屏」时,用 `CC_SWITCH_GDK_BACKEND=wayland` 启动即可切回原生 Wayland(平铺式合成器上遇到反向问题可设为 `x11`)。
- **Claude Sonnet 5**:新增 Sonnet 5 定价,并把各预设的默认 Sonnet 档升级到 `claude-sonnet-5`
- **会话分类视图与分组管理**:会话面板新增「供应商 → 项目目录」两级分组视图,分组头支持三态复选框一键批量选择。
- **新增供应商预设**:新增七牛云、FennoAI、ZetaAPI、TeamoRouter、NekoCode、Code0.ai、Amux 等供应商预设,覆盖各受管应用,开箱即可选用。
---
## 新功能
### 国产模型供应商的 Codex 原生直连(生成模型目录)
本版把国产供应商的 Codex 原生直连做通了。继 v3.16.4 把小米 MiMo、火山豆包、千问 Qwen3-Coder、美团 LongCat、MiniMax 等供应商切换到原生 Responses(`apiFormat: "openai_responses"`)之后,本版推翻了当时「原生直连就删掉模型目录」的做法:这些供应商不经过本地代理直连时,CC Switch 会为它们生成 `~/.codex/cc-switch-model-catalog.json`,让 Codex 桌面真正显示这些自定义模型、内置工具也能用——不会触发像 MiMo 这类原生网关会拒绝的 freeform `apply_patch``type=custom`)工具(编辑回退到 `shell_command`)。目录生成按 `apiFormat` 判定、与「本地路由」开关解耦,因此一个原生供应商无需开启本地路由映射也会持久化目录;而 `openai_chat` 格式仍保持既有的 Responses↔Chat 代理转换不变。由于 Codex 解析器要求每个条目都带 `base_instructions`,原生模板携带一个中性默认值、由各厂商官方文案覆盖(MiMo、MiniMax)。**存量原生供应商需重新保存一次以生成有效目录**(无需数据库迁移)。
配套地,对少数第一方模型不支持 OpenAI 内置 `web_search` 工具的国产网关(MiMo、LongCat、MiniMax、Qwen3-Coder),本版会在切换时自动禁用该工具,避免 Codex 默认带上它、被网关以硬 400 拒绝(详见下方「修复」)。
### 会话分类视图与分组管理
会话管理面板在原有平铺列表之外新增了分组视图,通过工具栏的 List / ListTree 选择器切换,视图模式与展开状态都持久化到 `localStorage`。分组构建「供应商 → 项目目录」两级层级:按项目目录名归组,缺少项目目录的会话落入「未知目录」桶。两级都是可折叠区块,并提供「全部折叠」按钮;在批量模式下,每个分组头会出现一个三态复选框,可一键选中 / 取消该组内全部可选会话,并显示已选 / 可选计数徽标。四语(zh / en / ja / zh-TW)文案已同步。该改动完全在前端,不涉及后端命令或数据访问层。([#4776](https://github.com/farion1231/cc-switch/pull/4776)
### Claude Sonnet 5 模型定价
`schema.rs` 里按 Anthropic list 价新增 `claude-sonnet-5` 定价行——输入 / 输出 \$3 / \$15 每百万 token、缓存读写 \$0.30 / \$3.75,与 Sonnet 4.6 一致。介绍期 \$2 / \$10 促销(有效期至 2026-08-31)刻意不入表,让记账反映稳态 list 价而非临时折扣。该行在应用下次启动时通过 `ensure_model_pricing_seeded` 应用,无需 `SCHEMA_VERSION` 变更。
### 新增供应商预设
本版新增了一批供应商预设,选中后填入自己的 API Key 即可使用:
- **七牛云(Qiniu**:覆盖全部 7 个受管应用(含 Gemini),中转原生 Claude / GPT / Gemini。
- **FennoAI / ZetaAPI / TeamoRouter / NekoCode**:各覆盖 6 个应用(Claude、Claude Desktop、Codex、OpenCode、OpenClaw、Hermes)。
- **Code0.ai**:覆盖全部 7 个应用(含 Gemini)。
- **Amux**:覆盖 6 个应用。
各预设的端点与默认模型已按对应应用配好——Claude 类走 Anthropic 兼容主机直连、Codex 走原生 Responses、其余走 OpenAI 兼容 `/v1`
---
## 变更
### 切换供应商时自动同步并传递通用配置
这是本版一个很实用的改动:切走一个启用了通用配置的 Claude 供应商时,服务会先从它的 live `settings.json` 里**重新提取可共享部分、更新到通用配置**,再带给下一个供应商,而不再只是单向写入。这样一来,你在运行中的应用里直接新增的插件(`enabledPlugins`)、hooks、环境变量(`env`)、主题(`theme`)等共享配置就不会在切换时被静默丢失,而是自动跟着走到下一个供应商;删除也会同步(移除的键不会被再次注入)。该同步严格限定在启用了通用配置的 Claude 供应商,被显式清空时会跳过,且所有失败都是非致命(仅告警)、永不阻断切换。
### Codex 模型映射与「本地路由」开关解耦
Codex 供应商表单向 Claude Code 对齐——模型映射目录现在独立于路由接管,因为原生 Responses 供应商(MiMo、豆包、MiniMax)需要它来做无代理直连,而 Chat 供应商无论如何都走代理。「需要本地路由」开关被移除(它没有后端字段,只是门控目录 / 推理的持久化,等价于「映射是否填了」)。模型映射现在对非官方供应商始终显示、非空即持久化,而推理能力的显示 / 持久化改由 Chat 格式门控。四语(zh / en / ja / zh-TW)文案随之重写。顺带修复了 `useCodexConfigState` 在加载已存供应商时丢掉 `supportsParallelToolCalls` / `inputModalities` / `baseInstructions` 的问题(会在编辑时静默丢失并行工具、图像输入与官方 base instructions)。
### 默认 Sonnet 档升级到 Claude Sonnet 5
把各供应商预设里的默认 Sonnet 档从 `claude-sonnet-4-6` 升级到 `claude-sonnet-5`(覆盖 claude / claude-desktop / hermes / openclaw / opencode 预设与通用 `NEWAPI_DEFAULT_MODELS`),涉及 `ANTHROPIC_MODEL` / `ANTHROPIC_DEFAULT_SONNET_MODEL` / `ANTHROPIC_DEFAULT_OPUS_MODEL` 等键及其带前缀变体。Claude Desktop 的默认路由 sonnet `route_id` 也一并迁移到 `claude-sonnet-5`。非 Anthropic 的 pingpt / gemini / glm / sonnet-4-5)保持不变。
### 豆包带日期 model id 与定价归一化
豆包(DouBaoSeed)预设的 model id 切换到带日期的 `doubao-seed-2-1-pro-260628`(覆盖各应用),因为火山方舟会以 404 拒绝裸名 `doubao-seed-2-1-pro`、只接受完整带日期 id。由于真实用量现在带日期后缀,`strip_model_date_suffix` 扩展为也能剥掉火山的 6 位 YYMMDD 形式(并校验月 01-12、日 01-31 以免误伤 `-123456` 这类非日期版本后缀),从而归一化命中定价表里的裸名 seed 行、修复豆包模型显示 \$0 成本的问题。
###「写入通用配置」更名为「应用通用配置」
原标签「写入通用配置」在数据流向上有歧义(读起来像「把当前配置写进通用配置」),而实际行为相反——是把已存的通用配置片段合并进本供应商配置。复选框在四语(zh / en / ja / zh-TW)里更名为「应用通用配置」,包括所有提示 / 攻略 / 说明引用,日文用户手册与 `README_JA.md` 也一并同步。([#4829](https://github.com/farion1231/cc-switch/pull/4829)
### 其它预设与资源调整
- **OpenClaw 豆包上下文对齐 262144**OpenClaw 的 DouBaoSeed 预设此前硬编码 128000,而 Codex 侧同模型用 262144,导致 OpenClaw 用户窗口偏小;已对齐并加了跨预设一致性测试防止再次漂移。
- **火山 / 豆包 / BytePlus 官网链接订正**:这三个预设的「访问官网」链接被误设成了控制台 / 注册链接,已恢复为干净的产品主页。
- **过大的供应商图标降采样到 256px**:一批捆绑图标此前远大于其 ~32px 的实际渲染尺寸,降采样后显著减小体积、无代码 / 文件名 / 导入改动(如 ZetaAPI 940KB→40KB、relaxcode 1.16MB→42KB),并删除了从未被引用的 1.4MB `dds.svg` 孤儿。
---
## 修复
### 对拒收 `web_search` 的原生 Codex 网关禁用该工具
一些原生 `/responses` 网关的第一方模型不具备 OpenAI 内置的 `web_search` 工具,会以「tool type 'web_search' is not supported」拒绝,而 Codex 默认就会带上该工具,导致硬 400。CC Switch 现在会为这些厂商写入顶层 TOML 行 `web_search = "disabled"`。作用域是一份黑名单(默认开启):仅命中 `base_url` 主机(`xiaomimimo.com``longcat.chat``minimax.io``minimaxi.com`)或模型品牌前缀(`mimo``longcat``minimax``qwen3-coder`)的供应商会被禁用,因此中转真 GPT、豆包、通用 Qwen 及任何未知供应商都保持 Codex 默认。其中 `qwen3-coder` 前缀只压制原生 `qwen3-coder-plus`(百炼 / DashScope 对 coder 系标记内置工具不支持),共享同一主机的通用 Qwen 保持开启;匹配走模型轴(会剥掉聚合器的 `vendor/` 路径段),因此也能兜住硅基流动这类中转拒收厂商模型的情形。选黑名单而非模糊的「是不是 GPT」白名单,是因为误让 `web_search` 保持开启会以硬 400 失败;同时用归属哨兵保证 CC Switch 只会移除由它自己写入的 `disabled` 值,因此存量供应商无需重存、切回也会重新启用。此外顺带把 LongCat-2.0-Preview 预设的上下文窗口从 131072128K)订正为真实的 10485761M)。
### 通用配置片段剥离全部凭据类键
`extract_claude_common_config` 此前只脱敏 `ANTHROPIC_API_KEY``ANTHROPIC_AUTH_TOKEN`,但 Claude 供应商合法地携带其它凭据(`OPENROUTER_API_KEY``GOOGLE_API_KEY`,可能还有 OpenAI / Gemini / AWS Bedrock / Vertex 密钥),这些可能泄漏进共享片段、再被注入到其它供应商。提取现在会按模式匹配并剥掉任何凭据形态的环境变量键(`*_API_KEY` / `*_AUTH_TOKEN` / `*secret*` / `*token*` 等),同时保留 `MAX_OUTPUT_TOKENS` 这类合法可共享的复数 `*_TOKENS` 值。手动「提取」与一次性自动提取路径的同一泄漏也一并堵上。
### 用量脚本凭据仅作显式覆盖持久化
供应商用量脚本存有可选的 `api_key` / `base_url` 字段用于查询配额时覆盖 live 凭据,但它们此前会静默镜像供应商自身的凭据——因此复制供应商或修改主 API key / base URL 后,用量脚本仍 pin 在旧端点旧 key,配额查询一直打向陈旧目标。现在 `ProviderService` 在持久化前会归一化:若脚本的 `api_key``base_url` 与供应商解析出的用量凭据相同(或为空)就清为 `None`,让查询回退到 live 配置;真正不同的覆盖才保留(`token_plan` 类脚本不动)。deeplink 导入路径也加了对应的归一化,前端在更新时会失效相关缓存键让首页用修正后的配置重新查询。([#4654](https://github.com/farion1231/cc-switch/pull/4654)
### Hermes 配置目录在 Windows 上正确解析
CC Switch 此前硬编码 `~/.hermes` 作为 Hermes 配置目录,但 Hermes 自身是按 `HERMES_HOME` 环境变量、再退到平台默认(Windows 上 `%LOCALAPPDATA%\hermes`)解析的。在 Windows 上这意味着 CC Switch 把供应商配置写到了 Hermes 根本不读的路径,导致供应商切换无效。`get_hermes_dir()` 现在镜像 Hermes 自己的解析顺序——显式覆盖、`HERMES_HOME`(原样取用、不做 `~` 展开)、平台默认——从而重新尊重被 #3470 丢掉的 `HERMES_HOME`Hermes 的 Windows 安装器把它作为重定位安装的首要机制)。([#4680](https://github.com/farion1231/cc-switch/pull/4680),参见 #3178#3470
### Linux Wayland:允许覆盖 AppImage 强制的 `GDK_BACKEND=x11`
AppImage 的 GTK 启动钩子无条件导出 `GDK_BACKEND=x11` 以规避一个历史上的原生 Wayland 崩溃。在较新的 Wayland + NVIDIA 环境上,这个被强制的 XWayland 会让 WebKitGTK 网页内容收不到指针事件(标题栏可点、页面却死了)、并在缩放时黑屏,而既有的 `WEBKIT_DISABLE_*` 缓解不起作用,因为根因是被强制的窗口后端而非渲染。`main.rs` 现在会在 GTK 初始化前读取一个可选的 `CC_SWITCH_GDK_BACKEND` 逃生开关(AppImage 的启动钩子从不改动它):不设保持现状(零回归)。遇到上述问题时,用它切回原生 Wayland 启动即可:
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
该覆盖是通用的——若你在平铺式 Wayland 合成器上遇到的是反向的输入问题,则改设为 `CC_SWITCH_GDK_BACKEND=x11`。([#4351](https://github.com/farion1231/cc-switch/pull/4351),修复 #4350
### Claude Desktop / OpenClaw / Hermes 表单显示「获取 API Key」链接
API key 输入框下的「获取 API Key」链接与合作推广块此前只对 claude / codex / gemini / opencode 生效。Claude Desktop 渲染的是不显示它的裸输入框,而 OpenClaw / Hermes 则被两处遗漏挡住(白名单只列了那四个 appId、供应商分类解析只认那四类预设 id 模式)。现在 Claude Desktop 改用共享的 `ApiKeySection`,白名单与分类解析都补上了 claude-desktop / openclaw / hermes;此外 Hermes / OpenClaw 表单不再让「官方」分类禁用 key 输入(这两个应用没有只走 OAuth 的官方供应商,如 Hermes 的 Nous Research 虽是官方但仍需用户自填 key)。
### 去重 Windows 上的 Codex npm 影子命令
在 Windows 上,npm 会把一个工具装成三个同名兄弟文件——`codex.cmd``codex.exe` 和一个无扩展名的 Unix shim `codex`——而 CC Switch 此前把三者都列为候选,导致无法直接执行的无扩展名 shim 被当作多余 / 失败候选去探测。现在仅当相邻没有可执行的 `.cmd` / `.exe` 兄弟时才追加无扩展名路径,路径解析也会优先选可执行的 `.cmd` / `.exe`,从而把版本探测与启动锚定到真正可运行的 Windows shim 上。([#4782](https://github.com/farion1231/cc-switch/pull/4782)
### 长下拉列表的滚动边界
`SelectContent` 弹层此前用 `overflow-hidden` 且没有高度上限,因此选项很多的下拉(如长模型 / 供应商列表)会渲染得比视口还高、把溢出项裁掉且无法触及。现在它设了 `max-h-[min(24rem,var(--radix-select-content-available-height))]``overflow-y-auto`,把内容限制在 24rem 或 Radix 计算出的可用高度内并允许纵向滚动。([#4798](https://github.com/farion1231/cc-switch/pull/4798)
### 日期范围选择器的日历在窄弹层里保持可见
自定义日期范围选择器此前按**视口宽度**(Tailwind `sm:` 640px 断点)切换两列布局(日期字段 | 日历),但弹层被夹在 `100vw - 2rem` 且锚定到触发器,实际可用宽度比视口窄。在窄窗口上,两列布局可能在弹层只放得下一列时被激活,把日历列挤出右边界裁掉(月份头与 7 列里的 4 列被切掉且无法触及)。现在布局改用 **CSS 容器查询**按弹层自身的行内尺寸切换,因此只有当弹层本身窄时才收成一列,让日历在任意窗口宽度下都完整可见。([#4860](https://github.com/farion1231/cc-switch/pull/4860)
---
## 文档
### `CC_SWITCH_GDK_BACKEND` 逃生开关文档
为可选的 `CC_SWITCH_GDK_BACKEND` 环境变量新增了 FAQ 条目,覆盖全部四种 README 语言与 zh / en / ja 用户手册的排障页,说明 Wayland + NVIDIA 用户如何在网页内容「点击失灵 + 缩放黑屏」时切回原生 Wayland,以及平铺式 Wayland 用户如何设为 `x11` 处理反向输入问题。
### Kimi 海外 README 指向 platform.kimi.ai
英语、德语、日语 README 的 Kimi K2.7 Code 合作段落的横幅与内联行动号召改指 `https://platform.kimi.ai?aff=cc-switch`(保留推荐标签),四语 README 也都新增了一行指向 `https://www.kimi.com/code/?aff=cc-switch` 的 Kimi For Coding 订阅推广。
---
## 升级提醒
### 原生 Codex 供应商需重存一次
本版重做了原生 Responses 直连的模型目录生成。如果你此前配过使用原生 Responses(`openai_responses`)的 Codex 供应商,请**重新从预设选择或打开该供应商并保存一次**,以生成新的 `~/.codex/cc-switch-model-catalog.json`——这样 Codex 桌面才能显示自定义模型、工具才可用。此过程无需数据库迁移,也不影响走 `openai_chat` 格式的供应商。
### `web_search` 黑名单是默认行为
对小米 MiMo、美团 LongCat、MiniMax、千问 Qwen3-Coder 这些已知拒收 `web_search` 的原生网关,本版会在切换时自动写入 `web_search = "disabled"`。中转真 GPT、豆包、通用 Qwen 及未知供应商不受影响、保持 Codex 默认。该开关由 CC Switch 用归属哨兵管理,切回到未命中黑名单的供应商会自动恢复,无需手动干预。
### 默认 Sonnet 档变化
新从预设创建的 Claude 类供应商,其默认 Sonnet 档现在指向 `claude-sonnet-5`。已配置好的存量供应商不受影响、配置保持原样;如需改用 Sonnet 5,可重新从预设选择一次并保存。
---
## 风险提示
本版本继续沿用此前版本对反向代理类功能的风险提示。
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#-风险提示)。
**Codex 第三方供应商 Chat 路由**:通过 CC Switch 本地代理把 Codex 请求转换并转发到第三方供应商时,各供应商对计费、合规与数据留存的约束不同,请在使用前阅读目标供应商的服务条款。
**Claude Desktop 第三方供应商代理切换**:通过 CC Switch 内置代理网关把 Claude Desktop 的请求转到第三方供应商时,同样需要遵守目标供应商的计费、合规与数据留存约束。
用户启用上述功能即表示自行承担相关风险。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
---
## 致谢
感谢以下贡献者在 v3.16.5 中提交的功能与修复:
- [#4776](https://github.com/farion1231/cc-switch/pull/4776):新增会话分类视图与分组管理,感谢 @alkaid616
- [#4829](https://github.com/farion1231/cc-switch/pull/4829):把「写入通用配置」更名为「应用通用配置」,感谢 @arichyx
- [#4654](https://github.com/farion1231/cc-switch/pull/4654):让用量脚本凭据仅作显式覆盖持久化,感谢 @yyhhyyyyyy
- [#4680](https://github.com/farion1231/cc-switch/pull/4680):修复 Windows 上 Hermes 供应商配置不生效,感谢 @thisTom
- [#4782](https://github.com/farion1231/cc-switch/pull/4782):去重 Windows 上的 Codex npm 影子命令,感谢 @justjavac
- [#4798](https://github.com/farion1231/cc-switch/pull/4798):修复长下拉列表无法滚动,感谢 @xwil1
- [#4351](https://github.com/farion1231/cc-switch/pull/4351):允许通过 `CC_SWITCH_GDK_BACKEND` 覆盖 AppImage 强制的 `GDK_BACKEND=x11`,感谢 @BoneLiu
- [#4860](https://github.com/farion1231/cc-switch/pull/4860):让日期范围选择器的日历在窄弹层里保持可见,感谢 @SaladDay
也感谢所有在 v3.16.4 发布后反馈 Codex 原生直连、通用配置、凭据复用与平台兼容性问题的用户,很多补丁都来自这些真实使用场景里的复现线索。
---
## 下载与安装
访问 [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.16.5-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.16.5-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
Windows ARM64 设备请选择文件名中带 `arm64` 标识的对应制品。
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.16.5-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.16.5-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.16.5-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
Homebrew 安装:
```bash
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
Linux 资产同时提供 **x86_64****ARM64**`aarch64`)两种架构。资产文件名中包含架构标识,请按你机器的 `uname -m` 输出选择对应版本:
- `CC-Switch-v3.16.5-Linux-x86_64.AppImage` / `.deb` / `.rpm`
- `CC-Switch-v3.16.5-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` |
+364
View File
@@ -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>
+362
View File
@@ -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 CodexCodex 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 Hy3256K 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` |
+362
View File
@@ -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 CodexCodex 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 / 372000Kimi 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` | 解压后拖入 ApplicationsUniversal 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
View File
@@ -554,7 +554,7 @@ When editing Claude providers, a set of **quick toggles** is available above the
When a toggle is unchecked, its corresponding config entry is removed entirely. Changes are reflected in the JSON editor in real-time.
Additionally, the **Write Common Config** checkbox enables merging a global config snippet into the provider. Click **Edit Common Config** to customize the shared snippet.
Additionally, the **Apply Common Config** checkbox enables merging a global config snippet into the provider. Click **Edit Common Config** to customize the shared snippet.
### Codex Local Routing and Model Mapping
@@ -29,6 +29,22 @@ chmod +x CC-Switch-*.AppImage
./CC-Switch-*.AppImage --no-sandbox
```
### Linux: Clicks Don't Register / Black Screen on Resize (Wayland + NVIDIA)
**Problem**: The web content area is completely unclickable (the title-bar minimize/maximize/close buttons still work), and the window black-screens on resize or maximize-restore. Common on Wayland sessions with an NVIDIA GPU.
**Cause**: The AppImage's GTK launch hook unconditionally forces `GDK_BACKEND=x11` (XWayland) to dodge a historical native-Wayland crash. On newer Wayland + NVIDIA setups, forced XWayland leaves the WebKitGTK web content unable to receive pointer events. The existing `WEBKIT_DISABLE_*` mitigations don't help here because the root cause is the forced window backend, not rendering.
**Solution**: Use the dedicated `CC_SWITCH_GDK_BACKEND` environment variable to switch back to native Wayland (it is read before GTK init, and the hook never overrides it):
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
- When launching from a desktop icon, add it to the `.desktop` `Exec=` line (e.g. `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`) or set it in your session environment — otherwise an icon launch won't see the variable.
- The variable is generic: on tiling Wayland compositors (sway/Hyprland) where clicks don't register, set `CC_SWITCH_GDK_BACKEND=x11` instead.
- Leaving it unset behaves exactly as before (still x11), with no side effects.
## Provider Issues
### Provider Switch Doesn't Take Effect
+1 -1
View File
@@ -554,7 +554,7 @@ Claude プロバイダーの編集時、JSON エディタの上部に **クイ
トグルのチェックを外すと、対応する設定エントリが完全に削除されます。変更は JSON エディタにリアルタイムで反映されます。
また、**共通設定を書き込み** チェックボックスを有効にすると、グローバル設定スニペットをプロバイダーにマージできます。**共通設定を編集** をクリックして共有スニペットをカスタマイズできます。
また、**共通設定を適用** チェックボックスを有効にすると、グローバル設定スニペットをプロバイダーにマージできます。**共通設定を編集** をクリックして共有スニペットをカスタマイズできます。
### Codex ローカルルーティングとモデルマッピング
@@ -29,6 +29,22 @@ chmod +x CC-Switch-*.AppImage
./CC-Switch-*.AppImage --no-sandbox
```
### Linux:クリックが効かない / リサイズで黒画面(Wayland + NVIDIA
**問題**:Web コンテンツ領域がまったくクリックできません(タイトルバーの最小化/最大化/閉じるボタンは動作します)。ウィンドウのリサイズや最大化-復元後に黒画面になります。Wayland セッション + NVIDIA GPU でよく発生します。
**原因**AppImage の GTK 起動フックが、過去のネイティブ Wayland クラッシュを避けるために `GDK_BACKEND=x11`(XWayland)を無条件で強制します。新しい Wayland + NVIDIA 環境では、強制された XWayland によって WebKitGTK の Web コンテンツがポインタイベントを受け取れなくなります。既存の `WEBKIT_DISABLE_*` の緩和策は、根本原因が強制されたウィンドウバックエンドであり描画ではないため、ここでは効きません。
**解決方法**:専用の環境変数 `CC_SWITCH_GDK_BACKEND` でネイティブ Wayland に戻します(GTK 初期化前に読み取られ、フックが上書きしません):
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
- デスクトップアイコンから起動する場合は、`.desktop``Exec=` 行に追記するか(例:`env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`)、セッション環境で設定してください。そうしないとアイコン起動では変数が読み取られません。
- この変数は汎用です:タイル型 Wayland コンポジタ(sway/Hyprland)でクリックが効かない場合は、`CC_SWITCH_GDK_BACKEND=x11` を設定してください。
- 未設定の場合は現状とまったく同じ動作(x11 のまま)で、副作用はありません。
## プロバイダーに関する問題
### プロバイダーを切り替えても反映されない
+1 -1
View File
@@ -554,7 +554,7 @@ v3.13.0 起新增的高级选项。默认情况下,CC Switch 会把配置的 `
取消勾选开关时,对应的配置项会被完全移除。更改会实时反映在 JSON 编辑器中。
此外,**写入通用配置** 复选框可将全局配置片段合并到供应商中。点击 **编辑通用配置** 可自定义共享的配置片段。
此外,**应用通用配置** 复选框可将全局配置片段合并到供应商中。点击 **编辑通用配置** 可自定义共享的配置片段。
### Codex 本地路由与模型映射
@@ -29,6 +29,22 @@ chmod +x CC-Switch-*.AppImage
./CC-Switch-*.AppImage --no-sandbox
```
### Linux 点击无响应 / 缩放后黑屏(Wayland + NVIDIA
**问题**:主界面网页内容区完全点不动(标题栏的最小化/最大化/关闭仍可点),窗口缩放或最大化-还原后黑屏。常见于 Wayland 会话 + NVIDIA 显卡。
**原因**AppImage 的 GTK 启动钩子会无条件强制 `GDK_BACKEND=x11`(走 XWayland)以规避历史上的原生 Wayland 崩溃;但在较新的 Wayland + NVIDIA 环境下,强制 XWayland 反而使 WebKitGTK 的网页内容收不到指针事件。现有的 `WEBKIT_DISABLE_*` 缓解措施对此无效,因为根因是被强制的窗口后端,而非渲染。
**解决方法**:用专用环境变量 `CC_SWITCH_GDK_BACKEND` 切回原生 Wayland(该开关在 GTK 初始化前生效,钩子不会覆盖它):
```bash
CC_SWITCH_GDK_BACKEND=wayland ./CC-Switch-*.AppImage
```
- 从桌面图标启动时,把它写进 `.desktop``Exec=` 行(如 `env CC_SWITCH_GDK_BACKEND=wayland /path/to/AppImage`),或在会话环境中设置,否则图标启动读不到该变量。
- 该变量是通用的:在 tiling Wayland 合成器(sway/Hyprland)下若反而出现点击失效,可设 `CC_SWITCH_GDK_BACKEND=x11`
- 不设置时行为与现状完全一致(仍走 x11),无副作用。
## 供应商问题
### 切换供应商后不生效
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
"version": "3.16.4",
"version": "3.17.0",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
+4
View File
@@ -2,3 +2,7 @@ packages: []
onlyBuiltDependencies:
- '@tailwindcss/oxide'
- esbuild
ignoredBuiltDependencies:
- msw
+1 -1
View File
@@ -758,7 +758,7 @@ dependencies = [
[[package]]
name = "cc-switch"
version = "3.16.4"
version = "3.17.0"
dependencies = [
"anyhow",
"arboard",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
version = "3.16.4"
version = "3.17.0"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
+3 -3
View File
@@ -46,7 +46,7 @@ pub struct ClaudeDesktopDefaultRoute {
pub const DEFAULT_PROXY_ROUTES: &[ClaudeDesktopDefaultRoute] = &[
ClaudeDesktopDefaultRoute {
route_id: "claude-sonnet-4-6",
route_id: "claude-sonnet-5",
env_key: "ANTHROPIC_DEFAULT_SONNET_MODEL",
supports_1m: true,
},
@@ -1966,9 +1966,9 @@ mod tests {
},
),
(
"claude-sonnet-4-6".to_string(),
"claude-sonnet-5".to_string(),
ClaudeDesktopModelRoute {
model: "claude-sonnet-4-6".to_string(),
model: "claude-sonnet-5".to_string(),
label_override: None,
supports_1m: Some(false),
},
File diff suppressed because it is too large Load Diff
+2 -50
View File
@@ -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;
+98
View File
@@ -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),
]
);
}
}
+3 -2
View File
@@ -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
View File
@@ -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
}
+17
View File
@@ -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,
+1 -7
View File
@@ -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())
}
+52 -4
View File
@@ -1445,11 +1445,15 @@ fn opencode_extra_search_paths(
fn tool_executable_candidates(tool: &str, dir: &Path) -> Vec<std::path::PathBuf> {
#[cfg(target_os = "windows")]
{
vec![
let extensionless = dir.join(tool);
let mut candidates = vec![
dir.join(format!("{tool}.cmd")),
dir.join(format!("{tool}.exe")),
dir.join(tool),
]
];
if windows_runnable_sibling_for_extensionless_tool(&extensionless).is_none() {
candidates.push(extensionless);
}
candidates
}
#[cfg(not(target_os = "windows"))]
@@ -1619,6 +1623,18 @@ fn is_windows_command_script(path: &Path) -> bool {
.unwrap_or(false)
}
#[cfg(target_os = "windows")]
fn windows_runnable_sibling_for_extensionless_tool(path: &Path) -> Option<std::path::PathBuf> {
if path.extension().is_some() {
return None;
}
["cmd", "exe"]
.iter()
.map(|ext| path.with_extension(ext))
.find(|candidate| candidate.is_file())
}
#[cfg(target_os = "windows")]
fn run_windows_tool_version_command(
tool_path: &Path,
@@ -1821,7 +1837,10 @@ fn resolve_path_default(tool: &str) -> Option<std::path::PathBuf> {
if first.is_empty() {
return None;
}
std::fs::canonicalize(first).ok()
let path = Path::new(first);
let preferred =
windows_runnable_sibling_for_extensionless_tool(path).unwrap_or_else(|| path.to_path_buf());
std::fs::canonicalize(preferred).ok()
}
/// 枚举工具在系统中的所有安装(不短路)。与 `scan_cli_version` 共用
@@ -5063,6 +5082,35 @@ mod tests {
);
}
#[cfg(target_os = "windows")]
#[test]
fn tool_executable_candidates_windows_skips_shadowed_npm_unix_shim() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let extensionless = dir.path().join("codex");
let cmd = dir.path().join("codex.cmd");
std::fs::write(&extensionless, "").expect("extensionless shim should be created");
std::fs::write(&cmd, "").expect("cmd shim should be created");
let candidates = tool_executable_candidates("codex", dir.path());
assert_eq!(candidates, vec![cmd.clone(), dir.path().join("codex.exe")]);
assert!(!candidates.contains(&extensionless));
}
#[cfg(target_os = "windows")]
#[test]
fn windows_runnable_sibling_prefers_cmd_over_extensionless_tool() {
let dir = tempfile::tempdir().expect("temp dir should be created");
let extensionless = dir.path().join("codex");
let cmd = dir.path().join("codex.cmd");
std::fs::write(&extensionless, "").expect("extensionless shim should be created");
std::fs::write(&cmd, "").expect("cmd shim should be created");
let preferred = windows_runnable_sibling_for_extensionless_tool(&extensionless);
assert_eq!(preferred.as_deref(), Some(cmd.as_path()));
}
#[test]
fn resolve_launch_cwd_accepts_existing_directory() {
let resolved =
+2
View File
@@ -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::*;
+195
View File
@@ -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)
}
+51 -52
View File
@@ -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(
// 其他供应商为 Noneservice 层沿用 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}"))?;
@@ -888,9 +902,7 @@ mod import_claude_desktop_tests {
None,
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
let r = routes
.get("claude-sonnet-4-6")
.expect("sonnet route present");
let r = routes.get("claude-sonnet-5").expect("sonnet route present");
assert_eq!(r.model, "claude-sonnet-4-5-20250929");
assert!(
!r.model.to_ascii_lowercase().contains("[1m]"),
@@ -909,9 +921,7 @@ mod import_claude_desktop_tests {
None,
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
let r = routes
.get("claude-sonnet-4-6")
.expect("sonnet route present");
let r = routes.get("claude-sonnet-5").expect("sonnet route present");
assert_eq!(r.model, "kimi-k2");
assert_eq!(r.label_override.as_deref(), Some("kimi-k2"));
// 默认 provider_type 缺省 → supports_1m_default = true
@@ -928,9 +938,7 @@ mod import_claude_desktop_tests {
None,
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
let r = routes
.get("claude-sonnet-4-6")
.expect("sonnet route present");
let r = routes.get("claude-sonnet-5").expect("sonnet route present");
assert_eq!(r.model, "kimi-k2");
assert_eq!(r.label_override.as_deref(), Some("Kimi K2"));
}
@@ -945,9 +953,7 @@ mod import_claude_desktop_tests {
Some("github_copilot"),
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
let r = routes
.get("claude-sonnet-4-6")
.expect("sonnet route present");
let r = routes.get("claude-sonnet-5").expect("sonnet route present");
assert_eq!(r.model, "gpt-5-codex");
assert_eq!(r.label_override.as_deref(), Some("gpt-5-codex"));
assert_eq!(r.supports_1m, Some(true));
@@ -962,9 +968,7 @@ mod import_claude_desktop_tests {
Some("github_copilot"),
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
let r = routes
.get("claude-sonnet-4-6")
.expect("sonnet route present");
let r = routes.get("claude-sonnet-5").expect("sonnet route present");
assert_eq!(r.model, "gpt-5-codex");
assert_eq!(r.label_override.as_deref(), Some("gpt-5-codex"));
assert_eq!(r.supports_1m, Some(false));
@@ -982,9 +986,7 @@ mod import_claude_desktop_tests {
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
assert_eq!(routes.len(), 1, "three aliases → one merged route");
let r = routes
.get("claude-sonnet-4-6")
.expect("merged route present");
let r = routes.get("claude-sonnet-5").expect("merged route present");
assert_eq!(r.model, "MiniMax-M2");
assert_eq!(r.label_override.as_deref(), Some("MiniMax-M2"));
}
@@ -1002,9 +1004,7 @@ mod import_claude_desktop_tests {
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
assert_eq!(routes.len(), 1);
let r = routes
.get("claude-sonnet-4-6")
.expect("merged route present");
let r = routes.get("claude-sonnet-5").expect("merged route present");
assert_eq!(r.supports_1m, Some(true));
}
@@ -1020,12 +1020,12 @@ mod import_claude_desktop_tests {
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
assert_eq!(routes.len(), 3);
assert_eq!(routes.get("claude-sonnet-4-6").unwrap().model, "GLM-4.6");
assert_eq!(routes.get("claude-sonnet-5").unwrap().model, "GLM-4.6");
assert_eq!(routes.get("claude-opus-4-8").unwrap().model, "GLM-4-Air");
assert_eq!(routes.get("claude-haiku-4-5").unwrap().model, "GLM-4-Flash");
assert_eq!(
routes
.get("claude-sonnet-4-6")
.get("claude-sonnet-5")
.unwrap()
.label_override
.as_deref(),
@@ -1045,7 +1045,7 @@ mod import_claude_desktop_tests {
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
assert_eq!(routes.len(), 1);
let r = routes
.get("claude-sonnet-4-6")
.get("claude-sonnet-5")
.expect("fallback route present");
assert_eq!(r.model, "kimi-k2");
assert_eq!(r.label_override.as_deref(), Some("kimi-k2"));
@@ -1060,13 +1060,10 @@ mod import_claude_desktop_tests {
None,
);
let routes = suggested_claude_desktop_routes(&p).expect("routes built");
assert!(routes.contains_key("claude-sonnet-4-6"));
assert!(routes.contains_key("claude-sonnet-5"));
assert!(!routes.contains_key("claude-claude-sonnet-4-5-20250929"));
assert_eq!(
routes
.get("claude-sonnet-4-6")
.expect("route")
.label_override,
routes.get("claude-sonnet-5").expect("route").label_override,
None
);
}
@@ -1098,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,
}
}
+8 -2
View File
@@ -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(),
-9
View File
@@ -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)
+6
View File
@@ -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;
+22 -21
View File
@@ -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
}
+3 -1
View File
@@ -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;
+207
View File
@@ -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(&current_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(())
}
}
+22 -1
View File
@@ -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");
+2 -1
View File
@@ -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",
+17
View File
@@ -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健康状态
+42 -4
View File
@@ -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()?;
+5 -2
View File
@@ -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> {
+195
View File
@@ -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 返回的模型名称标准化后一致
@@ -1301,6 +1385,15 @@ impl Database {
"0.50",
"6.25",
),
// Claude Sonnet 5list 价,与 Sonnet 4.6 一致;促销 $2/$10 至 2026-08-31 不入表)
(
"claude-sonnet-5",
"Claude Sonnet 5",
"3",
"15",
"0.30",
"3.75",
),
// Claude 4.7 系列
(
"claude-opus-4-7",
@@ -1394,6 +1487,25 @@ impl Database {
"0.30",
"3.75",
),
// GPT-5.6 系列(Sol / Terra / Luna2026-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"),
@@ -1831,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"),
(
@@ -2126,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 一致)
(
@@ -2593,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(())
}
}
+56
View File
@@ -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");
+46 -14
View File
@@ -185,6 +185,48 @@ fn get_primary_endpoint(request: &DeepLinkImportRequest) -> String {
.unwrap_or_default()
}
fn normalize_deeplink_api_key(api_key: &str) -> String {
api_key.trim().to_string()
}
fn normalize_deeplink_base_url(base_url: &str) -> String {
base_url.trim().trim_end_matches('/').to_string()
}
fn usage_api_key_override(request: &DeepLinkImportRequest) -> Option<String> {
let usage_api_key = normalize_deeplink_api_key(request.usage_api_key.as_deref()?);
if usage_api_key.is_empty() {
return None;
}
let provider_api_key = request
.api_key
.as_deref()
.map(normalize_deeplink_api_key)
.unwrap_or_default();
if !provider_api_key.is_empty() && usage_api_key == provider_api_key {
None
} else {
Some(usage_api_key)
}
}
fn usage_base_url_override(request: &DeepLinkImportRequest) -> Option<String> {
let usage_base_url = normalize_deeplink_base_url(request.usage_base_url.as_deref()?);
if usage_base_url.is_empty() {
return None;
}
let provider_base_url = normalize_deeplink_base_url(&get_primary_endpoint(request));
if !provider_base_url.is_empty() && usage_base_url == provider_base_url {
None
} else {
Some(usage_base_url)
}
}
/// Build provider meta with usage script configuration
fn build_provider_meta(request: &DeepLinkImportRequest) -> Result<Option<ProviderMeta>, AppError> {
// Check if any usage script fields are provided
@@ -211,25 +253,13 @@ fn build_provider_meta(request: &DeepLinkImportRequest) -> Result<Option<Provide
// Determine enabled state: explicit param > has code > false
let enabled = request.usage_enabled.unwrap_or(!code.is_empty());
// Build UsageScript - use provider's API key and endpoint as defaults
// Note: use primary endpoint only (first one if comma-separated)
let usage_script = UsageScript {
enabled,
language: "javascript".to_string(),
code,
timeout: Some(10),
api_key: request
.usage_api_key
.clone()
.or_else(|| request.api_key.clone()),
base_url: request.usage_base_url.clone().or_else(|| {
let primary = get_primary_endpoint(request);
if primary.is_empty() {
None
} else {
Some(primary)
}
}),
api_key: usage_api_key_override(request),
base_url: usage_base_url_override(request),
access_token: request.usage_access_token.clone(),
user_id: request.usage_user_id.clone(),
template_type: None, // Deeplink providers don't specify template type (will use backward compatibility logic)
@@ -237,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 {
+148
View File
@@ -260,6 +260,154 @@ fn test_build_gemini_provider_without_model() {
assert!(env.get("GEMINI_MODEL").is_none());
}
#[test]
fn test_deeplink_usage_script_does_not_copy_provider_credentials() {
use super::provider::build_provider_from_request;
let request = DeepLinkImportRequest {
version: "v1".to_string(),
resource: "provider".to_string(),
app: Some("claude".to_string()),
name: Some("Test Claude".to_string()),
homepage: Some("https://example.com".to_string()),
endpoint: Some("https://api.example.com/v1/".to_string()),
api_key: Some("sk-main".to_string()),
icon: None,
model: None,
notes: None,
haiku_model: None,
sonnet_model: None,
opus_model: None,
config: None,
config_format: None,
config_url: None,
apps: None,
repo: None,
directory: None,
branch: None,
content: None,
description: None,
enabled: None,
usage_enabled: Some(true),
usage_script: None,
usage_api_key: None,
usage_base_url: None,
usage_access_token: None,
usage_user_id: None,
usage_auto_interval: None,
};
let provider = build_provider_from_request(&AppType::Claude, &request).unwrap();
let script = provider
.meta
.as_ref()
.and_then(|meta| meta.usage_script.as_ref())
.expect("usage script should be created");
assert!(script.enabled);
assert_eq!(script.api_key, None);
assert_eq!(script.base_url, None);
}
#[test]
fn test_deeplink_usage_script_omits_explicit_credentials_that_match_provider() {
use super::provider::build_provider_from_request;
let request = DeepLinkImportRequest {
version: "v1".to_string(),
resource: "provider".to_string(),
app: Some("claude".to_string()),
name: Some("Test Claude".to_string()),
homepage: Some("https://example.com".to_string()),
endpoint: Some("https://api.example.com/v1/".to_string()),
api_key: Some("sk-main".to_string()),
icon: None,
model: None,
notes: None,
haiku_model: None,
sonnet_model: None,
opus_model: None,
config: None,
config_format: None,
config_url: None,
apps: None,
repo: None,
directory: None,
branch: None,
content: None,
description: None,
enabled: None,
usage_enabled: Some(true),
usage_script: None,
usage_api_key: Some(" sk-main ".to_string()),
usage_base_url: Some(" https://api.example.com/v1/ ".to_string()),
usage_access_token: None,
usage_user_id: None,
usage_auto_interval: None,
};
let provider = build_provider_from_request(&AppType::Claude, &request).unwrap();
let script = provider
.meta
.as_ref()
.and_then(|meta| meta.usage_script.as_ref())
.expect("usage script should be created");
assert_eq!(script.api_key, None);
assert_eq!(script.base_url, None);
}
#[test]
fn test_deeplink_usage_script_preserves_distinct_usage_credentials() {
use super::provider::build_provider_from_request;
let request = DeepLinkImportRequest {
version: "v1".to_string(),
resource: "provider".to_string(),
app: Some("claude".to_string()),
name: Some("Test Claude".to_string()),
homepage: Some("https://example.com".to_string()),
endpoint: Some("https://api.example.com/v1".to_string()),
api_key: Some("sk-main".to_string()),
icon: None,
model: None,
notes: None,
haiku_model: None,
sonnet_model: None,
opus_model: None,
config: None,
config_format: None,
config_url: None,
apps: None,
repo: None,
directory: None,
branch: None,
content: None,
description: None,
enabled: None,
usage_enabled: Some(true),
usage_script: None,
usage_api_key: Some(" sk-usage ".to_string()),
usage_base_url: Some(" https://usage.example/api/ ".to_string()),
usage_access_token: None,
usage_user_id: None,
usage_auto_interval: None,
};
let provider = build_provider_from_request(&AppType::Claude, &request).unwrap();
let script = provider
.meta
.as_ref()
.and_then(|meta| meta.usage_script.as_ref())
.expect("usage script should be created");
assert_eq!(script.api_key.as_deref(), Some("sk-usage"));
assert_eq!(
script.base_url.as_deref(),
Some("https://usage.example/api")
);
}
#[test]
fn test_parse_and_merge_config_claude() {
// Prepare Base64 encoded Claude config
+250 -2
View File
@@ -46,16 +46,55 @@ use std::sync::{Mutex, OnceLock};
/// 获取 Hermes 配置目录
///
/// 默认路径: `~/.hermes/`
/// 可通过 settings.hermes_config_dir 覆盖
/// 解析顺序对齐 Hermes 自身的 `get_hermes_home()`:
/// 1. CCS 设置 `hermes_config_dir`(显式覆盖)
/// 2. `HERMES_HOME` 环境变量(trim 后非空;按原样,不展开 `~`,与 Hermes `Path(val)` 一致)
/// 3. 平台默认(Windows: `%LOCALAPPDATA%\hermes`,Mac/Linux: `~/.hermes`)
pub fn get_hermes_dir() -> PathBuf {
if let Some(override_dir) = get_hermes_override_dir() {
return override_dir;
}
if let Some(raw) = std::env::var_os("HERMES_HOME") {
let value = raw.to_string_lossy();
let trimmed = value.trim();
if !trimmed.is_empty() {
return PathBuf::from(trimmed);
}
}
default_hermes_dir()
}
/// 平台默认 Hermes 目录(Windows):对齐 Hermes `_get_platform_default_hermes_home()`——
/// 读 `LOCALAPPDATA` 环境变量,缺失/空时回退 `~\AppData\Local`,再拼 `hermes`。
#[cfg(target_os = "windows")]
fn default_hermes_dir() -> PathBuf {
windows_local_hermes_dir(
std::env::var_os("LOCALAPPDATA").as_deref(),
&crate::config::get_home_dir(),
)
}
/// 平台默认 Hermes 目录(Mac/Linux):`~/.hermes`。
#[cfg(not(target_os = "windows"))]
fn default_hermes_dir() -> PathBuf {
crate::config::get_home_dir().join(".hermes")
}
/// Windows `%LOCALAPPDATA%\hermes` 路径计算(纯函数,便于跨平台单测)。
/// 对齐 Hermes 的 `os.environ.get("LOCALAPPDATA", "").strip()`:trim 后为空
/// (缺失/空/纯空白)则回退 `<home>\AppData\Local\hermes`。
#[cfg(any(target_os = "windows", test))]
fn windows_local_hermes_dir(localappdata: Option<&std::ffi::OsStr>, home: &Path) -> PathBuf {
localappdata
.map(|value| value.to_string_lossy().trim().to_string())
.filter(|value| !value.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData").join("Local"))
.join("hermes")
}
/// 获取 Hermes 配置文件路径
///
/// 返回 `~/.hermes/config.yaml`
@@ -1120,7 +1159,22 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let old_test_home = std::env::var_os("CC_SWITCH_TEST_HOME");
std::env::set_var("CC_SWITCH_TEST_HOME", tmp.path());
// Neutralize the env vars get_hermes_dir() consults, so an ambient
// HERMES_HOME / LOCALAPPDATA (e.g. set by a Hermes install) can't make
// tests escape the temp home. Restored below.
let old_hermes_home = std::env::var_os("HERMES_HOME");
let old_local_appdata = std::env::var_os("LOCALAPPDATA");
std::env::remove_var("HERMES_HOME");
std::env::remove_var("LOCALAPPDATA");
let result = test_fn();
match old_local_appdata {
Some(value) => std::env::set_var("LOCALAPPDATA", value),
None => std::env::remove_var("LOCALAPPDATA"),
}
match old_hermes_home {
Some(value) => std::env::set_var("HERMES_HOME", value),
None => std::env::remove_var("HERMES_HOME"),
}
match old_test_home {
Some(value) => std::env::set_var("CC_SWITCH_TEST_HOME", value),
None => std::env::remove_var("CC_SWITCH_TEST_HOME"),
@@ -2193,4 +2247,198 @@ user_profile_enabled: false
assert_eq!(user, MemoryKind::User);
assert!(serde_json::from_str::<MemoryKind>("\"bogus\"").is_err());
}
// ---- get_hermes_dir resolution (platform default + HERMES_HOME) ----
#[test]
#[serial]
fn hermes_home_env_takes_precedence_over_platform_default() {
with_test_home(|| {
// Clear any settings override so resolution reaches the HERMES_HOME branch.
let mut s = crate::settings::get_settings();
s.hermes_config_dir = None;
crate::settings::update_settings(s).unwrap();
let old = std::env::var_os("HERMES_HOME");
let custom = std::env::temp_dir().join("ccs-hermes-home-precedence");
std::env::set_var("HERMES_HOME", &custom);
let dir = get_hermes_dir();
match old {
Some(v) => std::env::set_var("HERMES_HOME", v),
None => std::env::remove_var("HERMES_HOME"),
}
assert_eq!(
dir, custom,
"HERMES_HOME should take precedence over the platform default, got {dir:?}"
);
});
}
#[test]
#[serial]
fn settings_override_takes_precedence_over_hermes_home() {
with_test_home(|| {
let custom = tempfile::tempdir().unwrap();
let custom_path = custom.path().to_path_buf();
let mut s = crate::settings::get_settings();
s.hermes_config_dir = Some(custom_path.to_string_lossy().to_string());
crate::settings::update_settings(s).unwrap();
let old = std::env::var_os("HERMES_HOME");
std::env::set_var("HERMES_HOME", "/tmp/should-be-ignored");
let dir = get_hermes_dir();
match old {
Some(v) => std::env::set_var("HERMES_HOME", v),
None => std::env::remove_var("HERMES_HOME"),
}
let mut s = crate::settings::get_settings();
s.hermes_config_dir = None;
crate::settings::update_settings(s).unwrap();
assert_eq!(
dir, custom_path,
"settings override should win over HERMES_HOME, got {dir:?}"
);
});
}
#[test]
#[serial]
fn blank_hermes_home_falls_through_to_platform_default() {
with_test_home(|| {
let mut s = crate::settings::get_settings();
s.hermes_config_dir = None;
crate::settings::update_settings(s).unwrap();
let old = std::env::var_os("HERMES_HOME");
std::env::set_var("HERMES_HOME", " ");
let dir = get_hermes_dir();
match old {
Some(v) => std::env::set_var("HERMES_HOME", v),
None => std::env::remove_var("HERMES_HOME"),
}
// Blank HERMES_HOME is ignored (matches Hermes' `.strip()` non-empty check),
// so resolution must reach the platform default, never the literal blank path.
assert_ne!(dir, PathBuf::from(" "));
assert_eq!(dir, default_hermes_dir());
});
}
#[test]
#[serial]
fn default_hermes_dir_without_override_is_platform_correct() {
with_test_home(|| {
let mut s = crate::settings::get_settings();
s.hermes_config_dir = None;
crate::settings::update_settings(s).unwrap();
let old = std::env::var_os("HERMES_HOME");
std::env::remove_var("HERMES_HOME");
let dir = get_hermes_dir();
if let Some(v) = old {
std::env::set_var("HERMES_HOME", v);
}
#[cfg(target_os = "windows")]
assert!(
dir.ends_with("hermes") && dir.to_string_lossy().to_lowercase().contains("local"),
"Windows default should be %LOCALAPPDATA%\\hermes, got {dir:?}"
);
#[cfg(not(target_os = "windows"))]
assert!(
dir.ends_with(".hermes"),
"Unix default should be ~/.hermes, got {dir:?}"
);
});
}
#[test]
fn windows_local_hermes_dir_uses_localappdata_when_set() {
let local = std::ffi::OsString::from("C:\\Users\\tester\\AppData\\Local");
let home = Path::new("C:\\Users\\tester");
// Uses LOCALAPPDATA (ignoring home) and appends `hermes`. Build the expected
// path with `join` so the separator matches the host OS.
assert_eq!(
windows_local_hermes_dir(Some(local.as_os_str()), home),
PathBuf::from(&local).join("hermes"),
);
}
#[test]
fn windows_local_hermes_dir_falls_back_to_home_when_localappdata_missing_or_empty() {
let home = Path::new("C:\\Users\\tester");
let expected = home.join("AppData").join("Local").join("hermes");
assert_eq!(windows_local_hermes_dir(None, home), expected);
let empty = std::ffi::OsString::from("");
assert_eq!(
windows_local_hermes_dir(Some(empty.as_os_str()), home),
expected,
);
}
#[test]
fn windows_local_hermes_dir_trims_localappdata() {
// Mirror Hermes' `os.environ.get("LOCALAPPDATA", "").strip()`.
let home = Path::new("C:\\Users\\tester");
// Whitespace-only -> treated as unset, fall back to <home>\AppData\Local.
let blank = std::ffi::OsString::from(" ");
assert_eq!(
windows_local_hermes_dir(Some(blank.as_os_str()), home),
home.join("AppData").join("Local").join("hermes"),
);
// Padded value -> trimmed before use.
let padded = std::ffi::OsString::from(" C:\\Custom\\Local ");
assert_eq!(
windows_local_hermes_dir(Some(padded.as_os_str()), home),
PathBuf::from("C:\\Custom\\Local").join("hermes"),
);
}
#[test]
#[serial]
fn with_test_home_neutralizes_hermes_env_vars() {
// An ambient HERMES_HOME / LOCALAPPDATA (e.g. set by a Hermes install)
// must not leak into the test home — otherwise other tests in this
// module would read/write a real Hermes config via get_hermes_config_path().
let saved_hh = std::env::var_os("HERMES_HOME");
let saved_la = std::env::var_os("LOCALAPPDATA");
std::env::set_var("HERMES_HOME", "/ambient/hermes-home");
std::env::set_var("LOCALAPPDATA", "/ambient/local-appdata");
let inside = with_test_home(|| {
(
std::env::var_os("HERMES_HOME"),
std::env::var_os("LOCALAPPDATA"),
)
});
match saved_hh {
Some(v) => std::env::set_var("HERMES_HOME", v),
None => std::env::remove_var("HERMES_HOME"),
}
match saved_la {
Some(v) => std::env::set_var("LOCALAPPDATA", v),
None => std::env::remove_var("LOCALAPPDATA"),
}
assert_eq!(
inside.0, None,
"with_test_home must clear ambient HERMES_HOME"
);
assert_eq!(
inside.1, None,
"with_test_home must clear ambient LOCALAPPDATA"
);
}
}
+26 -11
View File
@@ -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
+13
View File
@@ -16,6 +16,19 @@ fn main() {
if std::env::var("WEBKIT_DISABLE_COMPOSITING_MODE").is_err() {
std::env::set_var("WEBKIT_DISABLE_COMPOSITING_MODE", "1");
}
// AppImage 的 GTK 启动钩子 (linuxdeploy-plugin-gtk.sh) 会无条件
// `export GDK_BACKEND=x11` 强制走 XWayland,以规避历史上的 Wayland 崩溃
// (tauri-apps/tauri#8541)。但在较新的 Wayland + NVIDIA 环境下,强制 XWayland
// 反而使 WebKitGTK 的 webview 收不到指针事件(标题栏可点、网页内容点不动),
// resize 后黑屏;改回原生 Wayland 即可解决,且该崩溃在 WebKitGTK 2.52 上已不复现。
// 由于该钩子会覆盖用户预设的 GDK_BACKEND,这里提供一个钩子不会触碰的逃生开关:
// 设置 CC_SWITCH_GDK_BACKEND=wayland 即可强制覆盖,默认行为保持不变(零回归)。
if let Ok(backend) = std::env::var("CC_SWITCH_GDK_BACKEND") {
if !backend.is_empty() {
std::env::set_var("GDK_BACKEND", backend);
}
}
}
cc_switch_lib::run();
+5 -8
View File
@@ -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()
};
+276
View File
@@ -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
View File
@@ -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 {
+159 -99
View File
@@ -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
View File
@@ -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 形式,错误响应若仍保留
+39
View File
@@ -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());
}
}
+61 -137
View File
@@ -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",全程不出现 imageissue #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 {
+50
View File
@@ -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();
+1 -1
View File
@@ -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,
+15 -4
View File
@@ -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 foundopenai/codex#31967
// 本机 A/B 实测确认)。两个头必须成对发送,缺一即 404;version 需 ≥ 目标模型
// catalog 的 minimal_client_versionluna=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),
),
]
}
+508 -1
View File
@@ -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}\""));
}
}
+11 -3
View File
@@ -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)
);
}
}
+17 -3
View File
@@ -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
+92 -5
View File
@@ -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_tokensinclusive 上游)。
// 与流式 build_anthropic_usage_json (#2774) 及 transform_gemini 的 saturating_sub 对称。
// 最终 cache_read:直传字段优先于 nestedcache_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!({
+48 -6
View File
@@ -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!({
+4 -12
View File
@@ -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(),
}
}
}
+8 -5
View File
@@ -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]
+9 -1
View File
@@ -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,
+55 -36
View File
@@ -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!({
@@ -0,0 +1,39 @@
{
"slug": "native-responses-template",
"display_name": "native-responses-template",
"description": "native-responses-template",
"base_instructions": "You are Codex, a coding agent. You and the user share the same workspace and collaborate to achieve the user's goals.",
"default_reasoning_level": "high",
"supported_reasoning_levels": [
{
"effort": "none",
"description": "Disable Thinking"
},
{
"effort": "high",
"description": "Enabled Thinking"
}
],
"shell_type": "shell_command",
"visibility": "list",
"supported_in_api": true,
"priority": 0,
"supports_reasoning_summaries": true,
"default_reasoning_summary": "none",
"support_verbosity": false,
"truncation_policy": {
"mode": "bytes",
"limit": 10000
},
"supports_parallel_tool_calls": false,
"supports_image_detail_original": false,
"context_window": 262144,
"max_context_window": 262144,
"effective_context_window_percent": 95,
"experimental_supported_tools": [],
"input_modalities": [
"text",
"image"
],
"supports_search_tool": false
}

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