Compare commits

...

86 Commits

Author SHA1 Message Date
Jason c002688a84 chore(release): bump version to 3.14.1
- Add v3.14.1 release notes (en/zh/ja) covering tray usage visibility,
  Codex OAuth stability fixes, Skills import/install reliability, and
  removal of the Hermes config health scanner
- Cut [Unreleased] into [3.14.1] in CHANGELOG with PR references
- Bump version in package.json, Cargo.toml, Cargo.lock, tauri.conf.json
2026-04-23 21:17:30 +08:00
Jason 4737158439 feat(tray): show coding-plan usage for Kimi / Zhipu / MiniMax
dc04165f surfaced tray usage badges for Claude/Codex/Gemini official
OAuth only. Chinese coding-plan providers already expose 5h + weekly
windows through coding_plan::get_coding_plan_quota, but two gaps kept
the tray from rendering them.

- format_script_summary read only data.first(), truncating the tier-
  flattened UsageResult to a single window. Detect plan_name matching
  TIER_FIVE_HOUR / TIER_WEEKLY_LIMIT and emit the "🟢 h12% w80%" layout
  used by format_subscription_summary; worst utilization drives the
  emoji. Copilot / balance / custom scripts keep the legacy single-
  bucket output via fallback.

- usage_script previously required manual activation through
  UsageScriptModal. Auto-inject meta.usage_script on Claude provider
  creation when ANTHROPIC_BASE_URL matches a known coding plan, so the
  tray lights up without the user opening the modal. Does not overwrite
  existing usage_script on update.

Extract the URL route table out of UsageScriptModal into a shared
codingPlanProviders module so the modal, the creation hook, and the
Rust coding_plan::detect_provider mirror all agree on one list.
Add TIER_WEEKLY_LIMIT alongside TIER_FIVE_HOUR and a createUsageScript()
factory to collapse the duplicated default fields across four call
sites and drop the remaining stringly-typed tier names.
2026-04-23 17:34:39 +08:00
Jason cdcc423122 refactor(hermes): drop config health check scanner
The Hermes config.yaml schema has stabilized and users have migrated to
the current provider fields, so the value of scanning for model.provider
dangling references, custom_providers shape errors, v12 migration residue
etc. no longer justifies the maintenance surface — and the scan produces
false positives when users keep some providers under Hermes' v12+
providers: dict (Hermes' runtime merges both shapes, but CC Switch's
scanner only looked at the list form).

Removes the whole HermesHealthWarning type, scan_hermes_config_health
command, HermesHealthBanner React component, useHermesHealth hook,
warnings field on HermesWriteOutcome, and the three helper functions
(yaml_as_non_empty_str, collect_mapping_string_keys, hermes_warning)
that only served the scanner. Drops the matching i18n keys in
zh/en/ja and the fixInWebUI button label that only the banner used.
2026-04-23 16:18:38 +08:00
涂瑜 dc04165f18 feat(tray): show cached provider usage in the system tray menu (#2184)
* feat: add Rust-side write-through usage cache

Introduce an in-memory UsageCache on AppState that the existing usage
query commands populate on success. The cache is read-only to the rest
of the app today; the next commit consumes it from the tray menu.

- New services::usage_cache module with split maps: subscription keyed
  by AppType, script keyed by (AppType, provider_id).
- AppType gains Eq + Hash so it can be used as a HashMap key.
- commands::subscription::get_subscription_quota now takes State<AppState>
  and writes through on success (signature change is invisible to the
  frontend — Tauri injects State automatically).
- commands::provider::queryProviderUsage body extracted into an inner
  async fn; the public command wraps it with write-through, covering
  Copilot, coding-plan, balance, and generic script paths uniformly.

Cache is in-memory only; auto-query interval and the upcoming tray
refresh action rebuild it after restarts.

* feat(tray): surface cached usage in the system tray menu

Read UsageCache populated by the previous commit and render it in three
places, scoped to whatever TRAY_SECTIONS covers (Claude/Codex/Gemini):

1. Inline suffix on each provider submenu item
   "AnyProvider  · 🟢 5h 18% / 7d 23%"
2. Disabled summary row per visible app under "Show Main"
   "Claude · Anthropic Official · 🟢 5h 18% / 7d 23%"
3. "Refresh all usage" menu item that triggers get_subscription_quota +
   queryProviderUsage for every applicable provider, then rebuilds the
   tray menu via the existing refresh_tray_menu path.

Color encoding uses emoji (🟢 <70% / 🟠 70-89% / 🔴 ≥90%) since Tauri 2
tray labels are plain text. Missing cache entry leaves the label
unchanged — tray never issues network requests when opened. Three new
i18n-ready strings live in TrayTexts (en/zh/ja), following the existing
pattern for tray text.

Closes #2178.

* feat(usage): bridge tray UsageCache writes to frontend React Query

Why: tray hover triggers backend-only refresh that wrote to UsageCache but
never notified the frontend, leaving main UI stale while tray showed fresh
numbers. Emit a payload-carrying event after each cache write so React Query
can setQueryData directly, keeping both views in sync without duplicate fetches.

* fix(tray): skip hidden apps on hover refresh and drop stale disabled-script cache

Address P2 findings from automated review on #2184:

1. refresh_all_usage_in_tray now filters TRAY_SECTIONS by settings.visible_apps
   before scheduling subscription/script queries, matching create_tray_menu and
   preventing wasted external API calls (and rate-limit/auth-error log noise)
   for apps the user has hidden.

2. format_usage_suffix only trusts the script cache when provider.meta.usage_script
   is still enabled; when a script is disabled/removed the cached suffix is now
   invalidated so the tray label no longer shows stale data indefinitely.

* refactor: consolidate codex provider helpers and fix test semantics

- Add Provider::is_codex_oauth() and Provider::codex_fast_mode_enabled()
  to eliminate duplicated meta extraction in claude.rs and stream_check.rs
- Fix non-codex-oauth tests to pass codex_fast_mode=false (was true, harmless
  but semantically misleading)
- Remove redundant is_dir() guard after resolve_skill_source_dir already
  guarantees the returned path is a directory

* style: apply cargo fmt

* fix(tray): reflect failed refreshes in cache and support Gemini flash-lite

Follow-up to the tray usage-display feature addressing review feedback:

- Write snapshots for both Ok(success:false) and Err paths in
  queryProviderUsage / get_subscription_quota so stale success data
  no longer persists across failed refreshes; the original Err is
  still returned to the frontend onError handler.
- Include gemini_flash_lite tier in the tray summary with label "l".
  Matches the frontend SubscriptionQuotaFooter and keeps the worst
  emoji correct when lite is the highest utilization.
- Add TIER_GEMINI_PRO / _FLASH / _FLASH_LITE constants in
  services/subscription.rs and reuse them in classify_gemini_model
  and sort_order.
- Extract Provider::has_usage_script_enabled() to remove the
  duplicated meta.usage_script chain at two call sites.
- Use db.get_provider_by_id in refresh_all_usage_in_tray instead of
  materialising the full provider map, and parallelise subscription
  and script futures via futures::future::join.
- Narrow refresh_all_usage_in_tray to each section's effective
  current provider (script if enabled, else subscription when the
  provider is official). Hover refreshes now issue at most
  TRAY_SECTIONS.len() outbound requests.
- Add 10 unit tests in tray::tests covering Claude/Codex h/w dispatch,
  Gemini p/f/l dispatch (including lite-only and lite-worst cases),
  and success/failure guards.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 16:17:15 +08:00
Coconut-Fish 010b163430 Fix/一键配置失效 (#2249)
* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 更新供应商备注信息的显示样式

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段

* fix: 优化模型状态管理,确保配置更新时正确引用最新设置

* fix(skill): improve error handling for skill source directory resolution

Co-authored-by: Copilot <copilot@github.com>

* fix(gemini): simplify project directory retrieval in scan_sessions function

* fix(useModelState): optimize latestConfigRef assignment in useModelState hook

* fix(useModelState): remove unnecessary blank line in useModelState hook

---------

Co-authored-by: Copilot <copilot@github.com>
2026-04-23 15:36:03 +08:00
santugege 59735f976b fix(skill): resolve root-level repo skills consistently (#2231)
Co-authored-by: luoyaoqi <luoyaoqi@robam.com>
2026-04-23 12:21:47 +08:00
Jesus Díaz Rivas 10e0772d8c feat: Add Codex OAuth FAST mode toggle (#2210)
* Add Codex OAuth FAST mode toggle

* fix(codex-oauth): default FAST mode to off to avoid surprise quota burn

service_tier="priority" consumes ChatGPT subscription quota at a higher
rate. Users must now opt in explicitly rather than inherit FAST mode
silently when this feature ships.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 12:05:17 +08:00
lif 444c123ad0 [codex] Stabilize Codex OAuth cache routing (#2218)
* Stabilize Codex OAuth cache routing

Codex OAuth-backed Claude proxy requests now reuse a client-provided session identity for prompt cache routing and send Codex-like session headers when that identity exists. Generated proxy UUIDs are intentionally excluded so they do not fragment cache locality.\n\nThe same path exposed two runtime issues during validation: rustls needed an explicit process crypto provider, and Codex OAuth can return Responses SSE even when the original Claude request is non-streaming. Those are handled so cache-routed requests can complete instead of panicking or being parsed as JSON.\n\nConstraint: Official Codex uses conversation identity and Responses session headers for prompt cache routing.\nRejected: Always use generated proxy session IDs | generated IDs change per request and reduce cache reuse.\nConfidence: medium\nScope-risk: moderate\nDirective: Do not remove the client-provided-session guard unless generated session IDs become stable per conversation.\nTested: cargo test codex_oauth\nTested: Local dev app health check on 127.0.0.1:15721\nTested: Local proxy logs showed cache_read_tokens after restart\nNot-tested: Full cargo test without local cc-switch port conflict\nRelated: #2217

* feat(proxy): aggregate forced Codex OAuth SSE into JSON for non-streaming clients

Narrow override on top of #2235's streaming fallback.

Codex OAuth always forces upstream openai_responses into SSE, even
when the original Claude request is stream:false. #2235 handles this
by routing such responses through the streaming transform so the
client receives text/event-stream — that avoids the 422 that JSON
parsing would produce, and it also protects any other provider that
unexpectedly returns SSE (the response.is_sse() guard).

But for Claude SDK callers that sent stream:false, returning SSE
still violates the Anthropic non-streaming contract. This commit
adds an override on exactly one combination — non-streaming client
+ codex_oauth + openai_responses — to aggregate the upstream
Responses SSE into a synthetic Responses JSON and then run the
regular responses_to_anthropic non-streaming transform. All other
paths, including the generic response.is_sse() fallback, remain
on the streaming path from #2235.

The aggregator reuses proxy::sse::take_sse_block / strip_sse_field,
which support both \n\n and \r\n\r\n delimiters; a hand-rolled
split("\n\n") would silently fail on real HTTPS upstreams.

Tests cover the happy path, CRLF delimiters, response.failed
errors, and the missing response.completed defensive branch.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 11:15:01 +08:00
nmsn 3ad7d0b1cc fix: use TOML parser instead of regex for Codex model extraction (#2222) (#2227)
* fix(codex): use TOML parser instead of regex for model extraction

Regex only matched model=... on first line, TOML parser handles
multiline TOML correctly.

Fixes #2222

* fix(stream_check): drop unused regex::Regex import

The previous commit replaced the only Regex usage in stream_check.rs
with toml::Table parsing, leaving `use regex::Regex;` orphaned.
Without this removal, `cargo clippy -- -D warnings` (run in CI)
fails with `unused import: regex::Regex`.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-23 10:38:08 +08:00
涂瑜 29e87487a1 fix(skills): prevent duplicate imports when import button is double-clicked (#2211)
Closes #2139

Two related defects let the installed-skills count balloon when users
tap the import confirm button multiple times — either deliberately or
because the button is still clickable while a slow import is in flight:

- The confirm button only disabled itself while `selected.size === 0`,
  so it stayed clickable during a pending mutation. Each extra click
  triggered another `importFromApps` mutation.
- `useImportSkillsFromApps` appended the server response to the
  installed cache without deduping, so re-firing the mutation stacked
  the same skills into the list again.

Disable the confirm (and cancel) buttons while the mutation is pending
— matching the `isRestoring` / `isDeleting` pattern already used by
`RestoreSkillsDialog` — and merge success payloads by
`InstalledSkill.id` so repeated results overwrite rather than
accumulate.

The merge is extracted as a pure `mergeImportedSkills` reducer to make
the behaviour unit-testable and to short-circuit on an empty payload,
returning the existing reference so React Query does not notify
subscribers about a no-op cache update.
2026-04-23 10:25:01 +08:00
Coconut-Fish 7bfe2609db Style/session manager list UI (#2201)
* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 更新供应商备注信息的显示样式

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段

* style(App, SettingsPage, ScrollArea): 调整组件样式以改善布局和视觉效果

* style(App, SettingsPage, ScrollArea): 调整组件样式以改善布局和视觉效果

* style(SettingsPage, useSettings): 统一代码格式,调整样式和变量声明

* style(App): 调整底部内边距以改善布局
2026-04-23 08:56:57 +08:00
tison e7ff2ee47d fix: gemini cli resume session can have project_dir (#2240)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-23 08:55:11 +08:00
xpfo 7ddf7ffd66 fix(proxy): handle Codex OAuth responses as streaming (#2235) 2026-04-23 08:54:31 +08:00
tison 1b3c53d235 fix: always show name on hover (#2237)
Signed-off-by: tison <wander4096@gmail.com>
2026-04-22 23:19:52 +08:00
Jason c7ba3cf51d fix(pricing): correct Kimi K2.6 seed prices to match official rates
Moonshot's official USD pricing for kimi-k2.6 is $0.95 input /
$4.00 output / $0.16 cache-hit per 1M tokens (~58-60% higher than
K2.5). The previous commit copied K2.5's $0.60/$2.50/$0.10, which
would have under-billed K2.6 traffic in the usage dashboard.

No migration needed since this version is unreleased; INSERT OR
IGNORE will write the correct values on first launch.
2026-04-22 14:32:03 +08:00
Jason 85295cf23f chore(release): bump version to 3.14.0 2026-04-22 12:29:27 +08:00
Jason 1f25411524 feat(presets): upgrade Kimi K2.5 to K2.6 in direct Moonshot configs
Bump model id and display name from K2.5 to K2.6 in Hermes, OpenClaw,
OpenCode, and Claude (direct api.moonshot.cn) presets. Pricing,
context window, and base URL are unchanged.

Add kimi-k2.6 row to model_pricing seed; no migration needed since
seed_model_pricing uses INSERT OR IGNORE and runs on every startup
via ensure_model_pricing_seeded. Old kimi-k2.5 row is kept to
preserve historical usage stats.

Nvidia aggregator forwards (moonshotai/kimi-k2.5) intentionally keep
the K2.5 SKU until Nvidia's catalog confirms K2.6.
2026-04-22 12:17:19 +08:00
Jason 6495da03b7 docs(release-notes): add v3.14.0 release notes (en/zh/ja)
Cover Hermes Agent onboarding (6th managed app), Claude Opus 4.7
rollout, Gemini Native API proxy, "Local Routing" rename,
application-level window controls, Copilot premium consumption
deep optimization, session list virtualization, Usage date range
picker, Stream Check error classification, pricing v8->v9 reseed,
and related breaking changes.

18 external PR contributions credited in all three locales.
2026-04-22 11:51:32 +08:00
Jason 95b21ff27e docs(changelog): extend v3.14.0 entries with late additions
Fold six late commits into the v3.14.0 section (Added / Changed / Fixed)
and refresh the stats header against the actual v3.13.0..HEAD diff:
100 commits | 219 files | +20,548 / -3,569.

Late additions covered: Hermes dashboard toolbar launch, LemonData
preset across all six apps, DDSHub Codex endpoint, Hermes toolbar
icon + MCP reorder, Hermes health-check schema fix, Usage modal
support for Hermes/OpenClaw.
2026-04-22 11:51:25 +08:00
Jason ae1fd2b662 feat(presets): add DDSHub Codex preset
DDSHub now exposes a Codex-compatible endpoint at the same host as
its Claude service. Base URL omits the /v1 suffix since the gateway
auto-routes OpenAI SDK paths.
2026-04-22 10:42:24 +08:00
Jason f4a9021461 feat(presets): add LemonData provider across all six apps
Register LemonData (third-party partner) preset for Claude, Codex,
Gemini, OpenCode, OpenClaw, and Hermes, plus icon assets and i18n
partner promotion copy (zh/en/ja). Claude preset uses
ANTHROPIC_API_KEY auth; OpenAI-compatible apps target gpt-5.4.
2026-04-22 10:39:17 +08:00
Jason 2274da0b8e style(hermes): use dashboard icon and move MCP to toolbar end
Swap ExternalLink for LayoutDashboard on the Hermes Web UI button —
clicking it may launch `hermes dashboard` rather than just open a URL,
so a panel-style glyph reads truer than a generic external-link icon.
Also reorder the toolbar so MCP sits in the final slot, matching the
claude/codex/gemini/opencode layout.
2026-04-21 23:05:52 +08:00
Jason 7ac822d241 fix(hermes): stop health check from borrowing OpenClaw schema
Hermes providers were routed through check_additive_app_stream, the
OpenClaw dispatcher, which reads camelCase fields (baseUrl/apiKey/api)
and emits "OpenClaw is missing ..." errors. Hermes stores snake_case
fields (base_url/api_key/api_mode) with different protocol tags, so
users saw "OpenClaw provider is missing baseUrl" even after filling in
every Hermes field correctly.

Introduce check_hermes_stream with Hermes-specific extractors. Route
api_mode (chat_completions / anthropic_messages / codex_responses) to
the matching check_claude_stream api_format, and return bedrock_converse
as unsupported. Resolve api_mode before extracting URL/API key so users
who picked bedrock_converse see the real cause first rather than a
misleading "missing base_url" message.
2026-04-21 23:00:37 +08:00
Jason 4dd11ab427 fix(usage): support Hermes and OpenClaw in usage query modal
Extend getProviderCredentials to read flat settingsConfig fields for
Hermes (snake_case base_url / api_key) and OpenClaw (camelCase baseUrl
/ apiKey), so the "official balance" template auto-selects for matching
providers like SiliconFlow.

Also refactor the BALANCE and TOKEN_PLAN test paths in handleTest to
reuse the precomputed providerCredentials instead of re-reading
env.ANTHROPIC_* directly, which previously caused empty key errors for
non-Claude apps even when the key was configured.
2026-04-21 22:40:53 +08:00
Jason 8e9452b7ec feat(hermes): launch dashboard from toolbar when Web UI is offline
When the Hermes Web UI probe fails, the toolbar entry now opens an info
confirm dialog offering to run `hermes dashboard` in the user's preferred
terminal. Accepting spawns it via a temp bash/batch script; `hermes
dashboard` itself opens the browser once ready, so we do not poll.
The Memory panel and Health banner keep the existing toast behavior.

Also corrects the stale `hermes web` hint in the offline toast (the real
command is `hermes dashboard`) and reorders Linux terminal detection to
try `which` before stat'ing /usr/bin, /bin, /usr/local/bin.
2026-04-21 21:11:15 +08:00
Jason 38709c94db docs(changelog): add v3.14.0 release notes
Summarize the 94 commits since v3.13.0 (216 files, +19,923 / -3,554)
into Keep-a-Changelog entries: Hermes Agent as the 6th managed app,
Claude Opus 4.7 rollout, Gemini Native API proxy, Copilot GHES,
session list virtualization, usage date range picker, and the
"Local Proxy Takeover" -> "Local Routing" rename.

Breaking changes collected in a dedicated section: explicit Hermes
api_mode, ANTHROPIC_REASONING_MODEL removal, per-provider proxy
removal, schema bumps (v8->v9 pricing reseed, v9->v10 Hermes columns),
and XCodeAPI preset removal.
2026-04-21 17:32:53 +08:00
Jason db92f2b3b0 style(providers): apply prettier to common-config hooks
Reformat three hooks brought in from upstream #2191 so that
format:check passes in CI.
2026-04-21 12:05:48 +08:00
Jason eb1cd17ab2 fix(header): stop auto-compact from latching after maximize
useAutoCompact cached normalWidthRef = el.scrollWidth on every
non-compact resize, but per DOM spec scrollWidth === clientWidth
when content fits. Maximizing the window (content no longer
overflows) therefore wrote the container width into
normalWidthRef, making it impossible to re-enter compact when
the window was restored to its original size.

Move the assignment inside the overflow branch so the cache is
only written at the actual compact threshold, where scrollWidth
reflects the real content width.
2026-04-21 11:57:07 +08:00
Jason 29a28d2a74 style(header): unify toolbar icon button width across apps
Normalize all icon-only ghost buttons in the header toolbar to
32x32 (w-8 px-2). Previously Hermes/OpenClaw used default sm
padding (~40px) while Claude's Skills/Sessions used w-8 px-2,
so switching apps caused a width jump and put useAutoCompact's
cached normalWidthRef out of sync across apps.
2026-04-21 11:57:07 +08:00
Jason 1227e29d8b feat(skills): enable Hermes in unified Skills management
Wire hermes through SkillApps struct, DAO SQL, command parser, and
SKILLS_APP_IDS. Add a Skills entry to the Hermes toolbar. Simplify
skill_sync test fixtures to use SkillApps::default().
2026-04-21 11:57:07 +08:00
Jason 0be75668cc feat(hermes): align provider schema with Hermes Agent 0.10.0
Hermes 0.10.0 tightened custom_providers validation (commit 2cdae233):
invalid base_urls are rejected, unknown fields produce warnings, and
new fields (rate_limit_delay, bedrock_converse, key_env) landed.

- Add bedrock_converse to the api_mode selector (and i18n labels)
- Expose rate_limit_delay in a provider-level advanced panel
- Validate base_url client-side (URL shape, template-token friendly)
- Drop per-model max_tokens — not in _VALID_CUSTOM_PROVIDER_FIELDS
- Round-trip test asserts set_provider preserves rate_limit_delay /
  key_env / any unknown forward-compat field
2026-04-21 11:57:07 +08:00
Jason 111ddf8d73 style: apply prettier and rustfmt
No behavior changes. Brings three files back in line with the project
formatters (CI runs `pnpm format:check` and `cargo fmt --check`).
2026-04-21 11:57:07 +08:00
Jason 08727528aa test: sync stale fixtures and isolate openclaw env tests
Three unrelated test failures surfaced after rebase:

- McpFormModal expected the apps boolean set without `hermes`; Hermes MCP
  support is now wired, so the fixture must include `hermes: false`.
- therouter Gemini preset was bumped to `gemini-3.1-pro` in a later
  commit; update the assertions to match current config.
- openclaw_config tests mutate process-level `CC_SWITCH_TEST_HOME` and
  `HOME` inside a module-local Mutex, but hermes_config does the same
  under its own separate Mutex. Running both modules in parallel let the
  env races corrupt hermes_config's `with_test_home`. Tag the four
  env-mutating openclaw tests with `#[serial]` so they serialize across
  modules via serial_test's process-wide default key.
2026-04-21 11:57:07 +08:00
Jason c8d91298c7 fix(providers): drop legacy ANTHROPIC_REASONING_MODEL from Claude quick-set
The model-mapping quick-set button referenced an undefined `reasoningModel`
prop and wrote `ANTHROPIC_REASONING_MODEL`, which the backend explicitly
marks as deprecated legacy (see services/provider/mod.rs and
services/proxy.rs). Remove all three references so typecheck passes and
the button matches the provider model schema.
2026-04-21 11:57:07 +08:00
Jason 21a1518f9f refactor(hermes): drop "Auto" api_mode and require explicit protocol
Hermes' built-in api_mode detection only matches a handful of official
endpoints (api.openai.com, api.anthropic.com, api.x.ai, AWS Bedrock);
third-party / proxy endpoints silently fall back to chat_completions,
which causes opaque 401/404s on Anthropic-protocol or Codex-Responses
providers. The "Auto" option was misleading for the common third-party
case.

- Drop the "Auto" option from the API Mode dropdown; remove the
  HermesApiModeChoice sentinel type so writes always emit api_mode.
- Default new providers and legacy entries lacking api_mode to
  chat_completions (only persisted on user save).
- Deeplink imports now write api_mode: chat_completions explicitly
  instead of relying on URL heuristics; test renamed accordingly.
- Rename the "Codex Responses (Copilot / OpenCode)" label to
  "OpenAI Responses" to match OpenAI's /v1/responses naming.
2026-04-21 11:57:07 +08:00
Jason a9461ad52f docs(readme): update SiliconFlow signup bonus to ¥16
Sync the bonus credit amount across en/zh/ja README files to reflect
the current SiliconFlow sponsor offer.
2026-04-21 11:57:07 +08:00
Jason f57edfd697 refactor(hermes): share provider-source marker constants and write guard
After /simplify review of the P1-3 second wave, two small cleanups:

- Lift the `_cc_source` / `providers_dict` magic strings out of
  ProviderCard into a shared helper (`isHermesReadOnlyProvider`) and
  named constants in hermesProviderPresets.ts. Front-end and back-end
  now document the same marker contract in two mirrored places
  instead of drifting strings.

- Replace the duplicate `is_dict_only_provider` + `format!` branches
  at the top of `set_provider` / `remove_provider` with a single
  `ensure_provider_writable(config, name, verb)` guard. Future error
  copy tweaks only have to happen once.

No behaviour change; all 52 hermes_config tests stay green.
2026-04-21 11:57:07 +08:00
Jason abb305a82f feat(hermes): render providers: dict overlays as read-only cards
ProviderCard now detects Hermes provider entries sourced from the
v12+ `providers:` dict via the `_cc_source` marker that the backend
injects, and renders a "Hermes Managed" badge beside the title.
ProviderActions receives an `isReadOnly` prop that disables the Edit
and Delete buttons (with a tooltip pointing the user at Hermes Web
UI) while keeping Switch and Duplicate enabled — switching only
touches `model.*`, and duplicate lets users fork the overlay into
their own `custom_providers:` list.

Three-locale i18n keys `provider.managedByHermes` /
`provider.managedByHermesHint` added.
2026-04-21 11:57:07 +08:00
Jason 3f4739365e feat(hermes): surface providers: dict entries read-only
Hermes v12+ migrated some provider entries from the `custom_providers:`
list into a `providers:` dict (keyed by id). CC Switch previously
ignored that source entirely, leaving users blind to providers they had
configured via Hermes' own Web UI; the only feedback was a generic
migration warning in the health banner.

`get_providers()` now unions both sources, matching upstream
`get_compatible_custom_providers` dedup order (list wins on name
collision). Entries coming from the dict carry a `_cc_source =
"providers_dict"` marker plus the original `provider_key`, which the
UI layer will use to render them read-only. `set_provider` and
`remove_provider` now refuse to touch dict-only entries, steering the
user to Hermes Web UI. `sanitize_hermes_provider_keys` strips the UI
markers on write so they never reach YAML.

The `schema_migrated_v12` health warning copy reframes the situation:
entries are shown read-only in CC Switch rather than invisible.
2026-04-21 11:57:07 +08:00
Jason e10a300c80 fix(hermes): prevent YAML pollution and drop of OAuth mcp auth
DeepLink Hermes import was emitting camelCase (baseUrl / apiKey /
apiMode) that the Hermes runtime does not recognise, poisoning
`custom_providers:` entries on activation. The MCP sync path was
also stripping `auth: oauth` on round-trip, silently downgrading
OAuth-type servers to unauthenticated calls.

The Hermes deeplink branch now emits snake_case via a dedicated
builder; `sanitize_hermes_provider_keys` runs on both `set_provider`
and `get_providers` so legacy DB records heal on next access.
`HERMES_EXTRA_FIELDS` preserves `auth`. The `api_mode` dropdown gains
`codex_responses` (Copilot / OpenCode), and the schema-migrated
warning copy no longer hard-codes "v12" (upstream `_config_version`
is now 19).
2026-04-21 11:57:07 +08:00
Jason 185ac2be9b feat(hermes): memory enable switch + clearer migration warning copy
Replaces the greyed-out "Memory is disabled" banner with a real Switch
at the top of each memory tab. Users can now toggle Hermes' memory/user
blobs without leaving CC Switch; the underlying write goes through the
merge-aware `set_memory_enabled`, so budgets and external-provider
settings survive toggle operations. The new `useToggleHermesMemoryEnabled`
mutation invalidates the limits query so the Switch state and the
amber disabled-hint update in lockstep.

Reworks the `schema_migrated_v12` health banner copy to match the
simplified "CC Switch only manages custom_providers" posture — it now
tells users to reconcile migrated dict entries via Hermes Web UI,
instead of the earlier (and now inaccurate) "CC Switch reads both".
2026-04-21 11:57:07 +08:00
Jason b8a3534cb5 feat(settings): add Hermes config dir override with data-driven dispatch
Adds a dedicated Hermes row to the directory-override settings so users
can point CC Switch at alternate Hermes config locations (e.g. a second
profile directory for work/personal split). `get_config_dir` on the
Rust side already supports hermes; this just wires up the frontend row.

Wiring it through `useDirectorySettings` revealed a scaling problem:
every supported app required five parallel ternary chains across
`computeDefaultConfigDir`, `updateDirectory`, `browseDirectory`,
`resetDirectory`, and `updateDirectoryState`. Replaces those with two
lookup tables (`APP_DIRECTORY_META`, `DIRECTORY_KEY_TO_SETTINGS_FIELD`)
so adding the next app is two entries, not fifteen edit sites.

Drive-by cleanup from the same touch:
* `resetAllDirectories` takes a `ResolvedAppDirectoryOverrides` object
  instead of five positional optional strings.
* `setResolvedDirs` returns the same reference when the sanitized
  value is unchanged, so no-op edits don't cascade renders.

Also lands all i18n updates for this series (`hermesConfigDir` and
placeholder, Memory section's enable/disable/toggleFailed copy, and
the reworded `schemaMigratedV12` warning) in zh/en/ja together.
2026-04-21 11:57:07 +08:00
Jason 31fb998575 refactor(hermes): simplify schema handling + preserve unknown provider fields
Drops the v11→v12 providers-dict compat layer: CC Switch now only
reads/writes `custom_providers:`, leaving migrated `providers:` dict
entries to Hermes Web UI for reconciliation (Hermes' runtime already
merges both shapes via `get_compatible_custom_providers`). The
`schema_migrated_v12` health warning now points users there when a
dict-migrated config is detected.

Adds forward-compat merge to `set_provider`: when updating an existing
entry, on-disk fields the UI payload didn't submit (e.g. Hermes-only
`request_timeout_seconds`, `key_env`) are carried over. Without this,
editing one field via CC Switch would silently strip the rest.

Adds `set_memory_enabled` + `set_hermes_memory_enabled` Tauri command
for the upcoming memory-switch UI. Writes go through a merge-aware
section replacement so character budgets and external-provider fields
survive toggle operations.

Removes four dict-only helpers (`normalize_providers_dict_entry_for_read`,
`rename_alias_key`, `json_obj_non_empty_str`,
`resolve_provider_name_from_yaml_entry`) and the multi-section write
helper. Simplifies `get_providers` / `remove_provider` / health scan
back to list-only. Replaces nine obsolete dict-related tests with
`set_provider_preserves_unknown_fields_on_update` and
`set_memory_enabled_preserves_other_fields`.
2026-04-21 11:57:07 +08:00
Jason acc6d795e4 feat(hermes): replace Prompts entry with Memory panel
Hermes has no slash-prompt concept (templates live as Skills), so the
Prompts tab for the Hermes app was always empty. Swap the toolbar Book
button for a Brain button that opens a new Memory panel editing
~/.hermes/memories/{MEMORY,USER}.md — Hermes' first-class memory store
which its Web UI exposes only as on/off toggles, never as an editor.

The panel shows each file in its own tab with a character-budget bar
read from config.yaml's nested memory.* section (memory_char_limit /
user_char_limit, default 2200 / 1375). Edits are written atomically;
Hermes picks them up on the next session start per MemoryStore.

Also extract useDarkMode to src/hooks/useDarkMode.ts — the codebase
already repeats the same MutationObserver pattern in 12+ places; this
PR introduces the shared hook and uses it once, leaving the migration
of the other copies to a follow-up.
2026-04-21 11:57:07 +08:00
Jason 088b47b08a refactor(hermes): delegate deep config to Hermes Web UI
Slim the Hermes surface in CC Switch to match its core positioning —
cross-client provider switching and shared MCP/prompts/skills — and
delegate deep configuration (model, agent, env, skills, cron, logs)
to the Hermes Web UI at http://127.0.0.1:9119.

- Drop AgentPanel/EnvPanel/ModelPanel and their mutation commands,
  hooks, types, and i18n keys across zh/en/ja.
- Add open_hermes_web_ui Tauri command that probes /api/status and
  launches the URL in the system browser. Hermes injects its own
  session token into the returned HTML, so CC Switch doesn't need
  to touch auth.
- Surface the launcher from the Hermes toolbar and the health banner
  via a shared useOpenHermesWebUI() hook; the offline error code is
  defined once per side and referenced across the contract.
- Keep read-only access to model.provider so ProviderList can still
  highlight the active supplier; apply_switch_defaults continues to
  write the top-level model section when switching providers.

Net diff: +152 / -1253.
2026-04-21 11:57:06 +08:00
Jason 041f74db18 fix(presets): refresh stale context windows for DeepSeek and Claude 1M
- DeepSeek V3.2 / R1 (Hermes, OpenClaw): 64K → 128K context
- DeepSeek R1 max output: 8K → 64K (includes CoT tokens)
- Claude Opus 4.7 / Sonnet 4.6 via OpenRouter: 200K → 1M context
2026-04-21 11:57:06 +08:00
Jason ce5c3e5c6a fix(presets): refresh stale model IDs and backfill Hermes model lists
- Bump NewAPI universal preset to Claude 4.7 / Sonnet 4.6 / Haiku 4.5 and
  Gemini 3.1; fix opusModel mistakenly pointing to Sonnet
- Bump Gemini Native (Claude preset) to gemini-3.1-pro / gemini-3-flash
- Bump TheRouter Gemini preset to gemini-3.1-pro
- Backfill models[] + suggestedDefaults for 15 Hermes anthropic_messages
  presets:
    * Bailian For Coding: qwen3-coder-plus / qwen3-max
    * Kimi For Coding: kimi-for-coding
    * 13 third-party Claude proxies: claude-opus-4-7 / sonnet-4-6 /
      haiku-4-5-20251001
- Add Claude Haiku 4.5 entry to Hermes OpenRouter model list
2026-04-21 11:57:06 +08:00
Jason 3255b17185 feat(hermes): switch eligible presets to chat_completions + GPT-5.4
Migrate 18 Hermes provider presets from anthropic_messages to
chat_completions to sidestep known upstream Hermes bugs (model-name
dot-mangling in normalize_model_name, api_mode drop after v11->v12
migration, and auxiliary_client OpenAI hardcode).

Native providers now target each vendor's official OpenAI-compatible
endpoint with correct model IDs: Kimi (kimi-k2.5-preview on /v1),
Bailian (compatible-mode/v1 with Qwen3 defaults), Xiaomi MiMo, Longcat
(/openai/v1), Zhipu GLM (/api/paas/v4), ModelScope, MiniMax, SiliconFlow,
and Novita (/v3/openai).

Aggregators (Shengsuanyun, AiHubMix, DMXAPI, Compshare, TheRouter)
default to GPT-5.4 on chat_completions, mirroring the Codex preset
lineup. TheRouter omits gpt-5.4-pro since that variant is Responses-only
and Hermes implements only chat_completions. OpenRouter's existing
openai/gpt-5 entry is bumped to openai/gpt-5.4.

Claude-only proxies are left on anthropic_messages; their Codex
counterparts use wire_api=responses, so there is no evidence their
chat_completions endpoints serve OpenAI models.
2026-04-21 11:57:06 +08:00
Jason b4e29be8a0 chore(hermes): prune unused official presets and fix Nous endpoint
Remove the Anthropic, OpenAI, and Google AI presets from the Hermes
preset list. They were placeholder samples introduced when the Hermes
module first landed and do not match the actual user paths in
CC Switch (Claude / Codex go through OAuth, Gemini Native is its own
adapter), and the upstream endpoints are not reachable for most of
the target users anyway.

Fix the Nous Research preset: its base_url was a fabricated domain
(inference.nous.hermes.dev) that has never resolved. Point it at the
real Nous Portal endpoint (inference-api.nousresearch.com/v1) and
add apiKeyUrl so users can jump straight to portal.nousresearch.com
to provision a key.

Drop the now-orphan providerForm.presets.{anthropic,openai,googleai}
i18n keys from zh / en / ja since no preset references them anymore.
2026-04-21 11:57:06 +08:00
Jason 8d6353699c feat(presets): sync Claude provider presets to Hermes
Import 38 Claude presets into Hermes by mapping env-style
ANTHROPIC_BASE_URL/AUTH_TOKEN to flat base_url/api_key, deriving
api_mode from apiFormat (anthropic_messages or chat_completions),
deduping ANTHROPIC_*_MODEL into models[], and pointing
suggestedDefaults at ANTHROPIC_MODEL. Skip OAuth-only presets
(Codex, Copilot), Bedrock SigV4, Gemini Native, and the three
already shipped on the Hermes side (OpenRouter, Anthropic,
DeepSeek). Place Shengsuanyun at the head of the Hermes array so
the partner shows first in the preset panel.

In the Claude preset list, restore Shengsuanyun back ahead of
Gemini Native. The Gemini Native preset (#1918) was inserted
between Claude Official and Shengsuanyun, which made the
third_party category register first in the reduce-based grouping
and pushed the aggregator block (and Shengsuanyun) behind it.

Backfill the missing providerForm.presets translations across zh,
en, and ja (openrouter, anthropic, openai, googleai, deepseek,
together; plus shengsuanyun for en and ja) so existing Hermes
preset names no longer render literal i18n keys.
2026-04-21 11:57:06 +08:00
Jason 828ec2ce07 fix(hermes): show active provider and wire add/enable/remove actions
Switching a Hermes provider previously only fired a toast because the frontend treated Hermes as non-additive (unlike backend AppType::is_additive_mode, which lists OpenCode | OpenClaw | Hermes) and relied on the unused is_current DB flag for highlighting. Align the UI model with the backend:

- Include Hermes in ProviderActions' isAdditiveMode so the main button switches between "Add" and "Remove".
- Drive the "current" highlight from model.provider (via useHermesModelConfig) instead of the DB is_current field; model.provider is Hermes's real SSOT for the active provider.
- Reuse OpenClaw's set-as-default button slot to expose an "Enable" action on Hermes that calls switchProvider, so providers already in config can be activated without re-adding. switch_normal + apply_switch_defaults already atomically update custom_providers and model.provider, so no backend change is needed.
- Invalidate liveProviderIds + modelConfig + health in parallel after add/update/delete/switch via a new invalidateHermesProviderCaches helper, replacing four copies of three sequential awaits.
2026-04-21 11:57:06 +08:00
Jason 5056978d80 fix(hermes): persist providers under custom_providers so api_mode/model survive
Writing to the v12+ `providers:` dict broke every anthropic_messages
provider. Hermes `runtime_provider.py::_get_named_custom_provider` has a
bug in its `providers:` branch: the returned entry drops `api_mode`,
`transport`, `models`, and singular `model:`, and
`_resolve_named_custom_runtime` then falls back to `chat_completions` —
so an Anthropic-format endpoint receives OpenAI-format requests and
returns 404.

Keep using the legacy `custom_providers:` list; its normalization path
(`_normalize_custom_provider_entry`) preserves every field. In addition,
write a singular `model:` alongside the plural `models:` dict so the
Hermes runtime and `/model` picker see the default model id.

Also keep the `apply_switch_defaults` fix from the prior attempt:
`model.provider` is always updated, and `model.default` is only
overwritten when the new provider declares at least one model — so
switching to an incomplete provider no longer silently no-ops.
2026-04-21 11:57:06 +08:00
Jason 497a543c1b feat(hermes): add API mode dropdown and per-provider model editor in form
The Hermes provider form previously only exposed Base URL and API Key,
forcing users to drop into the Model panel to hand-edit model IDs after
adding a provider. Following OpenClaw's shape, the form now carries:

- An API Mode selector (auto-detect / chat_completions / anthropic_messages).
  "auto" is a UI-only sentinel — selecting it deletes api_mode from the
  config so the YAML doesn't leak a redundant field.
- A model list editor where the first row is badged as the default and
  each row has a collapsible Advanced panel for context_length and
  max_tokens. Adding/removing rows uses a UUID-keyed ref so typing in
  one input doesn't drop focus when another row is added.
- A Fetch Models button that pulls /v1/models from the configured
  endpoint and exposes the catalog in a per-row dropdown, identical to
  OpenClaw's flow. The vendor grouping is memoized so keystrokes don't
  trigger a reduce+sort per model row — Radix DropdownMenuContent does
  not lazy-mount, so the inner JSX evaluates on every render regardless
  of whether the menu is open.

Three-locale i18n keys are added together (zh/en/ja).
2026-04-21 11:57:06 +08:00
Jason f935bac633 feat(hermes): bind per-provider models to top-level model: on switch
Hermes custom_providers entries now carry an ordered models array
(id / context_length / max_tokens) plus suggestedDefaults. The backend
serializes the array to the YAML dict shape Hermes expects on write and
inverts it on read, preserving insertion order via the preserve_order
feature on serde_json.

When a user switches providers, switch_normal calls apply_switch_defaults
so the top-level model.default / model.provider follow the selected
provider's first model. Previously switching a Hermes provider only
shuffled custom_providers[] and left Hermes pointing at whatever
model.provider was set before.

Seven existing Hermes presets now ship with a curated models list so
switching lands on a working default without a detour through the
Model panel.
2026-04-21 11:57:06 +08:00
Jason 63aa310576 feat(copilot): strip thinking blocks before forwarding to save premium quota
Copilot routes through OpenAI-compatible endpoints that reject Anthropic's
thinking and redacted_thinking blocks. Previously the request would fail
upstream, burning one premium interaction, and only then trigger
thinking_rectifier to retry. This adds a proactive strip_thinking_blocks
pass in the Copilot optimization pipeline (step 3.5, after tool_result
merging). Signature fields and top-level thinking are left alone — those
are the reactive rectifier's job on the error path.

Also fixes a default-value inconsistency where CopilotOptimizerConfig's
Default impl used "gpt-4o-mini" while the serde default function returned
"gpt-5-mini" (aligned to gpt-5-mini, matching the reference implementation).

Aligned with yuegongzi/copilot-api's /v1/messages handler behavior.
2026-04-21 11:57:06 +08:00
Jason 615c430dd3 docs(readme): trim SSSAiCode sponsor blurb and sync across locales
Drop the ¥0.5/$ pricing claim and monthly/paygo line from the SSSAiCode
entry in all three READMEs, keeping only the fast-invoicing mention.
Also collapse a duplicate blank line after the LemonData row in the JA
README to match the ZH version.
2026-04-21 11:57:06 +08:00
Jason 5d3cd7eb85 fix(icons): replace placeholder Hermes icon with Nous brand artwork
The previous Hermes icon was an inline purple "H" SVG unrelated to the
real Hermes Agent brand. Replace it with the official Nous Research
avatar sourced from hermes-agent/landingpage/icon-512.png, routed
through iconUrls as a Vite URL import. The PNG is post-processed to
strip the 4px black rectangle border (cropped inward by 6px and pasted
back onto a 512x512 transparent canvas). Also switch defaultColor to
black to match the monochrome artwork when the asset falls back to an
initial glyph.
2026-04-21 11:57:06 +08:00
Jason 1684cb3233 feat(presets): migrate all aggregator and Bedrock presets to Claude Opus 4.7
- OpenClaw: replace opus-4-6 with opus-4-7 across 17 aggregator presets
  (id, name, primary, modelCatalog); AWS Bedrock entry rewritten to new
  SKU anthropic.claude-opus-4-7 (drops -v1 and dated suffix per official
  4.7 model card) and pricing corrected to $5/$25/$0.50/$6.25 during the
  SKU swap, aligning with schema.rs source of truth
- OpenCode: same replacement for 13 aggregators plus
  OPENCODE_PRESET_MODEL_VARIANTS entries for @ai-sdk/amazon-bedrock and
  @ai-sdk/anthropic, plus AWS Bedrock provider models map
- OpenRouter / TheRouter / GitHub Copilot in claudeProviderPresets use
  dot-style id; update to anthropic/claude-opus-4.7 (missed by 509d2250)
- omo: switch agent/category recommended to opus-4-7; replace key in
  OMO_BACKGROUND_TASK_PLACEHOLDER priority map
- hermes_config.rs: update doc comments and test fixtures to opus-4-7;
  Hermes ModelPanel placeholder and i18n defaultHint examples follow
- i18n unspecifiedHigh category description bumped to 'Claude Opus 4.7
  max variant' to match omo recommended
- Test fixtures updated: therouter preset assertion and opencode Bedrock
  variant lookup now check for opus-4-7
- Sonnet 4.6 / Haiku 4.5 untouched - no official 4.7 release for them
2026-04-21 11:57:06 +08:00
Jason 83c3c3b494 feat(pricing): add Claude Opus 4.7 with adaptive thinking and Bedrock SKU
- Seed claude-opus-4-7 pricing (same tier as 4.6: $5 / $25 / $0.50 /
  $6.25 per million tokens). Relies on incremental INSERT OR IGNORE
  seeding; no SCHEMA_VERSION bump needed.
- Whitelist opus-4-7 in thinking optimizer so it uses adaptive
  thinking + max effort + 1M context beta, matching 4.6 behavior.
- Bump default OPUS model in PIPELLM and AWS Bedrock (AKSK / API Key)
  presets to 4.7. Bedrock SKU drops the -v1 suffix per the official
  4.7 model card (anthropic.claude-opus-4-7 and
  global.anthropic.claude-opus-4-7).
2026-04-21 11:57:06 +08:00
Jason 50431b7ec9 feat(usage-script): add User-Agent header to New API template
Align the New API usage query template with the GENERAL template by
including "User-Agent: cc-switch/1.0" in its request headers, so
cc-switch requests are identifiable in provider server logs and less
likely to be blocked by UA-based rate limiting on some New API
deployments.
2026-04-21 11:57:06 +08:00
Jason 8b65a31c7c feat(claude): upgrade effort toggle from "high" to "max"
Per Anthropic's effort parameter docs, "high" is the API default and
setting effortLevel="high" is equivalent to omitting the field entirely.
The toggle previously produced no effect.

Claude Opus 4.6, Sonnet 4.6, and Opus 4.7 now support a "max" level
that enables unconstrained reasoning. Rename the checkbox (effortHigh
-> effortMax) and write effortLevel="max" when toggled on. Existing
"high" values in user configs are left untouched.

Updates zh/en/ja locales and user-manual entries accordingly.
2026-04-21 11:57:06 +08:00
Jason d03e6f9951 chore(lint): pin Rust toolchain to 1.95 and adopt clippy 1.95 suggestions
- Add rust-toolchain.toml to align local and CI Rust versions, eliminating
  clippy roulette caused by `dtolnay/rust-toolchain@stable` drift.
- Fix 9 clippy 1.95 findings introduced by Hermes Phase 4-8 modules:
  * 4x unnecessary_sort_by  -> sort_by_key (with Reverse for desc)
  * 3x collapsible_match    -> match guards
  * 1x while_let_loop       -> while let
  * 1x useless_conversion   -> drop redundant .into_iter()
2026-04-21 11:57:06 +08:00
Jason 0ca36b9d51 fix: address Hermes review findings (5 medium issues)
- Add missing Hermes MCP import on first launch (lib.rs)
- Add Hermes branch in ProviderForm defaultValues fallback
- Include Hermes in session manager subtitle (zh/en/ja)
- Rename check_openclaw_stream to check_additive_app_stream
- Cache parsed HERMES_DEFAULT_CONFIG to avoid repeated JSON.parse
2026-04-21 11:57:06 +08:00
Jason e8953c286f feat: implement Hermes session manager with SQLite + JSONL support (Phase 6)
- Add hermes.rs session provider with dual-source scanning:
  SQLite (state.db) as primary, JSONL transcripts as fallback
- Dynamic schema discovery via PRAGMA table_info for SQLite resilience
- Use read_head_tail_lines for efficient JSONL metadata extraction
  (head 30 lines for metadata, tail 10 for last_active_at)
- Support both flat and nested JSONL message formats
- Add SQLite session loading and transactional deletion
- Register hermes in parallel session scan (thread::scope)
- Add "hermes" to frontend ProviderFilter type
- 7 unit tests covering JSONL parsing, SQLite source parsing, deletion
2026-04-21 11:57:06 +08:00
Jason 240969d8c7 feat: add Hermes UI components, presets, and config panels (Phase 8)
- Add 7 provider presets (OpenRouter, Anthropic, OpenAI, Google, DeepSeek, Together, Nous)
- Create HermesFormFields + useHermesFormState for provider form integration
- Create Model/Agent/Env config panels with save/load functionality
- Create HermesHealthBanner for config warnings
- Add hermes icon (violet winged H) to icon system
- Integrate into App.tsx: 3 new view types (hermesModel/hermesAgent/hermesEnv),
  sidebar buttons (Brain/Bot/KeyRound), health banner, session support
- Integrate into ProviderForm: presets, form state, key validation, rendering
- Integrate into AddProviderDialog: universal tab exclusion, providerKey, base_url extraction
- Add i18n keys for all Hermes UI (zh/en/ja)
2026-04-21 11:57:06 +08:00
Jason a0b585992a feat: add Hermes frontend types, API layer, and hooks (Phase 7)
- Add "hermes" to AppId union type and all exhaustive Record<AppId>
- Add HermesModelConfig, HermesAgentConfig, HermesEnvConfig types
- Add hermes field to VisibleApps, McpApps, ProxyTakeoverStatus
- Create src/lib/api/hermes.ts with Tauri invoke wrappers
- Create src/hooks/useHermes.ts with 5 query + 3 mutation hooks
- Register hermes in APP_IDS, APP_ICON_MAP (violet color scheme)
- Split MCP_SKILLS_APP_IDS into MCP_APP_IDS (includes hermes) and
  SKILLS_APP_IDS (excludes hermes, since Hermes has no Skills support)
- Wire hermes additive-mode into App.tsx (remove/duplicate handlers),
  ProviderList.tsx (live provider ID query + In Config badge),
  mutations.ts (cache invalidation on switch/add/delete)
- Add Hermes checkbox to McpFormModal
- Add basic hermes i18n keys (en/zh/ja)
2026-04-21 11:57:06 +08:00
Jason 576ff53a75 feat: implement Hermes MCP sync module (Phase 4)
Add mcp/hermes.rs with bidirectional MCP format conversion:
- convert_to_hermes_format: strip type field, infer from command/url
- convert_from_hermes_format: infer type, strip Hermes-specific fields
- Merge-on-write: existing Hermes fields (tools, sampling, timeout,
  roots, enabled) preserved when user has customized them
- update_mcp_servers_yaml: closure-based read-modify-write under write
  lock to prevent TOCTOU races in concurrent sync operations
- 9 unit tests for format conversion and merge logic

Wire up all MCP service dispatch:
- Replace Hermes TODO stubs with real sync/remove calls
- Remove Hermes from sync_all_enabled skip list
- Enable deep link hermes MCP flag (apps.hermes = true)
- Add Hermes import to import_mcp_from_apps command
2026-04-21 11:57:06 +08:00
Jason 6d0e9f4c74 feat: implement Hermes config module and commands (Phase 3)
Add hermes_config.rs (~1190 lines) with YAML section-level replacement
that preserves comments and formatting in unmanaged sections:
- Type definitions: HermesModelConfig, HermesAgentConfig, HermesEnvConfig
- YAML section finder (find_yaml_section_range) with column-0 key detection
- Provider CRUD on custom_providers array (indexed by name field)
- Model/Agent config get/set via yaml<->json conversion
- .env dotenv read/write preserving comments and line ordering
- Health check, backup with rotation, write lock (OnceLock<Mutex>)
- MCP section access stubs for Phase 4
- 19 unit tests

Add commands/hermes.rs with 10 Tauri commands registered in lib.rs.
Replace all Hermes TODO stubs in services/provider/live.rs with real
implementations (import, remove, write-to-live, read-live-settings).
2026-04-21 11:57:06 +08:00
Jason a2e9e1938b feat: add database migration v9→v10 for Hermes support (Phase 2)
- Bump SCHEMA_VERSION from 9 to 10
- Add enabled_hermes column to mcp_servers and skills tables
- Add migrate_v9_to_v10 with table_exists guard for skills (may not
  exist in databases migrated from very old versions)
- Update dao/mcp.rs to fully read/write enabled_hermes in all queries
- Update dao/skills.rs: don't SELECT enabled_hermes (Hermes doesn't
  support Skills yet), keep column indices clean
2026-04-21 11:57:06 +08:00
Jason 81af0a57f9 feat: add Hermes Agent as 6th supported app type (Phase 1)
Register AppType::Hermes across the entire Rust backend:
- Add Hermes variant to AppType enum with additive mode and MCP support
- Add hermes field to McpApps, SkillApps, CommonConfigSnippets, and all
  per-app structs (McpRoot, PromptRoot, VisibleApps, AppSettings)
- Create minimal hermes_config.rs with get_hermes_dir() respecting
  settings override, matching the pattern of other app config modules
- Update all match arms in commands, services, deeplink, proxy, mcp,
  session_manager, and test files
- Extract shared build_additive_app_settings() to eliminate duplication
  between OpenClaw and Hermes deep link handling
- Combine identical OpenClaw/Hermes proxy match arms into unified arms
2026-04-21 11:57:06 +08:00
Jason 701e7d9581 fix: surface backend error details in proxy toast messages
The takeover.failed i18n template lacked the {{detail}} placeholder
and three useProxyStatus onError callbacks omitted the detail variable,
so proxy start/stop/takeover failures all displayed a generic message
regardless of the underlying cause.
2026-04-21 11:57:06 +08:00
Jason e4c34b34e7 fix: remove ANTHROPIC_REASONING_MODEL to decouple thinking from model selection (#2081)
ANTHROPIC_REASONING_MODEL was a non-official env var that forced all
requests with thinking params to use a single "reasoning model",
overriding the user's /model selection. Since new Claude Code versions
send adaptive thinking by default, this caused /model to silently fail.

- Remove reasoning_model field and has_thinking_enabled() from model_mapper
- Simplify map_model() to pure type-based matching (haiku/sonnet/opus)
- Remove reasoning model UI field from provider form
- Retain ANTHROPIC_REASONING_MODEL in ENV_EXCLUDES and override-key
  cleanup lists so legacy configs don't leak into common config
2026-04-21 11:57:06 +08:00
Jason eab0a69d2c fix: unify weekly_limit tier label to match official 7-day naming 2026-04-21 11:57:06 +08:00
Jason 4e790ac059 fix: hide unknown subscription quota tiers from provider card UI 2026-04-21 11:57:06 +08:00
chengww c5b15dd25e fix(claude-plugin): sync current provider config to settings.json (#1905)
* fix(claude-plugin): sync current provider config to settings.json on toggle enable

- Extract syncClaudePluginIfChanged to share logic between autoSaveSettings and saveSettings
- Fix P1: enableClaudePluginIntegration toggle in General tab now actually syncs ~/.claude/settings.json
- Fix P2: check syncCurrentProvidersLiveSafe() return value and show toast on failure
- Fix P3: sync providers on both enable and disable, not just enable
- Fix P4: avoid double syncCurrentProvidersLiveSafe when plugin toggle + dir change happen together
- Remove duplicate comment
- Add missing providersApi.getCurrent/getAll mocks in tests

* style: reformat after rebase onto main

Prettier flagged a line-break introduced by the openclaw directory
change (from main) after rebase.

* fix(claude-plugin): read prev enabled state from live cache to avoid stale closure

syncClaudePluginIfChanged compared enabled against data?.enableClaudePluginIntegration
captured in a useCallback closure. After invalidateQueries + refetch, the React
Query cache is up to date, but the consuming hook's closure does not see the new
value until React re-renders. Quick on->off toggles could therefore skip
applyClaudePluginConfig, leaving ~/.claude/config.json in the previously enabled
state even though settings.json was persisted as disabled.

Read the previous value synchronously from queryClient.getQueryData(["settings"])
before saveMutation.mutateAsync(), then pass it to the helper as prevEnabled.
getQueryData bypasses the closure and reflects the live cache at call time.

Test covers the race: closure data stays at false while the cache reports true;
the helper must still call applyClaudePluginConfig({ official: true }).

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-21 11:56:13 +08:00
zxZeng cc77a040e2 fix: common config checkbox state not persisting for Codex/Claude/Gemini (#2191)
修复:Codex/Claude/Gemini 通用配置勾选状态无法正确保存的问题

Co-authored-by: 曾兴 <zengx@gantsoftware.com>
2026-04-21 11:04:31 +08:00
hengm3467 1b345fbefb Add StepFun and StepFun en Step Plan presets (#2155)
* Add StepFun CN and EN presets

* Add StepFun 2603 model presets

* Make StepFun 2603 the default model

* Revert StepFun branding assets
2026-04-21 10:46:26 +08:00
Li Yang 61bfc29d82 fix(tray): use an app-specific tray id (#1978)
Co-authored-by: liyang <liyang25@pku.edu.cn>
2026-04-21 10:42:59 +08:00
Suda202 2c9252dec5 Fix Ghostty session restore launch path (#1976)
* fix: launch Ghostty via shell command

Use Ghostty's shell execution path instead of injecting raw terminal input so Claude resume commands run reliably when opening a session terminal.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(ghostty): pass cwd via --working-directory instead of shell string

Use Ghostty's native --working-directory flag to set the working
directory, matching the pattern used by Alacritty. This avoids shell
expansion of special characters (e.g. $VAR, spaces) in project paths.

The command is now passed directly to -c without a cd prefix.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 12:42:00 +08:00
Franklin 34349a2743 Add OpenClaw config directory settings (#1518)
Co-authored-by: 张斌 <zhangbin25@xiaomi.com>
2026-04-20 08:44:38 +08:00
King 8ba92b5470 feat(ui): add quick-set button for model mapping fields (#2179)
* feat(ui): add quick-set button for model mapping fields

Add a "一键设置" (Quick Set) button in the model mapping section to
simplify provider configuration. When users enter a model name in any
of the five model fields, they can now click this button to populate
all fields with that same value.

This addresses the UX friction of manually filling all five model
mapping fields (主模型, 推理模型, Haiku, Sonnet, Opus) when the
provider uses the same model name across all request types.

Implementation:
- Add Wand2 icon import from lucide-react
- Insert quick-set button alongside existing fetch-models button
- Logic picks first non-empty model value and applies to all fields
- Show success toast after applying
- Disabled state when all model fields are empty
- Add i18n strings for zh, en, ja locales

Relates to user feedback about tedious model configuration workflow.

* style(ui): format ClaudeFormFields component code

Apply consistent code formatting to ClaudeFormFields.tsx following
project linting rules. Includes multi-line import statements and
improved readability for conditional expressions.
2026-04-19 21:42:17 +08:00
hotelbe 87635e7fc6 feat(copilot): add GitHub Enterprise Server support (#2175)
* feat(copilot): add GitHub Enterprise Server support

* fix(copilot): address GHES PR review findings (P1 + 2×P2)

- P1: Use composite account ID (domain:user_id) for GHES to prevent
  cross-instance ID collisions; github.com keeps plain numeric ID for
  backward compatibilit
- P2-a: Use get_api_endpoint() for model list URL with automatic
  fallback to static URL when dynamic endpoint resolution fails
- P2-b: Add normalize_github_domain() as backend SSOT for domain
  normalization (lowercase, strip protocol/path/query, reject userinfo)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 20:29:46 +08:00
YaoguoHH 9871d3d1eb fix(skills): sync imported skills to app directories after import (#2101)
`import_from_apps()` saves skills to the database but does not create
symlinks/copies in the target app directories (e.g. `~/.claude/skills/`).
This causes skills to appear as "installed" in the UI while the actual
files are missing from the app directories.

Add `sync_to_app_dir()` calls after `db.save_skill()` in the import
loop, matching the pattern used by `install()` and `toggle_app()`.
2026-04-19 15:25:25 +08:00
Coconut-Fish 1126c7459d Style/add provider.notes (#2138)
* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 显示供应商备注信息

* style(FailoverQueueItem): 添加供应商备注字段以支持备注信息显示

* style(FailoverQueueManager): 更新供应商备注信息的显示样式

* style(FailoverQueueItem): 添加条件序列化以优化供应商备注字段
2026-04-18 17:48:58 +08:00
Dex Miller 03a0f9661b feat(proxy): Gemini Native API proxy integration (#1918)
* refactor(proxy): extract take_sse_block helper with CRLF delimiter support

Replace inline `buffer.find("\n\n")` SSE splitting logic across streaming,
streaming_responses, response_handler, and response_processor with a shared
`take_sse_block` function that handles both `\n\n` and `\r\n\r\n` delimiters.

* feat(proxy): add Gemini Native URL builder and full-URL resolver

Introduce gemini_url module that normalizes legacy Gemini/OpenAI-compatible
base URLs into canonical models/*:generateContent endpoints. Supports both
structured Gemini URLs (auto-normalized) and opaque relay URLs (pass-through
with query params only).

* feat(proxy): add Gemini Native schema, shadow store, transform, and streaming

- gemini_schema: Gemini generateContent request/response type definitions
- gemini_shadow: session-scoped shadow store for thinking signature and
  tool-call state replay across streaming chunks
- transform_gemini: bidirectional Anthropic Messages ↔ Gemini Native
  request/response conversion with thinking block and tool-use support
- streaming_gemini: Gemini SSE → Anthropic SSE streaming adapter with
  incremental thinking/text/tool_use delta emission

* feat(proxy): wire Gemini Native format into proxy core and Claude adapter

Integrate gemini_native api_format throughout the proxy pipeline:
- ClaudeAdapter: detect Gemini provider type, Google/GoogleOAuth auth
  strategies, and suppress Anthropic-specific headers for Gemini targets
- Forwarder: Gemini URL resolution, shadow store threading, endpoint
  rewriting to models/*:generateContent with stream/non-stream variants
- Handlers: route Gemini streaming through streaming_gemini adapter and
  non-streaming through transform_gemini converter
- Server/State: add GeminiShadowStore to shared ProxyState
- StreamCheck: support gemini_native health check with proper auth headers

* feat(ui): add Gemini Native provider preset and api format option

- Add gemini_native to ClaudeApiFormat type and ProviderMeta.apiFormat
- Add "Gemini Native" provider preset with default Google AI endpoints
- Show Gemini-specific endpoint hints and full-URL mode guidance
- Add gemini_native option to API format selector in ClaudeFormFields
- Add i18n strings for zh/en/ja

* feat(proxy): add Gemini Native tool argument rectification

* feat(proxy): update Gemini streaming and transformation logic

* fix(proxy): align shadow turns to tail on client history truncation

* fix: revert unrelated cache_key change in claude proxy transform

Restore .unwrap_or(&provider.id) fallback for cache_key to match main
branch behavior. Only gemini_native related changes should be in this branch.

* Prevent Gemini review regressions in streaming and tool rectification

PR #1918 review feedback exposed two correctness issues in the Gemini Native adapter path. Gemini SSE buffering was still using lossy UTF-8 decoding, which could corrupt split multibyte payloads and drop streamed output. Tool arg rectification also removed top-level parameters eagerly, which broke tools that legitimately define a parameters field.

This change moves Gemini SSE buffering onto the existing append_utf8_safe path and makes parameters flattening conditional on the schema actually expecting nested extraction. The old Skill rectification path stays intact, and new regression tests cover both the preserved parameters case and UTF-8-split JSON payloads.

Constraint: Existing PR #1918 review feedback must be fixed without staging unrelated local docs and artifact files
Rejected: Keep String::from_utf8_lossy in Gemini SSE buffering | corrupts split multibyte payloads and can drop JSON chunks
Rejected: Always preserve the parameters wrapper | regresses the existing nested-parameters rectification path for Skill-style tools
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep Gemini SSE buffering on the UTF-8-safe accumulator path and only unwrap parameters when the target schema does not declare it as a legitimate field
Tested: cargo fmt --manifest-path src-tauri/Cargo.toml --all; cargo test --manifest-path src-tauri/Cargo.toml preserves_utf8_boundaries_when_json_payload_spans_chunks; cargo test --manifest-path src-tauri/Cargo.toml gemini_to_anthropic_rectifies_tool_args_from_schema_hints; cargo test --manifest-path src-tauri/Cargo.toml rectifies_streamed_skill_args_from_nested_parameters; cargo test --manifest-path src-tauri/Cargo.toml gemini_to_anthropic_preserves_legitimate_parameters_arg
Not-tested: Full src-tauri test suite; live end-to-end Gemini relay traffic against upstream services

* Keep Gemini tool replay stable across Claude request boundaries

Claude Code follow-up requests were still falling back to locally reconstructed functionCall parts, which dropped Gemini thought signatures and triggered INVALID_ARGUMENT errors from the official Gemini API. The replay path needed to survive real Claude request boundaries, not just idealized in-process test flows.

This change makes Claude requests reuse X-Claude-Code-Session-Id as the shadow session key, records streamed Gemini tool turns before tool_use events are fully drained, and matches assistant tool_use turns to shadow state by tool_use id and normalized tool name before positional fallback. Together these fixes keep thoughtSignature-bearing Gemini tool calls available for the next request in the loop.

Constraint: Claude Code sends a stable X-Claude-Code-Session-Id header while metadata.session_id may be absent on follow-up requests
Rejected: Rely on metadata-only Claude session extraction | generated fresh session ids and broke cross-request shadow replay
Rejected: Record Gemini shadow only after streaming completes | loses the race when the client sends the next request immediately after tool_use
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Preserve Gemini shadow continuity across requests by keying Claude sessions from the header first and persisting tool-call shadow before yielding tool_use events downstream
Tested: cargo fmt --manifest-path src-tauri/Cargo.toml --all; cargo test --manifest-path src-tauri/Cargo.toml test_extract_session_from_claude_header; cargo test --manifest-path src-tauri/Cargo.toml test_extract_session_from_claude_header_precedes_metadata; cargo test --manifest-path src-tauri/Cargo.toml stores_tool_shadow_before_tool_use_events_are_fully_drained; cargo test --manifest-path src-tauri/Cargo.toml shadow_replay_matches_tool_use_turn_by_id_when_position_drifts; cargo test --manifest-path src-tauri/Cargo.toml shadow_replay_aligns_to_latest_turns_after_client_truncation
Not-tested: Full src-tauri test suite without test filters; live end-to-end Gemini relay after this exact commit hash

* style: apply cargo fmt to pass Backend Checks CI

Wrap prompt_cache_key chained call across lines per rustfmt default
formatting. Pure formatting change, no behavior difference.

* fix(proxy/gemini): synthesize unique ids for no-id tool calls + enforce object params schema

P1 — Parallel tool calls without Gemini-assigned ids no longer collapse.
Gemini 2.x native parallel `functionCall` entries may omit the `id` field.
The previous `merge_tool_call_snapshots` fell back to matching by `name`,
which silently merged two parallel calls to the same function into one
entry — dropping the first call's args. The non-streaming path and shadow
store further bottlenecked on empty-string ids: multiple `tool_use` blocks
shared the same id, and `tool_name_by_id.get("")` could only return one
mapping, causing later `tool_result` round-trips to fail with
`Unable to resolve Gemini functionResponse.name` or bind to the wrong tool.

Fix: introduce `synthesize_tool_call_id()` producing `gemini_synth_<uuid>`.
Both streaming and non-streaming response paths now guarantee every
Anthropic-visible tool_use carries a unique id. `merge_tool_call_snapshots`
matches by id first, falling back to the `parts` array position (for the
cumulative-streaming case) while preserving the synthesized id across
chunks. `convert_message_content_to_parts` detects the synthetic prefix
and strips the id from outbound `functionCall`/`functionResponse` so the
internal identifier never leaks upstream. `shadow_parts` performs the
same strip when replaying a recorded assistant turn.

P2 — Vertex AI rejects empty `parameters` schemas. When an Anthropic tool
arrives with missing or empty `input_schema`, the proxy used to emit
`"parameters": {}` (no `type`), which fails Vertex AI validation with
`functionDeclaration parameters schema should be of type OBJECT`.
Contrary to the automated-review suggestion, the fix is not to omit
`parameters` (that too is rejected) but to normalize to the canonical
empty-object form `{type: "object", properties: {}}`.
Refs: google-gemini/generative-ai-python#423, BerriAI/litellm#5055.

Fix: new `ensure_object_schema` helper in `gemini_schema` promotes
missing `type` to `"object"` and adds empty `properties` when absent,
while leaving atomic (non-object) schemas untouched.

Tests: seven new regressions covering parallel no-id calls, cumulative
chunk id reuse, synthetic-id round-trip both directions, shadow replay
id stripping, and the three Vertex-AI schema shapes.

The two existing wrapper functions (`gemini_to_anthropic` and
`gemini_to_anthropic_with_shadow`) gain `#[allow(dead_code)]` to clear
a pre-existing clippy -D warnings failure — they are part of the public
transform API surface and intentionally kept for future callers.

Addresses Codex review P1/P2 on #1918.

* fix(proxy/gemini): narrow URL normalization + guard empty OAuth access_token

P2a — Preserve opaque relay URLs that contain `/v1/models/` prefixes.

`should_normalize_gemini_full_url` previously flagged any full URL whose
path merely contained `/v1beta/models/` or `/v1/models/` as a structured
Gemini endpoint, forcing rewrite to `.../v1beta/models/{model}:method`.
This silently dropped legitimate relay route segments (e.g.
`https://relay.example/v1/models/invoke` → `.../v1beta/models/...:generateContent`,
losing `/invoke`) and sent traffic to the wrong upstream path.

Replace the bare `contains(...)` checks with
`matches_structured_gemini_models_path`, which requires the
`/models/` segment to be followed by a canonical Gemini method call
(`*:generateContent` or `*:streamGenerateContent`). The
`matches_bare_gemini_models_path` helper is generalized (and renamed) to
handle both `/v1beta/models/` and `/v1/models/` alongside the original
bare `/models/` shape.

P2b — Reject empty Gemini OAuth access_tokens before they reach the
bearer header.

`GeminiAdapter::parse_oauth_credentials` accepts refresh-token-only JSON
(and surfaces `{"access_token": "", ...}` for expired credentials) with
`access_token` defaulting to `""`. The Claude adapter's GeminiCli branch
then called `AuthInfo::with_access_token(key, creds.access_token)`
unconditionally, so the bearer-header builder at
`AuthStrategy::GoogleOAuth` resolved to `Authorization: Bearer ` — a
deterministic 401 from upstream.

CC Switch does not currently exchange the refresh_token for a fresh
access_token (`OAuthCredentials::needs_refresh` / `can_refresh` are
annotated `#[allow(dead_code)]`). Until that exists, only attach
`access_token` when it is non-empty; fall back to plain GoogleOAuth
strategy with the raw key and log a warn pointing users at
`~/.gemini/oauth_creds.json` so the failure mode is observable.

Tests:
- gemini_url.rs: three new regressions — opaque `/v1/models/invoke`,
  opaque `/v1beta/models/route`, and the positive counter-case where a
  structured `/v1/models/...:generateContent` path still normalizes.
- claude.rs: three new `test_extract_auth_gemini_cli_*` tests covering
  refresh-only JSON, empty-string access_token JSON, and the valid-JSON
  pass-through.

All 839 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex review P2 findings on #1918.

* fix(proxy/gemini): treat empty-string functionCall id as missing in streaming path

Follow-up to the earlier P1 fix: some Gemini relays serialize an absent
functionCall id as `"id": ""` instead of omitting the field. The
non-streaming `extract_tool_call_meta` already filters these via
`.filter(|s| !s.is_empty())`, but the streaming counterpart
`extract_tool_calls` passed the empty string straight through
`function_call.get("id").and_then(|v| v.as_str())` into
`GeminiToolCallMeta::new`, producing a `Some("")` id.

Downstream, `merge_tool_call_snapshots` would then match two parallel
no-id calls against each other on their shared empty-string id,
collapsing them into a single snapshot (silent data loss for the first
call) and emitting an Anthropic `tool_use.id: ""` that breaks tool_result
correlation on the Claude Code client.

Fix:
- `extract_tool_calls`: apply the same `filter(|s| !s.is_empty())` guard
  used in the non-streaming path so empty strings become `None` before
  reaching the shadow meta.
- `merge_tool_call_snapshots`: defensively collapse any incoming
  `Some("")` to `None` up front — keeps the "missing vs present" invariant
  local to the merge step for future callers that might build
  `GeminiToolCallMeta` by hand.

Tests (2 new, both in streaming_gemini):
- `parallel_empty_string_id_calls_are_treated_as_missing_and_preserved`
  covers two parallel calls with explicit `"id": ""` — asserts both
  surface, no empty tool_use id leaks, and each gets a unique
  `gemini_synth_` id.
- `single_empty_string_id_tool_call_gets_synthesized_id` covers the
  non-parallel degraded-relay case.

All 841 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex follow-up P1 on #1918.

* fix(proxy/gemini): gate generic REST path suffixes behind Google host whitelist

`should_normalize_gemini_full_url` previously treated any full URL whose
path ends with `/v1`, `/v1/models`, `/models`, `/v1/openai`, or `/openai`
as a structured Gemini endpoint and rewrote it to
`/v1beta/models/{model}:generateContent`. These are ubiquitous REST
conventions — opaque relays such as `https://relay.example/custom/v1`
legitimately use them for fixed endpoints — so the rewrite silently
routed traffic to the wrong upstream path.

Split the predicate into two layers:

- **Unconditional**: `matches_structured_gemini_models_path` (i.e. a
  `/models/...:generateContent` method call anywhere in the path), the
  Google-specific `/v1beta*` family, and the deep OpenAI-compat paths
  (`/v1beta/openai/chat/completions`, `/openai/chat/completions`, and
  their `responses` siblings). These remain host-agnostic because the
  path grammar itself is Gemini-specific.
- **Google-host gated**: `/v1`, `/v1/models`, `/models`, `/v1/openai`,
  `/openai`. Only normalized when the host is one of
  `generativelanguage.googleapis.com`, `aiplatform.googleapis.com`, or a
  real `*-aiplatform.googleapis.com` Vertex regional endpoint. The match
  is exact/suffix (not `contains`), so lookalike hosts like
  `aiplatform.example.com` are correctly treated as opaque relays.

Tests (8 new in `gemini_url::tests`):
- Four opaque-relay cases: `/custom/v1`, `/custom/models`,
  `/custom/v1/models`, `/custom/openai` — all preserved as-is.
- Three Google-host counter-cases: `/v1`, `/models`, and
  `us-central1-aiplatform.googleapis.com/v1` still normalize.
- One lookalike safety case: `aiplatform.example.com/v1` is NOT
  treated as Google.

All 849 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex review P2 on #1918.

* fix(proxy/gemini): align shadow id with client-visible id in non-streaming path

When Gemini returns a `functionCall` without an id (common in 2.x
parallel calls), `gemini_to_anthropic_with_shadow_and_hints` previously
generated TWO independent synthesized UUIDs:

  1. Line 186-197 — synthesized id `A` used for the Anthropic-visible
     `content[tool_use].id` returned to the client.
  2. Line 850-881 — `extract_tool_call_meta` independently synthesized
     id `B ≠ A`, which populated `shadow_turn.tool_calls[i].id`.

`shadow_content` (line 225-228, cloned from `rectified_parts`) retained
the original missing/empty id. Result: the client sees id `A`, the
shadow store holds id `B`.

On the next turn, `convert_messages_to_contents` builds
`tool_name_by_id` from `build_tool_name_map_from_shadow_turns`, which
uses `tool_calls[i].id` — so the map contains `B → name` but not
`A → name`. When the client sends back `tool_result(tool_use_id=A)`,
resolution fails with:

  Unable to resolve Gemini functionResponse.name for tool_use_id `A`

This affects both truncated histories (client sends only the
tool_result) and full histories (shadow-replay branch at line 342-354
skips `convert_message_content_to_parts`, so the assistant tool_use
block never registers id `A` itself).

Fix: make `rectified_parts` the single source of truth. After
`rectify_tool_call_parts`, run a pre-pass that writes
`synthesize_tool_call_id()` back into any `functionCall` that lacks a
non-empty id. All three readers — the content builder (186-197), the
shadow_content clone (225-228), and `extract_tool_call_meta` — then
observe the same id. `shadow_parts()` already strips synthesized ids on
replay (line 616-628), so the internal identifier never leaks to
Gemini upstream.

This mirrors the streaming path, which already has single-source-of-
truth semantics via `tool_call_snapshots` in `streaming_gemini.rs` —
no change needed there.

Tests (5 new in `transform_gemini::tests`):
- `non_stream_shadow_id_matches_client_visible_id`: asserts
  `response.content[0].id == shadow.tool_calls[0].id ==
  shadow.assistant_content.parts[0].functionCall.id`.
- `non_stream_missing_id_scenario_a_truncated_history_resolves`: turn 2
  sends only `[tool_result(id=A)]`; resolution must succeed.
- `non_stream_missing_id_scenario_b_full_history_replay_resolves`: turn 2
  sends `[assistant(tool_use=A), tool_result(A)]`; shadow-replay branch
  strips the synth id from outgoing `functionCall` while still
  resolving the subsequent `tool_result`.
- `non_stream_preserves_original_gemini_id_when_present`: regression —
  genuine Gemini ids flow through unchanged.
- `non_stream_synthesized_id_not_leaked_to_gemini_via_shadow_replay`:
  defensive — shadow-replay path must strip synth ids from both
  `functionCall.id` and `functionResponse.id`.

All 854 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex follow-up P1 on #1918.

* refactor(proxy/gemini): share build_anthropic_usage between stream and non-stream paths

`streaming_gemini::anthropic_usage_from_gemini` and
`transform_gemini::build_anthropic_usage` were byte-for-byte identical
(32 lines each) — both converting Gemini `usageMetadata` into the
Anthropic `usage` shape including `cache_read_input_tokens` mapping.

Promote the non-streaming version to `pub(crate)` and reuse it from the
streaming SSE converter. Removes ~30 lines of duplication and guarantees
the two paths cannot drift apart.

No behavioral change; all 854 lib tests pass; cargo fmt + clippy -D
warnings clean.

* fix(proxy/gemini): gate /v1beta behind Google host + normalize models/ model id prefix

Two related P2 corrections to the Gemini Native URL surface, both
folding into the existing Google-host-whitelist architecture.

## P2a — `/v1beta` suffix should not unconditionally trigger rewrite

`should_normalize_gemini_full_url` placed `/v1beta` and `/v1beta/models`
in the unconditional layer on the reasoning that `/v1beta` is
Google-specific. In practice an opaque relay fronting a non-Gemini
service at `https://relay.example/custom/v1beta` would still be
silently rewritten to `/v1beta/models/{model}:generateContent`,
breaking the deployment.

Move `/v1beta`, `/v1beta/models`, and `/v1beta/openai` into the
Google-host gated layer alongside `/v1`, `/models`, and friends. The
unconditional layer now only accepts paths whose grammar is
intrinsically Gemini — `/models/...:generateContent` method calls and
the deep OpenAI-compat endpoints like `/openai/chat/completions` and
`/openai/responses`. Pasted AI-Studio URLs such as
`https://generativelanguage.googleapis.com/v1beta` still normalize
because the host matches the whitelist.

## P2b — `model: "models/gemini-2.5-pro"` produced doubled path prefix

Gemini SDKs (and the official `list_models` response) commonly surface
model ids in resource-name form `models/gemini-2.5-pro`. Raw
interpolation into `format!("/v1beta/models/{model}:...")` produced
`/v1beta/models/models/gemini-2.5-pro:streamGenerateContent` which
upstream rejects — yielding false-negative health checks for otherwise
valid provider configs.

Introduce `normalize_gemini_model_id(&str) -> &str` in `gemini_url`
as the single source of truth: strips an optional leading `/` then an
optional `models/` prefix, leaving bare ids untouched. Apply in the
three call sites that build a Gemini method URL:
- `services/stream_check.rs::resolve_claude_stream_url` (unified path)
- `services/stream_check.rs::check_gemini_stream` (Gemini-only path)
- `proxy/forwarder.rs::rewrite_claude_transform_endpoint` (production)

Tests (9 new):
- `gemini_url`: 3 regressions for opaque vs Google-host `/v1beta*`
  handling + 5 unit tests pinning `normalize_gemini_model_id` behavior
  (strip prefix, leave bare id, preserve nested slashes past the one
  stripped prefix, tolerate leading slash, pass through empty input).
- `stream_check`: one end-to-end regression confirming
  `models/gemini-2.5-pro` collapses to the expected single-prefix URL.
- `forwarder`: one end-to-end regression on the production rewrite
  path.

All 864 lib tests pass; cargo fmt + clippy -D warnings clean.

Addresses Codex P2 feedback on #1918.

* fix(proxy/gemini): trim API key before provider-type detection and OAuth parsing

Leading whitespace on a copied oauth_creds.json (e.g. trailing newline
when the user copies the file content as-is) would slip past the
`starts_with("ya29.") || starts_with('{')` prefix check in
`ClaudeAdapter::provider_type`, causing the provider to be misclassified
as raw-API-key Gemini and fall back to `x-goog-api-key` with the raw
JSON as the key — which upstream rejects with 401.

The frontend's `handleApiKeyChange` already trims on keystrokes but
deep-link imports, the JSON editor, and live-config backfill all bypass
that path. Trim at every backend extraction point so the coverage is
uniform:

- `ClaudeAdapter::extract_key` (5 env / fallback branches) gets
  `.map(str::trim)` before `.filter(|s| !s.is_empty())` so that
  whitespace-only values are also treated as missing.
- `GeminiAdapter::extract_key_raw` gets the same chain (including
  the `.filter` it was missing before).
- `GeminiAdapter::parse_oauth_credentials` gets a defensive
  `let key = key.trim();` at the entry as a belt-and-suspenders guard.

Adds two regression tests covering JSON and bare `ya29.` keys with
leading newline/space.

* fix(proxy/gemini): gate generic REST suffix stripping behind Google host in non-full-URL mode

`build_gemini_native_url` unconditionally stripped `/v1`, `/v1beta`,
`/models`, and `/openai` suffixes from the base path regardless of
host. This worked for Google's own endpoints but silently rewrote
third-party relay URLs like `https://relay.example/custom/v1` to
`.../custom/v1beta/models/...`, breaking any relay that mounts its
Gemini-compatible namespace under a versioned prefix.

The result was also asymmetric with the previously-fixed full-URL
branch: toggling the "full URL" switch changed the outbound URL for
the same base_url, which is exactly the kind of invisible behavior
that makes debugging proxy deployments painful.

Align `normalize_gemini_base_path` with
`should_normalize_gemini_full_url`'s layered model:

- Unconditional: `/models/...:method` structured paths and deep
  OpenAI-compat endpoints (`/openai/chat/completions`,
  `/openai/responses` and their versioned variants) — these are
  unambiguous Gemini-specific grammar on any host.
- Google-host gated: generic `/v1`, `/v1beta`, `/models`, `/openai`
  suffixes only get stripped on `generativelanguage.googleapis.com`,
  `aiplatform.googleapis.com`, or `*-aiplatform.googleapis.com`.
  Other hosts preserve the prefix verbatim so relays keep their
  intended routing.

Adds seven regression tests for the non-full-URL flow: opaque relay
preservation (v1 / v1beta / models / openai suffix variants), Google
host normalization (counter-case), and boundary cases (structured
method path and deep OpenAI-compat endpoint stripped regardless of
host).

Test count: 864 -> 873.

* Revert "fix(proxy/gemini): gate generic REST suffix stripping behind Google host in non-full-URL mode"

This reverts commit d19ff09cb7.

* test(proxy/gemini): pin non-full-URL versioned relay base stripping

Adds two regression tests that lock in the intentional asymmetry
between full-URL and non-full-URL modes:

- Full-URL mode: opaque base path (e.g. `https://relay.example/custom/v1beta`)
  is preserved verbatim. Already covered by
  `preserves_opaque_full_url_with_bare_v1beta_suffix`.
- Non-full-URL mode: base path MUST strip `/v1`, `/v1beta`, etc. so the
  standard `/v1beta/models/{model}:method` endpoint can be appended
  without producing a doubled `/v1beta/v1beta/models/...` path.

The non-full-URL contract is "base URL + cc-switch appends the
canonical Gemini endpoint". A user who needs a relay's custom
namespace (e.g. `/v1/models/...`) must use full-URL mode and paste
the complete method path. This commit adds regression coverage so a
future attempt to mirror full-URL's host-whitelist gating into
`normalize_gemini_base_path` will fail the test suite immediately.

* chore(lint): address clippy 1.95 findings in existing modules

CI upgraded to Rust 1.95 and flagged ten pre-existing warnings that
older toolchains did not enforce. None relate to the Gemini proxy
integration PR itself but they block CI on the feature branch, so
clean them up here as a separate commit for easy review:

collapsible_match:
- proxy/providers/gemini_schema.rs: `"items" if value.is_object()`
  match guard instead of nested if.
- proxy/providers/transform_responses.rs: fold
  `map_responses_stop_reason`'s `"completed"` / `"incomplete"` arms
  into match guards, relying on the existing `_ => "end_turn"` fall-
  through for non-matching guard conditions (semantics preserved).
- services/session_usage_codex.rs: fold
  `"session_meta" if state.session_id.is_none()` guard, relying on
  the existing `_ => {}` fall-through.

unnecessary_sort_by:
- services/provider/endpoints.rs: `sort_by_key(|ep| Reverse(ep.added_at))`.
- services/skill.rs (backup list): same Reverse idiom on `created_at`.
- services/skill.rs (skill listings x2): `sort_by_key(|s| s.name.to_lowercase())`.

useless_conversion:
- services/skill.rs: drop the explicit `.into_iter()` on `zip`'s argument.

while_let_loop:
- services/webdav_auto_sync.rs: `while let Some(wait_for) = ...`
  instead of `loop { let Some(...) = ... else { break }; ... }`.

All changes are mechanical and preserve behavior. `cargo test --lib`
remains green (868 passed).

* fix(proxy/gemini): reconcile synthesized tool-call ids with later real ids + preserve thoughtSignature

Three related findings on `streaming_gemini.rs` for Gemini's cumulative
`streamGenerateContent` stream, all centered on `merge_tool_call_snapshots`:

1. (P1) Match upgraded tool-call IDs by position.
   When Gemini delivers a `functionCall` without an id on chunk 1
   (cc-switch synthesizes `gemini_synth_*`) and then upgrades it to a
   real id on chunk 2, the `Some(incoming_id)` branch only matched by
   id and missed the existing synthesized snapshot. A second entry
   would be pushed, yielding duplicate `tool_use` content blocks at
   stream end — one with the synthesized id, one with the real id —
   which could trigger duplicate tool execution and break tool_result
   correlation. Add a positional fallback: when no id match exists but
   the same-position slot holds a synthesized id, merge into it.
   `or(preserved_id)` already lets the real id win the merge.

2. (P2) Preserve prior thoughtSignature when merging snapshots.
   `tool_call_snapshots[index] = tool_call` overwrote the slot
   entirely, dropping any `thoughtSignature` captured on an earlier
   chunk if the current cumulative snapshot omitted it. Since
   `build_shadow_assistant_parts` writes `thoughtSignature` into the
   shadow turn from `tool_call.thought_signature`, a dropped signature
   would cause later replay requests to Gemini to be rejected with
   invalid-signature errors. Preserve the existing signature when the
   incoming chunk does not carry one.

3. (P2) Document the part-order streaming trade-off.
   All `tool_use` content blocks are emitted after the final text
   `content_block_stop`, so interleaved [text, functionCall, text,
   functionCall] parts arrive at the Anthropic client as [text(concat),
   tool_use, tool_use] — different from the non-streaming transformer,
   which preserves part order. This is intentional given the cumulative
   snapshot model and the consumers we target (claude-code-like clients
   don't depend on strict interleaving for tool execution correctness).
   Add a block comment at the flush site describing the trade-off and
   what a strict-order fix would entail, so this isn't rediscovered as
   a bug later.

Regression tests:
- upgraded_real_id_merges_into_existing_synthesized_snapshot
- thought_signature_preserved_when_later_chunk_omits_it

Test count: 868 -> 870. clippy 1.95 clean. fmt clean.

* fix(proxy/gemini): prefer exact tool-call id over normalized-name fallback

The shadow-turn matcher used a three-branch `||` chain (id / full name /
normalized name). When two tools share a suffix (e.g. `server_a:search`
and `server_b:search`), the normalized-name clause could short-circuit
on an earlier turn whose id is actually wrong for the incoming tool_use,
mis-routing replay state (functionCall id / thoughtSignature) for later
tool_result resolution.

Split matching into two layers: when the incoming message carries any
tool_use ids, run id-based lookup first and return on the earliest hit.
Only fall back to full-name / normalized-name matching when the incoming
ids are absent or none of them resolve.

Add two regressions:

- shadow_replay_prefers_exact_id_match_over_normalized_name_collision
  Two shadow turns with colliding normalized names and two assistant
  messages whose ids cross the positional order; asserts each message
  replays the id-correct shadow turn (including thoughtSignature).

- shadow_replay_falls_back_to_name_when_ids_absent
  Shadow turn with no id and incoming tool_use with an empty id;
  asserts the name fallback still populates the replayed part.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-16 22:42:49 +08:00
Dex Miller de23216e49 feat(usage): refine usage dashboard UI and date range picker (#2002)
* feat(usage): enhance usage stats backend and query hooks

* feat(usage): redesign calendar date range picker with auto-switch and simplified layout

* refactor(usage): streamline dashboard layout and stats components

* refactor(usage): compact request log table with merged cache/multiplier columns and centered layout

* feat(i18n): add cache short labels and usage stats translations for zh/en/ja

* Align usage dashboard stats with range boundaries

The usage dashboard mixed second-precision detail rows with day-level rollups, which caused custom half-day ranges to overcount historical rollup data and left the request log paginator on stale pages after top-level filter changes.

This change limits rollups to fully covered local days, aligns multi-day trend buckets with natural local days, and resets request log pagination when the dashboard range or app filter changes.

Constraint: usage_daily_rollups stores only daily aggregates after pruning old detail rows
Rejected: Include partial boundary rollups proportionally | historical intra-day detail is unavailable after pruning
Rejected: Force RequestLogTable remount on range change | would discard local draft filters unnecessarily
Confidence: high
Scope-risk: moderate
Reversibility: clean
Directive: Keep summary, trends, provider stats, and model stats on the same rollup-boundary rules
Tested: cargo test --manifest-path src-tauri/Cargo.toml usage_stats
Tested: pnpm exec vitest run tests/components/RequestLogTable.test.tsx
Tested: pnpm typecheck
Not-tested: Manual UI validation in the Tauri app

* Preserve full-day usage filters at minute precision

The latest review surfaced two interaction bugs in the usage dashboard: rollup-backed stats undercounted end days selected via the minute-precision picker, and immediate select changes accidentally applied unsubmitted text drafts from the request log filters.

This change treats 23:59 as a fully selected local end day for rollup inclusion and narrows select-side state syncing so app/status updates do not commit provider/model drafts.

Constraint: The custom range picker emits minute-precision timestamps, while rollups are stored at day granularity
Rejected: Require exact 23:59:59 end timestamps | unreachable from the current picker UI
Rejected: Rebuild applied filters from the full draft state on select changes | silently commits unsaved text input
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Keep request-log text fields on explicit apply semantics even when select filters remain immediate
Tested: cargo test --manifest-path src-tauri/Cargo.toml usage_stats
Tested: pnpm exec vitest run tests/components/RequestLogTable.test.tsx
Tested: pnpm typecheck
Not-tested: Manual Tauri dashboard interaction

* refactor(usage): move range presets into date picker, single-row layout

- UsageDateRangePicker: add preset shortcuts (今天/1d/7d/14d/30d) inside
  popover top; clicking a preset applies immediately and closes popover
- UsageDashboard: collapse to single row (app filters + refresh + picker);
  remove standalone preset buttons and summary stats bar
- RequestLogTable: replace static Calendar badge with interactive
  UsageDateRangePicker via onRangeChange prop; single filter row

* Keep usage pagination regression coverage aligned with the rendered UI

The new regression test was asserting a non-existent pagination label and page summary text, so it failed before it could verify the real page-reset behavior. This commit switches the assertions to the numbered pagination buttons that the component actually renders and validates the reset through the query hook arguments.

Constraint: RequestLogTable exposes numbered pagination buttons, not a "Next page" label or "2 / 6" summary text
Rejected: Add synthetic pagination labels solely for the test | would couple production markup to a test-only assumption
Confidence: high
Scope-risk: narrow
Reversibility: clean
Directive: Prefer pagination assertions that follow the rendered controls or hook inputs instead of invented summary text
Tested: pnpm vitest run tests/components/RequestLogTable.test.tsx; pnpm typecheck; pnpm test:unit

* refactor(usage): clean up dead code and polish date range picker

- Remove unused exports MAX_CUSTOM_USAGE_RANGE_SECONDS,
  timestampToLocalDatetime, and localDatetimeToTimestamp from
  usageRange.ts (replaced by the calendar picker)
- Deduplicate getPresetLabel from UsageDashboard and
  UsageDateRangePicker into shared getUsageRangePresetLabel helper
- Add aria-label, aria-current and aria-pressed to calendar day
  buttons so screen readers can disambiguate same-numbered days
  across adjacent months
- Drop unused cacheReadShort and cacheWriteShort i18n keys (zh/en/ja);
  the request log table renders R/W prefixes inline
- Align customRangeHint copy with the removed 30-day limit by
  dropping "up to 30 days" wording (zh/en/ja)

* fix(usage): align rollup cutoff to local midnight to keep days complete

`rollup_and_prune` previously used `Utc::now() - retain_days * 86400`
as the cutoff. Because rollups are bucketed by *local* date and detail
rows below the cutoff are pruned, an unaligned cutoff left the youngest
rolled-up day half-rolled-up and half-pruned. Combined with the new
`compute_rollup_date_bounds` boundary trimming (which excludes any
rollup day not fully covered by the requested range), custom range
queries that touch that day silently under-count summary, trend,
provider, and model stats.

Fix the invariant at the source: snap the cutoff to the next local
midnight after `(now - retain_days)`. Every rollup row now reflects a
complete local day, so the boundary trimmer's all-or-nothing assumption
holds.

Includes unit tests for the cutoff math (typical case + already-on-
midnight case). DST gap is handled defensively by bumping forward by
an hour.

Addresses Codex P2 review finding on PR #2002.

---------

Co-authored-by: Jason <farion1231@gmail.com>
2026-04-16 17:00:28 +08:00
206 changed files with 20824 additions and 1992 deletions
+130
View File
@@ -5,6 +5,136 @@ All notable changes to CC Switch will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [3.14.1] - 2026-04-23
Development since v3.14.0 focuses on Codex OAuth stability, tray usage visibility, Skills import/install reliability, Gemini session restore paths, and simplifying Hermes configuration health handling.
**Stats**: 13 commits | 48 files changed | +1,883 insertions | -808 deletions
### Added
- **Tray Usage Visibility**: System tray submenus now show cached usage for the current Claude / Codex / Gemini provider, including subscription and script-based usage summaries with utilization color markers. Tray-triggered refreshes are throttled, limited to visible apps, and synchronized back into React Query so the main window and tray share fresh usage data (#2184).
- **Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)**: System tray now renders 5-hour + weekly window usage for Chinese coding-plan providers using the same `🟢 h12% w80%` two-window layout as official subscription badges (worst utilization drives the emoji). Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host now auto-injects `meta.usage_script`, so the tray lights up without opening the Usage Script modal. Existing `usage_script` values are preserved on update.
- **Codex OAuth FAST Mode**: Added an explicit FAST mode toggle for Codex OAuth-backed Claude providers. When enabled, converted Responses requests send `service_tier="priority"` for lower latency; the toggle stays off by default to avoid unexpectedly increasing ChatGPT quota consumption (#2210).
### Changed
- **Session and Settings Layout Polish**: Hardened the scroll-area viewport with width containment to fix horizontal overflow, and tightened app bottom spacing plus settings footer spacing so long session/settings views fit more cleanly (#2201).
### Removed
- **Hermes Config Health Scanner**: Removed the in-app Hermes config health scanner, warning banner, `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload. CC Switch now keeps the Hermes surface focused on active provider display, provider switching defaults, memory editing, and launching the Hermes Web UI for deep configuration.
### Fixed
- **Codex OAuth Cache Routing**: Stabilized ChatGPT Codex reverse-proxy cache identity by using client-provided session IDs for `prompt_cache_key` and Codex session headers, preserving explicit cache keys, and avoiding generated UUID cache churn (#2218).
- **Codex OAuth Responses SSE Aggregation**: Non-streaming Anthropic clients now receive JSON even when the ChatGPT Codex upstream forces OpenAI Responses SSE; CC Switch aggregates the upstream SSE events before running the non-streaming transform (#2235).
- **Codex OAuth Stream Check Parity**: Stream checks now build Codex OAuth test requests with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production proxy requests (#2210).
- **Codex Model Extraction**: Replaced first-line regex matching with TOML parsing when reading Codex config models, so multiline TOML is handled correctly (#2227).
- **Model Quick-Set / One-Click Config**: Model quick-set updates now apply against the latest provider form config, preventing stale state from making one-click configuration fail (#2249).
- **Skills Import Duplicates**: The Skills import dialog disables actions while import is pending and the installed-skills cache deduplicates imported results by ID, preventing double-clicks from adding duplicate installed entries (#2139, #2211).
- **Root-Level Skill Repos**: Skill install and update flows now consistently resolve three source patterns: direct nested paths, install-name recursive search, and repository-root `SKILL.md` sources (#2231).
- **Gemini Session Restore Paths**: Gemini session scanning now reads `.project_root` metadata so restore flows can pass the original project directory when available (#2240).
- **Provider Hover Names**: Provider icons now expose the provider name on hover for inline SVG, image URL, and fallback initials render paths (#2237).
## [3.14.0] - 2026-04-21
Development since v3.13.0 focuses on onboarding Hermes Agent as a first-class managed app, rolling out Claude Opus 4.7 across the preset matrix, adding a Gemini Native API proxy, and sharpening session, usage, and proxy workflows.
**Stats**: 100 commits | 219 files changed | +20,548 insertions | -3,569 deletions
### Added
- **Hermes Agent Support (6th Managed App)**: Added Hermes Agent as a first-class managed app with database migration v9→v10, full Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, session manager with SQLite + JSONL support, and dedicated frontend panels. Supports four API protocols (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) aligned with Hermes Agent 0.10.0 schema. Read-only rendering for providers owned by the user-authored `providers:` dict, with deep configuration delegated to the Hermes Web UI.
- **Hermes Memory Panel**: Added a Memory panel for editing `MEMORY.md` and `USER.md` directly from CC Switch, with an enable switch, character-count limits, and a live save flow. Replaces the Prompts entry for Hermes.
- **Hermes Provider Presets**: Added ~50 Hermes provider presets spanning Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo.
- **Claude Opus 4.7 Support**: Added Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix). Migrated all aggregator and Bedrock presets to Opus 4.7 as the default Opus model.
- **Claude `max` Effort Tier**: Upgraded the Claude effort dropdown from `high` to `max` for extended reasoning capacity.
- **Gemini Native API Proxy**: Added `api_format = "gemini_native"` so the proxy can forward to Google's `generateContent` API with full streaming, schema conversion, and shadow request support. Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module.
- **GitHub Copilot Enterprise Server**: Added GHES authentication and endpoint configuration for Copilot-backed Claude providers, plus thinking-block stripping before upstream to preserve premium interaction quota.
- **Session List Virtualization**: Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly; long session messages are now collapsed by default to reduce text layout cost.
- **Codex / OpenClaw Session Title Extraction**: Added meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display; strips OpenClaw `message_id` suffix noise.
- **Usage Date Range Picker**: Added a date range selector to the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d), a custom date + time calendar picker, and a page-jump input on paginated lists.
- **Model Mapping Quick-Set**: Added a quick-set button next to model mapping fields in provider forms for faster edits.
- **Stream Check Error Classification**: Classified Stream Check errors and surfaced them as color-coded toasts; refreshed default probe models and added explicit detection for "model not found" responses.
- **Block Official Provider Switching During Local Routing**: Blocks switching to official providers while Local Routing is active, since routing official API traffic through the local proxy carries account-suspension risk. A warning toast surfaces the block.
- **Pricing Database Refresh (v8 → v9)**: Added ~50 new model pricing entries and corrected stale prices via a reseed-on-migration step, including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, and GLM-5/5.1. DeepSeek and Kimi K2.5 prices updated.
- **Application-Level Window Controls**: Added an opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of the system decorations, materially improving the experience on Linux Wayland where compositor-drawn buttons can become inert.
- **Hermes in Unified Skills Management**: Added Hermes to the unified Skills surface; skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
- **OpenClaw Config Directory Override**: Added a settings option to point CC Switch at a custom `openclaw.json` location.
- **Hermes Config Directory Override**: Added a settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch.
- **StepFun Step Plan Preset**: Added StepFun Step Plan (EN/ZH) provider presets.
- **New API Usage Script Template**: Added a User-Agent header to the New API usage script template for better upstream compatibility.
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry now offers to run `hermes dashboard` in the user's preferred terminal via a temp bash/batch script. `hermes dashboard` opens the browser itself once ready, so no polling is required. Also corrects the stale `hermes web` hint in the offline toast (the real command is `hermes dashboard`) and reorders Linux terminal detection to try `which` before stat'ing `/usr/bin`, `/bin`, `/usr/local/bin`.
- **LemonData Provider Preset (All Six Apps)**: Registered LemonData as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes, with icon assets and zh/en/ja partner-promotion copy. Claude uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`.
- **DDSHub Codex Preset**: Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service; base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths.
### Changed
- **"Local Proxy Takeover" → "Local Routing"**: Unified terminology across UI copy, README, and docs in all three locales. Functional behavior is unchanged.
- **Hermes `Auto` api_mode Removed**: Users must now pick an explicit protocol; new deeplinks default to `chat_completions`. Eliminates URL-based heuristic surprises.
- **Hermes Provider Form**: Added an API mode dropdown and per-provider model editor; bound per-provider models to the top-level `model:` when switching active providers.
- **Hermes Deep Config Delegation**: Deep YAML knobs are now delegated to the Hermes Web UI via a direct launch action, rather than duplicated in the CC Switch form.
- **`ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set**: Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form.
- **Per-Provider Proxy Config Removed**: Consolidated into global Local Routing; the provider-level proxy toggle and associated storage are gone.
- **Unified Toolbar Icon Button Width**: Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look.
- **Rust Toolchain Pinned to 1.95**: Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift.
- **Tray Menu ID Constant**: The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites.
- **Copilot Request Classification**: Refined request routing inside the Copilot optimizer to further reduce unnecessary premium interaction consumption.
- **Usage Script Intranet Support**: Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints. Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped.
- **Failover Queue Notes**: Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues.
- **Hermes Toolbar Layout**: Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL), and moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout.
### Fixed
- **Header Auto-Compact Latching After Maximize**: The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes.
- **Hermes YAML Pollution & OAuth MCP Auth Drop**: Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys; guard tests added via `tests/hermes_roundtrip.rs`.
- **Hermes Active Provider Display**: Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions.
- **Hermes Provider Persistence**: Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads.
- **Codex `cache_control` Preservation**: Preserve `cache_control` when merging system prompts during Codex format conversion (#1946).
- **Claude Prompt Cache Key Leak**: Stopped sending prompt cache keys during Claude chat conversions (#2003).
- **Proxy Hop-by-Hop Header Stripping**: Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230.
- **Permissive Proxy CORS Removed**: Removed the permissive CORS layer from the proxy (#1915).
- **Copilot Premium Consumption**: Further reduced unnecessary Copilot premium interaction consumption during pass-through traffic.
- **Backend Error Details in Proxy Toast**: Surface backend error payload details in proxy-related toast messages instead of a generic failure string.
- **Usage Log Deduplication**: Deduplicated proxy and session-log usage records so the same request is no longer double-counted; synced the request log time range with the dashboard's 1d / 7d / 30d selector.
- **Common Config Checkbox Persistence**: Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens.
- **Claude Plugin `settings.json` Sync**: Editing the current provider now syncs back to `settings.json` for the Claude plugin path.
- **Google Official Gemini Env Preservation**: Saving the Google Official Gemini provider no longer clobbers the `env` block.
- **OpenCode JSON5 Parser for Trailing Commas**: OpenCode config reads now tolerate trailing commas via a JSON5 parser.
- **Preset Refreshes**: Refreshed stale context windows for DeepSeek and Claude 1M; refreshed stale model IDs; backfilled Hermes model lists; fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork; pruned unused official Hermes presets.
- **Auto-Expand Collapsed Messages on Search Hit**: Collapsed messages now auto-expand when a search match lands inside hidden content.
- **Unknown Subscription Quota Tiers Hidden**: Provider cards no longer render unknown subscription quota tiers.
- **Weekly Limit Label Unified**: Aligned the weekly_limit tier label with the official 7-day naming across locales.
- **Root-Level Skill Repo Install**: Fixed skill installation when the repository root itself is a skill.
- **Session ID Parsing Clippy**: Removed a redundant closure in session ID parsing (clippy warning).
- **Usage Log Stat Dedup**: Deduplicated proxy-sourced and session-log-sourced usage records for accurate totals.
- **Stream Check Default Models Refresh**: Updated stream-check default probe models to match each vendor's current lineup.
- **Skills Import Sync**: Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database, so the UI no longer shows "installed" while the target app directory is missing the skill.
- **Ghostty Session Restore**: Fixed Ghostty session restore launch by using shell execution with `--working-directory`, avoiding `cwd` escaping issues when the path contains spaces or special characters.
- **Hermes Health Check Borrowing OpenClaw Schema**: Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled. Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`, and returns `bedrock_converse` as unsupported. `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url".
- **Usage Query Modal for Hermes & OpenClaw**: `getProviderCredentials` now reads flat `settingsConfig` fields for Hermes (snake_case `base_url` / `api_key`) and OpenClaw (camelCase `baseUrl` / `apiKey`), so the "official balance" template auto-selects for matching providers like SiliconFlow. Also refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured.
### Docs
- **README Sponsor Updates**: Updated SiliconFlow signup bonus to ¥16, trimmed the SSSAiCode sponsor blurb, updated partner logos, and added LemonData as a new sponsor.
- **Global Proxy Hint Clarified**: Clarified the global proxy hint about local routing across all three locales.
- **Takeover → Routing Rename**: Renamed takeover docs to routing and updated anchors across all languages.
- **PIPELLM Website URL**: Updated the PIPELLM sponsor website URL to `code.pipellm.ai`.
### Breaking
- **Hermes requires explicit `api_mode`**: The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`. Users with prior `Auto` configs will be prompted to pick a protocol.
- **`ANTHROPIC_REASONING_MODEL` removed from Claude quick-set**: The legacy field is no longer exposed; existing settings are cleaned up automatically.
- **Per-provider proxy configuration removed**: Migrate to the global Local Routing setting. Existing per-provider proxy values are ignored.
- **Database schema bumped v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` (auto-migrated with `DEFAULT 0`; no data loss).
- **Pricing table reseeded (v8 → v9)**: The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices.
- **XCodeAPI preset removed**: Users of the XCodeAPI preset should switch to another provider.
---
## [3.13.0] - 2026-04-10
Development since v3.12.3 focuses on quota visibility, provider workflow upgrades, stronger proxy compatibility, and lower-overhead tray / session workflows.
+2 -2
View File
@@ -48,7 +48,7 @@ MiniMax-M2.7 is a next-generation large language model designed for autonomous e
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥20 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
<td>Thanks to SiliconFlow for sponsoring this project! SiliconFlow is a high-performance AI infrastructure and model API platform, providing fast and reliable access to language, speech, image, and video models in one place. With pay-as-you-go billing, broad multimodal model support, high-speed inference, and enterprise-grade stability, SiliconFlow helps developers and teams build and scale AI applications more efficiently. Register via <a href="https://cloud.siliconflow.cn/i/drGuwc9k">this link</a> and complete real-name verification to receive ¥16 in bonus credit, usable across models on the platform. SiliconFlow is also now compatible with OpenClaw, allowing users to connect a SiliconFlow API key and call major AI models for free.</td>
</tr>
<tr>
@@ -89,7 +89,7 @@ Claude Code / Codex / Gemini official channels at 38% / 2% / 9% of original pric
<tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, <strong>offering high cost-effective official Claude service at just ¥0.5/$ equivalent</strong>, supporting monthly and pay-as-you-go billing plans with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
<td>Thanks to SSSAiCode for sponsoring this project! SSSAiCode is a stable and reliable API relay service, dedicated to providing stable, reliable, and affordable Claude and Codex model services, with same-day fast invoicing. SSSAiCode offers a special deal for CC Switch users: register via <a href="https://www.sssaicode.com/register?ref=DCP0SM">this link</a> to enjoy $10 extra credit on every top-up!</td>
</tr>
<tr>
+2 -3
View File
@@ -48,7 +48,7 @@ MiniMax-M2.7 は、自律的進化と実世界の生産性向上のために設
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_en.jpg" alt="SiliconFlow" width="150"></a></td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥20 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
<td>SiliconFlow のご支援に感謝します!SiliconFlow は高性能 AI インフラストラクチャおよびモデル API プラットフォームで、言語・音声・画像・動画モデルへの高速かつ信頼性の高いアクセスをワンストップで提供します。従量課金制、豊富なマルチモーダルモデル対応、高速推論、エンタープライズグレードの安定性を備え、開発者やチームがより効率的に AI アプリケーションを構築・拡張できるようサポートします。<a href="https://cloud.siliconflow.cn/i/drGuwc9k">このリンク</a>から登録し、本人確認を完了すると、プラットフォーム内の全モデルで利用可能な ¥16 のボーナスクレジットが付与されます。SiliconFlow は OpenClaw にも対応しており、SiliconFlow の API キーを接続することで主要な AI モデルを無料で呼び出すことができます。</td>
</tr>
<tr>
@@ -91,7 +91,7 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。<strong>高コストパフォーマンスの公式 Claude サービスを 0.5¥/$ 換算で提供</strong>、月額制・Paygo など多様な課金方式に対応し、当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
<td>SSSAiCode のご支援に感謝します!SSSAiCode は安定性と信頼性に優れた API 中継サービスで、安定的で信頼性が高く、手頃な価格の Claude・Codex モデルサービスを提供しています。当日の迅速な請求書発行をサポート。CC Switch ユーザー向けの特別特典:<a href="https://www.sssaicode.com/register?ref=DCP0SM">こちらのリンク</a>から登録すると、毎回のチャージで $10 の追加ボーナスを受けられます!</td>
</tr>
<tr>
@@ -103,7 +103,6 @@ Claude Code / Codex / Gemini 公式チャンネルが最安で元価格の 38% /
<td>LemonData のご支援に感謝します!LemonData は高性能 AI API アグリゲーションプラットフォームで、GPT、Claude、Gemini、DeepSeek など 300 以上のモデルに 1 つの API キーでアクセス可能。全モデルが公式価格の 30〜70% オフで自動フェイルオーバー、スマートルーティング、無制限同時接続に対応。新規ユーザーは登録だけで即座に $1 の無料クレジットを獲得 — <a href="https://lemondata.cc/r/FFX1ZDUP">こちらのリンク</a>から登録してボーナスを獲得し、すぐに開発を始めましょう!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>CTok.ai のご支援に感謝します!CTok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code のプロフェッショナルプランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex にも対応しています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシストプログラミングを真の生産性ツールにします。<a href="https://ctok.ai">こちら</a>から登録してください!</td>
+2 -3
View File
@@ -48,7 +48,7 @@ MiniMax M2.7 是 MiniMax 首个深度参与自我迭代的模型,可自主构
<tr>
<td width="180"><a href="https://cloud.siliconflow.cn/i/drGuwc9k"><img src="assets/partners/logos/silicon_zh.jpg" alt="SiliconFlow" width="150"></a></td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥20 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
<td>感谢硅基流动赞助了本项目!硅基流动是一个高性能 AI 基础设施与模型 API 平台,一站式提供语言、语音、图像、视频等多模态模型的快速、可靠访问。平台支持按量计费、丰富的多模态模型选择、高速推理和企业级稳定性,帮助开发者和团队更高效地构建和扩展 AI 应用。通过<a href="https://cloud.siliconflow.cn/i/drGuwc9k">此链接</a>注册并完成实名认证,即可获得 ¥16 奖励金,可在平台内跨模型使用。硅基流动现已兼容 OpenClaw,用户可接入硅基流动 API Key 免费调用主流 AI 模型。</td>
</tr>
<tr>
@@ -90,7 +90,7 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<tr>
<td width="180"><a href="https://www.sssaicode.com/register?ref=DCP0SM"><img src="assets/partners/logos/sssaicode.png" alt="SSSAiCode" width="150"></a></td>
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,<strong>提供高性价比折合0.5¥/$的官方Claude服务</strong>,支持包月、Paygo多种计费方式、支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
<td>感谢 SSSAiCode 赞助了本项目!SSSAiCode 是一家稳定可靠的API中转站,致力于提供稳定、可靠、平价的Claude、CodeX模型服务,支持当日快速开票,SSSAiCode为本软件的用户提供特别优惠,使用<a href="https://www.sssaicode.com/register?ref=DCP0SM">此链接</a>注册每次充值均可享受10$的额外奖励!</td>
</tr>
<tr>
@@ -102,7 +102,6 @@ Claude Code / Codex / Gemini 官方渠道低至 3.8 / 0.2 / 0.9 折,充值更
<td>感谢 LemonData 赞助了本项目!LemonData 是一个高性能 AI API 聚合平台——一个 API Key 即可访问 GPT、Claude、Gemini、DeepSeek 等 300+ 模型。所有模型定价为官方价格的 30%-70%,支持自动故障转移、智能路由和无限并发。新用户注册即获 $1 免费额度——通过<a href="https://lemondata.cc/r/FFX1ZDUP">此链接</a>注册即可领取奖励,立即开始开发!</td>
</tr>
<tr>
<td width="180"><a href="https://ctok.ai"><img src="assets/partners/logos/ctok.png" alt="CTok" width="150"></a></td>
<td>感谢 CTok.ai 赞助了本项目!CTok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://ctok.ai">这里</a>注册!</td>
+469
View File
@@ -0,0 +1,469 @@
# CC Switch v3.14.0
> Hermes Agent becomes the 6th managed app, Claude Opus 4.7 rolls out across the preset matrix, Gemini Native API proxy, "Local Routing" rename, and application-level window controls
**[中文版 →](v3.14.0-zh.md) | [日本語版 →](v3.14.0-ja.md)**
---
## Overview
CC Switch v3.14.0 is a major release centered on onboarding **Hermes Agent as the 6th first-class managed app** and rolling out **Claude Opus 4.7** across the full aggregator and Bedrock preset matrix. Hermes support covers a database v9 → v10 migration, a complete Rust command surface, YAML-backed `~/.hermes/config.yaml` read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, and dedicated frontend panels including a Memory editor. All four API protocols aligned with Hermes Agent 0.10.0 (`chat_completions`, `anthropic_messages`, `codex_responses`, `bedrock_converse`) are selectable. Providers owned by the user-authored `providers:` dict are rendered as read-only cards, and deep YAML configuration is delegated directly to the Hermes Web UI.
Beyond Hermes, this release adds a **Gemini Native API proxy** (`api_format = "gemini_native"`) so the proxy can forward directly to Google's `generateContent` endpoint with full streaming, schema conversion, and shadow request support; renames the legacy "Local Proxy Takeover" to **Local Routing** across UI copy, README, and docs in all three locales; introduces **application-level window controls**, an opt-in setting that materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert; and bundles late additions for launching `hermes dashboard` from the toolbar, a LemonData preset across all six apps, a DDSHub Codex endpoint, plus several Hermes health-check and Usage modal fixes.
On the session side, the message list is **virtualized** via `@tanstack/react-virtual` so conversations with thousands of records scroll smoothly and long messages collapse by default; the Usage dashboard adds a **date range picker** (Today / 1d / 7d / 14d / 30d + custom date-time calendar) and a page-jump input; **Stream Check error classification** now surfaces color-coded toasts with refreshed default probe models and an explicit "model not found" branch; and switching to official providers is **blocked while Local Routing is active** to avoid account-suspension risk. The pricing database is reseeded from v8 → v9 with ~50 new model entries (Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1 and others) and corrected stale prices.
**Release Date**: 2026-04-21
**Update Scale**: 100 commits | 219 files changed | +20,548 / -3,569 lines
---
## Highlights
- **Hermes Agent Support (6th Managed App)**: Database v9 → v10 migration, full Rust command surface, YAML read/write with atomic backups, MCP sync, Skills sync, SQLite + JSONL session management, dedicated frontend panels, and four API protocols (`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`)
- **Claude Opus 4.7 Rollout**: Adaptive thinking whitelisting, per-million pricing seed, Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix); all aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
- **Claude `max` Effort Tier**: Effort dropdown upgraded from `high` to `max`
- **Gemini Native API Proxy**: New `api_format = "gemini_native"` forwards directly to Google's `generateContent` with full streaming / schema conversion / shadow request support
- **GitHub Copilot Enterprise Server**: GHES authentication and endpoint configuration for Copilot-backed Claude providers
- **Copilot Premium Consumption Deep Optimization**: Proactive thinking-block stripping before forwarding, `tool_result` classification fix, subagent detection, `x-interaction-id` billing merge, orphan `tool_result` sanitization, and default warmup downgrade — a systematic reduction in premium interaction consumption
- **Session List Virtualization**: Long conversations scroll smoothly and long messages collapse by default to reduce text layout cost
- **Codex / OpenClaw Session Title Extraction**: Meaningful title extraction with 2-line display; strips OpenClaw `message_id` suffix noise
- **Usage Date Range Picker**: Today / 1d / 7d / 14d / 30d preset tabs + custom date-time calendar; page-jump input on paginated lists
- **Stream Check Error Classification**: Color-coded error toasts; refreshed default probe models; explicit "model not found" detection
- **Block Official Provider Switching During Local Routing**: Routing official API traffic through the local proxy carries account-suspension risk — switches are blocked with a warning toast
- **Pricing Database Refresh (v8 → v9)**: ~50 new model entries and corrected stale prices
- **Application-Level Window Controls**: Opt-in setting to render CC Switch's own min/max/close buttons, materially improving Linux Wayland experience
- **Hermes in Unified Skills Management**: Skill install, enable, and filter now cover Hermes
- **Hermes / OpenClaw Config Directory Override**: Point CC Switch at a custom `~/.hermes/config.yaml` or `openclaw.json` location
- **Launch Hermes Dashboard from Toolbar**: When the Hermes Web UI probe fails, the toolbar entry offers to run `hermes dashboard` in the user's preferred terminal
- **New Partner Presets**: LemonData across all six apps; DDSHub Codex endpoint; StepFun Step Plan
---
## Added
### Hermes Agent Support (6th Managed App)
CC Switch now treats Hermes Agent as a first-class managed app alongside Claude / Codex / Gemini / OpenCode / OpenClaw.
- **Database Migration v9 → v10**: Adds `enabled_hermes` columns to `mcp_servers` and `skills` tables (`DEFAULT 0`, auto-migrated, no data loss)
- **YAML Configuration Read/Write**: `~/.hermes/config.yaml` read/write with atomic backups; `tests/hermes_roundtrip.rs` guards against dropped OAuth MCP `auth` blocks or pollution of unrelated YAML keys
- **Four API Protocols**: Aligned with Hermes Agent 0.10.0 — `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`; new deeplinks default to `chat_completions`
- **User `providers:` Dict Read-Only Rendering**: User-authored providers in the YAML appear as read-only cards in CC Switch; deep configuration delegates to the Hermes Web UI
- **Additive Switching**: Unlike Claude / Codex's "override" style, all Hermes providers coexist in the same YAML
### Hermes Memory Panel
- New Memory panel for editing `MEMORY.md` / `USER.md` directly, with an enable switch, character-count limits, and a live save flow
- Replaces the Prompts entry for Hermes
### Hermes Provider Presets (~50)
- Covers Nous Research, Shengsuanyun, OpenRouter, DeepSeek, Together AI, StepFun, Zhipu GLM, Bailian, Kimi, MiniMax, DouBao, BaiLing, ModelScope, KAT-Coder, PackyCode, Cubence, AIGoCode, RightCode, AICodeMirror, AICoding, CrazyRouter, SSSAiCode, Micu, CTok.ai, DDSHub, E-FlowCode, LionCCAPI, PIPELLM, Compshare, SiliconFlow, AiHubMix, DMXAPI, TheRouter, Novita, Nvidia, and Xiaomi MiMo
### Launch Hermes Dashboard from Toolbar
- When the Hermes Web UI probe fails, the toolbar entry opens a confirm dialog offering to run `hermes dashboard` in the user's preferred terminal
- Spawned via a temp bash / batch script; `hermes dashboard` opens the browser itself once ready, so no polling is required
- The Memory panel and Health banner keep the existing toast behavior
- Also corrects the stale `hermes web` hint in the offline toast (the real command is `hermes dashboard`)
- Linux terminal detection reordered to try `which` before stat'ing `/usr/bin`, `/bin`, `/usr/local/bin`
### Claude Opus 4.7 Support
- New Claude Opus 4.7 with adaptive thinking whitelisting, per-million pricing seed, and Bedrock SKU (`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`, dropping the legacy `-v1` suffix)
- All aggregator and Bedrock presets migrated to Opus 4.7 as the default Opus model
### Claude `max` Effort Tier
- Claude effort dropdown upgraded from `high` to `max` for extended reasoning capacity
### Gemini Native API Proxy
- New `api_format = "gemini_native"` so the proxy can forward directly to Google's `generateContent` API (#1918, thanks @yovinchen)
- Full streaming, schema conversion, and shadow request support
- Adds `gemini_url.rs`, `gemini_schema.rs`, `gemini_shadow.rs`, `streaming_gemini.rs`, and `transform_gemini.rs` under the proxy providers module
### GitHub Copilot Enterprise Server (GHES)
- GHES authentication and endpoint configuration for Copilot-backed Claude providers (#2175, thanks @hotelbe)
### Session List Virtualization
- Virtualized the session list via `@tanstack/react-virtual` so long conversations (thousands of records) scroll smoothly
- Long session messages are collapsed by default to reduce text layout cost
### Codex / OpenClaw Session Title Extraction
- Meaningful title auto-extraction for Codex and OpenClaw sessions with 2-line display
- Strips OpenClaw `message_id` suffix noise
### Usage Date Range Picker
- New date range selector on the usage dashboard with preset tabs (Today / 1d / 7d / 14d / 30d) + custom date + time calendar (#2002, thanks @yovinchen)
- Page-jump input added on paginated lists
### Model Mapping Quick-Set
- New quick-set button next to model mapping fields in provider forms for faster edits (#2179, thanks @lispking)
### Stream Check Error Classification
- Stream Check errors are classified and surfaced as color-coded toasts
- Refreshed default probe models to match each vendor's current lineup
- Explicit detection for "model not found" responses
### Block Official Provider Switching During Local Routing
- Switching to official providers is blocked while Local Routing is active, with a warning toast
- Reason: routing official API traffic through the local proxy carries account-suspension risk
### Pricing Database Refresh (v8 → v9)
- Reseed-on-migration pricing table
- ~50 new model pricing entries including Claude 4.7, Opus 4.7 Adaptive Thinking, Grok 4, Qwen 3.5/3.6, MiniMax M2.5/M2.7, Doubao Seed 2.0 series, GLM-5/5.1
- Corrected stale prices for DeepSeek, Kimi K2.5, and others
### Application-Level Window Controls
- Opt-in setting to render CC Switch's own minimize / toggle-maximize / close buttons instead of system decorations (#1119, thanks @git1677967754)
- Materially improves the experience on Linux Wayland where compositor-drawn buttons can become inert
### Hermes in Unified Skills Management
- Hermes is added to the unified Skills surface
- Skill install, enable, and filter now cover the Hermes app alongside Claude / Codex / Gemini / OpenCode / OpenClaw
### OpenClaw Config Directory Override
- New settings option to point CC Switch at a custom `openclaw.json` location (#1518, thanks @mrFranklin)
### Hermes Config Directory Override
- New settings option to point CC Switch at a custom `~/.hermes/config.yaml` location, backed by data-driven dispatch
### StepFun Step Plan Preset
- StepFun Step Plan (EN / ZH) provider presets (#2155, thanks @hengm3467)
### New API Usage Script Template
- Added a User-Agent header to the New API usage script template for better upstream compatibility
### LemonData Provider Preset (All Six Apps)
- LemonData registered as a third-party partner preset across Claude, Codex, Gemini, OpenCode, OpenClaw, and Hermes
- Icon assets and zh / en / ja partner-promotion copy
- Claude preset uses `ANTHROPIC_API_KEY` auth; OpenAI-compatible apps target `gpt-5.4`
### DDSHub Codex Preset
- Added a Codex-compatible endpoint for DDSHub at the same host as its Claude service
- Base URL omits the `/v1` suffix because the gateway auto-routes OpenAI SDK paths
---
## Changed
### "Local Proxy Takeover" → "Local Routing"
- Unified the terminology across UI copy, README, and docs in all three locales
- Functional behavior is unchanged
### Hermes `Auto` api_mode Removed
- Users must pick an explicit protocol; new deeplinks default to `chat_completions`
- Eliminates URL-based heuristic surprises
### Hermes Provider Form
- Added an API mode dropdown and per-provider model editor
- Binds per-provider models to the top-level `model:` when switching active providers
### Hermes Deep Config Delegation
- Deep YAML knobs are no longer duplicated in the CC Switch form — they are delegated to the Hermes Web UI via a direct launch action
### Hermes Toolbar Layout
- Swapped the Hermes Web UI button from `ExternalLink` to `LayoutDashboard` (clicking may spawn `hermes dashboard` rather than just opening a URL)
- Moved MCP to the final toolbar slot so Hermes matches the Claude / Codex / Gemini / OpenCode layout
### `ANTHROPIC_REASONING_MODEL` Removed from Claude Quick-Set
- Decoupled the reasoning capability from model selection; the legacy field is no longer surfaced in the quick-set form
### Per-Provider Proxy Config Removed
- Consolidated into global Local Routing
- Provider-level proxy toggle and associated storage are gone
### Unified Toolbar Icon Button Width
- Normalized icon-button widths across Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes panels for a consistent header look
### Rust Toolchain Pinned to 1.95
- Adopted clippy 1.95 suggestions across the workspace and pinned the toolchain to prevent nightly drift
### Tray Menu ID Constant
- The tray identifier moved from the hardcoded string `"main"` to a `TRAY_ID` constant (`"cc-switch"`) across all call sites (#1978, thanks @lidaxian121)
### Copilot Premium Consumption Deep Optimization
A systematic overhaul to reduce Copilot reverse-proxy premium interaction consumption across multiple dimensions:
- **Proactive Thinking Block Stripping Before Forwarding**: Anthropic's `thinking` / `redacted_thinking` blocks are rejected by OpenAI-compatible endpoints. Previously, the request failed upstream, burning one premium interaction before the `thinking_rectifier` could retry. A new proactive strip step (Copilot optimization pipeline step 3.5, after `tool_result` merging) eliminates that wasted interaction
- **Request Classification Fix**: Messages containing `tool_result` are now classified as agent continuation instead of user-initiated, preventing every tool call from being falsely counted as a premium interaction
- **Subagent Detection**: Identifies subagents via `__SUBAGENT_MARKER__` with `metadata._agent_` fallback, setting `x-interaction-type=conversation-subagent`
- **Deterministic `x-interaction-id` Billing Merge**: Derives `x-interaction-id` from the session ID so multiple requests within the same session collapse into a single billing interaction
- **Orphan `tool_result` Sanitization**: Cleans up orphan `tool_result` entries to prevent upstream errors that would trigger retries and duplicate billing
- **Warmup Downgrade Enabled by Default**: Uses `gpt-5-mini` as the default downgrade model
- **Optimization Pipeline Reorder**: classify → sanitize → merge → warmup, so classification sees raw `tool_result` semantics
- Fixed a `CopilotOptimizerConfig` default-value inconsistency (unified to `gpt-5-mini`)
### Usage Script Intranet Support
- Removed private-IP / suspicious-hostname blocking from usage scripts, unblocking enterprise intranet, Docker, and self-hosted API endpoints
- Built-in templates still enforce HTTPS (except localhost) and same-origin checks; custom templates remain user-controlled with those request-URL checks skipped
### Failover Queue Notes
- Provider notes now appear in failover queue selectors and queue rows for easier identification across multi-provider queues (#2138, thanks @Coconut-Fish)
---
## Fixed
### Header Auto-Compact Latching After Maximize
- The toolbar no longer stays compacted after maximize/restore; compaction now reevaluates on size changes
### Hermes YAML Pollution & OAuth MCP `auth` Drop
- Round-tripping through CC Switch no longer drops OAuth MCP `auth` blocks or pollutes unrelated YAML keys
- Guard tests added via `tests/hermes_roundtrip.rs`
### Hermes Active Provider Display
- Hermes UI now correctly surfaces the active provider and wires add / enable / remove actions
### Hermes Provider Persistence
- Providers persist under `custom_providers:` so `api_mode` and `model` survive restarts and config reloads
### Hermes Health Check Borrowing OpenClaw Schema
- Hermes providers were routed through `check_additive_app_stream` (the OpenClaw dispatcher), which reads camelCase `baseUrl` / `apiKey` / `api` and surfaced "OpenClaw provider is missing baseUrl" even when every Hermes field was filled
- Introduced `check_hermes_stream` with Hermes-specific extractors that map `api_mode` (`chat_completions` / `anthropic_messages` / `codex_responses`) to the matching `check_claude_stream` `api_format`; `bedrock_converse` returns as unsupported
- `api_mode` is now resolved before URL / API key extraction, so `bedrock_converse` users see the real cause rather than a misleading "missing base_url"
### Usage Query Modal for Hermes & OpenClaw
- `getProviderCredentials` now reads flat `settingsConfig` fields for Hermes (snake_case `base_url` / `api_key`) and OpenClaw (camelCase `baseUrl` / `apiKey`), so the "official balance" template auto-selects for matching providers like SiliconFlow
- Refactored the BALANCE and TOKEN_PLAN test paths to reuse the precomputed `providerCredentials` instead of re-reading `env.ANTHROPIC_*` directly, fixing the "empty key" error for non-Claude apps even when the key was configured
### Codex `cache_control` Preservation
- Preserve `cache_control` when merging system prompts during Codex format conversion (#1946, thanks @yovinchen)
### Claude Prompt Cache Key Leak
- Stopped sending prompt cache keys during Claude chat conversions (#2003, thanks @yovinchen)
### Proxy Hop-by-Hop Header Stripping
- Strip hop-by-hop response headers (Connection, Keep-Alive, Transfer-Encoding, etc.) per RFC 7230 (#2060, thanks @yovinchen)
### Permissive Proxy CORS Removed
- Removed the permissive CORS layer from the proxy (#1915, thanks @zerone0x)
### Backend Error Details in Proxy Toast
- Surface backend error payload details in proxy-related toast messages instead of a generic failure string
### Usage Log Deduplication
- Deduplicated proxy and session-log usage records so the same request is no longer double-counted
- Synced the request log time range with the dashboard's 1d / 7d / 30d selector
### Common Config Checkbox Persistence
- Checkbox state for Claude / Codex / Gemini common-config toggles now persists correctly across reopens (#2191, thanks @zxZeng)
### Claude Plugin `settings.json` Sync
- Editing the current provider now syncs back to `settings.json` for the Claude plugin path (#1905, thanks @chengww5217)
### Google Official Gemini Env Preservation
- Saving the Google Official Gemini provider no longer clobbers the `env` block
### OpenCode JSON5 Parser for Trailing Commas
- OpenCode config reads now tolerate trailing commas via a JSON5 parser (#2023, thanks @wwminger)
### Preset Refreshes
- Refreshed stale context windows for DeepSeek and Claude 1M
- Refreshed stale model IDs; backfilled Hermes model lists
- Fixed the Nous endpoint and replaced the Hermes placeholder icon with Nous brand artwork
- Pruned unused official Hermes presets
### Auto-Expand Collapsed Messages on Search Hit
- Collapsed messages now auto-expand when a search match lands inside hidden content
### Unknown Subscription Quota Tiers Hidden
- Provider cards no longer render unknown subscription quota tiers
### Weekly Limit Label Unified
- Aligned the `weekly_limit` tier label with the official 7-day naming across locales
### Root-Level Skill Repo Install
- Fixed skill installation when the repository root itself is a skill
### Session ID Parsing Clippy
- Removed a redundant closure in session ID parsing (clippy warning)
### Stream Check Default Models Refresh
- Updated stream-check default probe models to match each vendor's current lineup
### Skills Import Sync
- Imported Skills are now immediately synced into enabled app directories instead of only being recorded in the database (#2101, thanks @yaoguohh)
- The UI no longer shows "installed" while the target app directory is missing the skill
### Ghostty Session Restore
- Fixed Ghostty session restore launch by using shell execution with `--working-directory` (#1976, thanks @Suda202)
- Avoids `cwd` escaping issues when the path contains spaces or special characters
---
## Docs
### README Sponsor Updates
- Updated SiliconFlow signup bonus to ¥16
- Trimmed the SSSAiCode sponsor blurb
- Updated partner logos
- Added LemonData as a new sponsor
### Global Proxy Hint Clarified
- Clarified the global proxy hint about local routing across all three locales
### Takeover → Routing Rename
- Renamed takeover docs to routing and updated anchors across all languages
### PIPELLM Website URL
- Updated the PIPELLM sponsor website URL to `code.pipellm.ai`
---
## ⚠️ Breaking Changes
### Hermes requires explicit `api_mode`
- The `Auto` mode is gone; imported or deeplinked providers default to `chat_completions`
- Users with prior `Auto` configs will be prompted to pick a protocol
### `ANTHROPIC_REASONING_MODEL` removed from Claude quick-set
- The legacy field is no longer exposed; existing settings are cleaned up automatically
### Per-provider proxy configuration removed
- Migrate to the global Local Routing setting
- Existing per-provider proxy values are ignored
### Database schema v9 → v10
- Adds `enabled_hermes` columns to `mcp_servers` and `skills`
- Auto-migrated with `DEFAULT 0`; no data loss
### Pricing table reseeded (v8 → v9)
- The `model_pricing` table is cleared and reseeded on first launch to pick up new models and corrected prices
### XCodeAPI preset removed
- Users of the XCodeAPI preset should switch to another provider
---
## ⚠️ Risk Notice
This release inherits the risk notices originally introduced in v3.12.3 / v3.13.0 for reverse-proxy-style features.
**GitHub Copilot Reverse Proxy**: Using Copilot's reverse-proxy path may violate GitHub / Microsoft's terms of service. See [v3.12.3 release notes](v3.12.3-en.md#-risk-notice).
**Codex OAuth Reverse Proxy**: Using the Codex OAuth reverse proxy with a ChatGPT subscription may violate OpenAI's terms of service. See [v3.13.0 release notes](v3.13.0-en.md#-risk-notice).
By enabling these features, users **accept all associated risks**. CC Switch is not responsible for any account restrictions, warnings, or service suspensions that result from using these features.
---
## Download & Installation
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
### System Requirements
| OS | Minimum Version | Architecture |
| ------- | ----------------------- | ----------------------------------- |
| Windows | Windows 10 or later | x64 |
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 |
### Windows
| File | Description |
| ---------------------------------------- | ----------------------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **Recommended** - MSI installer, supports auto-update |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | Portable, extract and run, no registry writes |
### macOS
| File | Description |
| -------------------------------- | -------------------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **Recommended** - DMG installer, drag into Applications |
| `CC-Switch-v3.14.0-macOS.zip` | Extract and drag into Applications, Universal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | For Homebrew installation and auto-update |
> macOS builds are Apple code-signed and notarized — install directly.
### Homebrew (macOS)
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
Update:
```bash
brew upgrade --cask cc-switch
```
### Linux
| Distribution | Recommended | Installation |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run, or use AUR |
| Other distros / not sure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+469
View File
@@ -0,0 +1,469 @@
# CC Switch v3.14.0
> Hermes Agent が 6 番目の管理対象アプリに、Claude Opus 4.7 をプリセットマトリクス全体へ展開、Gemini Native API プロキシ、「Local Routing」への名称統一、アプリケーションレベルのウィンドウコントロール
**[中文版 →](v3.14.0-zh.md) | [English →](v3.14.0-en.md)**
---
## 概要
CC Switch v3.14.0 は、**Hermes Agent を 6 番目の一等管理対象アプリケーション**として CC Switch に取り込み、**Claude Opus 4.7** をアグリゲーターおよび Bedrock プリセットのマトリクス全体に展開することを中心に据えた大型リリースです。Hermes サポートは、データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付きの YAML ベースな `~/.hermes/config.yaml` 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、および Memory エディターを含む専用のフロントエンドパネルをカバーします。Hermes Agent 0.10.0 スキーマに整合する 4 つの API プロトコル(`chat_completions``anthropic_messages``codex_responses``bedrock_converse`)すべてを選択可能です。ユーザーが直接記述した `providers:` dict のエントリは読み取り専用カードとして表示され、深い YAML 設定は Hermes Web UI に委譲されます。
Hermes に加えて、本リリースでは **Gemini Native API プロキシ**`api_format = "gemini_native"`)を追加し、プロキシがリクエストを Google の `generateContent` エンドポイントに直接転送できるようにしました(完全なストリーミング、スキーマ変換、シャドウリクエストをサポート)。また、旧「Local Proxy Takeover」を三言語の UI / README / ドキュメント全体で **Local Routing** に統一リネームし、コンポジターが描画するボタンが無反応になり得る Linux Wayland などのシーンで、CC Switch が自前で最小化 / 最大化 / 閉じるボタンを描画できるオプション「**アプリケーションレベルのウィンドウコントロール**」を導入しました。さらにリリース直前に、ツールバーからの `hermes dashboard` 直接起動、LemonData の全アプリプリセット、DDSHub の Codex エンドポイント、および複数の Hermes ヘルスチェックと Usage モーダルの修正が追加されました。
セッション側では、`@tanstack/react-virtual` によるセッションリストの**仮想化**で数千件のレコードを持つ長い会話も滑らかにスクロールでき、長いメッセージはデフォルトで折り畳まれます。Usage ダッシュボードには**日付範囲ピッカー**(今日 / 1d / 7d / 14d / 30d + カスタム日時カレンダー)とページジャンプ入力が追加され、**Stream Check エラー分類**は色分けされたトーストで提示され、デフォルトの探索モデルが更新され、「モデルが見つからない」レスポンスを個別に識別するようになりました。また、Local Routing が有効な間に公式プロバイダーへの切り替えを**強制的にブロック**する保護を追加し、公式 API トラフィックがローカルプロキシを経由することによるアカウント停止リスクを防ぎます。Pricing データベースは v8 → v9 で再シードされ、約 50 件の新しいモデルエントリ(Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 など)を追加し、いくつかの古い価格を修正しました。
**リリース日**: 2026-04-21
**更新規模**: 100 commits | 219 files changed | +20,548 / -3,569 lines
---
## ハイライト
- **Hermes Agent サポート(6 番目の管理対象アプリ)**: データベース v9 → v10 マイグレーション、完全な Rust コマンド面、アトミックバックアップ付き YAML 読み書き、MCP 同期、Skills 同期、SQLite + JSONL セッション管理、専用フロントエンドパネル、4 つの API プロトコル(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`
- **Claude Opus 4.7 の全面展開**: 適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)、全アグリゲーター / Bedrock プリセットを Opus 4.7 をデフォルト Opus モデルに移行
- **Claude `max` エフォートティア**: エフォートのドロップダウンを `high` から `max` に引き上げ
- **Gemini Native API プロキシ**: 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` に直接転送可能に(完全なストリーミング / スキーマ変換 / シャドウリクエスト対応)
- **GitHub Copilot Enterprise Server**: Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加
- **Copilot 交互消費の大幅最適化**: 転送前の thinking ブロック主動削除、`tool_result` メッセージ分類修正、subagent 検出、`x-interaction-id` 課金マージ、孤立 `tool_result` のサニタイズ、Warmup ダウングレードのデフォルト有効化など、premium 交互消費を系統的に削減
- **セッションリスト仮想化**: 長い会話が滑らかにスクロール。長いメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
- **Codex / OpenClaw セッションタイトル抽出**: 意味のあるタイトルを自動抽出(2 行表示)、OpenClaw の `message_id` 末尾ノイズを除去
- **Usage 日付範囲ピッカー**: Today / 1d / 7d / 14d / 30d プリセットタブ + カスタム日時カレンダー。ページネーションリストにページジャンプ入力
- **Stream Check エラー分類**: エラーを分類し色分けトーストで提示。デフォルト探索モデル更新。「モデルが見つからない」レスポンスを明示的に検出
- **Local Routing 有効時の公式プロバイダー切り替えブロック**: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため、切り替えを強制ブロックして警告トーストを表示
- **Pricing データベース刷新(v8 → v9)**: 約 50 件の新しいモデルエントリを追加し、古い価格を修正
- **アプリケーションレベルのウィンドウコントロール**: CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定。Linux Wayland での体験を大きく改善
- **統一 Skills 管理への Hermes 追加**: Skill のインストール / 有効化 / フィルターが Hermes をカバー
- **Hermes / OpenClaw 設定ディレクトリのカスタマイズ**: 設定で `~/.hermes/config.yaml``openclaw.json` のカスタム位置を指定可能
- **ツールバーからの Hermes Dashboard 起動**: Hermes Web UI のプローブに失敗した際、ツールバーエントリからユーザーの優先ターミナルで `hermes dashboard` を実行可能
- **新パートナープリセット**: LemonData を全 6 アプリにわたって追加、DDSHub の Codex エンドポイント、StepFun Step Plan
---
## 新機能
### Hermes Agent サポート(6 番目の管理対象アプリ)
CC Switch は Hermes Agent を Claude / Codex / Gemini / OpenCode / OpenClaw と並ぶ一等の管理対象アプリとして初めてサポートします。
- **データベースマイグレーション v9 → v10**: `mcp_servers``skills` テーブルに `enabled_hermes` カラムを追加(`DEFAULT 0`、自動マイグレーション、データ損失なし)
- **YAML 設定の読み書き**: `~/.hermes/config.yaml` をアトミックバックアップ付きで読み書き。`tests/hermes_roundtrip.rs` が OAuth MCP `auth` ブロックの消失や無関係なキーの汚染を防止
- **4 つの API プロトコル**: Hermes Agent 0.10.0 と整合する `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`。新しいディープリンクはデフォルトで `chat_completions`
- **ユーザー `providers:` dict の読み取り専用表示**: YAML に手書きされたプロバイダーエントリは CC Switch で読み取り専用カードとして表示され、深い設定は Hermes Web UI に委譲
- **加算的な切り替え**: Claude / Codex の「上書き」型切り替えと異なり、Hermes ではすべてのプロバイダーが同じ YAML に共存
### Hermes Memory パネル
- `MEMORY.md` / `USER.md` を直接編集できる Memory パネルを追加(有効化スイッチ、文字数制限、ライブ保存フロー付き)
- Hermes の Prompts エントリを置き換え
### Hermes プロバイダープリセット(約 50 個)
- Nous Research、Shengsuanyun(胜算云)、OpenRouter、DeepSeek、Together AI、StepFun、Zhipu GLM、Bailian(百炼)、Kimi、MiniMax、DouBao(豆包)、BaiLing(百灵)、ModelScope(魔搭)、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、Xiaomi MiMo をカバー
### ツールバーからの Hermes Dashboard 起動
- Hermes Web UI のプローブに失敗した際、ツールバーエントリがユーザーの優先ターミナルで `hermes dashboard` を実行する確認ダイアログを表示
- 一時 bash / batch スクリプト経由で起動。`hermes dashboard` 自身が準備完了後にブラウザを開くため、ポーリングは不要
- Memory パネルと Health バナーは既存のトースト動作を維持
- オフラインのトーストにあった古い `hermes web` のヒントも修正(正しいコマンドは `hermes dashboard`
- Linux ターミナル検出の順序を変更し、`/usr/bin``/bin``/usr/local/bin` を stat する前に `which` を試すように
### Claude Opus 4.7 サポート
- Claude Opus 4.7 を追加。適応的思考のホワイトリスト、百万トークン単位の価格シード、Bedrock SKU(`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`、旧 `-v1` サフィックスを廃止)
- 全アグリゲーター / Bedrock プリセットをデフォルト Opus モデルとして Opus 4.7 に移行
### Claude `max` エフォートティア
- Claude エフォートドロップダウンを `high` から `max` に引き上げ、より強力な推論容量を解放
### Gemini Native API プロキシ
- 新しい `api_format = "gemini_native"` により、プロキシが Google の `generateContent` API に直接転送可能 (#1918, 感謝 @yovinchen)
- 完全なストリーミング、スキーマ変換、シャドウリクエストに対応
- proxy providers モジュール下に `gemini_url.rs``gemini_schema.rs``gemini_shadow.rs``streaming_gemini.rs``transform_gemini.rs` を追加
### GitHub Copilot Enterprise ServerGHES
- Copilot ベースの Claude プロバイダーに GHES 認証とエンドポイント設定を追加 (#2175, 感謝 @hotelbe)
### セッションリスト仮想化
- `@tanstack/react-virtual` によりセッションリストを仮想化。数千件のレコードを持つ長い会話も滑らかにスクロール
- 長いセッションメッセージはデフォルトで折り畳まれ、テキストレイアウトコストを削減
### Codex / OpenClaw セッションタイトル抽出
- Codex と OpenClaw セッションから意味のあるタイトルを自動抽出し、2 行表示
- OpenClaw の `message_id` 末尾ノイズを除去
### Usage 日付範囲ピッカー
- Usage ダッシュボードに日付範囲セレクターを追加。プリセットタブ(Today / 1d / 7d / 14d / 30d+ カスタム日時カレンダー (#2002, 感謝 @yovinchen)
- ページネーションリストにページジャンプ入力を追加
### モデルマッピングのクイック入力
- プロバイダーフォームのモデルマッピングフィールドの横にクイック入力ボタンを追加し、編集を高速化 (#2179, 感謝 @lispking)
### Stream Check エラー分類
- Stream Check エラーを分類し、色分けトーストとして提示
- デフォルトの探索モデルを各ベンダーの現行ラインナップに合わせて更新
- 「モデルが見つからない」レスポンスを明示的に検出
### Local Routing 有効時の公式プロバイダー切り替えブロック
- Local Routing が有効な状態で公式プロバイダーに切り替えようとすると、強制的にブロックされ警告トーストが表示される
- 理由: 公式 API トラフィックをローカルプロキシ経由で流すとアカウント停止のリスクがあるため
### Pricing データベース刷新(v8 → v9)
- マイグレーション時に定価テーブルを再シード
- Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 などを含む約 50 件の新しいモデルエントリを追加
- DeepSeek、Kimi K2.5 などの古い価格を修正
### アプリケーションレベルのウィンドウコントロール
- CC Switch が自前で最小化 / 最大化トグル / 閉じるボタンを描画するオプション設定を追加。システム装飾の代わりに使用 (#1119, 感謝 @git1677967754)
- コンポジター描画ボタンが無反応になり得る Linux Wayland での体験を大きく改善
### 統一 Skills 管理への Hermes 追加
- 統一 Skills サーフェスに Hermes を追加
- Skill のインストール / 有効化 / フィルターが、Claude / Codex / Gemini / OpenCode / OpenClaw と並んで Hermes アプリをカバー
### OpenClaw 設定ディレクトリのカスタマイズ
- CC Switch が参照する `openclaw.json` のカスタム位置を設定できるオプションを追加 (#1518, 感謝 @mrFranklin)
### Hermes 設定ディレクトリのカスタマイズ
- CC Switch が参照する `~/.hermes/config.yaml` のカスタム位置を設定できるオプションを追加。データ駆動 dispatch でサポート
### StepFun Step Plan プリセット
- StepFun Step PlanEN / ZH)プロバイダープリセットを追加 (#2155, 感謝 @hengm3467)
### New API 用量スクリプトテンプレート
- New API の用量スクリプトテンプレートに User-Agent ヘッダーを追加し、上流互換性を向上
### LemonData プロバイダープリセット(全 6 アプリ)
- LemonData をサードパーティパートナープリセットとして Claude、Codex、Gemini、OpenCode、OpenClaw、Hermes の全 6 アプリに登録
- アイコンアセットと zh / en / ja 三言語のパートナー推奨文面を追加
- Claude プリセットは `ANTHROPIC_API_KEY` 認証を使用。OpenAI 互換アプリは `gpt-5.4` をターゲット
### DDSHub Codex プリセット
- DDSHub の Codex 互換エンドポイントを追加(Claude サービスと同じホスト)
- ベース URL は `/v1` サフィックスを省略(ゲートウェイが OpenAI SDK パスを自動ルーティング)
---
## 変更
### 「Local Proxy Takeover」→「Local Routing」
- 三言語の UI 文言、README、ドキュメント全体で用語を統一リネーム
- 機能的な動作は変更なし
### Hermes `Auto` api_mode の削除
- ユーザーは明示的にプロトコルを選択する必要あり。新しいディープリンクはデフォルトで `chat_completions`
- URL ベースのヒューリスティックによる意外な挙動を排除
### Hermes プロバイダーフォーム
- API モードドロップダウンとプロバイダー単位のモデルエディターを追加
- アクティブなプロバイダーを切り替える際、プロバイダー単位のモデルをトップレベルの `model:` にバインド
### Hermes 深い設定の委譲
- 深い YAML 設定は CC Switch フォームで重複させず、「Hermes Web UI を起動」ボタン経由で Web UI に直接委譲
### Hermes ツールバーレイアウト
- Hermes Web UI ボタンのアイコンを `ExternalLink` から `LayoutDashboard` に変更(クリック時に単に URL を開くのではなく `hermes dashboard` を起動する場合があるため、パネル型アイコンのほうが意味的に正確)
- MCP をツールバーの末尾に移動し、Hermes のレイアウトを Claude / Codex / Gemini / OpenCode と揃える
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
- 推論能力とモデル選択を分離。レガシーフィールドは Quick-Set フォームから除外
### プロバイダー単位のプロキシ設定を削除
- グローバルな Local Routing に統合
- プロバイダー単位のプロキシトグルと関連ストレージは削除済み
### ツールバーアイコンボタン幅の統一
- Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes パネルの間でアイコンボタン幅を正規化し、ヘッダーの見た目を統一
### Rust Toolchain を 1.95 にピン留め
- ワークスペース全体で clippy 1.95 の提案を採用し、nightly ドリフトを防ぐためツールチェーンをピン留め
### トレイメニュー ID 定数
- トレイ識別子をハードコーディング文字列 `"main"` から `TRAY_ID` 定数(`"cc-switch"`)に移行。すべての呼び出し箇所で同期 (#1978, 感謝 @lidaxian121)
### Copilot 交互消費の大幅最適化
Copilot リバースプロキシの premium 交互消費を削減するための系統的な最適化。以下の複数の改善をカバー:
- **転送前に thinking ブロックを主動削除**: Anthropic の `thinking` / `redacted_thinking` ブロックは OpenAI 互換エンドポイントに拒否される。従来は上流でリクエストが失敗して premium 交互を 1 回消費した後、`thinking_rectifier` によってリトライされていた。新しい主動削除ステップ(Copilot 最適化パイプラインの 3.5 ステップ目、`tool_result` マージ後)により、この無駄な premium 消費を直接解消
- **リクエスト分類の修正**: `tool_result` を含むメッセージをユーザー発起の新規リクエストではなく、エージェント継続として分類。ツール呼び出しが毎回 premium 交互としてカウントされる問題を防止
- **subagent 検出**: `__SUBAGENT_MARKER__``metadata._agent_` フォールバックで subagent を識別し、`x-interaction-type=conversation-subagent` を設定
- **決定論的 `x-interaction-id` による課金マージ**: セッション ID から `x-interaction-id` を導出し、同一セッション内の複数リクエストを 1 回の課金交互に統合
- **孤立 `tool_result` のサニタイズ**: 孤立した `tool_result` を整理し、上流エラーによるリトライおよび重複課金を防止
- **Warmup ダウングレードをデフォルトで有効化**: `gpt-5-mini` をデフォルトのダウングレードモデルとして使用
- **最適化パイプラインの並び替え**: classify → sanitize → merge → warmup の順序で、分類が生の `tool_result` セマンティクスを参照可能に
- `CopilotOptimizerConfig` のデフォルト値の不一致を修正(`gpt-5-mini` に統一)
### 用量スクリプトのイントラネットサポート
- 用量スクリプトからプライベート IP / 不審なホスト名のブロッキングを削除し、エンタープライズイントラネット、Docker、自己ホスト API エンドポイントを解放
- ビルトインテンプレートは引き続き HTTPS(localhost を除く)と同一オリジンチェックを強制。カスタムテンプレートはユーザー制御のまま、リクエスト URL のチェックをスキップ
### Failover キューの備考表示
- プロバイダーの備考が failover キューセレクターとキュー行に表示され、マルチプロバイダーキューでの識別が容易に (#2138, 感謝 @Coconut-Fish)
---
## バグ修正
### 最大化後のツールバー自動折り畳みラッチ
- ウィンドウの最大化 / 復元後、ツールバーが折り畳まれたままになる問題を修正。折り畳み判定はサイズ変更時に再評価される
### Hermes YAML 汚染と OAuth MCP `auth` 消失
- CC Switch 経由でラウンドトリップしても OAuth MCP `auth` ブロックが消失したり、無関係な YAML キーが汚染されたりしなくなった
- `tests/hermes_roundtrip.rs` をガードテストとして追加
### Hermes アクティブプロバイダー表示
- Hermes UI がアクティブプロバイダーを正しく表示するようになり、追加 / 有効化 / 削除アクションが正しく動作
### Hermes プロバイダーの永続化
- プロバイダーは `custom_providers:` の下に永続化され、`api_mode``model` が再起動 / 設定再読み込みを生き延びる
### Hermes ヘルスチェックが OpenClaw のスキーマを流用していた問題
- 以前 Hermes プロバイダーは `check_additive_app_stream`(OpenClaw のディスパッチャー)にルーティングされており、これは camelCase の `baseUrl` / `apiKey` / `api` を読むため、Hermes フィールドをすべて記入しても "OpenClaw provider is missing baseUrl" と表示されていた
- `check_hermes_stream` を導入し、Hermes 専用のエクストラクターで `api_mode``chat_completions` / `anthropic_messages` / `codex_responses`)を対応する `check_claude_stream``api_format` にマッピング。`bedrock_converse` は非対応として返す
- URL / API キーの抽出前に `api_mode` を解決することで、`bedrock_converse` を選んだユーザーには「missing base_url」という誤解を招くメッセージではなく実際の原因が表示される
### Hermes / OpenClaw 向け Usage クエリモーダル
- `getProviderCredentials` が Hermessnake_case の `base_url` / `api_key`)と OpenClawcamelCase の `baseUrl` / `apiKey`)のフラットな `settingsConfig` フィールドを読むようになり、SiliconFlow などマッチするプロバイダーで「official balance」テンプレートが自動選択される
- BALANCE と TOKEN_PLAN テストパスをリファクタリングし、`env.ANTHROPIC_*` を直接再読するのではなく、事前計算された `providerCredentials` を再利用するように変更。これにより非 Claude アプリでキーが設定されていても「empty key」エラーが出ていた問題を修正
### Codex `cache_control` 保持
- Codex フォーマット変換中に system prompt をマージする際の `cache_control` を保持 (#1946, 感謝 @yovinchen)
### Claude プロンプトキャッシュキーのリーク
- Claude chat 変換時にプロンプトキャッシュキーを送信しないように修正 (#2003, 感謝 @yovinchen)
### プロキシ Hop-by-Hop レスポンスヘッダーの削除
- RFC 7230 に従ってプロキシレスポンスの hop-by-hop ヘッダー(Connection、Keep-Alive、Transfer-Encoding など)を削除 (#2060, 感謝 @yovinchen)
### プロキシの寛容な CORS レイヤー削除
- プロキシの寛容な CORS レイヤーを削除 (#1915, 感謝 @zerone0x)
### プロキシトーストでのバックエンドエラー詳細表示
- プロキシ関連のトーストメッセージで、汎用的な失敗文字列ではなくバックエンドのエラーペイロードの詳細を表示
### Usage ログの重複排除
- プロキシとセッションログの用量レコードを重複排除し、同じリクエストが二重にカウントされないように修正
- リクエストログの時間範囲をダッシュボードの 1d / 7d / 30d セレクターと同期
### Common Config チェックボックスの永続化
- Claude / Codex / Gemini の common-config トグルのチェック状態が再オープンをまたいで正しく保持されるように修正 (#2191, 感謝 @zxZeng)
### Claude プラグイン `settings.json` 同期
- 現在のプロバイダーを編集すると、Claude プラグインパスの `settings.json` に同期されるように修正 (#1905, 感謝 @chengww5217)
### Google Official Gemini の env 保持
- Google Official Gemini プロバイダーを保存しても `env` ブロックが消えないように修正
### OpenCode の JSON5 による末尾カンマ解析
- OpenCode 設定読み取りが JSON5 パーサーにより末尾カンマを許容するように修正 (#2023, 感謝 @wwminger)
### プリセットの刷新
- DeepSeek と Claude 1M の古いコンテキストウィンドウを刷新
- 古いモデル ID を刷新。Hermes のモデルリストをバックフィル
- Nous エンドポイントを修正し、Hermes のプレースホルダーアイコンを Nous ブランドのアートワークに置き換え
- 未使用の公式 Hermes プリセットを整理
### 検索ヒット時の折り畳みメッセージの自動展開
- 隠されたコンテンツ内部で検索マッチが発生した場合、折り畳みメッセージを自動展開してマッチを示す
### 不明なサブスクリプション配額ティアの非表示
- プロバイダーカードは不明なサブスクリプション配額ティアを表示しないように変更
### weekly_limit ラベルの統一
- `weekly_limit` ティアラベルを公式の「7 日」命名にロケール間で揃えた
### ルートレベルの Skill リポジトリインストール
- リポジトリのルート自体が skill の場合のインストール失敗を修正
### Session ID 解析の clippy 警告
- session ID 解析内の冗長なクロージャを削除(clippy 警告)
### Stream Check デフォルトモデルの刷新
- Stream Check のデフォルト探索モデルを各ベンダーの現行ラインナップに合わせて更新
### Skills インポートの同期
- インポートされた Skills はデータベースに記録されるだけでなく、有効化されたアプリディレクトリにも即座に同期されるように変更 (#2101, 感謝 @yaoguohh)
- UI が「インストール済み」と表示しているのに対象アプリディレクトリに skill が存在しない状態を解消
### Ghostty セッション復元
- Ghostty セッション復元の起動を `--working-directory` 付きのシェル実行に変更 (#1976, 感謝 @Suda202)
- パスにスペースや特殊文字が含まれる場合の `cwd` エスケープ問題を回避
---
## ドキュメント
### README スポンサー更新
- SiliconFlow のサインアップボーナスを ¥16 に更新
- SSSAiCode のスポンサー文面を簡潔化
- パートナーロゴを更新
- 新しいスポンサーとして LemonData を追加
### グローバルプロキシヒントの明確化
- 三言語でグローバルプロキシと Local Routing の関係を明確化
### Takeover → Routing ドキュメントのリネーム
- テイクオーバー関連ドキュメントを三言語で routing にリネームし、アンカーを同期更新
### PIPELLM ウェブサイト URL
- PIPELLM スポンサーのウェブサイト URL を `code.pipellm.ai` に更新
---
## ⚠️ 重要な変更(Breaking
### Hermes は明示的な `api_mode` が必須
- `Auto` モードは廃止。インポートまたはディープリンクで取得したプロバイダーはデフォルトで `chat_completions`
- 既存の `Auto` 設定のユーザーはプロトコルを選択するよう促される
### Claude Quick-Set から `ANTHROPIC_REASONING_MODEL` を削除
- レガシーフィールドは公開されなくなった。既存の設定は自動的にクリーンアップされる
### プロバイダー単位のプロキシ設定を削除
- グローバル Local Routing 設定に移行
- 既存のプロバイダー単位のプロキシ値は無視される
### データベーススキーマ v9 → v10
- `mcp_servers``skills``enabled_hermes` カラムを追加
- `DEFAULT 0` で自動マイグレーション、データ損失なし
### Pricing テーブルの再シード(v8 → v9)
- 新しいモデルと修正済み価格を取り込むため、初回起動時に `model_pricing` テーブルがクリアされ再シードされる
### XCodeAPI プリセットの削除
- XCodeAPI プリセットを使用していたユーザーは別のプロバイダーに切り替える必要がある
---
## ⚠️ リスクに関する注意事項
本リリースは、リバースプロキシ型機能について v3.12.3 / v3.13.0 で提起された既存のリスク注意事項を継承します。
**GitHub Copilot リバースプロキシ**: Copilot のリバースプロキシパスを使用すると、GitHub / Microsoft の利用規約に違反する可能性があります。詳細は [v3.12.3 リリースノート](v3.12.3-ja.md#-リスクに関する注意事項) を参照してください。
**Codex OAuth リバースプロキシ**: ChatGPT サブスクリプションで Codex OAuth リバースプロキシを使用すると、OpenAI の利用規約に違反する可能性があります。詳細は [v3.13.0 リリースノート](v3.13.0-ja.md#-リスクに関する注意事項) を参照してください。
これらの機能を有効にすることで、ユーザーは**すべての関連リスクを自己責任で受諾**したものとみなされます。CC Switch はこれらの機能の使用に起因するアカウントの制限、警告、サービス停止について一切の責任を負いません。
---
## ダウンロード・インストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から対応バージョンをダウンロードしてください。
### システム要件
| OS | 最小バージョン | アーキテクチャ |
| ------- | ---------------------------- | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表参照 | x64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | ------------------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ不要 |
### macOS
| ファイル | 説明 |
| -------------------------------- | -------------------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **推奨** - DMG インストーラー、Applications にドラッグ |
| `CC-Switch-v3.14.0-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | Homebrew インストールと自動更新用 |
> macOS 版は Apple のコード署名および公証済みで、直接インストールして使用できます。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して実行、または AUR を使用 |
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+468
View File
@@ -0,0 +1,468 @@
# CC Switch v3.14.0
> Hermes Agent 成为第 6 个受管应用、Claude Opus 4.7 全面接入、Gemini Native API 代理、Local Routing 统一重命名、应用级窗口控件
**[English →](v3.14.0-en.md) | [日本語版 →](v3.14.0-ja.md)**
---
## 概览
CC Switch v3.14.0 是一次大版本更新,核心焦点是把 **Hermes Agent 作为第 6 个一等受管应用**接入 CC Switch,并把 **Claude Opus 4.7** 铺设到全部聚合器与 Bedrock 预设矩阵。Hermes 支持覆盖数据库 v9 → v10 迁移、完整的 Rust 命令面、基于 YAML 的 `~/.hermes/config.yaml` 读写(含原子备份)、MCP 同步、Skills 同步、SQLite + JSONL 会话管理,以及专属的前端面板和 Memory 编辑面板;与 Hermes Agent 0.10.0 schema 对齐的四种协议(`chat_completions``anthropic_messages``codex_responses``bedrock_converse`)全部可选。用户自行维护的 `providers:` dict 条目以只读卡片形式呈现,深度 YAML 配置则直接委托给 Hermes Web UI。
除了 Hermes,本次还新增了 **Gemini Native API 代理**`api_format = "gemini_native"`),让代理可以把请求直接转发到 Google 的 `generateContent` 端点,完整支持流式、schema 转换和 shadow 请求;把老的 "Local Proxy Takeover" 在三语 UI / README / 文档中统一重命名为 **Local Routing**;新增 **应用级窗口控件**,在 Linux Wayland 等合成器绘制按钮失灵的场景下可选让 CC Switch 自绘最小化 / 最大化 / 关闭按钮;并在本版本发布前额外合入了从工具栏直接启动 `hermes dashboard`、LemonData 全应用预设、DDSHub Codex 端点以及若干 Hermes 健康检查与 Usage 模态框的修复。
会话侧通过 `@tanstack/react-virtual` **虚拟化会话列表**,让上千条记录的长会话也能流畅滚动,长消息默认折叠;Usage 面板新增**日期范围选择器**(今日 / 1d / 7d / 14d / 30d + 自定义日期时间)和翻页输入;**Stream Check 错误分类**以彩色 toast 呈现,默认探测模型重新梳理,"模型不存在"响应被单独识别;并新增在 Local Routing 激活时**阻止切换到官方供应商**的保护,以免官方流量被引入本地代理造成账号风险。Pricing 数据库 v8 → v9 重新种入约 50 个新模型条目(包括 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1 等),并修正了多项陈旧价格。
**发布日期**2026-04-21
**更新规模**100 commits | 219 files changed | +20,548 / -3,569 lines
---
## 重点内容
- **Hermes Agent 支持(第 6 个受管应用)**:数据库 v9 → v10 迁移、完整 Rust 命令面、YAML 读写带原子备份、MCP 同步、Skills 同步、SQLite + JSONL 会话管理、专属前端面板、四种 API 协议(`chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`
- **Claude Opus 4.7 全面接入**:自适应思维白名单、按百万 token 定价种子、Bedrock SKU`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀),全部聚合器 / Bedrock 预设升级为默认 Opus 模型
- **Claude `max` 推理力度**:推理下拉从 `high` 升级到 `max`
- **Gemini Native API 代理**:新增 `api_format = "gemini_native"`,代理可直达 Google `generateContent`,完整流式 / schema 转换 / shadow 请求
- **GitHub Copilot 企业版**:为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置
- **Copilot 次数消耗深度优化**:转发前主动剥离 thinking 块、`tool_result` 消息归类修正、subagent 检测、`x-interaction-id` 合并计费、orphan `tool_result` 清理、默认启用 warmup 降级 —— 系统性降低 premium 交互消耗
- **会话列表虚拟化**:长会话流畅滚动,长消息默认折叠降低文字布局成本
- **Codex / OpenClaw 会话标题提取**:自动抽取有意义标题,两行显示,剥离 OpenClaw `message_id` 尾噪声
- **Usage 日期范围选择器**Today / 1d / 7d / 14d / 30d 预设 + 自定义日期时间日历;分页列表支持页码跳转输入
- **Stream Check 错误分类**:错误按类别分色 toast;默认探测模型刷新;单独识别 "model not found"
- **Local Routing 激活时阻止官方供应商切换**:官方流量走本地代理有账号暂停风险,强制拦截并 toast 警告
- **Pricing 数据库刷新(v8 → v9)**:新增 ~50 条模型条目并修正陈旧价格
- **应用级窗口控件**:可选让 CC Switch 自绘 min/max/close,显著改善 Linux Wayland 体验
- **Hermes 接入统一 Skills 管理**Skills 安装 / 启用 / 过滤现覆盖 Hermes
- **Hermes / OpenClaw 配置目录自定义**:在设置里指定 `~/.hermes/config.yaml``openclaw.json` 的自定义位置
- **从工具栏启动 Hermes Dashboard**Web UI 探测失败时,点击可在用户首选终端中启动 `hermes dashboard`
- **新合作伙伴预设**:LemonData 覆盖全部 6 个应用;DDSHub 新增 Codex 端点;StepFun Step Plan
---
## 新功能
### Hermes Agent 支持(第 6 个受管应用)
CC Switch 首次支持 Hermes Agent 作为一等受管应用,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列。
- **数据库迁移 v9 → v10**:为 `mcp_servers``skills` 表新增 `enabled_hermes` 列(`DEFAULT 0` 自动迁移,无数据丢失)
- **YAML 配置读写**`~/.hermes/config.yaml` 读写带原子备份;`tests/hermes_roundtrip.rs` 守护不损坏不相关键和 OAuth MCP `auth`
- **四种 API 协议**:与 Hermes Agent 0.10.0 对齐的 `chat_completions` / `anthropic_messages` / `codex_responses` / `bedrock_converse`;新 deeplink 默认为 `chat_completions`
- **用户 `providers:` dict 只读呈现**:用户在 YAML 里手写的 providers 条目在 CC Switch 中以只读卡片展示,深度配置跳转到 Hermes Web UI
- **累加式切换**:与 Claude / Codex 的"覆盖式"切换不同,Hermes 所有供应商共存于同一 YAML
### Hermes Memory 面板
- 新增 Memory 面板直接编辑 `MEMORY.md` / `USER.md`,带启用开关、字符数限制和保存流
- 替换 Hermes 的 Prompts 入口
### Hermes 供应商预设(约 50 个)
- 覆盖 Nous Research、胜算云、OpenRouter、DeepSeek、Together AI、StepFun、智谱 GLM、百炼、Kimi、MiniMax、豆包、百灵、魔搭、KAT-Coder、PackyCode、Cubence、AIGoCode、RightCode、AICodeMirror、AICoding、CrazyRouter、SSSAiCode、Micu、CTok.ai、DDSHub、E-FlowCode、LionCCAPI、PIPELLM、Compshare、SiliconFlow、AiHubMix、DMXAPI、TheRouter、Novita、Nvidia、小米 MiMo
### 从工具栏启动 Hermes Dashboard
- Hermes Web UI 探测失败时,工具栏按钮改为弹出确认框,提供在用户首选终端里运行 `hermes dashboard`
- 通过临时 bash / batch 脚本启动,`hermes dashboard` 就绪后自动打开浏览器,无需轮询
- Memory 面板和 Health banner 保留原有 toast 行为
- 顺便修正了离线 toast 里过时的 `hermes web` 提示(正确命令是 `hermes dashboard`
- Linux 终端探测改为先 `which` 后 stat,提升兼容性
### Claude Opus 4.7 支持
- 新增 Claude Opus 4.7 及其自适应思维白名单、按百万 token 定价种子、Bedrock SKU`anthropic.claude-opus-4-7` / `global.anthropic.claude-opus-4-7`,丢弃老 `-v1` 后缀)
- 全部聚合器 / Bedrock 预设升级为默认 Opus 模型
### Claude `max` 推理力度
- Claude 推理下拉从 `high` 升级到 `max`,解锁更强的思考容量
### Gemini Native API 代理
- 新增 `api_format = "gemini_native"`,代理可直接转发到 Google `generateContent` API (#1918, 感谢 @yovinchen)
- 完整支持流式、schema 转换、shadow 请求
- 在 proxy providers 模块下新增 `gemini_url.rs``gemini_schema.rs``gemini_shadow.rs``streaming_gemini.rs``transform_gemini.rs`
### GitHub Copilot 企业版(GHES
- 为 Copilot 型 Claude 供应商新增 GHES 认证与端点配置 (#2175, 感谢 @hotelbe)
### 会话列表虚拟化
- 通过 `@tanstack/react-virtual` 虚拟化会话列表,上千条记录流畅滚动
- 长会话消息默认折叠,减少文字布局开销
### Codex / OpenClaw 会话标题提取
- Codex 和 OpenClaw 会话自动抽取有意义的标题,两行显示
- 剥离 OpenClaw `message_id` 后缀噪声
### Usage 日期范围选择器
- Usage 面板新增日期范围选择器,预设 TabToday / 1d / 7d / 14d / 30d+ 自定义日期 + 时间日历 (#2002, 感谢 @yovinchen)
- 分页列表新增页码跳转输入
### 模型映射快速填入
- 供应商表单的模型映射字段旁新增快速填入按钮,加快编辑 (#2179, 感谢 @lispking)
### Stream Check 错误分类
- 按类别为 Stream Check 错误上色并以 toast 呈现
- 刷新所有厂商默认探测模型到当前主力机型
- 对 "model not found" 响应做单独识别
### Local Routing 激活时阻止官方供应商切换
- 在 Local Routing 激活状态下,切换到官方供应商会被强制拦截并弹出警告 toast
- 原因:官方 API 流量经由本地代理存在账号暂停风险
### Pricing 数据库刷新(v8 → v9
- 迁移时重新种入定价表
- 新增约 50 条模型条目,覆盖 Claude 4.7、Opus 4.7 Adaptive Thinking、Grok 4、Qwen 3.5/3.6、MiniMax M2.5/M2.7、Doubao Seed 2.0 系列、GLM-5/5.1
- 修正 DeepSeek、Kimi K2.5 等陈旧价格
### 应用级窗口控件
- 新增可选设置,让 CC Switch 自绘最小化 / 切换最大化 / 关闭按钮,代替系统装饰 (#1119, 感谢 @git1677967754)
- 在合成器按钮可能失灵的 Linux Wayland 上显著改善体验
### Hermes 接入统一 Skills 管理
- 统一的 Skills 界面新增 Hermes
- Skills 安装 / 启用 / 过滤现覆盖 Hermes,与 Claude / Codex / Gemini / OpenCode / OpenClaw 并列
### OpenClaw 配置目录自定义
- 新增设置项,允许把 CC Switch 指向自定义的 `openclaw.json` 位置 (#1518, 感谢 @mrFranklin)
### Hermes 配置目录自定义
- 新增设置项,允许把 CC Switch 指向自定义的 `~/.hermes/config.yaml` 位置,底层通过数据驱动 dispatch
### StepFun Step Plan 预设
- 新增 StepFun Step PlanEN / ZH)供应商预设 (#2155, 感谢 @hengm3467)
### New API 用量脚本模板
- 为 New API 用量脚本模板新增 User-Agent 头,提升上游兼容性
### LemonData 全应用预设
- LemonData 作为第三方合作伙伴预设覆盖 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 全部 6 个应用
- 含图标资源和 zh / en / ja 三语合作伙伴推广文案
- Claude 预设使用 `ANTHROPIC_API_KEY` 认证,OpenAI 兼容应用目标为 `gpt-5.4`
### DDSHub Codex 预设
- 新增 DDSHub 的 Codex 兼容端点(与 Claude 服务同 host
- base URL 省略 `/v1` 后缀,由网关自动路由 OpenAI SDK 路径
---
## 变更
### "Local Proxy Takeover" → "Local Routing"
- 三语 UI 文案、README、文档中全部统一重命名
- 功能行为保持不变
### Hermes `Auto` api_mode 移除
- 用户必须显式选择协议;新 deeplink 默认为 `chat_completions`
- 消除了基于 URL 的启发式识别带来的意外
### Hermes 供应商表单
- 新增 API mode 下拉和按供应商的模型编辑器
- 切换激活供应商时,把按供应商的模型绑定到顶层 `model:`
### Hermes 深度配置委托
- 深度 YAML 配置不再在 CC Switch 表单里重复,直接通过"启动 Hermes Web UI"按钮交给 Web UI
### Hermes 工具栏布局
- Web UI 按钮图标从 `ExternalLink` 换成 `LayoutDashboard` —— 点击可能启动 `hermes dashboard` 而非仅仅打开 URL,面板式图标语义更准
- MCP 移到工具栏末尾,与 Claude / Codex / Gemini / OpenCode 的布局对齐
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
- 把推理能力和模型选择解耦,quick-set 表单不再暴露该遗留字段
### 按供应商代理配置移除
- 统一到全局的 Local Routing
- 按供应商的代理开关和存储都已移除
### 统一工具栏图标按钮宽度
- 在 Claude / Codex / Gemini / OpenCode / OpenClaw / Hermes 面板之间规格化图标按钮宽度,表头视觉一致
### Rust Toolchain 锁定 1.95
- 全仓库采纳 clippy 1.95 建议并锁定 toolchain,防止 nightly 漂移
### 托盘菜单 ID 常量
- 托盘标识符从硬编码字符串 `"main"` 改为 `TRAY_ID` 常量(`"cc-switch"`),所有调用点同步 (#1978, 感谢 @lidaxian121)
### Copilot 次数消耗深度优化
一次系统性优化专门降低 Copilot 反向代理的 premium 交互消耗,涵盖以下多项改进:
- **转发前主动剥离 thinking 块**Anthropic 的 `thinking` / `redacted_thinking` 块会被 OpenAI 兼容端点拒绝,过去一次请求先失败消耗一次 premium 交互、再由 `thinking_rectifier` 触发重试。新增主动剥离步骤(Copilot 优化管线第 3.5 步,位于 `tool_result` 合并之后),直接省掉那一次无谓的 premium 消耗
- **请求分类修正**:含 `tool_result` 的消息归类为代理继续,而不是用户发起的新请求 —— 避免每次工具调用都被错误计入 premium 次数
- **subagent 检测**:通过 `__SUBAGENT_MARKER__``metadata._agent_` 回退识别 subagent,设置 `x-interaction-type=conversation-subagent`
- **确定性 `x-interaction-id` 合并计费**:从 session ID 推导 `x-interaction-id`,把同一会话内的多次请求合并为一次计费交互
- **Orphan `tool_result` 清理**:清理孤立的 `tool_result`,避免触发上游错误导致重试和重复计费
- **Warmup 降级默认开启**:使用 `gpt-5-mini` 作为默认降级模型
- **优化管线重排**classify → sanitize → merge → warmup,让分类看到原始 `tool_result` 语义
- 修复 `CopilotOptimizerConfig` 默认值不一致(统一到 `gpt-5-mini`
### 用量脚本内网支持
- 移除 usage script 的私网 IP / 可疑主机名屏蔽,解锁企业内网、Docker、自建 API 端点
- 内置模板仍强制 HTTPS(localhost 除外)和同源检查;自定义模板仍由用户控制,这类请求 URL 检查跳过
### Failover 队列备注
- 供应商备注现在在 failover 队列选择器和队列行中显示,方便在多供应商队列里识别 (#2138, 感谢 @Coconut-Fish)
---
## Bug 修复
### 工具栏最大化后持续折叠
- 窗口最大化 / 还原后,工具栏不再卡在折叠状态;折叠判定会随尺寸变化重新计算
### Hermes YAML 污染与 OAuth MCP `auth` 丢失
- 经 CC Switch 往返写入不再丢失 OAuth MCP `auth` 块、也不污染不相关的 YAML 键
- 新增 `tests/hermes_roundtrip.rs` 作为守护测试
### Hermes 激活供应商展示
- Hermes UI 现在正确展示激活供应商,并连通添加 / 启用 / 移除动作
### Hermes 供应商持久化
- 供应商持久化到 `custom_providers:` 下,`api_mode``model` 可跨重启 / 配置重载存活
### Hermes 健康检查错借 OpenClaw schema
- 以前 Hermes 供应商被路由到 `check_additive_app_stream`(OpenClaw 的调度器),后者读 camelCase 的 `baseUrl` / `apiKey` / `api`,导致即便 Hermes 字段全填还是报 "OpenClaw provider is missing baseUrl"
- 新增 `check_hermes_stream`,用 Hermes 专用提取器把 `api_mode``chat_completions` / `anthropic_messages` / `codex_responses`)映射到对应的 `check_claude_stream` `api_format``bedrock_converse` 明确标记为不支持
- 先解析 `api_mode` 再抽 URL / API key,让 `bedrock_converse` 用户看到真实原因,而不是误导性的 "missing base_url"
### Usage 查询模态框支持 Hermes / OpenClaw
- `getProviderCredentials` 新增对 Hermessnake_case `base_url` / `api_key`)和 OpenClawcamelCase `baseUrl` / `apiKey`)的扁平 `settingsConfig` 字段读取,让 SiliconFlow 等匹配供应商自动选中 "official balance" 模板
- 重构 BALANCE 和 TOKEN_PLAN 测试路径复用 `providerCredentials`,不再直接读 `env.ANTHROPIC_*`,修正了非 Claude 应用即使配置了 key 也报 "empty key" 的问题
### Codex `cache_control` 保留
- 在 Codex 格式转换合并 system prompt 时保留 `cache_control` (#1946, 感谢 @yovinchen)
### Claude prompt cache key 泄漏
- Claude chat 转换时不再发送 prompt cache key (#2003, 感谢 @yovinchen)
### 代理逐跳响应头剥离
- 按 RFC 7230 剥离代理响应的 hop-by-hop 头(Connection、Keep-Alive、Transfer-Encoding 等) (#2060, 感谢 @yovinchen)
### 代理 CORS 层移除
- 移除代理中过于宽松的 CORS 层 (#1915, 感谢 @zerone0x)
### 代理 toast 显示后端错误详情
- 代理相关 toast 现在展示后端错误 payload 的详情,而不是一句笼统的失败
### Usage 日志去重
- 代理和会话日志的用量记录去重,相同请求不再被重复计数
- 请求日志时间范围与面板的 1d / 7d / 30d 选择器同步
### Common Config 勾选持久化
- Claude / Codex / Gemini common-config 勾选状态重开后正确保留 (#2191, 感谢 @zxZeng)
### Claude 插件 `settings.json` 同步
- 编辑当前供应商时,会同步回 Claude 插件路径下的 `settings.json` (#1905, 感谢 @chengww5217)
### Google Official Gemini env 保留
- 保存 Google Official Gemini 供应商时不再清空 `env`
### OpenCode JSON5 尾逗号解析
- OpenCode 配置读取容忍尾逗号(JSON5) (#2023, 感谢 @wwminger)
### 预设刷新
- 刷新 DeepSeek 和 Claude 1M 的陈旧 context 窗口
- 刷新陈旧模型 ID,回填 Hermes 模型列表
- 修正 Nous 端点,Hermes 占位图替换为 Nous 品牌图
- 移除未使用的官方 Hermes 预设
### 搜索命中时折叠消息自动展开
- 搜索匹配落在折叠内容内部时,消息自动展开以定位匹配
### 未知订阅配额等级隐藏
- 供应商卡片不再渲染未知订阅配额等级
### weekly_limit 标签统一
- 跨语言把 `weekly_limit` 等级标签对齐到官方的"7 天"命名
### 根级 Skill 仓库安装
- 修复当仓库根本身就是一个 skill 时的安装失败
### Session ID 解析 clippy
- 移除 session ID 解析里的冗余闭包(clippy 警告)
### Stream Check 默认探测模型刷新
- 默认探测模型更新到每家厂商当前主力
### Skills 导入同步
- 导入的 Skills 即时同步到启用应用目录,不再仅记录在数据库里导致 UI 显示"已安装"但目标目录空缺 (#2101, 感谢 @yaoguohh)
### Ghostty 会话恢复
- 改为通过 shell 执行 + `--working-directory` 启动 Ghostty 会话恢复 (#1976, 感谢 @Suda202)
- 避免路径含空格 / 特殊字符时 `cwd` 转义问题
---
## 文档
### README 赞助商更新
- SiliconFlow 注册赠送更新为 ¥16
- 精简 SSSAiCode 赞助文案
- 更新合作伙伴 logo
- 新增 LemonData 赞助商
### 全局代理提示澄清
- 三语澄清全局代理与 Local Routing 的关系
### Takeover → Routing 文档重命名
- 接管相关文档在三语下重命名为 routing,同步更新锚点
### PIPELLM 网站 URL
- PIPELLM 赞助商网站 URL 更新为 `code.pipellm.ai`
---
## ⚠️ 重要变更(Breaking
### Hermes 必须显式 `api_mode`
- `Auto` 模式移除;导入或 deeplink 得到的供应商默认落到 `chat_completions`
- 既有 `Auto` 配置的用户会被提示选择协议
### Claude Quick-Set 移除 `ANTHROPIC_REASONING_MODEL`
- 该遗留字段不再暴露;既有设置自动清理
### 按供应商代理配置移除
- 迁移到全局 Local Routing 设置
- 既有按供应商代理值被忽略
### 数据库 schema v9 → v10
-`mcp_servers``skills` 表新增 `enabled_hermes`
- 自动迁移,`DEFAULT 0`,无数据丢失
### Pricing 表 v8 → v9 重置
- 首次启动时 `model_pricing` 表被清空并重新种入,以应用新模型和修正后的价格
### XCodeAPI 预设移除
- 使用 XCodeAPI 预设的用户请迁移到其它供应商
---
## ⚠️ 风险提示
本版本在涉及反向代理类功能上沿用 v3.12.3 / v3.13.0 提出的风险提示。
**GitHub Copilot 反向代理**:使用 Copilot 的反代路径可能违反 GitHub / Microsoft 服务条款。详情见 [v3.12.3 release notes](v3.12.3-zh.md#-风险提示)。
**Codex OAuth 反向代理**:使用 ChatGPT 订阅的 Codex OAuth 反代可能违反 OpenAI 服务条款,详情见 [v3.13.0 release notes](v3.13.0-zh.md#-风险提示)。
用户启用上述功能即表示**自行承担所有风险**。CC Switch 不对因使用这些功能而导致的任何账号限制、警告或服务暂停承担责任。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.14.0-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.14.0-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.14.0-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.14.0-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.14.0-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb``sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm``sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> Tray usage visibility, Codex OAuth stability fixes, Skills import/install reliability, and removal of the Hermes config health scanner
**[中文版 →](v3.14.1-zh.md) | [日本語版 →](v3.14.1-ja.md)**
---
## Overview
CC Switch v3.14.1 is a patch release following v3.14.0, focused on **Codex OAuth reverse-proxy stability**, **tray usage visibility**, **Skills import / install reliability**, **Gemini session restore paths**, and **simplifying Hermes configuration health handling**.
For the first time, the system tray surfaces **cached usage** for the current Claude / Codex / Gemini provider directly in its submenus — including subscription summaries and usage-script summaries with color-coded utilization markers. For Chinese coding-plan providers like Kimi / Zhipu / MiniMax, the tray additionally renders a **5-hour + weekly window** layout in the `🟢 h12% w80%` style (worst utilization drives the emoji), semantically identical to the official subscription badges. Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host now auto-injects `meta.usage_script` so the tray lights up without opening the Usage Script modal.
Several Codex OAuth reverse-proxy stability issues are addressed this release: client-provided session IDs are now used as both `prompt_cache_key` and the Codex session header to avoid UUID-driven cache churn; non-streaming Anthropic clients receive proper JSON responses even when the ChatGPT Codex upstream forces OpenAI Responses SSE; and Stream Check now builds probes with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production requests, eliminating the "check fails but it actually works" mismatch. Paired with a new explicit **FAST mode toggle**, users can now opt into `service_tier="priority"` on Codex OAuth-backed Claude providers, trading latency against ChatGPT quota consumption on their own terms.
Additionally, the in-app **Hermes config health scanner** and its warning banner are removed (along with the `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload), refocusing the Hermes surface on active provider display, switching defaults, memory editing, and launching the Hermes Web UI — deep configuration health is now Hermes's own responsibility.
**Release Date**: 2026-04-23
**Update Scale**: 13 commits | 48 files changed | +1,883 / -808 lines
---
## Highlights
- **Tray Usage Visibility**: Claude / Codex / Gemini tray submenus show cached usage for the current provider, including subscription and script-based summaries with color markers; refreshes are throttled, limited to visible apps, and synchronized back into React Query (#2184, thanks @TuYv)
- **Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)**: The tray renders 5-hour + weekly window usage using the `🟢 h12% w80%` layout; Claude providers whose base URL matches a known host auto-inject `meta.usage_script`
- **Codex OAuth FAST Mode**: New explicit FAST mode toggle for Codex OAuth-backed Claude providers; when enabled, converted Responses requests send `service_tier="priority"`. Off by default (#2210, thanks @JesusDR01)
- **Codex OAuth Stability**: Fixed reverse-proxy cache routing (#2218, thanks @majiayu000), Responses SSE aggregation (#2235, thanks @xpfo-go), and Stream Check parity with production (#2210, thanks @JesusDR01)
- **Hermes Config Health Scanner Removed**: Refocuses the Hermes surface on provider management, memory editing, and launching the Web UI — no longer duplicates deep configuration health judgments
- **Skills Import / Install Reliability**: Import dialog disables actions while pending and deduplicates results by ID (#2211, thanks @TuYv); model quick-set / one-click config applies against the latest form state (#2249, thanks @Coconut-Fish); root-level `SKILL.md` repo installs are stable (#2231, thanks @santugege)
- **Gemini Session Restore Paths**: Session scanning reads `.project_root` metadata and passes the original project directory back into restore flows (#2240, thanks @tisonkun)
- **Session / Settings Layout Polish**: Hardened the scroll-area viewport with width containment to fix horizontal overflow; tightened app bottom and settings footer spacing (#2201, thanks @Coconut-Fish)
---
## Added
### Tray Usage Visibility
- System tray submenus now show **cached usage** for the current Claude / Codex / Gemini provider (#2184, thanks @TuYv)
- Includes subscription quota summaries and usage-script summaries with color-coded utilization markers
- Tray-triggered refreshes are **throttled**, **limited to visible apps**, and synchronized back into React Query so the main window and tray share the same usage data
### Tray Coding-Plan Usage (Kimi / Zhipu / MiniMax)
- The tray renders **5-hour + weekly window** usage for Chinese coding-plan providers
- Uses the same `🟢 h12% w80%` two-window layout as official subscription badges (worst utilization drives the emoji color)
- Creating a Claude provider whose `ANTHROPIC_BASE_URL` matches a known coding-plan host **auto-injects** `meta.usage_script`, so the tray lights up without opening the Usage Script modal
- Existing `usage_script` values are **preserved on update**, never clobbering user customizations
### Codex OAuth FAST Mode
- New explicit FAST mode toggle for Codex OAuth-backed Claude providers (#2210, thanks @JesusDR01)
- When enabled, converted Responses requests send `service_tier="priority"` for lower latency
- Off by default to avoid unexpectedly increasing ChatGPT quota consumption
---
## Changed
### Session and Settings Layout Polish
- Hardened the scroll-area viewport with width containment to fix horizontal overflow (#2201, thanks @Coconut-Fish)
- Tightened app bottom and settings footer spacing so long session / settings views fit more cleanly
---
## Removed
### Hermes Config Health Scanner
- Removed the in-app Hermes config health scanner and its warning banner
- Removed the `scan_hermes_config_health` command, `HermesHealthWarning` type, and `HermesWriteOutcome.warnings` payload
- The CC Switch Hermes surface now focuses on its core job: active provider display, default provider switching, memory editing, and launching the Hermes Web UI for deep configuration
---
## Fixed
### Codex OAuth Cache Routing
- Use the client-provided session ID as both `prompt_cache_key` and the Codex session header, preserving explicit cache keys (#2218, thanks @majiayu000)
- Stop generating UUIDs that caused cache-identity churn, stabilizing the ChatGPT Codex reverse-proxy cache identity
### Codex OAuth Responses SSE Aggregation
- Non-streaming Anthropic clients now receive proper JSON even when the ChatGPT Codex upstream forces OpenAI Responses SSE (#2235, thanks @xpfo-go)
- CC Switch aggregates the upstream SSE events before running the non-streaming transform
### Codex OAuth Stream Check Parity
- Stream Check now builds Codex OAuth probe requests with the same `store: false`, encrypted reasoning include, and provider FAST mode setting as production proxy traffic (#2210, thanks @JesusDR01)
- Eliminates the "check fails but it actually works" mismatch
### Codex Model Extraction
- Reading the `model` field from Codex config now uses TOML parsing instead of first-line regex matching (#2227, thanks @nmsn)
- Multiline TOML is handled correctly
### Model Quick-Set / One-Click Config
- Model quick-set now applies against the **latest** provider form config (#2249, thanks @Coconut-Fish)
- Fixes stale form state preventing one-click configuration from succeeding
### Skills Import Duplicates
- The Skills import dialog disables actions while import is pending (#2211, thanks @TuYv)
- The installed-skills cache deduplicates imported results by ID, preventing double-clicks from adding duplicate installed entries (#2139)
### Root-Level Skill Repos
- Skill install and update flows now consistently resolve three source patterns: direct nested paths, install-name recursive search, and repository-root `SKILL.md` sources (#2231, thanks @santugege)
### Gemini Session Restore Paths
- Gemini session scanning now reads `.project_root` metadata (#2240, thanks @tisonkun)
- Restore flows can pass the original project directory when available
### Provider Hover Names
- Provider icons now expose the provider name on hover for inline SVG, image URL, and fallback initials render paths (#2237, thanks @tisonkun)
---
## Notes & Caveats
- **Hermes Health Scanner Removed**: If you were relying on CC Switch to surface deep Hermes YAML configuration issues, switch to the "Launch Hermes Web UI" toolbar button and inspect them in Hermes's own panel. Day-to-day provider management, switching, memory editing, and MCP / Skills sync continue to be handled by CC Switch.
- **Codex OAuth FAST Mode Off by Default**: Only turn it on if you accept potentially increased ChatGPT quota consumption in exchange for lower latency.
- **Tray Cached Usage**: Refreshes are throttled and limited to the currently visible app to avoid unnecessary upstream API calls; values are synchronized into React Query so the main window and tray stay in sync.
---
## Download & Installation
Visit [Releases](https://github.com/farion1231/cc-switch/releases/latest) to download the appropriate version.
### System Requirements
| OS | Minimum Version | Architecture |
| ------- | ---------------------------- | ----------------------------------- |
| Windows | Windows 10 or later | x64 |
| macOS | macOS 12 (Monterey) or later | Intel (x64) / Apple Silicon (arm64) |
| Linux | See table below | x64 |
### Windows
| File | Description |
| ---------------------------------------- | ----------------------------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **Recommended** - MSI installer, supports auto-update |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | Portable, extract and run, no registry writes |
### macOS
| File | Description |
| -------------------------------- | ------------------------------------------------------- |
| `CC-Switch-v3.14.1-macOS.dmg` | **Recommended** - DMG installer, drag into Applications |
| `CC-Switch-v3.14.1-macOS.zip` | Extract and drag into Applications, Universal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | For Homebrew installation and auto-update |
> macOS builds are Apple code-signed and notarized — install directly.
### Homebrew (macOS)
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
Update:
```bash
brew upgrade --cask cc-switch
```
### Linux
| Distribution | Recommended | Installation |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` or `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` or `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | Add execute permission and run, or use AUR |
| Other distros / not sure | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> トレイでの用量可視化、Codex OAuth の複数の安定性修正、Skills インポート/インストールの信頼性向上、Hermes 設定ヘルススキャナーの削除
**[中文版 →](v3.14.1-zh.md) | [English →](v3.14.1-en.md)**
---
## 概要
CC Switch v3.14.1 は v3.14.0 に続くパッチリリースで、**Codex OAuth リバースプロキシの安定性**、**トレイでの用量可視化**、**Skills インポート / インストールの信頼性**、**Gemini セッション復元パス**、および **Hermes 設定ヘルス処理の簡素化**を中心に据えています。
システムトレイは初めて、現在の Claude / Codex / Gemini プロバイダーの**キャッシュ済み用量**をサブメニューに直接表示するようになりました — サブスクリプション要約と用量スクリプト要約を、使用率に応じた色分けマーカーとともに表示します。Kimi / Zhipu / MiniMax のような中国系コーディングプランプロバイダーには、公式サブスクリプションバッジと同じ `🟢 h12% w80%` スタイルで **5 時間 + 週次ウィンドウ**の 2 ウィンドウレイアウトを追加描画します(より厳しい方の使用率が絵文字色を決定)。`ANTHROPIC_BASE_URL` が既知のコーディングプランホストに一致する Claude プロバイダーを作成すると、`meta.usage_script` が自動注入されるため、Usage Script モーダルを開かなくてもトレイが点灯します。
Codex OAuth 側では、複数のリバースプロキシ安定性の問題を修正しました: クライアント提供の session ID を `prompt_cache_key` と Codex session ヘッダーの両方に使用し、UUID 生成によるキャッシュ揺らぎを回避。ChatGPT Codex 上流が OpenAI Responses SSE を強制する場合でも、非ストリーミングの Anthropic クライアントが適切な JSON レスポンスを受け取れるようになりました。Stream Check は、本番環境と同じ `store: false`、暗号化 reasoning include、およびプロバイダーの FAST モード設定でプローブを構築するようになり、「検出は失敗するのに実際は動く」というズレが解消されました。新しい明示的な **FAST モードトグル**と組み合わせることで、ユーザーは Codex OAuth バックの Claude プロバイダーで `service_tier="priority"` を選択的に送信でき、レイテンシと ChatGPT 配額消費の間で自分で選べるようになりました。
さらに、CC Switch 内蔵の **Hermes 設定ヘルススキャナー**と警告バナー(および対応する `scan_hermes_config_health` コマンド、`HermesHealthWarning` 型、`HermesWriteOutcome.warnings` ペイロード)を削除し、Hermes サーフェスをアクティブプロバイダー表示、デフォルト切り替え、Memory 編集、および Hermes Web UI の起動に再フォーカスしました — 深い設定ヘルスは Hermes 自身の責任になります。
**リリース日**: 2026-04-23
**更新規模**: 13 commits | 48 files changed | +1,883 / -808 lines
---
## ハイライト
- **トレイでの用量可視化**: Claude / Codex / Gemini のトレイサブメニューに、現在のプロバイダーのキャッシュ済み用量(サブスクリプション要約とスクリプト要約、色分けマーカー付き)を表示。リフレッシュはスロットル、可視アプリに限定、React Query に同期 (#2184, 感謝 @TuYv)
- **トレイのコーディングプラン用量(Kimi / Zhipu / MiniMax**: トレイが 5 時間 + 週次ウィンドウの用量を `🟢 h12% w80%` レイアウトで描画。既知のホストにマッチする Claude プロバイダーは `meta.usage_script` を自動注入
- **Codex OAuth FAST モード**: Codex OAuth バックの Claude プロバイダーに明示的な FAST モードトグルを追加。有効時は変換された Responses リクエストに `service_tier="priority"` を送信、デフォルトは OFF (#2210, 感謝 @JesusDR01)
- **Codex OAuth 安定性**: リバースプロキシのキャッシュルーティング (#2218, 感謝 @majiayu000)、Responses SSE 集約 (#2235, 感謝 @xpfo-go)、Stream Check と本番の一致性 (#2210, 感謝 @JesusDR01) を修正
- **Hermes 設定ヘルススキャナー削除**: Hermes サーフェスをプロバイダー管理、Memory 編集、Web UI 起動に再フォーカス。深い設定ヘルス判定を重複して担わなくなる
- **Skills インポート / インストールの信頼性**: インポート中はダイアログのアクションを無効化し、結果を ID で重複排除 (#2211, 感謝 @TuYv); ワンクリック設定は最新のフォーム状態に基づいて適用 (#2249, 感謝 @Coconut-Fish); ルートレベルの `SKILL.md` リポジトリインストールが安定 (#2231, 感謝 @santugege)
- **Gemini セッション復元パス**: セッションスキャン時に `.project_root` メタデータを読み、元のプロジェクトディレクトリを復元フローに渡す (#2240, 感謝 @tisonkun)
- **セッション / 設定レイアウトの磨き込み**: スクロールエリアビューポートに幅制約を追加して横方向のはみ出しを修正。アプリ下部と設定フッター間隔をよりタイトに (#2201, 感謝 @Coconut-Fish)
---
## 新機能
### トレイでの用量可視化
- システムトレイサブメニューに、現在の Claude / Codex / Gemini プロバイダーの**キャッシュ済み用量**を表示 (#2184, 感謝 @TuYv)
- サブスクリプション配額要約と用量スクリプト要約を含み、使用率に応じた色分けマーカー付き
- トレイ起因のリフレッシュは**スロットル**、**可視アプリに限定**、React Query に同期されるため、メインウィンドウとトレイが同じ用量データを共有
### トレイのコーディングプラン用量(Kimi / Zhipu / MiniMax
- 中国系コーディングプランプロバイダー向けに、トレイが **5 時間 + 週次ウィンドウ**の用量を描画
- 公式サブスクリプションバッジと同じ `🟢 h12% w80%` の 2 ウィンドウレイアウトを使用(より厳しい使用率が絵文字色を決定)
- `ANTHROPIC_BASE_URL` が既知のコーディングプランホストにマッチする Claude プロバイダーを作成すると、`meta.usage_script` が**自動注入**され、Usage Script モーダルを開かなくてもトレイが点灯
- 更新時は既存の `usage_script` 値を**保持**し、ユーザーカスタマイズを上書きしない
### Codex OAuth FAST モード
- Codex OAuth バックの Claude プロバイダーに明示的な FAST モードトグルを追加 (#2210, 感謝 @JesusDR01)
- 有効時は変換された Responses リクエストに `service_tier="priority"` を送信してレイテンシを低減
- 予期せぬ ChatGPT 配額消費の増加を避けるため、デフォルトは OFF
---
## 変更
### セッション・設定レイアウトの磨き込み
- スクロールエリアビューポートに幅制約を追加して横方向のはみ出しを修正 (#2201, 感謝 @Coconut-Fish)
- アプリ下部と設定フッター間隔をよりタイトにし、長いセッション / 設定ビューをすっきり表示
---
## 削除
### Hermes 設定ヘルススキャナー
- アプリ内の Hermes 設定ヘルススキャナーと警告バナーを削除
- `scan_hermes_config_health` コマンド、`HermesHealthWarning` 型、`HermesWriteOutcome.warnings` ペイロードを削除
- CC Switch の Hermes サーフェスは本来の役割に回帰: アクティブプロバイダー表示、デフォルトプロバイダー切り替え、Memory 編集、および深い設定用の Hermes Web UI 起動
---
## バグ修正
### Codex OAuth キャッシュルーティング
- クライアント提供の session ID を `prompt_cache_key` と Codex session ヘッダーの両方に使用し、明示的なキャッシュキーを保持 (#2218, 感謝 @majiayu000)
- キャッシュアイデンティティの揺らぎを引き起こしていた UUID 生成を停止し、ChatGPT Codex リバースプロキシのキャッシュアイデンティティを安定化
### Codex OAuth Responses SSE 集約
- ChatGPT Codex 上流が OpenAI Responses SSE を強制する場合でも、非ストリーミングの Anthropic クライアントが適切な JSON を受け取れるように修正 (#2235, 感謝 @xpfo-go)
- CC Switch が非ストリーミング変換を実行する前に上流 SSE イベントを集約
### Codex OAuth Stream Check の一致性
- Stream Check が構築する Codex OAuth プローブリクエストは、本番プロキシと同じ `store: false`、暗号化 reasoning include、プロバイダー FAST モード設定を使用するように修正 (#2210, 感謝 @JesusDR01)
- 「検出は失敗するのに実際は動く」ズレを解消
### Codex モデル抽出
- Codex 設定の `model` フィールドを読む際、先頭行の正規表現マッチではなく TOML パーサーを使用するように変更 (#2227, 感謝 @nmsn)
- 複数行 TOML も正しく処理
### モデルのクイック入力 / ワンクリック設定
- モデルクイック入力は**最新の**プロバイダーフォーム設定に対して適用されるように修正 (#2249, 感謝 @Coconut-Fish)
- 古いフォーム状態によってワンクリック設定が失敗する問題を修正
### Skills インポートの重複排除
- Skills インポートダイアログは、インポート中にすべてのアクションボタンを無効化 (#2211, 感謝 @TuYv)
- インストール済み Skills のキャッシュを ID で重複排除し、ダブルクリックによる重複したインストール済みエントリを防止 (#2139)
### ルートレベルの Skill リポジトリ
- Skill のインストールと更新フローが 3 つのソースパターンを一貫して解決: 直接ネストパス、install-name の再帰検索、およびリポジトリルートの `SKILL.md` ソース (#2231, 感謝 @santugege)
### Gemini セッション復元パス
- Gemini セッションスキャンが `.project_root` メタデータを読み取るように修正 (#2240, 感謝 @tisonkun)
- 復元フローは利用可能な場合に元のプロジェクトディレクトリを渡せる
### プロバイダー名のホバー表示
- プロバイダーアイコンは、inline SVG、画像 URL、およびフォールバックの頭文字レンダリングパスで、ホバー時にプロバイダー名を表示 (#2237, 感謝 @tisonkun)
---
## 備考・注意事項
- **Hermes ヘルススキャナー削除済み**: Hermes YAML の深い設定の問題提示を CC Switch に頼っていた場合は、ツールバーの「Hermes Web UI を起動」ボタンから Hermes 自身のパネルで確認してください。日常のプロバイダー管理、切り替え、Memory 編集、MCP / Skills 同期は引き続き CC Switch が担います。
- **Codex OAuth FAST モードはデフォルト OFF**: レイテンシ低減と引き換えに ChatGPT 配額消費が増える可能性を許容する場合にのみ有効化してください。
- **トレイのキャッシュ用量**: リフレッシュはスロットル済み、かつ現在可視のアプリに限定されており、不要な上流 API 呼び出しを回避します。値は React Query に同期されるため、メインウィンドウとトレイで同じ値が見えます。
---
## ダウンロード・インストール
[Releases](https://github.com/farion1231/cc-switch/releases/latest) から対応バージョンをダウンロードしてください。
### システム要件
| OS | 最小バージョン | アーキテクチャ |
| ------- | ------------------------ | ----------------------------------- |
| Windows | Windows 10 以降 | x64 |
| macOS | macOS 12 (Monterey) 以降 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 下表参照 | x64 |
### Windows
| ファイル | 説明 |
| ---------------------------------------- | ------------------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **推奨** - MSI インストーラー、自動更新対応 |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | ポータブル版、解凍して実行、レジストリ不要 |
### macOS
| ファイル | 説明 |
| -------------------------------- | ------------------------------------------------------ |
| `CC-Switch-v3.14.1-macOS.dmg` | **推奨** - DMG インストーラー、Applications にドラッグ |
| `CC-Switch-v3.14.1-macOS.zip` | 解凍して Applications にドラッグ、Universal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | Homebrew インストールと自動更新用 |
> macOS 版は Apple のコード署名および公証済みで、直接インストールして使用できます。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| ディストリビューション | 推奨形式 | インストール方法 |
| --------------------------------------- | ----------- | -------------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb` または `sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm` または `sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 実行権限を付与して実行、または AUR を使用 |
| その他のディストリビューション / 不明 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+185
View File
@@ -0,0 +1,185 @@
# CC Switch v3.14.1
> 托盘用量可见化、Codex OAuth 多项稳定性修复、Skills 导入/安装可靠性提升、Hermes 配置健康扫描器移除
**[English →](v3.14.1-en.md) | [日本語版 →](v3.14.1-ja.md)**
---
## 概览
CC Switch v3.14.1 是 v3.14.0 之后的一次补丁版本,围绕 **Codex OAuth 反代稳定性**、**托盘用量可见化**、**Skills 导入 / 安装可靠性**、**Gemini 会话恢复路径**,以及**简化 Hermes 配置健康处理**展开。
系统托盘第一次把当前 Claude / Codex / Gemini 供应商的**缓存用量**直接呈现在子菜单里——包含订阅额度摘要和用量脚本摘要,并用颜色标记利用率;针对 Kimi / 智谱 / MiniMax 这类中国编码套餐供应商,托盘还会额外渲染 `🟢 h12% w80%` 风格的 **5 小时 + 周窗口**双窗口排版,语义与官方订阅徽章完全一致(取更紧的那个驱动 emoji)。创建 Claude 供应商时,如果 `ANTHROPIC_BASE_URL` 命中已知的编码套餐 host,会自动注入 `meta.usage_script`,托盘可以不打开 Usage Script 模态框就直接点亮。
Codex OAuth 侧修复了多项反代稳定性问题:使用客户端自带的 session ID 作为 `prompt_cache_key` 和 Codex session 头,避免生成 UUID 造成缓存抖动,显著提高缓存命中率;非流式 Anthropic 客户端在 ChatGPT Codex 上游强制 OpenAI Responses SSE 时也能正确拿到 JSON 响应;Stream Check 现在会以和生产一致的 `store: false`、encrypted reasoning include 以及供应商 FAST 模式构造探测请求,避免出现"检测失败但实际能用"的错位。配合新增的 **FAST 模式显式开关**,让用户可以在 Codex OAuth 型 Claude 供应商上按需发 `service_tier="priority"`,在延迟和 ChatGPT 配额消耗之间自己选。
另外,移除了 CC Switch 内置的 **Hermes 配置健康扫描器**及其警告横幅(以及对应的 `scan_hermes_config_health` 命令、`HermesHealthWarning` 类型和 `HermesWriteOutcome.warnings` 载荷),把 Hermes 面板聚焦回当前供应商展示、默认切换、Memory 编辑和启动 Hermes Web UI,深度配置健康度由 Hermes 自己负责。
**发布日期**2026-04-23
**更新规模**13 commits | 48 files changed | +1,883 / -808 lines
---
## 重点内容
- **托盘用量可见化**Claude / Codex / Gemini 托盘子菜单展示当前供应商缓存用量,含订阅与脚本摘要及颜色标记;刷新带节流、仅针对可见应用、并回写到 React Query (#2184, 感谢 @TuYv)
- **托盘编码套餐用量(Kimi / 智谱 / MiniMax**:托盘渲染 5 小时 + 周窗口双窗口用量,沿用 `🟢 h12% w80%` 排版;命中已知 host 的 Claude 供应商自动注入 `meta.usage_script`
- **Codex OAuth FAST 模式**:为 Codex OAuth 型 Claude 供应商新增显式 FAST 开关,开启后转换后的 Responses 请求发 `service_tier="priority"`,默认关闭 (#2210, 感谢 @JesusDR01)
- **Codex OAuth 稳定性**:修复反代缓存路由 (#2218, 感谢 @majiayu000)、Responses SSE 聚合 (#2235, 感谢 @xpfo-go)、Stream Check 与生产一致性 (#2210, 感谢 @JesusDR01)
- **Hermes 配置健康扫描器移除**:把 Hermes 面板聚焦回供应商管理、Memory 编辑和 Web UI 启动,不再重复承担深度配置健康判断
- **Skills 导入 / 安装可靠性**:导入过程中禁用操作按钮、结果按 ID 去重 (#2211, 感谢 @TuYv);一键配置基于最新表单状态 (#2249, 感谢 @Coconut-Fish);根级 `SKILL.md` 仓库安装稳定 (#2231, 感谢 @santugege)
- **Gemini 会话恢复路径**:扫描会话时读取 `.project_root` 元数据,把原始项目目录带回恢复流程 (#2240, 感谢 @tisonkun)
- **Session / 设置布局打磨**:滚动区域视口加宽度约束修复横向溢出,应用底部和设置页底部间距更紧凑 (#2201, 感谢 @Coconut-Fish)
---
## 新功能
### 托盘用量可见化
- 系统托盘子菜单新增当前 Claude / Codex / Gemini 供应商的**缓存用量**展示 (#2184, 感谢 @TuYv)
- 包含订阅额度摘要和用量脚本摘要,并用颜色标记利用率
- 托盘触发的刷新**带节流**、**只覆盖可见应用**,并同步回 React Query,主窗口和托盘共享同一份用量数据
### 托盘编码套餐用量(Kimi / 智谱 / MiniMax
- 托盘为中国编码套餐供应商渲染 **5 小时 + 周窗口**双窗口用量
- 使用与官方订阅徽章一致的 `🟢 h12% w80%` 两窗口排版,取更紧的那个利用率驱动 emoji 颜色
- 创建 Claude 供应商时,如果 `ANTHROPIC_BASE_URL` 匹配已知编码套餐 host,会**自动注入** `meta.usage_script`,托盘不打开 Usage Script 模态框也能直接点亮
- 更新时会**保留已有** `usage_script` 值,不覆盖用户自定义
### Codex OAuth FAST 模式
- 为 Codex OAuth 型 Claude 供应商新增显式 FAST 模式开关 (#2210, 感谢 @JesusDR01)
- 开启时,转换后的 Responses 请求会发 `service_tier="priority"` 以降低延迟
- 默认关闭,避免意外增加 ChatGPT 配额消耗
---
## 变更
### Session 与设置布局打磨
- 滚动区域视口加上宽度约束,修复横向溢出 (#2201, 感谢 @Coconut-Fish)
- 应用底部和设置页底部间距更紧凑,让长 Session / 设置视图看起来更干净
---
## 移除
### Hermes 配置健康扫描器
- 移除应用内的 Hermes 配置健康扫描器和警告横幅
- 移除 `scan_hermes_config_health` 命令、`HermesHealthWarning` 类型以及 `HermesWriteOutcome.warnings` 载荷
- CC Switch 的 Hermes 面板回归核心职责:当前供应商展示、切换默认供应商、Memory 编辑、以及启动 Hermes Web UI 处理深度配置
---
## 修复
### Codex OAuth 缓存路由
- 使用客户端自带的 session ID 作为 `prompt_cache_key` 和 Codex session 头,保留显式缓存 key (#2218, 感谢 @majiayu000)
- 停止生成 UUID 导致的缓存抖动,让 ChatGPT Codex 反代的缓存身份更稳定
### Codex OAuth Responses SSE 聚合
- ChatGPT Codex 上游强制 OpenAI Responses SSE 时,非流式 Anthropic 客户端也能正确拿到 JSON (#2235, 感谢 @xpfo-go)
- CC Switch 会在非流式转换之前先聚合上游 SSE 事件
### Codex OAuth Stream Check 对齐
- Stream Check 构造的 Codex OAuth 测试请求现在与生产代理一致,使用相同的 `store: false`、加密 reasoning include 和供应商 FAST 模式设置 (#2210, 感谢 @JesusDR01)
- 避免"检测失败但实际能用"的错位
### Codex 模型提取
- 读取 Codex 配置的 `model` 字段时,改用 TOML 解析替代首行正则匹配 (#2227, 感谢 @nmsn)
- 多行 TOML 也能正确处理
### 模型快速填入 / 一键配置
- 模型快速填入现在基于**最新的**供应商表单配置应用 (#2249, 感谢 @Coconut-Fish)
- 修复陈旧表单状态导致一键配置失败的问题
### Skills 导入去重
- Skills 导入对话框在导入进行时禁用所有操作按钮 (#2211, 感谢 @TuYv)
- 已安装 Skills 的缓存按 ID 去重,避免双击造成重复的已安装条目 (#2139)
### 根级 Skill 仓库
- Skill 的安装与更新流程现在能一致地识别三种源路径:直接嵌套路径、按 install-name 递归搜索、以及仓库根的 `SKILL.md` 源 (#2231, 感谢 @santugege)
### Gemini 会话恢复路径
- Gemini 会话扫描时读取 `.project_root` 元数据 (#2240, 感谢 @tisonkun)
- 恢复流程可以在可用时把原始项目目录传回
### 供应商名悬浮提示
- 供应商图标在 inline SVG、图像 URL、以及首字母回退渲染路径下都会在 hover 时展示供应商名称 (#2237, 感谢 @tisonkun)
---
## 说明与注意事项
- **Hermes 健康扫描器已移除**:如果你依赖 CC Switch 提示 Hermes YAML 的深度配置问题,请改为通过工具栏的"启动 Hermes Web UI"按钮在 Hermes 原生面板里查看。日常供应商管理、切换、Memory 编辑、MCP 与 Skills 同步仍然由 CC Switch 负责。
- **Codex OAuth FAST 模式默认关闭**:只有在你接受可能增加 ChatGPT 配额消耗换取更低延迟时,才需要打开。
- **托盘缓存用量**:刷新带节流,只覆盖当前显示的应用,避免无必要的上游 API 调用;数据会回写到 React Query,因此主窗口和托盘看到的值一致。
---
## 下载与安装
访问 [Releases](https://github.com/farion1231/cc-switch/releases/latest) 下载对应版本。
### 系统要求
| 系统 | 最低版本 | 架构 |
| ------- | -------------------------- | ----------------------------------- |
| Windows | Windows 10 及以上 | x64 |
| macOS | macOS 12 (Monterey) 及以上 | Intel (x64) / Apple Silicon (arm64) |
| Linux | 见下表 | x64 |
### Windows
| 文件 | 说明 |
| ---------------------------------------- | ----------------------------------- |
| `CC-Switch-v3.14.1-Windows.msi` | **推荐** - MSI 安装包,支持自动更新 |
| `CC-Switch-v3.14.1-Windows-Portable.zip` | 便携版,解压即用,不写入注册表 |
### macOS
| 文件 | 说明 |
| -------------------------------- | --------------------------------------------- |
| `CC-Switch-v3.14.1-macOS.dmg` | **推荐** - DMG 安装包,拖入 Applications 即可 |
| `CC-Switch-v3.14.1-macOS.zip` | 解压后拖入 ApplicationsUniversal Binary |
| `CC-Switch-v3.14.1-macOS.tar.gz` | 用于 Homebrew 安装和自动更新 |
> macOS 版本已通过 Apple 代码签名和公证,可直接安装使用。
### HomebrewmacOS
```bash
brew tap farion1231/ccswitch
brew install --cask cc-switch
```
更新:
```bash
brew upgrade --cask cc-switch
```
### Linux
| 发行版 | 推荐格式 | 安装方式 |
| --------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| Ubuntu / Debian / Linux Mint / Pop!\_OS | `.deb` | `sudo dpkg -i CC-Switch-*.deb``sudo apt install ./CC-Switch-*.deb` |
| Fedora / RHEL / CentOS / Rocky Linux | `.rpm` | `sudo rpm -i CC-Switch-*.rpm``sudo dnf install ./CC-Switch-*.rpm` |
| openSUSE | `.rpm` | `sudo zypper install ./CC-Switch-*.rpm` |
| Arch Linux / Manjaro | `.AppImage` | 添加执行权限后直接运行,或使用 AUR |
| 其他发行版 / 不确定 | `.AppImage` | `chmod +x CC-Switch-*.AppImage && ./CC-Switch-*.AppImage` |
+1 -1
View File
@@ -509,7 +509,7 @@ When editing Claude providers, a set of **quick toggles** is available above the
| **Hide Attribution** | Clears commit/PR attribution metadata | Sets `attribution: {commit: "", pr: ""}` |
| **Enable Teammates** | Enables the agent teams feature | Sets `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
| **Enable Tool Search** | Enables tool search functionality | Sets `env.ENABLE_TOOL_SEARCH = "true"` |
| **High Effort** | Sets effort level to high | Sets `effortLevel = "high"` |
| **Max Effort** | Sets effort level to max | Sets `effortLevel = "max"` |
| **Disable Auto Upgrade** | Prevents Claude Code auto-updates | Sets `env.DISABLE_AUTOUPDATER = "1"` |
When a toggle is unchecked, its corresponding config entry is removed entirely. Changes are reflected in the JSON editor in real-time.
+1 -1
View File
@@ -509,7 +509,7 @@ Claude プロバイダーの編集時、JSON エディタの上部に **クイ
| **帰属情報を非表示** | コミット/PR の帰属メタデータをクリア | `attribution: {commit: "", pr: ""}` を設定 |
| **チームメイトを有効化** | エージェントチーム機能を有効化 | `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` を設定 |
| **ツール検索を有効化** | ツール検索機能を有効化 | `env.ENABLE_TOOL_SEARCH = "true"` を設定 |
| **高強度** | エフォートレベルをに設定 | `effortLevel = "high"` を設定 |
| **最大強度思考** | エフォートレベルを max に設定 | `effortLevel = "max"` を設定 |
| **自動アップグレードを無効化** | Claude Code の自動更新を防止 | `env.DISABLE_AUTOUPDATER = "1"` を設定 |
トグルのチェックを外すと、対応する設定エントリが完全に削除されます。変更は JSON エディタにリアルタイムで反映されます。
+1 -1
View File
@@ -509,7 +509,7 @@ v3.13.0 起新增的高级选项。默认情况下,CC Switch 会把配置的 `
| **隐藏署名** | 清除提交/PR 的署名元数据 | 设置 `attribution: {commit: "", pr: ""}` |
| **启用 Teammates** | 启用 Agent 团队功能 | 设置 `env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1"` |
| **启用工具搜索** | 启用工具搜索功能 | 设置 `env.ENABLE_TOOL_SEARCH = "true"` |
| **高效能模式** | 将 effort 级别设为 high | 设置 `effortLevel = "high"` |
| **最大强度思考** | 将 effort 级别设为 max | 设置 `effortLevel = "max"` |
| **禁用自动更新** | 阻止 Claude Code 自动更新 | 设置 `env.DISABLE_AUTOUPDATER = "1"` |
取消勾选开关时,对应的配置项会被完全移除。更改会实时反映在 JSON 编辑器中。
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cc-switch",
"version": "3.13.0",
"version": "3.14.1",
"description": "All-in-One Assistant for Claude Code, Codex & Gemini CLI",
"type": "module",
"scripts": {
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.95"
components = ["rustfmt", "clippy"]
profile = "minimal"
+1 -1
View File
@@ -735,7 +735,7 @@ dependencies = [
[[package]]
name = "cc-switch"
version = "3.13.0"
version = "3.14.1"
dependencies = [
"anyhow",
"arboard",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "cc-switch"
version = "3.13.0"
version = "3.14.1"
description = "All-in-One Assistant for Claude Code, Codex & Gemini CLI"
authors = ["Jason Young"]
license = "MIT"
+47 -7
View File
@@ -15,6 +15,8 @@ pub struct McpApps {
pub gemini: bool,
#[serde(default)]
pub opencode: bool,
#[serde(default)]
pub hermes: bool,
}
impl McpApps {
@@ -26,6 +28,7 @@ impl McpApps {
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::OpenClaw => false, // OpenClaw doesn't support MCP
AppType::Hermes => self.hermes,
}
}
@@ -37,6 +40,7 @@ impl McpApps {
AppType::Gemini => self.gemini = enabled,
AppType::OpenCode => self.opencode = enabled,
AppType::OpenClaw => {} // OpenClaw doesn't support MCP, ignore
AppType::Hermes => self.hermes = enabled,
}
}
@@ -55,12 +59,15 @@ impl McpApps {
if self.opencode {
apps.push(AppType::OpenCode);
}
if self.hermes {
apps.push(AppType::Hermes);
}
apps
}
/// 检查是否所有应用都未启用
pub fn is_empty(&self) -> bool {
!self.claude && !self.codex && !self.gemini && !self.opencode
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
}
}
@@ -75,6 +82,8 @@ pub struct SkillApps {
pub gemini: bool,
#[serde(default)]
pub opencode: bool,
#[serde(default)]
pub hermes: bool,
}
impl SkillApps {
@@ -85,6 +94,7 @@ impl SkillApps {
AppType::Codex => self.codex,
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::Hermes => self.hermes,
AppType::OpenClaw => false, // OpenClaw doesn't support Skills
}
}
@@ -96,6 +106,7 @@ impl SkillApps {
AppType::Codex => self.codex = enabled,
AppType::Gemini => self.gemini = enabled,
AppType::OpenCode => self.opencode = enabled,
AppType::Hermes => self.hermes = enabled,
AppType::OpenClaw => {} // OpenClaw doesn't support Skills, ignore
}
}
@@ -115,12 +126,15 @@ impl SkillApps {
if self.opencode {
apps.push(AppType::OpenCode);
}
if self.hermes {
apps.push(AppType::Hermes);
}
apps
}
/// 检查是否所有应用都未启用
pub fn is_empty(&self) -> bool {
!self.claude && !self.codex && !self.gemini && !self.opencode
!self.claude && !self.codex && !self.gemini && !self.opencode && !self.hermes
}
/// 仅启用指定应用(其他应用设为禁用)
@@ -251,6 +265,9 @@ pub struct McpRoot {
/// OpenClaw MCP 配置(v4.1.0+,实际使用 openclaw.json
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
pub openclaw: McpConfig,
/// Hermes MCP 配置(实际使用 config.yaml
#[serde(default, skip_serializing_if = "McpConfig::is_empty")]
pub hermes: McpConfig,
}
impl Default for McpRoot {
@@ -264,6 +281,7 @@ impl Default for McpRoot {
gemini: McpConfig::default(),
opencode: McpConfig::default(),
openclaw: McpConfig::default(),
hermes: McpConfig::default(),
}
}
}
@@ -288,6 +306,8 @@ pub struct PromptRoot {
pub opencode: PromptConfig,
#[serde(default)]
pub openclaw: PromptConfig,
#[serde(default)]
pub hermes: PromptConfig,
}
use crate::config::{copy_file, get_app_config_dir, get_app_config_path, write_json_file};
@@ -296,7 +316,7 @@ use crate::prompt_files::prompt_file_path;
use crate::provider::ProviderManager;
/// 应用类型
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppType {
Claude,
@@ -304,6 +324,7 @@ pub enum AppType {
Gemini,
OpenCode,
OpenClaw,
Hermes,
}
impl AppType {
@@ -314,15 +335,19 @@ impl AppType {
AppType::Gemini => "gemini",
AppType::OpenCode => "opencode",
AppType::OpenClaw => "openclaw",
AppType::Hermes => "hermes",
}
}
/// Check if this app uses additive mode
///
/// - Switch mode (false): Only the current provider is written to live config (Claude, Codex, Gemini)
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw)
/// - Additive mode (true): All providers are written to live config (OpenCode, OpenClaw, Hermes)
pub fn is_additive_mode(&self) -> bool {
matches!(self, AppType::OpenCode | AppType::OpenClaw)
matches!(
self,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
)
}
/// Return an iterator over all app types
@@ -333,6 +358,7 @@ impl AppType {
AppType::Gemini,
AppType::OpenCode,
AppType::OpenClaw,
AppType::Hermes,
]
.into_iter()
}
@@ -349,10 +375,11 @@ impl FromStr for AppType {
"gemini" => Ok(AppType::Gemini),
"opencode" => Ok(AppType::OpenCode),
"openclaw" => Ok(AppType::OpenClaw),
"hermes" => Ok(AppType::Hermes),
other => Err(AppError::localized(
"unsupported_app",
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw。"),
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw."),
format!("不支持的应用标识: '{other}'。可选值: claude, codex, gemini, opencode, openclaw, hermes"),
format!("Unsupported app id: '{other}'. Allowed: claude, codex, gemini, opencode, openclaw, hermes."),
)),
}
}
@@ -375,6 +402,9 @@ pub struct CommonConfigSnippets {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub openclaw: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hermes: Option<String>,
}
impl CommonConfigSnippets {
@@ -386,6 +416,7 @@ impl CommonConfigSnippets {
AppType::Gemini => self.gemini.as_ref(),
AppType::OpenCode => self.opencode.as_ref(),
AppType::OpenClaw => self.openclaw.as_ref(),
AppType::Hermes => self.hermes.as_ref(),
}
}
@@ -397,6 +428,7 @@ impl CommonConfigSnippets {
AppType::Gemini => self.gemini = snippet,
AppType::OpenCode => self.opencode = snippet,
AppType::OpenClaw => self.openclaw = snippet,
AppType::Hermes => self.hermes = snippet,
}
}
}
@@ -438,6 +470,7 @@ impl Default for MultiAppConfig {
apps.insert("gemini".to_string(), ProviderManager::default());
apps.insert("opencode".to_string(), ProviderManager::default());
apps.insert("openclaw".to_string(), ProviderManager::default());
apps.insert("hermes".to_string(), ProviderManager::default());
Self {
version: 2,
@@ -598,6 +631,7 @@ impl MultiAppConfig {
AppType::Gemini => &self.mcp.gemini,
AppType::OpenCode => &self.mcp.opencode,
AppType::OpenClaw => &self.mcp.openclaw,
AppType::Hermes => &self.mcp.hermes,
}
}
@@ -609,6 +643,7 @@ impl MultiAppConfig {
AppType::Gemini => &mut self.mcp.gemini,
AppType::OpenCode => &mut self.mcp.opencode,
AppType::OpenClaw => &mut self.mcp.openclaw,
AppType::Hermes => &mut self.mcp.hermes,
}
}
@@ -624,6 +659,7 @@ impl MultiAppConfig {
Self::auto_import_prompt_if_exists(&mut config, AppType::Gemini)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenCode)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::OpenClaw)?;
Self::auto_import_prompt_if_exists(&mut config, AppType::Hermes)?;
Ok(config)
}
@@ -645,6 +681,7 @@ impl MultiAppConfig {
|| !self.prompts.gemini.prompts.is_empty()
|| !self.prompts.opencode.prompts.is_empty()
|| !self.prompts.openclaw.prompts.is_empty()
|| !self.prompts.hermes.prompts.is_empty()
{
return Ok(false);
}
@@ -658,6 +695,7 @@ impl MultiAppConfig {
AppType::Gemini,
AppType::OpenCode,
AppType::OpenClaw,
AppType::Hermes,
] {
// 复用已有的单应用导入逻辑
if Self::auto_import_prompt_if_exists(self, app)? {
@@ -729,6 +767,7 @@ impl MultiAppConfig {
AppType::Gemini => &mut config.prompts.gemini.prompts,
AppType::OpenCode => &mut config.prompts.opencode.prompts,
AppType::OpenClaw => &mut config.prompts.openclaw.prompts,
AppType::Hermes => &mut config.prompts.hermes.prompts,
};
prompts.insert(id, prompt);
@@ -769,6 +808,7 @@ impl MultiAppConfig {
AppType::Gemini => &self.mcp.gemini.servers,
AppType::OpenCode => &self.mcp.opencode.servers,
AppType::OpenClaw => continue, // OpenClaw MCP is still in development, skip
AppType::Hermes => continue, // Hermes didn't exist in v3.6.x, skip
};
for (id, entry) in old_servers {
+9 -2
View File
@@ -18,6 +18,7 @@ pub struct ManagedAuthAccount {
pub avatar_url: Option<String>,
pub authenticated_at: i64,
pub is_default: bool,
pub github_domain: String,
}
#[derive(Debug, Clone, serde::Serialize)]
@@ -59,6 +60,7 @@ fn map_account(
login: account.login,
avatar_url: account.avatar_url,
authenticated_at: account.authenticated_at,
github_domain: account.github_domain,
}
}
@@ -79,6 +81,7 @@ fn map_device_code_response(
#[tauri::command(rename_all = "camelCase")]
pub async fn auth_start_login(
auth_provider: String,
github_domain: Option<String>,
copilot_state: State<'_, CopilotAuthState>,
codex_state: State<'_, CodexOAuthState>,
) -> Result<ManagedAuthDeviceCodeResponse, String> {
@@ -87,7 +90,7 @@ pub async fn auth_start_login(
AUTH_PROVIDER_GITHUB_COPILOT => {
let auth_manager = copilot_state.0.read().await;
let response = auth_manager
.start_device_flow()
.start_device_flow(github_domain.as_deref())
.await
.map_err(|e| e.to_string())?;
Ok(map_device_code_response(auth_provider, response))
@@ -108,6 +111,7 @@ pub async fn auth_start_login(
pub async fn auth_poll_for_account(
auth_provider: String,
device_code: String,
github_domain: Option<String>,
copilot_state: State<'_, CopilotAuthState>,
codex_state: State<'_, CodexOAuthState>,
) -> Result<Option<ManagedAuthAccount>, String> {
@@ -115,7 +119,10 @@ pub async fn auth_poll_for_account(
match auth_provider {
AUTH_PROVIDER_GITHUB_COPILOT => {
let auth_manager = copilot_state.0.write().await;
match auth_manager.poll_for_token(&device_code).await {
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
Ok(account) => {
let default_account_id = auth_manager.get_status().await.default_account_id;
Ok(account.map(|account| {
+11
View File
@@ -101,6 +101,15 @@ pub async fn get_config_status(app: String) -> Result<ConfigStatus, String> {
Ok(ConfigStatus { exists, path })
}
AppType::Hermes => {
let config_path = crate::hermes_config::get_hermes_config_path();
let exists = config_path.exists();
let path = crate::hermes_config::get_hermes_dir()
.to_string_lossy()
.to_string();
Ok(ConfigStatus { exists, path })
}
}
}
@@ -117,6 +126,7 @@ pub async fn get_config_dir(app: String) -> Result<String, String> {
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
Ok(dir.to_string_lossy().to_string())
@@ -130,6 +140,7 @@ pub async fn open_config_folder(handle: AppHandle, app: String) -> Result<bool,
AppType::Gemini => crate::gemini_config::get_gemini_dir(),
AppType::OpenCode => crate::opencode_config::get_opencode_dir(),
AppType::OpenClaw => crate::openclaw_config::get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
if !config_dir.exists() {
+12 -3
View File
@@ -20,11 +20,12 @@ pub struct CopilotAuthState(pub Arc<RwLock<CopilotAuthManager>>);
/// 返回设备码和用户码,用于 OAuth 认证
#[tauri::command]
pub async fn copilot_start_device_flow(
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<GitHubDeviceCodeResponse, String> {
let auth_manager = state.0.read().await;
auth_manager
.start_device_flow()
.start_device_flow(github_domain.as_deref())
.await
.map_err(|e| e.to_string())
}
@@ -36,10 +37,14 @@ pub async fn copilot_start_device_flow(
#[tauri::command(rename_all = "camelCase")]
pub async fn copilot_poll_for_auth(
device_code: String,
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<bool, String> {
let auth_manager = state.0.write().await;
match auth_manager.poll_for_token(&device_code).await {
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
Ok(Some(_account)) => {
log::info!("[CopilotAuth] 用户已授权");
Ok(true)
@@ -61,10 +66,14 @@ pub async fn copilot_poll_for_auth(
#[tauri::command(rename_all = "camelCase")]
pub async fn copilot_poll_for_account(
device_code: String,
github_domain: Option<String>,
state: State<'_, CopilotAuthState>,
) -> Result<Option<GitHubAccount>, String> {
let auth_manager = state.0.write().await;
match auth_manager.poll_for_token(&device_code).await {
match auth_manager
.poll_for_token(&device_code, github_domain.as_deref())
.await
{
Ok(account) => Ok(account),
Err(crate::proxy::providers::copilot_auth::CopilotAuthError::AuthorizationPending) => {
Ok(None)
+1 -1
View File
@@ -162,7 +162,7 @@ pub async fn set_auto_failover_enabled(
// 刷新托盘菜单,确保状态同步
if let Ok(new_menu) = crate::tray::create_tray_menu(&app, &state) {
if let Some(tray) = app.tray_by_id("main") {
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
let _ = tray.set_menu(Some(new_menu));
}
}
+143
View File
@@ -0,0 +1,143 @@
use std::time::Duration;
use tauri::{AppHandle, State};
use tauri_plugin_opener::OpenerExt;
use crate::hermes_config;
use crate::store::AppState;
/// Error string returned when `open_hermes_web_ui` cannot reach the Hermes
/// FastAPI server. Kept in sync with the `HERMES_WEB_OFFLINE_ERROR` constant
/// in `src/hooks/useHermes.ts` so the frontend can branch on it.
const HERMES_WEB_OFFLINE_ERROR: &str = "hermes_web_offline";
// ============================================================================
// Hermes Provider Commands
// ============================================================================
/// Import providers from Hermes live config to database.
///
/// Hermes uses additive mode — users may already have providers
/// configured in config.yaml.
#[tauri::command]
pub fn import_hermes_providers_from_live(state: State<'_, AppState>) -> Result<usize, String> {
crate::services::provider::import_hermes_providers_from_live(state.inner())
.map_err(|e| e.to_string())
}
/// Get provider names in the Hermes live config.
#[tauri::command]
pub fn get_hermes_live_provider_ids() -> Result<Vec<String>, String> {
hermes_config::get_providers()
.map(|providers| providers.keys().cloned().collect())
.map_err(|e| e.to_string())
}
/// Get a single Hermes provider fragment from live config.
#[tauri::command]
pub fn get_hermes_live_provider(
#[allow(non_snake_case)] providerId: String,
) -> Result<Option<serde_json::Value>, String> {
hermes_config::get_provider(&providerId).map_err(|e| e.to_string())
}
// ============================================================================
// Model Configuration Commands
// ============================================================================
/// Get Hermes model config (model section of config.yaml). Read-only — writes
/// happen implicitly through `apply_switch_defaults` when switching providers.
#[tauri::command]
pub fn get_hermes_model_config() -> Result<Option<hermes_config::HermesModelConfig>, String> {
hermes_config::get_model_config().map_err(|e| e.to_string())
}
// ============================================================================
// Memory Files Commands
// ============================================================================
#[tauri::command]
pub fn get_hermes_memory(kind: hermes_config::MemoryKind) -> Result<String, String> {
hermes_config::read_memory(kind).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn set_hermes_memory(kind: hermes_config::MemoryKind, content: String) -> Result<(), String> {
hermes_config::write_memory(kind, &content).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_hermes_memory_limits() -> Result<hermes_config::HermesMemoryLimits, String> {
hermes_config::read_memory_limits().map_err(|e| e.to_string())
}
#[tauri::command]
pub fn set_hermes_memory_enabled(
kind: hermes_config::MemoryKind,
enabled: bool,
) -> Result<hermes_config::HermesWriteOutcome, String> {
hermes_config::set_memory_enabled(kind, enabled).map_err(|e| e.to_string())
}
// ============================================================================
// Hermes Web UI launcher
// ============================================================================
/// Probe the local Hermes Web UI (FastAPI) and open it in the system browser.
///
/// Port discovery priority:
/// 1. `HERMES_WEB_PORT` environment variable
/// 2. Default 9119
///
/// Hermes wraps all `/api/*` routes in a Bearer-token middleware, so a GET
/// against `/api/status` returning **either 200 or 401** confirms the server
/// is live. The session token lives only in the Hermes process memory and is
/// injected into the returned HTML via `window.__HERMES_SESSION_TOKEN__`, so
/// there is no need (and no way) for CC Switch to inject it — we just open
/// the URL and let Hermes handle auth.
#[tauri::command]
pub async fn open_hermes_web_ui(app: AppHandle, path: Option<String>) -> Result<(), String> {
let port = std::env::var("HERMES_WEB_PORT")
.ok()
.and_then(|raw| raw.trim().parse::<u16>().ok())
.unwrap_or(9119);
let base = format!("http://127.0.0.1:{port}");
// Probe /api/status with a short timeout. Hermes returns 200 when open or
// 401 when the session token is required — either way the server is live.
// Only a connection error / timeout means the server isn't running.
let probe_url = format!("{base}/api/status");
let client = reqwest::Client::builder()
.timeout(Duration::from_millis(1200))
.no_proxy()
.build()
.map_err(|e| format!("failed to build probe client: {e}"))?;
match client.get(&probe_url).send().await {
Ok(_) => {}
Err(_) => return Err(HERMES_WEB_OFFLINE_ERROR.to_string()),
}
let target = match path.as_deref() {
Some(p) if p.starts_with('/') => format!("{base}{p}"),
Some(p) if !p.is_empty() => format!("{base}/{p}"),
_ => format!("{base}/"),
};
app.opener()
.open_url(&target, None::<String>)
.map_err(|e| format!("failed to open Hermes Web UI: {e}"))
}
/// Open the preferred terminal and run `hermes dashboard`. Non-blocking —
/// callers should reinvoke `open_hermes_web_ui` once the server is ready,
/// since Hermes startup can take several seconds and may fail outright if
/// the `hermes-agent[web]` extras are missing.
#[tauri::command]
pub async fn launch_hermes_dashboard() -> Result<(), String> {
tokio::task::spawn_blocking(|| {
crate::commands::misc::launch_terminal_running("hermes dashboard", "hermes_dashboard")
})
.await
.map_err(|e| format!("launch task join error: {e}"))?
}
+1
View File
@@ -202,5 +202,6 @@ pub async fn import_mcp_from_apps(state: State<'_, AppState>) -> Result<usize, S
total += McpService::import_from_codex(&state).unwrap_or(0);
total += McpService::import_from_gemini(&state).unwrap_or(0);
total += McpService::import_from_opencode(&state).unwrap_or(0);
total += McpService::import_from_hermes(&state).unwrap_or(0);
Ok(total)
}
+182
View File
@@ -1310,6 +1310,188 @@ fn run_windows_start_command(args: &[&str], terminal_name: &str) -> Result<(), S
Ok(())
}
/// 打开用户首选终端并在其中执行一条命令行。脚本尾部 `read -n 1` / `pause`
/// 是刻意设计的——让命令退出后窗口不要瞬间关闭,用户才看得到 `command
/// not found` / `ModuleNotFoundError` 这类诊断信息。
///
/// **Security**`command_line` 会被原样拼进 shell/batch 脚本,调用方必须
/// 保证它是可信字符串(当前只由后端硬编码调用)。
pub(crate) fn launch_terminal_running(command_line: &str, label: &str) -> Result<(), String> {
let temp_dir = std::env::temp_dir();
let pid = std::process::id();
#[cfg(any(target_os = "macos", target_os = "linux"))]
let (script_file, script_content) = {
let file = temp_dir.join(format!("cc_switch_{}_{}.sh", label, pid));
let content = format!(
r#"#!/bin/bash
trap 'rm -f "{script_path}"' EXIT
echo "[cc-switch] Starting: {cmd}"
echo ""
{cmd}
echo ""
echo "[cc-switch] Command exited. Press any key to close."
read -n 1 -s
"#,
script_path = file.display(),
cmd = command_line,
);
(file, content)
};
#[cfg(target_os = "macos")]
{
use std::os::unix::fs::PermissionsExt;
std::fs::write(&script_file, &script_content)
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("terminal");
let result = match terminal {
"iterm2" => launch_macos_iterm2(&script_file),
"alacritty" => launch_macos_open_app("Alacritty", &script_file, true),
"kitty" => launch_macos_open_app("kitty", &script_file, false),
"ghostty" => launch_macos_open_app("Ghostty", &script_file, true),
"wezterm" => launch_macos_open_app("WezTerm", &script_file, true),
"kaku" => launch_macos_open_app("Kaku", &script_file, true),
_ => launch_macos_terminal_app(&script_file),
};
if result.is_err() && terminal != "terminal" {
log::warn!(
"首选终端 {} 启动失败,回退到 Terminal.app: {:?}",
terminal,
result.as_ref().err()
);
return launch_macos_terminal_app(&script_file);
}
result
}
#[cfg(target_os = "linux")]
{
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
std::fs::write(&script_file, &script_content)
.map_err(|e| format!("写入启动脚本失败: {e}"))?;
std::fs::set_permissions(&script_file, std::fs::Permissions::from_mode(0o755))
.map_err(|e| format!("设置脚本权限失败: {e}"))?;
let preferred = crate::settings::get_preferred_terminal();
let default_terminals = [
("gnome-terminal", vec!["--"]),
("konsole", vec!["-e"]),
("xfce4-terminal", vec!["-e"]),
("mate-terminal", vec!["--"]),
("lxterminal", vec!["-e"]),
("alacritty", vec!["-e"]),
("kitty", vec!["-e"]),
("ghostty", vec!["-e"]),
];
let terminals_to_try: Vec<(&str, Vec<&str>)> = if let Some(ref pref) = preferred {
let pref_args = default_terminals
.iter()
.find(|(name, _)| *name == pref.as_str())
.map(|(_, args)| args.to_vec())
.unwrap_or_else(|| vec!["-e"]);
let mut list = vec![(pref.as_str(), pref_args)];
for (name, args) in &default_terminals {
if *name != pref.as_str() {
list.push((*name, args.to_vec()));
}
}
list
} else {
default_terminals
.iter()
.map(|(name, args)| (*name, args.to_vec()))
.collect()
};
let mut last_error = String::from("未找到可用的终端");
for (terminal, args) in terminals_to_try {
let terminal_exists = which_command(terminal)
|| ["/usr/bin", "/bin", "/usr/local/bin"]
.iter()
.any(|dir| std::path::Path::new(&format!("{}/{}", dir, terminal)).exists());
if terminal_exists {
let spawn_result = Command::new(terminal)
.args(&args)
.arg("bash")
.arg(script_file.to_string_lossy().as_ref())
.spawn();
match spawn_result {
Ok(_) => return Ok(()),
Err(e) => {
last_error = format!("执行 {} 失败: {}", terminal, e);
}
}
}
}
let _ = std::fs::remove_file(&script_file);
Err(last_error)
}
#[cfg(target_os = "windows")]
{
let preferred = crate::settings::get_preferred_terminal();
let terminal = preferred.as_deref().unwrap_or("cmd");
let bat_file = temp_dir.join(format!("cc_switch_{}_{}.bat", label, pid));
let content = format!(
"@echo off\r\necho [cc-switch] Starting: {cmd}\r\necho.\r\n{cmd}\r\necho.\r\necho [cc-switch] Command exited. Press any key to close.\r\npause >nul\r\ndel \"%~f0\" >nul 2>&1\r\n",
cmd = command_line,
);
std::fs::write(&bat_file, &content).map_err(|e| format!("写入批处理文件失败: {e}"))?;
let bat_path = bat_file.to_string_lossy();
let ps_cmd = format!("& '{}'", bat_path);
let result = match terminal {
"powershell" => run_windows_start_command(
&["powershell", "-NoExit", "-Command", &ps_cmd],
"PowerShell",
),
"wt" => run_windows_start_command(&["wt", "cmd", "/K", &bat_path], "Windows Terminal"),
_ => run_windows_start_command(&["cmd", "/K", &bat_path], "cmd"),
};
let final_result = if result.is_err() && terminal != "cmd" {
log::warn!(
"首选终端 {} 启动失败,回退到 cmd: {:?}",
terminal,
result.as_ref().err()
);
run_windows_start_command(&["cmd", "/K", &bat_path], "cmd")
} else {
result
};
// The .bat self-deletes (`del "%~f0"`) after it runs, but that only
// fires if *some* terminal actually launched it. If every attempt
// failed, sweep the temp file ourselves to avoid pollution.
if final_result.is_err() {
let _ = std::fs::remove_file(&bat_file);
}
final_result
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
{
let _ = (temp_dir, pid, command_line, label);
Err("不支持的操作系统".to_string())
}
}
/// 设置窗口主题(Windows/macOS 标题栏颜色)
/// theme: "dark" | "light" | "system"
#[tauri::command]
+2
View File
@@ -10,6 +10,7 @@ mod deeplink;
mod env;
mod failover;
mod global_proxy;
mod hermes;
mod import_export;
mod mcp;
mod misc;
@@ -42,6 +43,7 @@ pub use deeplink::*;
pub use env::*;
pub use failover::*;
pub use global_proxy::*;
pub use hermes::*;
pub use import_export::*;
pub use mcp::*;
pub use misc::*;
+40 -4
View File
@@ -1,5 +1,5 @@
use indexmap::IndexMap;
use tauri::State;
use tauri::{Emitter, State};
use crate::app_config::AppType;
use crate::commands::copilot::CopilotAuthState;
@@ -153,19 +153,55 @@ pub fn import_default_config(state: State<'_, AppState>, app: String) -> Result<
#[allow(non_snake_case)]
#[tauri::command]
pub async fn queryProviderUsage(
app_handle: tauri::AppHandle,
state: State<'_, AppState>,
copilot_state: State<'_, CopilotAuthState>,
#[allow(non_snake_case)] providerId: String, // 使用 camelCase 匹配前端
app: String,
) -> 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 回调,不吞错误。
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}");
}
state.usage_cache.put_script(app_type, providerId, snapshot);
crate::tray::schedule_tray_refresh(&app_handle);
inner
}
async fn query_provider_usage_inner(
state: &AppState,
copilot_state: &CopilotAuthState,
app_type: AppType,
provider_id: &str,
) -> Result<crate::provider::UsageResult, String> {
// 从数据库读取供应商信息,检查特殊模板类型
let providers = state
.db
.get_all_providers(app_type.as_str())
.map_err(|e| format!("Failed to get providers: {e}"))?;
let provider = providers.get(&providerId);
let provider = providers.get(provider_id);
let usage_script = provider
.and_then(|p| p.meta.as_ref())
.and_then(|m| m.usage_script.as_ref());
@@ -294,7 +330,7 @@ pub async fn queryProviderUsage(
}
// ── 通用 JS 脚本路径 ──
ProviderService::query_usage(state.inner(), app_type, &providerId)
ProviderService::query_usage(state, app_type, provider_id)
.await
.map_err(|e| e.to_string())
}
@@ -406,7 +442,7 @@ pub fn update_providers_sort_order(
use crate::provider::UniversalProvider;
use std::collections::HashMap;
use tauri::{AppHandle, Emitter};
use tauri::AppHandle;
#[derive(Clone, serde::Serialize)]
pub struct UniversalProviderSyncedEvent {
+1
View File
@@ -25,6 +25,7 @@ fn parse_app_type(app: &str) -> Result<AppType, String> {
"codex" => Ok(AppType::Codex),
"gemini" => Ok(AppType::Gemini),
"opencode" => Ok(AppType::OpenCode),
"hermes" => Ok(AppType::Hermes),
_ => Err(format!("不支持的 app 类型: {app}")),
}
}
+35 -4
View File
@@ -1,10 +1,41 @@
use crate::services::subscription::SubscriptionQuota;
use std::str::FromStr;
use tauri::{Emitter, State};
use crate::app_config::AppType;
use crate::services::subscription::{CredentialStatus, SubscriptionQuota};
use crate::store::AppState;
/// 查询官方订阅额度
///
/// 读取 CLI 工具已有的 OAuth 凭据并调用官方 API 获取使用额度。
/// 不需要 AppState(不访问数据库),直接读文件 + 发 HTTP。
/// 结果(无论业务失败还是 transport 层 Err)都会写入 `UsageCache`、通知托盘
/// 刷新,并 emit `usage-cache-updated`,让前端 React Query 与托盘共享同一份
/// 最新数据。失败快照写入后 `format_subscription_summary` 会通过 `success=false`
/// 守卫返回 `None`,托盘 suffix 自然消失,避免长期滞留旧配额数字。
/// Err 原样向前端返回,React Query 的 onError 不会被吞掉。
#[tauri::command]
pub async fn get_subscription_quota(tool: String) -> Result<SubscriptionQuota, String> {
crate::services::subscription::get_subscription_quota(&tool).await
pub async fn get_subscription_quota(
app: tauri::AppHandle,
state: State<'_, AppState>,
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}");
}
state.usage_cache.put_subscription(app_type, snapshot);
crate::tray::schedule_tray_refresh(&app);
}
inner
}
+10 -2
View File
@@ -35,18 +35,26 @@ pub fn get_usage_trends(
#[tauri::command]
pub fn get_provider_stats(
state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
) -> Result<Vec<ProviderStats>, AppError> {
state.db.get_provider_stats(app_type.as_deref())
state
.db
.get_provider_stats(start_date, end_date, app_type.as_deref())
}
/// 获取模型统计
#[tauri::command]
pub fn get_model_stats(
state: State<'_, AppState>,
start_date: Option<i64>,
end_date: Option<i64>,
app_type: Option<String>,
) -> Result<Vec<ModelStats>, AppError> {
state.db.get_model_stats(app_type.as_deref())
state
.db
.get_model_stats(start_date, end_date, app_type.as_deref())
}
/// 获取请求日志列表
+4 -1
View File
@@ -14,6 +14,8 @@ pub struct FailoverQueueItem {
pub provider_id: String,
pub provider_name: String,
pub sort_index: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_notes: Option<String>,
}
impl Database {
@@ -23,7 +25,7 @@ impl Database {
let mut stmt = conn
.prepare(
"SELECT id, name, sort_index
"SELECT id, name, sort_index, notes
FROM providers
WHERE app_type = ?1 AND in_failover_queue = 1
ORDER BY COALESCE(sort_index, 999999), id ASC",
@@ -36,6 +38,7 @@ impl Database {
provider_id: row.get(0)?,
provider_name: row.get(1)?,
sort_index: row.get(2)?,
provider_notes: row.get(3)?,
})
})
.map_err(|e| AppError::Database(e.to_string()))?
+6 -3
View File
@@ -13,7 +13,7 @@ impl Database {
pub fn get_all_mcp_servers(&self) -> Result<IndexMap<String, McpServer>, AppError> {
let conn = lock_conn!(self.conn);
let mut stmt = conn.prepare(
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
"SELECT id, name, server_config, description, homepage, docs, tags, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
FROM mcp_servers
ORDER BY name ASC, id ASC"
).map_err(|e| AppError::Database(e.to_string()))?;
@@ -31,6 +31,7 @@ impl Database {
let enabled_codex: bool = row.get(8)?;
let enabled_gemini: bool = row.get(9)?;
let enabled_opencode: bool = row.get(10)?;
let enabled_hermes: bool = row.get(11)?;
let server = serde_json::from_str(&server_config_str).unwrap_or_default();
let tags = serde_json::from_str(&tags_str).unwrap_or_default();
@@ -46,6 +47,7 @@ impl Database {
codex: enabled_codex,
gemini: enabled_gemini,
opencode: enabled_opencode,
hermes: enabled_hermes,
},
description,
homepage,
@@ -70,8 +72,8 @@ impl Database {
conn.execute(
"INSERT OR REPLACE INTO mcp_servers (
id, name, server_config, description, homepage, docs, tags,
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
params![
server.id,
server.name,
@@ -87,6 +89,7 @@ impl Database {
server.apps.codex,
server.apps.gemini,
server.apps.opencode,
server.apps.hermes,
],
)
.map_err(|e| AppError::Database(e.to_string()))?;
+15 -12
View File
@@ -23,7 +23,7 @@ impl Database {
.prepare(
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
installed_at, content_hash, updated_at
enabled_hermes, installed_at, content_hash, updated_at
FROM skills ORDER BY name ASC",
)
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -44,10 +44,11 @@ impl Database {
codex: row.get(9)?,
gemini: row.get(10)?,
opencode: row.get(11)?,
hermes: row.get(12)?,
},
installed_at: row.get(12)?,
content_hash: row.get(13)?,
updated_at: row.get::<_, i64>(14).unwrap_or(0),
installed_at: row.get(13)?,
content_hash: row.get(14)?,
updated_at: row.get::<_, i64>(15).unwrap_or(0),
})
})
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -67,7 +68,7 @@ impl Database {
.prepare(
"SELECT id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
installed_at, content_hash, updated_at
enabled_hermes, installed_at, content_hash, updated_at
FROM skills WHERE id = ?1",
)
.map_err(|e| AppError::Database(e.to_string()))?;
@@ -87,10 +88,11 @@ impl Database {
codex: row.get(9)?,
gemini: row.get(10)?,
opencode: row.get(11)?,
hermes: row.get(12)?,
},
installed_at: row.get(12)?,
content_hash: row.get(13)?,
updated_at: row.get::<_, i64>(14).unwrap_or(0),
installed_at: row.get(13)?,
content_hash: row.get(14)?,
updated_at: row.get::<_, i64>(15).unwrap_or(0),
})
});
@@ -107,9 +109,9 @@ impl Database {
conn.execute(
"INSERT OR REPLACE INTO skills
(id, name, description, directory, repo_owner, repo_name, repo_branch,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode,
readme_url, enabled_claude, enabled_codex, enabled_gemini, enabled_opencode, enabled_hermes,
installed_at, content_hash, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)",
params![
skill.id,
skill.name,
@@ -123,6 +125,7 @@ impl Database {
skill.apps.codex,
skill.apps.gemini,
skill.apps.opencode,
skill.apps.hermes,
skill.installed_at,
skill.content_hash,
skill.updated_at,
@@ -154,8 +157,8 @@ impl Database {
let conn = lock_conn!(self.conn);
let affected = conn
.execute(
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4 WHERE id = ?5",
params![apps.claude, apps.codex, apps.gemini, apps.opencode, id],
"UPDATE skills SET enabled_claude = ?1, enabled_codex = ?2, enabled_gemini = ?3, enabled_opencode = ?4, enabled_hermes = ?5 WHERE id = ?6",
params![apps.claude, apps.codex, apps.gemini, apps.opencode, apps.hermes, id],
)
.map_err(|e| AppError::Database(e.to_string()))?;
Ok(affected > 0)
+90 -1
View File
@@ -4,13 +4,61 @@
use crate::database::{lock_conn, Database};
use crate::error::AppError;
use chrono::{Duration, Local, TimeZone};
/// Compute the rollup/prune cutoff aligned to a local-day boundary.
///
/// Anything strictly older than the returned timestamp will be aggregated into
/// `usage_daily_rollups` and deleted from `proxy_request_logs`. Aligning to the
/// next local midnight after `(now - retain_days)` guarantees that the youngest
/// rollup row always represents a *complete* local day. Without this alignment
/// the cutoff falls mid-day, leaving the day half-rolled-up and half-pruned —
/// which would silently under-count any range query that touches that day
/// after `compute_rollup_date_bounds` trims partial-coverage rollup days.
fn compute_local_midnight_cutoff(
now: chrono::DateTime<Local>,
retain_days: i64,
) -> Result<i64, AppError> {
let target_day = now
.checked_sub_signed(Duration::days(retain_days))
.ok_or_else(|| AppError::Database("rollup cutoff overflow".to_string()))?
.date_naive();
// Use the *next* day's midnight so anything before it has fully been bucketed.
let next_day = target_day
.succ_opt()
.ok_or_else(|| AppError::Database("rollup cutoff next-day overflow".to_string()))?;
let naive_midnight = next_day
.and_hms_opt(0, 0, 0)
.ok_or_else(|| AppError::Database("rollup cutoff midnight overflow".to_string()))?;
let local_dt = match Local.from_local_datetime(&naive_midnight) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => {
// DST gap: fall back to one hour later, which always exists.
let bumped = naive_midnight + Duration::hours(1);
match Local.from_local_datetime(&bumped) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => {
return Err(AppError::Database(
"rollup cutoff fell into DST gap".to_string(),
))
}
}
}
};
Ok(local_dt.timestamp())
}
impl Database {
/// Aggregate proxy_request_logs older than `retain_days` into usage_daily_rollups,
/// then delete the aggregated detail rows.
/// Returns the number of deleted detail rows.
pub fn rollup_and_prune(&self, retain_days: i64) -> Result<u64, AppError> {
let cutoff = chrono::Utc::now().timestamp() - retain_days * 86400;
let cutoff = compute_local_midnight_cutoff(Local::now(), retain_days)?;
let conn = lock_conn!(self.conn);
// Check if there are any rows to process
@@ -110,8 +158,49 @@ impl Database {
#[cfg(test)]
mod tests {
use super::compute_local_midnight_cutoff;
use crate::database::Database;
use crate::error::AppError;
use chrono::{Local, TimeZone};
fn local_dt(
year: i32,
month: u32,
day: u32,
hour: u32,
minute: u32,
second: u32,
) -> chrono::DateTime<Local> {
match Local.with_ymd_and_hms(year, month, day, hour, minute, second) {
chrono::LocalResult::Single(dt) => dt,
chrono::LocalResult::Ambiguous(earliest, _) => earliest,
chrono::LocalResult::None => panic!("invalid local datetime in test fixture"),
}
}
#[test]
fn cutoff_is_aligned_to_local_midnight_after_target_day() -> Result<(), AppError> {
// now = 2026-04-16 14:32:17 local; retain_days = 30
// target day = 2026-03-17; cutoff should be 2026-03-18 00:00 local.
let now = local_dt(2026, 4, 16, 14, 32, 17);
let cutoff_ts = compute_local_midnight_cutoff(now, 30)?;
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
let expected = local_dt(2026, 3, 18, 0, 0, 0);
assert_eq!(cutoff_dt, expected);
Ok(())
}
#[test]
fn cutoff_at_local_midnight_now_still_lands_on_midnight() -> Result<(), AppError> {
// If `now` is itself local midnight, the math should not introduce drift.
let now = local_dt(2026, 4, 16, 0, 0, 0);
let cutoff_ts = compute_local_midnight_cutoff(now, 7)?;
let cutoff_dt = Local.timestamp_opt(cutoff_ts, 0).single().unwrap();
// (2026-04-16 - 7d) = 2026-04-09; cutoff = 2026-04-10 00:00 local.
let expected = local_dt(2026, 4, 10, 0, 0, 0);
assert_eq!(cutoff_dt, expected);
Ok(())
}
#[test]
fn test_rollup_and_prune() -> Result<(), AppError> {
+1 -1
View File
@@ -44,7 +44,7 @@ use std::sync::Mutex;
/// 当前 Schema 版本号
/// 每次修改表结构时递增,并在 schema.rs 中添加相应的迁移逻辑
pub(crate) const SCHEMA_VERSION: i32 = 9;
pub(crate) const SCHEMA_VERSION: i32 = 10;
/// 安全地序列化 JSON,避免 unwrap panic
pub(crate) fn to_json_string<T: Serialize>(value: &T) -> Result<String, AppError> {
+41 -1
View File
@@ -65,7 +65,8 @@ impl Database {
id TEXT PRIMARY KEY, name TEXT NOT NULL, server_config TEXT NOT NULL,
description TEXT, homepage TEXT, docs TEXT, tags TEXT NOT NULL DEFAULT '[]',
enabled_claude BOOLEAN NOT NULL DEFAULT 0, enabled_codex BOOLEAN NOT NULL DEFAULT 0,
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0
enabled_gemini BOOLEAN NOT NULL DEFAULT 0, enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
enabled_hermes BOOLEAN NOT NULL DEFAULT 0
)",
[],
)
@@ -93,6 +94,7 @@ impl Database {
enabled_codex BOOLEAN NOT NULL DEFAULT 0,
enabled_gemini BOOLEAN NOT NULL DEFAULT 0,
enabled_opencode BOOLEAN NOT NULL DEFAULT 0,
enabled_hermes BOOLEAN NOT NULL DEFAULT 0,
installed_at INTEGER NOT NULL DEFAULT 0,
content_hash TEXT,
updated_at INTEGER NOT NULL DEFAULT 0
@@ -423,6 +425,11 @@ impl Database {
Self::migrate_v8_to_v9(conn)?;
Self::set_user_version(conn, 9)?;
}
9 => {
log::info!("迁移数据库从 v9 到 v10(添加 Hermes Agent 支持)");
Self::migrate_v9_to_v10(conn)?;
Self::set_user_version(conn, 10)?;
}
_ => {
return Err(AppError::Database(format!(
"未知的数据库版本 {version},无法迁移到 {SCHEMA_VERSION}"
@@ -1168,11 +1175,43 @@ impl Database {
Ok(())
}
/// v9 -> v10 迁移:添加 Hermes Agent 支持
fn migrate_v9_to_v10(conn: &Connection) -> Result<(), AppError> {
Self::add_column_if_missing(
conn,
"mcp_servers",
"enabled_hermes",
"BOOLEAN NOT NULL DEFAULT 0",
)?;
// skills table may not exist in databases migrated from very old versions
if Self::table_exists(conn, "skills")? {
Self::add_column_if_missing(
conn,
"skills",
"enabled_hermes",
"BOOLEAN NOT NULL DEFAULT 0",
)?;
}
log::info!("v9 -> v10 迁移完成:已添加 Hermes Agent 支持");
Ok(())
}
/// 插入默认模型定价数据
/// 格式: (model_id, display_name, input, output, cache_read, cache_creation)
/// 注意: model_id 使用短横线格式(如 claude-haiku-4-5),与 API 返回的模型名称标准化后一致
fn seed_model_pricing(conn: &Connection) -> Result<(), AppError> {
let pricing_data = [
// Claude 4.7 系列
(
"claude-opus-4-7",
"Claude Opus 4.7",
"5",
"25",
"0.50",
"6.25",
),
// Claude 4.6 系列
(
"claude-opus-4-6-20260206",
@@ -1600,6 +1639,7 @@ impl Database {
"0",
),
("kimi-k2.5", "Kimi K2.5", "0.60", "2.50", "0.10", "0"),
("kimi-k2.6", "Kimi K2.6", "0.95", "4.00", "0.16", "0"),
// MiniMax 系列
("minimax-m2.1", "MiniMax M2.1", "0.27", "0.95", "0.03", "0"),
(
+2
View File
@@ -167,6 +167,7 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
codex: false,
gemini: false,
opencode: false,
hermes: false,
};
for app in apps_str.split(',') {
@@ -179,6 +180,7 @@ pub(crate) fn parse_mcp_apps(apps_str: &str) -> Result<McpApps, AppError> {
// OpenClaw doesn't support MCP, ignore silently
log::debug!("OpenClaw doesn't support MCP, ignoring in apps parameter");
}
"hermes" => apps.hermes = true,
other => {
return Err(AppError::InvalidInput(format!(
"Invalid app in 'apps': {other}"
+1 -1
View File
@@ -31,7 +31,7 @@ pub use skill::import_skill_from_deeplink;
///
/// Represents a parsed ccswitch:// URL ready for processing.
/// This struct contains all possible fields for all resource types.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeepLinkImportRequest {
/// Protocol version (e.g., "v1")
+6 -6
View File
@@ -81,10 +81,10 @@ fn parse_provider_deeplink(
// Validate app type
if !matches!(
app.as_str(),
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
)));
}
@@ -190,10 +190,10 @@ fn parse_prompt_deeplink(
// Validate app type
if !matches!(
app.as_str(),
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{app}'"
"Invalid app type: must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{app}'"
)));
}
@@ -262,10 +262,10 @@ fn parse_mcp_deeplink(
let trimmed = app.trim();
if !matches!(
trimmed,
"claude" | "codex" | "gemini" | "opencode" | "openclaw"
"claude" | "codex" | "gemini" | "opencode" | "openclaw" | "hermes"
) {
return Err(AppError::InvalidInput(format!(
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', or 'openclaw', got '{trimmed}'"
"Invalid app in 'apps': must be 'claude', 'codex', 'gemini', 'opencode', 'openclaw', or 'hermes', got '{trimmed}'"
)));
}
}
+133 -7
View File
@@ -146,7 +146,8 @@ pub(crate) fn build_provider_from_request(
AppType::Codex => build_codex_settings(request),
AppType::Gemini => build_gemini_settings(request),
AppType::OpenCode => build_opencode_settings(request),
AppType::OpenClaw => build_openclaw_settings(request),
AppType::OpenClaw => build_additive_app_settings(request),
AppType::Hermes => build_hermes_settings(request),
};
// Build usage script configuration if provided
@@ -393,11 +394,11 @@ fn build_opencode_settings(request: &DeepLinkImportRequest) -> serde_json::Value
})
}
fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
/// Build settings for OpenClaw (camelCase live config).
/// Format: { baseUrl, apiKey, api, models }
fn build_additive_app_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
let endpoint = get_primary_endpoint(request);
// Build OpenClaw provider config
// Format: { baseUrl, apiKey, api, models }
let mut config = serde_json::Map::new();
if !endpoint.is_empty() {
@@ -408,10 +409,49 @@ fn build_openclaw_settings(request: &DeepLinkImportRequest) -> serde_json::Value
config.insert("apiKey".to_string(), json!(api_key));
}
// Default to OpenAI-compatible API
config.insert("api".to_string(), json!("openai-completions"));
// Build models array
if let Some(model) = &request.model {
config.insert(
"models".to_string(),
json!([{ "id": model, "name": model }]),
);
}
json!(config)
}
/// Build Hermes provider settings (snake_case YAML-native fields).
///
/// Hermes' `custom_providers:` entries use `base_url` / `api_key` / `api_mode`
/// (see `_VALID_CUSTOM_PROVIDER_FIELDS` in upstream `hermes_cli/config.py`).
/// Emitting camelCase here — as the OpenClaw path does — would poison the
/// YAML with unknown root fields the Hermes runtime ignores.
///
/// `api_mode` is always written explicitly. Deeplinks have no field to carry
/// it, so we default to `chat_completions` (the most widely compatible
/// protocol) and let the user adjust via the UI after import. We never rely
/// on Hermes' built-in URL heuristics, which only recognize a handful of
/// official endpoints.
fn build_hermes_settings(request: &DeepLinkImportRequest) -> serde_json::Value {
let endpoint = get_primary_endpoint(request);
let mut config = serde_json::Map::new();
if let Some(name) = request.name.as_deref().filter(|s| !s.is_empty()) {
config.insert("name".to_string(), json!(name));
}
if !endpoint.is_empty() {
config.insert("base_url".to_string(), json!(endpoint));
}
if let Some(api_key) = &request.api_key {
config.insert("api_key".to_string(), json!(api_key));
}
config.insert("api_mode".to_string(), json!("chat_completions"));
if let Some(model) = &request.model {
config.insert(
"models".to_string(),
@@ -484,7 +524,7 @@ pub fn parse_and_merge_config(
"codex" => merge_codex_config(&mut merged, &config_value)?,
"gemini" => merge_gemini_config(&mut merged, &config_value)?,
// Additive mode apps use JSON config directly; pass through as-is
"openclaw" | "opencode" => {
"openclaw" | "opencode" | "hermes" => {
merge_additive_config(&mut merged, &config_value)?;
}
"" => {
@@ -711,3 +751,89 @@ fn extract_codex_base_url(toml_value: &toml::Value) -> Option<String> {
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn hermes_request() -> DeepLinkImportRequest {
DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("hermes".to_string()),
name: Some("MyHermes".to_string()),
endpoint: Some("https://api.example.com/v1".to_string()),
api_key: Some("sk-test".to_string()),
model: Some("anthropic/claude-opus-4-7".to_string()),
..Default::default()
}
}
#[test]
fn build_hermes_settings_emits_snake_case() {
let settings = build_hermes_settings(&hermes_request());
let obj = settings.as_object().expect("settings must be object");
assert_eq!(obj.get("name").unwrap(), "MyHermes");
assert_eq!(obj.get("base_url").unwrap(), "https://api.example.com/v1");
assert_eq!(obj.get("api_key").unwrap(), "sk-test");
// camelCase and legacy fields must NOT be present
assert!(obj.get("baseUrl").is_none(), "no camelCase baseUrl");
assert!(obj.get("apiKey").is_none(), "no camelCase apiKey");
assert!(obj.get("api").is_none(), "no legacy 'api' field");
// models array with the deeplink model id
let models = obj.get("models").unwrap().as_array().unwrap();
assert_eq!(models.len(), 1);
assert_eq!(models[0]["id"], "anthropic/claude-opus-4-7");
}
#[test]
fn build_hermes_settings_writes_default_api_mode() {
let settings = build_hermes_settings(&hermes_request());
assert_eq!(
settings.as_object().unwrap().get("api_mode").unwrap(),
"chat_completions",
"api_mode must be written explicitly so Hermes never falls back to URL auto-detection"
);
}
#[test]
fn build_hermes_settings_skips_missing_optional_fields() {
let request = DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("hermes".to_string()),
name: Some("Minimal".to_string()),
endpoint: None,
api_key: None,
model: None,
..Default::default()
};
let settings = build_hermes_settings(&request);
let obj = settings.as_object().unwrap();
assert_eq!(obj.get("name").unwrap(), "Minimal");
assert!(obj.get("base_url").is_none());
assert!(obj.get("api_key").is_none());
assert!(obj.get("models").is_none());
assert_eq!(obj.get("api_mode").unwrap(), "chat_completions");
}
#[test]
fn openclaw_still_uses_camel_case() {
// OpenClaw's live config natively uses camelCase; guard against a
// refactor accidentally flipping it to snake_case.
let request = DeepLinkImportRequest {
resource: "provider".to_string(),
app: Some("openclaw".to_string()),
name: Some("c".to_string()),
endpoint: Some("https://api.example.com".to_string()),
api_key: Some("k".to_string()),
..Default::default()
};
let settings = build_additive_app_settings(&request);
let obj = settings.as_object().unwrap();
assert!(obj.contains_key("baseUrl"));
assert!(obj.contains_key("apiKey"));
}
}
File diff suppressed because it is too large Load Diff
+42 -5
View File
@@ -11,6 +11,7 @@ mod deeplink;
mod error;
mod gemini_config;
mod gemini_mcp;
pub mod hermes_config;
mod init_status;
mod lightweight;
#[cfg(target_os = "linux")]
@@ -168,7 +169,7 @@ async fn update_tray_menu(
) -> Result<bool, String> {
match tray::create_tray_menu(&app, state.inner()) {
Ok(new_menu) => {
if let Some(tray) = app.tray_by_id("main") {
if let Some(tray) = app.tray_by_id(tray::TRAY_ID) {
tray.set_menu(Some(new_menu))
.map_err(|e| format!("更新托盘菜单失败: {e}"))?;
return Ok(true);
@@ -272,6 +273,8 @@ pub fn run() {
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_store::Builder::new().build())
.setup(|app| {
let _ = rustls::crypto::ring::default_provider().install_default();
// 预先刷新 Store 覆盖配置,确保后续路径读取正确(日志/数据库等)
app_store::refresh_app_config_dir_override(app.handle());
panic_hook::init_app_config_dir(crate::config::get_app_config_dir());
@@ -540,6 +543,13 @@ pub fn run() {
Ok(_) => log::debug!("○ No new OpenClaw providers to import"),
Err(e) => log::warn!("✗ Failed to import OpenClaw providers: {e}"),
}
match crate::services::provider::import_hermes_providers_from_live(&app_state) {
Ok(count) if count > 0 => {
log::info!("✓ Imported {count} Hermes provider(s) from live config");
}
Ok(_) => log::debug!("○ No new Hermes providers to import"),
Err(e) => log::warn!("✗ Failed to import Hermes providers: {e}"),
}
// 2. OMO 配置导入(当数据库中无 OMO provider 时,从本地文件导入)
{
@@ -627,6 +637,14 @@ pub fn run() {
Ok(_) => log::debug!("○ No OpenCode MCP servers found to import"),
Err(e) => log::warn!("✗ Failed to import OpenCode MCP: {e}"),
}
match crate::services::mcp::McpService::import_from_hermes(&app_state) {
Ok(count) if count > 0 => {
log::info!("✓ Imported {count} MCP server(s) from Hermes");
}
Ok(_) => log::debug!("○ No Hermes MCP servers found to import"),
Err(e) => log::warn!("✗ Failed to import Hermes MCP: {e}"),
}
}
// 4. 导入提示词文件(表空时触发)
@@ -639,6 +657,7 @@ pub fn run() {
crate::app_config::AppType::Gemini,
crate::app_config::AppType::OpenCode,
crate::app_config::AppType::OpenClaw,
crate::app_config::AppType::Hermes,
] {
match crate::services::prompt::PromptService::import_from_file_on_first_launch(
&app_state,
@@ -728,10 +747,17 @@ pub fn run() {
let menu = tray::create_tray_menu(app.handle(), &app_state)?;
// 构建托盘
let mut tray_builder = TrayIconBuilder::with_id("main")
.on_tray_icon_event(|_tray, event| match event {
// 左键点击已通过 show_menu_on_left_click(true) 打开菜单,这里不再额外处理
TrayIconEvent::Click { .. } => {}
let mut tray_builder = TrayIconBuilder::with_id(tray::TRAY_ID)
.on_tray_icon_event(|tray, event| match event {
// 鼠标悬停/点击到托盘图标时,后台异步刷新用量缓存,
// 让用户下一次(或快速打开菜单的那一刻)看到较新的数字。
// refresh_all_usage_in_tray 内部有 10 秒防抖。
TrayIconEvent::Enter { .. } | TrayIconEvent::Click { .. } => {
let app = tray.app_handle().clone();
tauri::async_runtime::spawn(async move {
crate::tray::refresh_all_usage_in_tray(&app).await;
});
}
_ => log::debug!("unhandled event {event:?}"),
})
.menu(&menu)
@@ -1234,6 +1260,17 @@ pub fn run() {
commands::set_openclaw_env,
commands::get_openclaw_tools,
commands::set_openclaw_tools,
// Hermes specific
commands::import_hermes_providers_from_live,
commands::get_hermes_live_provider_ids,
commands::get_hermes_live_provider,
commands::get_hermes_model_config,
commands::open_hermes_web_ui,
commands::launch_hermes_dashboard,
commands::get_hermes_memory,
commands::set_hermes_memory,
commands::get_hermes_memory_limits,
commands::set_hermes_memory_enabled,
// Global upstream proxy
commands::get_global_proxy_url,
commands::set_global_proxy_url,
+1
View File
@@ -92,6 +92,7 @@ pub fn import_from_claude(config: &mut MultiAppConfig) -> Result<usize, AppError
codex: false,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
+1
View File
@@ -236,6 +236,7 @@ pub fn import_from_codex(config: &mut MultiAppConfig) -> Result<usize, AppError>
codex: true,
gemini: false,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
+1
View File
@@ -88,6 +88,7 @@ pub fn import_from_gemini(config: &mut MultiAppConfig) -> Result<usize, AppError
codex: false,
gemini: true,
opencode: false,
hermes: false,
},
description: None,
homepage: None,
+574
View File
@@ -0,0 +1,574 @@
//! Hermes MCP sync and import module
//!
//! Handles conversion between CC Switch unified MCP format and Hermes config.yaml format.
//!
//! ## Format mapping
//!
//! | CC Switch unified (JSON) | Hermes config.yaml (YAML) |
//! |-------------------------------------------------|---------------------------------|
//! | `{"type":"stdio","command":"npx","args":[...],"env":{}}` | `command: npx`, `args: [...]`, `env: {}` |
//! | `{"type":"sse"/"http","url":"...","headers":{}}` | `url: "..."`, `headers: {}` |
//!
//! Key differences from Claude format:
//! - Hermes has NO explicit `type` field -- it infers stdio (has `command`) vs HTTP (has `url`)
//! - Hermes has extra fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
//! - These Hermes-specific fields are preserved on merge-on-write and stripped on import
use serde_json::{json, Value};
use std::collections::HashMap;
use crate::app_config::{McpApps, McpServer, MultiAppConfig};
use crate::error::AppError;
use crate::hermes_config;
use super::validation::validate_server_spec;
/// Hermes-specific fields preserved on merge-on-write, stripped on import.
/// Update this list when Hermes adds new per-server config fields.
///
/// `auth` ("oauth" / absent) is an OAuth-type declaration read by Hermes —
/// CC Switch has no OAuth UI, but losing the field on round-trip downgrades
/// the server to unauthenticated calls.
const HERMES_EXTRA_FIELDS: &[&str] = &[
"enabled",
"timeout",
"connect_timeout",
"tools",
"sampling",
"roots",
"auth",
];
// ============================================================================
// Helper Functions
// ============================================================================
/// Check if Hermes MCP sync should proceed
fn should_sync_hermes_mcp() -> bool {
hermes_config::get_hermes_dir().exists()
}
// ============================================================================
// Format Conversion: CC Switch -> Hermes
// ============================================================================
/// Convert CC Switch unified format to Hermes format
///
/// Conversion rules:
/// - `stdio`: output `command`, `args`, `env` (strip `type` field)
/// - `sse`/`http`: output `url`, `headers` (strip `type` field)
/// - Always add `enabled: true`
fn convert_to_hermes_format(spec: &Value) -> Result<Value, AppError> {
let obj = spec
.as_object()
.ok_or_else(|| AppError::McpValidation("MCP spec must be a JSON object".into()))?;
let typ = obj.get("type").and_then(|v| v.as_str()).unwrap_or("stdio");
let mut result = serde_json::Map::new();
match typ {
"stdio" => {
if let Some(command) = obj.get("command") {
result.insert("command".into(), command.clone());
}
if let Some(args) = obj.get("args") {
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
result.insert("args".into(), args.clone());
}
}
if let Some(env) = obj.get("env") {
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("env".into(), env.clone());
}
}
}
"sse" | "http" => {
if let Some(url) = obj.get("url") {
result.insert("url".into(), url.clone());
}
if let Some(headers) = obj.get("headers") {
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true)
{
result.insert("headers".into(), headers.clone());
}
}
}
_ => {
return Err(AppError::McpValidation(format!("Unknown MCP type: {typ}")));
}
}
result.insert("enabled".into(), json!(true));
Ok(Value::Object(result))
}
// ============================================================================
// Format Conversion: Hermes -> CC Switch
// ============================================================================
/// Convert Hermes format to CC Switch unified format
///
/// Conversion rules:
/// - If `command` exists: set `type: "stdio"`, extract `command`, `args`, `env`
/// - If `url` exists: set `type: "sse"`, extract `url`, `headers`
/// - Strip Hermes-specific fields: `enabled`, `timeout`, `connect_timeout`, `tools`, `sampling`
fn convert_from_hermes_format(id: &str, spec: &Value) -> Result<Value, AppError> {
let obj = spec
.as_object()
.ok_or_else(|| AppError::McpValidation("Hermes MCP spec must be a JSON object".into()))?;
let mut result = serde_json::Map::new();
if obj.contains_key("command") {
// stdio type
result.insert("type".into(), json!("stdio"));
if let Some(command) = obj.get("command") {
result.insert("command".into(), command.clone());
}
if let Some(args) = obj.get("args") {
if args.is_array() && !args.as_array().map(|a| a.is_empty()).unwrap_or(true) {
result.insert("args".into(), args.clone());
}
}
if let Some(env) = obj.get("env") {
if env.is_object() && !env.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("env".into(), env.clone());
}
}
} else if obj.contains_key("url") {
// HTTP/SSE type
result.insert("type".into(), json!("sse"));
if let Some(url) = obj.get("url") {
result.insert("url".into(), url.clone());
}
if let Some(headers) = obj.get("headers") {
if headers.is_object() && !headers.as_object().map(|o| o.is_empty()).unwrap_or(true) {
result.insert("headers".into(), headers.clone());
}
}
} else {
return Err(AppError::McpValidation(format!(
"Hermes MCP server '{id}' has neither 'command' nor 'url' field"
)));
}
// Note: Hermes-specific fields (enabled, timeout, connect_timeout, tools, sampling)
// are intentionally NOT copied -- they are stripped on import.
Ok(Value::Object(result))
}
// ============================================================================
// Public API: Sync Functions
// ============================================================================
/// Sync a single MCP server to Hermes live config (merge-on-write)
///
/// Strategy:
/// 1. Read existing mcp_servers from config.yaml
/// 2. If server already exists, merge: keep Hermes-specific fields, overwrite core fields
/// 3. Set `enabled: true`
/// 4. Write back
pub fn sync_single_server_to_hermes(
_config: &MultiAppConfig,
id: &str,
server_spec: &Value,
) -> Result<(), AppError> {
if !should_sync_hermes_mcp() {
return Ok(());
}
let hermes_spec = convert_to_hermes_format(server_spec)?;
let id_owned = id.to_string();
hermes_config::update_mcp_servers_yaml(|servers| {
let id_yaml = serde_yaml::Value::String(id_owned.clone());
let merged_json = if let Some(existing_yaml) = servers.get(&id_yaml) {
let existing_json = hermes_config::yaml_to_json(existing_yaml)?;
merge_hermes_spec(&existing_json, &hermes_spec)
} else {
hermes_spec.clone()
};
let merged_yaml_value = hermes_config::json_to_yaml(&merged_json)?;
servers.insert(id_yaml, merged_yaml_value);
Ok(())
})
}
/// Merge new spec into existing Hermes spec, preserving Hermes-specific fields.
///
/// Core fields (command, args, env, url, headers) come from `new_spec`.
/// Hermes-specific fields (enabled, tools, sampling, etc.) are kept from
/// `existing` — this prevents CC Switch from overwriting user customizations.
fn merge_hermes_spec(existing: &Value, new_spec: &Value) -> Value {
let mut result = serde_json::Map::new();
// Copy Hermes-specific fields from existing config
if let Some(existing_obj) = existing.as_object() {
for &field in HERMES_EXTRA_FIELDS {
if let Some(val) = existing_obj.get(field) {
result.insert(field.to_string(), val.clone());
}
}
}
// Overwrite with core fields from new spec; for Hermes-specific fields,
// only apply from new_spec if existing didn't already have them
if let Some(new_obj) = new_spec.as_object() {
for (key, val) in new_obj {
if HERMES_EXTRA_FIELDS.contains(&key.as_str()) && result.contains_key(key) {
continue; // Existing Hermes-specific field takes precedence
}
result.insert(key.clone(), val.clone());
}
}
Value::Object(result)
}
/// Remove a single MCP server from Hermes live config
pub fn remove_server_from_hermes(id: &str) -> Result<(), AppError> {
if !should_sync_hermes_mcp() {
return Ok(());
}
let id_owned = id.to_string();
hermes_config::update_mcp_servers_yaml(|servers| {
servers.remove(serde_yaml::Value::String(id_owned.clone()));
Ok(())
})
}
/// Import MCP servers from Hermes config to unified structure
///
/// Existing servers will have Hermes app enabled without overwriting other fields.
pub fn import_from_hermes(config: &mut MultiAppConfig) -> Result<usize, AppError> {
let yaml_map = hermes_config::get_mcp_servers_yaml()?;
if yaml_map.is_empty() {
return Ok(0);
}
// Ensure servers map exists
let servers = config.mcp.servers.get_or_insert_with(HashMap::new);
let mut changed = 0;
let mut errors = Vec::new();
for (key, spec_yaml) in &yaml_map {
let id = match key.as_str() {
Some(s) => s.to_string(),
None => {
log::warn!("Skip Hermes MCP server with non-string key");
continue;
}
};
// Convert YAML value to JSON
let spec_json = match hermes_config::yaml_to_json(spec_yaml) {
Ok(j) => j,
Err(e) => {
log::warn!("Skip Hermes MCP server '{id}': failed to convert YAML to JSON: {e}");
errors.push(format!("{id}: {e}"));
continue;
}
};
// Convert from Hermes format to unified format
let unified_spec = match convert_from_hermes_format(&id, &spec_json) {
Ok(s) => s,
Err(e) => {
log::warn!("Skip invalid Hermes MCP server '{id}': {e}");
errors.push(format!("{id}: {e}"));
continue;
}
};
// Validate the converted spec
if let Err(e) = validate_server_spec(&unified_spec) {
log::warn!("Skip invalid MCP server '{id}' after conversion: {e}");
errors.push(format!("{id}: {e}"));
continue;
}
if let Some(existing) = servers.get_mut(&id) {
// Existing server: just enable Hermes app
if !existing.apps.hermes {
existing.apps.hermes = true;
changed += 1;
log::info!("MCP server '{id}' enabled for Hermes");
}
} else {
// New server: default to only Hermes enabled
servers.insert(
id.clone(),
McpServer {
id: id.clone(),
name: id.clone(),
server: unified_spec,
apps: McpApps {
claude: false,
codex: false,
gemini: false,
opencode: false,
hermes: true,
},
description: None,
homepage: None,
docs: None,
tags: Vec::new(),
},
);
changed += 1;
log::info!("Imported new MCP server '{id}' from Hermes");
}
}
if !errors.is_empty() {
log::warn!(
"Import completed with {} failures: {:?}",
errors.len(),
errors
);
}
Ok(changed)
}
#[cfg(test)]
mod tests {
use super::*;
// ========================================================================
// convert_to_hermes_format tests
// ========================================================================
#[test]
fn test_convert_stdio_to_hermes() {
let spec = json!({
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": { "HOME": "/Users/test" }
});
let result = convert_to_hermes_format(&spec).unwrap();
// No type field in Hermes format
assert!(result.get("type").is_none());
assert_eq!(result["command"], "npx");
assert_eq!(result["args"][0], "-y");
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
assert_eq!(result["env"]["HOME"], "/Users/test");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_http_to_hermes() {
let spec = json!({
"type": "sse",
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer xxx" }
});
let result = convert_to_hermes_format(&spec).unwrap();
assert!(result.get("type").is_none());
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_http_type_to_hermes() {
let spec = json!({
"type": "http",
"url": "https://example.com/mcp"
});
let result = convert_to_hermes_format(&spec).unwrap();
assert!(result.get("type").is_none());
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_stdio_empty_env_to_hermes() {
let spec = json!({
"type": "stdio",
"command": "node",
"args": [],
"env": {}
});
let result = convert_to_hermes_format(&spec).unwrap();
assert_eq!(result["command"], "node");
// Empty args and env should be omitted
assert!(result.get("args").is_none());
assert!(result.get("env").is_none());
assert_eq!(result["enabled"], true);
}
#[test]
fn test_convert_unknown_type_to_hermes_fails() {
let spec = json!({ "type": "grpc", "command": "foo" });
assert!(convert_to_hermes_format(&spec).is_err());
}
// ========================================================================
// convert_from_hermes_format tests
// ========================================================================
#[test]
fn test_convert_hermes_stdio_to_unified() {
let spec = json!({
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem"],
"env": { "HOME": "/Users/test" },
"enabled": true,
"timeout": 30,
"connect_timeout": 10,
"tools": { "include": ["read_file"] },
"sampling": { "enabled": true }
});
let result = convert_from_hermes_format("filesystem", &spec).unwrap();
assert_eq!(result["type"], "stdio");
assert_eq!(result["command"], "npx");
assert_eq!(result["args"][0], "-y");
assert_eq!(result["args"][1], "@modelcontextprotocol/server-filesystem");
assert_eq!(result["env"]["HOME"], "/Users/test");
// Hermes-specific fields should be stripped
assert!(result.get("enabled").is_none());
assert!(result.get("timeout").is_none());
assert!(result.get("connect_timeout").is_none());
assert!(result.get("tools").is_none());
assert!(result.get("sampling").is_none());
}
#[test]
fn test_convert_hermes_http_to_unified() {
let spec = json!({
"url": "https://example.com/mcp",
"headers": { "Authorization": "Bearer xxx" },
"enabled": true,
"timeout": 60
});
let result = convert_from_hermes_format("remote-server", &spec).unwrap();
assert_eq!(result["type"], "sse");
assert_eq!(result["url"], "https://example.com/mcp");
assert_eq!(result["headers"]["Authorization"], "Bearer xxx");
// Hermes-specific fields should be stripped
assert!(result.get("enabled").is_none());
assert!(result.get("timeout").is_none());
}
#[test]
fn test_convert_hermes_no_command_no_url_fails() {
let spec = json!({ "enabled": true, "timeout": 30 });
assert!(convert_from_hermes_format("bad-server", &spec).is_err());
}
// ========================================================================
// Merge-on-write tests
// ========================================================================
#[test]
fn test_merge_preserves_hermes_specific_fields() {
let existing = json!({
"command": "old-cmd",
"args": ["old-arg"],
"enabled": true,
"timeout": 30,
"connect_timeout": 10,
"tools": { "include": ["read_file"] },
"sampling": { "enabled": true }
});
let new_spec = json!({
"command": "new-cmd",
"args": ["new-arg"],
"env": { "KEY": "value" },
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
// Core fields should be overwritten
assert_eq!(merged["command"], "new-cmd");
assert_eq!(merged["args"][0], "new-arg");
assert_eq!(merged["env"]["KEY"], "value");
// Hermes-specific fields should be preserved from existing
assert_eq!(merged["timeout"], 30);
assert_eq!(merged["connect_timeout"], 10);
assert_eq!(merged["tools"]["include"][0], "read_file");
assert_eq!(merged["sampling"]["enabled"], true);
assert_eq!(merged["enabled"], true);
}
#[test]
fn test_merge_preserves_auth_field() {
let existing = json!({
"url": "https://mcp.example.com",
"auth": "oauth",
"enabled": true
});
let new_spec = json!({
"url": "https://mcp.example.com/updated",
"headers": { "X-Trace": "abc" },
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
assert_eq!(merged["url"], "https://mcp.example.com/updated");
assert_eq!(merged["headers"]["X-Trace"], "abc");
assert_eq!(
merged["auth"], "oauth",
"auth declaration must survive CC Switch round-trip"
);
}
#[test]
fn test_convert_hermes_strips_auth_on_import() {
let spec = json!({
"url": "https://mcp.example.com",
"auth": "oauth",
"enabled": true
});
let result = convert_from_hermes_format("remote", &spec).unwrap();
assert_eq!(result["type"], "sse");
assert_eq!(result["url"], "https://mcp.example.com");
assert!(
result.get("auth").is_none(),
"auth stays Hermes-specific; stripped from unified format"
);
}
#[test]
fn test_merge_new_server_no_existing_extra_fields() {
let existing = json!({
"command": "old-cmd"
});
let new_spec = json!({
"command": "new-cmd",
"args": ["arg1"],
"enabled": true
});
let merged = merge_hermes_spec(&existing, &new_spec);
assert_eq!(merged["command"], "new-cmd");
assert_eq!(merged["args"][0], "arg1");
assert_eq!(merged["enabled"], true);
// No extra fields to preserve
assert!(merged.get("timeout").is_none());
}
}
+3
View File
@@ -9,10 +9,12 @@
//! - `codex` - Codex MCP 同步和导入(含 TOML 转换)
//! - `gemini` - Gemini MCP 同步和导入
//! - `opencode` - OpenCode MCP 同步和导入(含 local/remote 格式转换)
//! - `hermes` - Hermes MCP 同步和导入
mod claude;
mod codex;
mod gemini;
mod hermes;
mod opencode;
mod validation;
@@ -28,6 +30,7 @@ pub use gemini::{
import_from_gemini, remove_server_from_gemini, sync_enabled_to_gemini,
sync_single_server_to_gemini,
};
pub use hermes::{import_from_hermes, remove_server_from_hermes, sync_single_server_to_hermes};
pub use opencode::{
import_from_opencode, remove_server_from_opencode, sync_single_server_to_opencode,
};
+1
View File
@@ -259,6 +259,7 @@ pub fn import_from_opencode(config: &mut MultiAppConfig) -> Result<usize, AppErr
codex: false,
gemini: false,
opencode: true,
hermes: false,
},
description: None,
homepage: None,
+5
View File
@@ -914,6 +914,7 @@ pub fn set_tools_config(tools: &OpenClawToolsConfig) -> Result<OpenClawWriteOutc
#[cfg(test)]
mod tests {
use super::*;
use serial_test::serial;
use std::sync::{Mutex, OnceLock};
fn test_guard() -> std::sync::MutexGuard<'static, ()> {
@@ -966,6 +967,7 @@ mod tests {
}
#[test]
#[serial]
fn default_model_write_preserves_top_level_comments() {
let source = r#"{
// top-level comment
@@ -994,6 +996,7 @@ mod tests {
}
#[test]
#[serial]
fn default_model_noop_write_skips_backup() {
let source = r#"{
models: {
@@ -1028,6 +1031,7 @@ mod tests {
}
#[test]
#[serial]
fn save_detects_external_conflict() {
let source = r#"{
models: {
@@ -1050,6 +1054,7 @@ mod tests {
}
#[test]
#[serial]
fn remove_last_provider_writes_empty_providers_without_panic() {
let source = r#"{
models: {
+2 -2
View File
@@ -16,14 +16,14 @@ pub fn prompt_file_path(app: &AppType) -> Result<PathBuf, AppError> {
AppType::Gemini => get_gemini_dir(),
AppType::OpenCode => get_opencode_dir(),
AppType::OpenClaw => get_openclaw_dir(),
AppType::Hermes => crate::hermes_config::get_hermes_dir(),
};
let filename = match app {
AppType::Claude => "CLAUDE.md",
AppType::Codex => "AGENTS.md",
AppType::Gemini => "GEMINI.md",
AppType::OpenCode => "AGENTS.md",
AppType::OpenClaw => "AGENTS.md", // OpenClaw uses AGENTS.md for agent instructions
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => "AGENTS.md",
};
Ok(base_dir.join(filename))
+30 -1
View File
@@ -65,6 +65,25 @@ impl Provider {
in_failover_queue: false,
}
}
pub fn is_codex_oauth(&self) -> bool {
self.meta.as_ref().and_then(|m| m.provider_type.as_deref()) == Some("codex_oauth")
}
pub fn codex_fast_mode_enabled(&self) -> bool {
self.meta
.as_ref()
.map(|m| m.codex_fast_mode_enabled())
.unwrap_or(false)
}
pub fn has_usage_script_enabled(&self) -> bool {
self.meta
.as_ref()
.and_then(|m| m.usage_script.as_ref())
.map(|s| s.enabled)
.unwrap_or(false)
}
}
/// 供应商管理器
@@ -258,9 +277,13 @@ pub struct ProviderMeta {
pub is_full_url: Option<bool>,
/// Prompt cache key for OpenAI Responses-compatible endpoints.
/// When set, injected into converted Responses requests to improve cache hit rate.
/// If not set, provider ID is used automatically during Claude -> Responses conversion.
/// If not set, Codex OAuth uses the current session ID; other Claude -> Responses
/// conversions fall back to provider ID.
#[serde(rename = "promptCacheKey", skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: 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>,
/// 累加模式应用中,该 provider 是否已写入 live config。
/// `None` 表示旧数据/未知状态,`Some(false)` 表示明确仅存在于数据库中。
#[serde(rename = "liveConfigManaged", skip_serializing_if = "Option::is_none")]
@@ -276,6 +299,12 @@ pub struct ProviderMeta {
}
impl ProviderMeta {
/// Codex OAuth FAST mode 是否启用。默认关闭,因为 `service_tier="priority"`
/// 会按更高速率消耗 ChatGPT 订阅配额,用户需显式开启以换取更低延迟。
pub fn codex_fast_mode_enabled(&self) -> bool {
self.codex_fast_mode.unwrap_or(false)
}
/// 解析指定托管认证供应商绑定的账号 ID。
///
/// 新版优先读取 authBinding,旧版继续兼容 githubAccountId。
+169
View File
@@ -443,6 +443,41 @@ pub fn sanitize_orphan_tool_results(mut body: Value) -> Value {
body
}
/// 请求前主动剥离所有 assistant 消息里的 thinking / redacted_thinking block
///
/// Copilot 的三条目标端点(`/chat/completions`、`/v1/responses`、`/v1/chat/completions`
/// 均为 OpenAI 兼容格式,不识别 Anthropic 的 thinking block。若原样转发,上游会
/// 拒绝并返回 invalid_request_error —— 届时 `thinking_rectifier` 才做反应式清理并
/// 重试。那次已经失败的请求依旧消耗一次 premium quota,所以此处提前剥离。
///
/// 与 `thinking_rectifier::rectify_anthropic_request` 的区别:
/// - 本函数只剥 thinking / redacted_thinking 两类 block,不触碰 signature,也不
/// 移除顶层 thinking 字段——那些是错误路径上的激进整流,常规路径不需要。
/// - 保持与 `merge_tool_results` / `sanitize_orphan_tool_results` 一致的"消费 body、
/// 返回新 body"签名,便于接入 forwarder 管道。
pub fn strip_thinking_blocks(mut body: Value) -> Value {
let Some(messages) = body.get_mut("messages").and_then(|m| m.as_array_mut()) else {
return body;
};
for msg in messages.iter_mut() {
if msg.get("role").and_then(|r| r.as_str()) != Some("assistant") {
continue;
}
let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) else {
continue;
};
content.retain(|block| {
!matches!(
block.get("type").and_then(|t| t.as_str()),
Some("thinking") | Some("redacted_thinking")
)
});
}
body
}
// ─── 内部辅助 ─────────────────────────────────
/// 从请求体的 `system` 字段提取文本(处理 string/array 两种格式)。
@@ -1371,4 +1406,138 @@ mod tests {
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "text");
}
// === strip_thinking_blocks 测试 ===
#[test]
fn test_strip_thinking_removes_assistant_thinking_blocks() {
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [{"type": "text", "text": "hi"}]},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "let me ponder", "signature": "sig"},
{"type": "redacted_thinking", "data": "opaque"},
{"type": "text", "text": "hello"},
{"type": "tool_use", "id": "t1", "name": "read", "input": {}}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][1]["content"].as_array().unwrap();
assert_eq!(content.len(), 2);
assert_eq!(content[0]["type"], "text");
assert_eq!(content[1]["type"], "tool_use");
}
#[test]
fn test_strip_thinking_leaves_user_messages_untouched() {
// 仅处理 assistantuser 的 thinking 块(极少见,但可能)不动
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [
{"type": "thinking", "thinking": "x"},
{"type": "text", "text": "hi"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 2);
}
#[test]
fn test_strip_thinking_handles_missing_messages() {
let body = serde_json::json!({ "model": "claude-3-5-sonnet" });
let result = strip_thinking_blocks(body.clone());
assert_eq!(result, body);
}
#[test]
fn test_strip_thinking_leaves_empty_content_array() {
// 仅含 thinking 的 assistant 消息剥完后 content 为空——保留上游自处理
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "solo"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 0);
}
#[test]
fn test_strip_thinking_preserves_signature_on_non_thinking_blocks() {
// signature 留给 thinking_rectifier 在错误路径处理,此处不动
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "tool_use", "id": "t1", "name": "x", "input": {}, "signature": "s"}
]}
]
});
let result = strip_thinking_blocks(body);
let block = &result["messages"][0]["content"][0];
assert_eq!(block["signature"], "s");
}
#[test]
fn test_strip_thinking_multiple_assistant_turns() {
let body = serde_json::json!({
"messages": [
{"role": "user", "content": [{"type": "text", "text": "q1"}]},
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "a"},
{"type": "text", "text": "r1"}
]},
{"role": "user", "content": [{"type": "text", "text": "q2"}]},
{"role": "assistant", "content": [
{"type": "redacted_thinking", "data": "x"},
{"type": "text", "text": "r2"}
]}
]
});
let result = strip_thinking_blocks(body);
let a1 = result["messages"][1]["content"].as_array().unwrap();
let a2 = result["messages"][3]["content"].as_array().unwrap();
assert_eq!(a1.len(), 1);
assert_eq!(a1[0]["text"], "r1");
assert_eq!(a2.len(), 1);
assert_eq!(a2[0]["text"], "r2");
}
#[test]
fn test_strip_thinking_ignores_string_content() {
// assistant.content 是字符串而非 block 数组 — 历史请求或极简客户端会这样
// 不应崩溃,也不应转换结构
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": "plain text response"}
]
});
let result = strip_thinking_blocks(body.clone());
assert_eq!(result, body);
}
#[test]
fn test_strip_thinking_preserves_block_order() {
let body = serde_json::json!({
"messages": [
{"role": "assistant", "content": [
{"type": "thinking", "thinking": "pre"},
{"type": "text", "text": "A"},
{"type": "tool_use", "id": "t1", "name": "x", "input": {}},
{"type": "redacted_thinking", "data": "mid"},
{"type": "text", "text": "B"}
]}
]
});
let result = strip_thinking_blocks(body);
let content = result["messages"][0]["content"].as_array().unwrap();
assert_eq!(content.len(), 3);
assert_eq!(content[0]["text"], "A");
assert_eq!(content[1]["type"], "tool_use");
assert_eq!(content[2]["text"], "B");
}
}
+1 -1
View File
@@ -111,7 +111,7 @@ impl FailoverSwitchManager {
}
if let Ok(new_menu) = crate::tray::create_tray_menu(app, app_state.inner()) {
if let Some(tray) = app.tray_by_id("main") {
if let Some(tray) = app.tray_by_id(crate::tray::TRAY_ID) {
if let Err(e) = tray.set_menu(Some(new_menu)) {
log::error!("[Failover] 更新托盘菜单失败: {e}");
}
+244 -9
View File
@@ -9,7 +9,10 @@ use super::{
failover_switch::FailoverSwitchManager,
log_codes::fwd as log_fwd,
provider_router::ProviderRouter,
providers::{get_adapter, AuthInfo, AuthStrategy, ProviderAdapter, ProviderType},
providers::{
gemini_shadow::GeminiShadowStore, get_adapter, AuthInfo, AuthStrategy, ProviderAdapter,
ProviderType,
},
thinking_budget_rectifier::{rectify_thinking_budget, should_rectify_thinking_budget},
thinking_rectifier::{
normalize_thinking_type, rectify_anthropic_request, should_rectify_thinking_signature,
@@ -43,12 +46,17 @@ pub struct RequestForwarder {
router: Arc<ProviderRouter>,
status: Arc<RwLock<ProxyStatus>>,
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
gemini_shadow: Arc<GeminiShadowStore>,
/// 故障转移切换管理器
failover_manager: Arc<FailoverSwitchManager>,
/// AppHandle,用于发射事件和更新托盘
app_handle: Option<tauri::AppHandle>,
/// 请求开始时的"当前供应商 ID"(用于判断是否需要同步 UI/托盘)
current_provider_id_at_start: String,
/// 代理会话 ID(用于 Gemini Native shadow replay
session_id: String,
/// Session ID 是否由客户端提供;生成值不能作为上游缓存身份。
session_client_provided: bool,
/// 整流器配置
rectifier_config: RectifierConfig,
/// 优化器配置
@@ -66,9 +74,12 @@ impl RequestForwarder {
non_streaming_timeout: u64,
status: Arc<RwLock<ProxyStatus>>,
current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
gemini_shadow: Arc<GeminiShadowStore>,
failover_manager: Arc<FailoverSwitchManager>,
app_handle: Option<tauri::AppHandle>,
current_provider_id_at_start: String,
session_id: String,
session_client_provided: bool,
_streaming_first_byte_timeout: u64,
_streaming_idle_timeout: u64,
rectifier_config: RectifierConfig,
@@ -79,9 +90,12 @@ impl RequestForwarder {
router,
status,
current_providers,
gemini_shadow,
failover_manager,
app_handle,
current_provider_id_at_start,
session_id,
session_client_provided,
rectifier_config,
optimizer_config,
copilot_optimizer_config,
@@ -811,6 +825,12 @@ impl RequestForwarder {
mapped_body = super::copilot_optimizer::merge_tool_results(mapped_body);
}
// 3.5. 主动剥离 thinking block — Copilot 走 OpenAI 兼容端点不识别该块
// 避免上游拒绝后由 rectifier 反应式重试(首次请求已消耗 quota)
if self.copilot_optimizer_config.strip_thinking {
mapped_body = super::copilot_optimizer::strip_thinking_blocks(mapped_body);
}
// 4. Warmup 小模型降级
if self.copilot_optimizer_config.warmup_downgrade && classification.is_warmup {
log::info!(
@@ -918,7 +938,7 @@ impl RequestForwarder {
let api_format = resolved_claude_api_format
.as_deref()
.unwrap_or_else(|| super::providers::get_claude_api_format(provider));
rewrite_claude_transform_endpoint(endpoint, api_format, is_copilot)
rewrite_claude_transform_endpoint(endpoint, api_format, is_copilot, &mapped_body)
} else {
(
endpoint.to_string(),
@@ -928,7 +948,13 @@ impl RequestForwarder {
)
};
let url = if is_full_url {
let url = if matches!(resolved_claude_api_format.as_deref(), Some("gemini_native")) {
super::gemini_url::resolve_gemini_native_url(
&base_url,
&effective_endpoint,
is_full_url,
)
} else if is_full_url {
append_query_to_full_url(&base_url, passthrough_query.as_deref())
} else {
adapter.build_url(&base_url, &effective_endpoint)
@@ -944,6 +970,9 @@ impl RequestForwarder {
mapped_body,
provider,
api_format,
self.session_client_provided
.then_some(self.session_id.as_str()),
Some(self.gemini_shadow.as_ref()),
)?
} else {
adapter.transform_request(mapped_body, provider)?
@@ -960,6 +989,7 @@ impl RequestForwarder {
// Codex OAuth 需要注入的 ChatGPT-Account-Id(在动态 token 获取期间填充)
let mut codex_oauth_account_id: Option<String> = None;
let mut should_send_codex_oauth_session_headers = false;
// 获取认证头(提前准备,用于内联替换)
let mut auth_headers = if let Some(mut auth) = adapter.extract_auth(provider) {
@@ -1041,6 +1071,7 @@ impl RequestForwarder {
match token_result {
Ok(token) => {
auth = AuthInfo::new(token, AuthStrategy::CodexOAuth);
should_send_codex_oauth_session_headers = true;
// 解析使用的 account_id(用于注入 ChatGPT-Account-Id header
codex_oauth_account_id = match account_id {
Some(id) => Some(id),
@@ -1078,6 +1109,13 @@ impl RequestForwarder {
}
}
let codex_oauth_session_headers =
if should_send_codex_oauth_session_headers && self.session_client_provided {
build_codex_oauth_session_headers(&self.session_id)
} else {
Vec::new()
};
// --- Copilot 优化器:动态 header 注入 ---
if let Some((ref classification, ref det_request_id, ref interaction_id)) =
copilot_optimization
@@ -1143,8 +1181,11 @@ impl RequestForwarder {
.ok()
.and_then(|u| u.authority().map(|a| a.to_string()));
let should_send_anthropic_headers = adapter.name() == "Claude"
&& matches!(resolved_claude_api_format.as_deref(), Some("anthropic"));
// 预计算 anthropic-beta 值(仅 Claude
let anthropic_beta_value = if adapter.name() == "Claude" {
let anthropic_beta_value = if should_send_anthropic_headers {
const CLAUDE_CODE_BETA: &str = "claude-code-20250219";
Some(if let Some(beta) = headers.get("anthropic-beta") {
if let Ok(beta_str) = beta.to_str() {
@@ -1264,8 +1305,10 @@ impl RequestForwarder {
// --- anthropic-version — 透传客户端值 ---
if key_str.eq_ignore_ascii_case("anthropic-version") {
saw_anthropic_version = true;
ordered_headers.append(key.clone(), value.clone());
if should_send_anthropic_headers {
saw_anthropic_version = true;
ordered_headers.append(key.clone(), value.clone());
}
continue;
}
@@ -1306,13 +1349,19 @@ impl RequestForwarder {
}
// anthropic-version:仅在缺失时补充默认值
if adapter.name() == "Claude" && !saw_anthropic_version {
if should_send_anthropic_headers && !saw_anthropic_version {
ordered_headers.append(
"anthropic-version",
http::HeaderValue::from_static("2023-06-01"),
);
}
// Codex OAuth 反代尽量对齐官方 Codex CLI 的会话路由信号。
// 只发送客户端提供的 session_id;生成的 UUID 每次不同,反而会破坏前缀缓存。
for (name, value) in codex_oauth_session_headers {
ordered_headers.insert(name, value);
}
// 序列化请求体
let body_bytes = serde_json::to_vec(&filtered_body)
.map_err(|e| ProxyError::Internal(format!("Failed to serialize request body: {e}")))?;
@@ -1650,6 +1699,7 @@ fn rewrite_claude_transform_endpoint(
endpoint: &str,
api_format: &str,
is_copilot: bool,
body: &Value,
) -> (String, Option<String>) {
let (path, query) = split_endpoint_and_query(endpoint);
let passthrough_query = if is_claude_messages_path(path) {
@@ -1662,6 +1712,36 @@ fn rewrite_claude_transform_endpoint(
return (endpoint.to_string(), passthrough_query);
}
if api_format == "gemini_native" {
let model =
super::providers::transform_gemini::extract_gemini_model(body).unwrap_or("unknown");
// Accept both bare ids (`gemini-2.5-pro`) and the resource-name
// form (`models/gemini-2.5-pro`) that Gemini SDKs emit. See
// `normalize_gemini_model_id` for rationale.
let model = super::gemini_url::normalize_gemini_model_id(model);
let is_stream = body
.get("stream")
.and_then(|value| value.as_bool())
.unwrap_or(false);
let target_path = if is_stream {
format!("/v1beta/models/{model}:streamGenerateContent")
} else {
format!("/v1beta/models/{model}:generateContent")
};
let rewritten_query = merge_query_params(
passthrough_query.as_deref(),
if is_stream { Some("alt=sse") } else { None },
);
let rewritten = match rewritten_query.as_deref() {
Some(query) if !query.is_empty() => format!("{target_path}?{query}"),
_ => target_path,
};
return (rewritten, rewritten_query);
}
let target_path = if is_copilot && api_format == "openai_responses" {
"/v1/responses"
} else if is_copilot {
@@ -1680,6 +1760,26 @@ fn rewrite_claude_transform_endpoint(
(rewritten, passthrough_query)
}
fn merge_query_params(base_query: Option<&str>, extra_param: Option<&str>) -> Option<String> {
let mut params: Vec<String> = base_query
.into_iter()
.flat_map(|query| query.split('&'))
.filter(|pair| !pair.is_empty())
.filter(|pair| !pair.starts_with("alt="))
.map(ToString::to_string)
.collect();
if let Some(extra_param) = extra_param {
params.push(extra_param.to_string());
}
if params.is_empty() {
None
} else {
Some(params.join("&"))
}
}
fn append_query_to_full_url(base_url: &str, query: Option<&str>) -> String {
match query {
Some(query) if !query.is_empty() => {
@@ -1693,6 +1793,28 @@ fn append_query_to_full_url(base_url: &str, query: Option<&str>) -> String {
}
}
fn build_codex_oauth_session_headers(
session_id: &str,
) -> Vec<(http::HeaderName, http::HeaderValue)> {
let session_id = session_id.trim();
if session_id.is_empty() {
return Vec::new();
}
let mut headers = Vec::new();
if let Ok(value) = http::HeaderValue::from_str(session_id) {
headers.push((http::HeaderName::from_static("session_id"), value.clone()));
headers.push((http::HeaderName::from_static("x-client-request-id"), value));
}
let window_id = format!("{session_id}:0");
if let Ok(value) = http::HeaderValue::from_str(&window_id) {
headers.push((http::HeaderName::from_static("x-codex-window-id"), value));
}
headers
}
fn should_force_identity_encoding(
endpoint: &str,
body: &Value,
@@ -1802,12 +1924,35 @@ mod tests {
assert_eq!(summary, "line1 line2...");
}
#[test]
fn codex_oauth_session_headers_match_codex_cache_identity() {
let headers = build_codex_oauth_session_headers("session-123");
let mut map = HeaderMap::new();
for (name, value) in headers {
map.insert(name, value);
}
assert_eq!(
map.get("session_id"),
Some(&HeaderValue::from_static("session-123"))
);
assert_eq!(
map.get("x-client-request-id"),
Some(&HeaderValue::from_static("session-123"))
);
assert_eq!(
map.get("x-codex-window-id"),
Some(&HeaderValue::from_static("session-123:0"))
);
}
#[test]
fn rewrite_claude_transform_endpoint_strips_beta_for_chat_completions() {
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
"/v1/messages?beta=true&foo=bar",
"openai_chat",
false,
&json!({ "model": "gpt-5.4" }),
);
assert_eq!(endpoint, "/v1/chat/completions?foo=bar");
@@ -1820,6 +1965,7 @@ mod tests {
"/claude/v1/messages?beta=true&x-id=1",
"openai_responses",
false,
&json!({ "model": "gpt-5.4" }),
);
assert_eq!(endpoint, "/v1/responses?x-id=1");
@@ -1828,8 +1974,12 @@ mod tests {
#[test]
fn rewrite_claude_transform_endpoint_uses_copilot_path() {
let (endpoint, passthrough_query) =
rewrite_claude_transform_endpoint("/v1/messages?beta=true&x-id=1", "anthropic", true);
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
"/v1/messages?beta=true&x-id=1",
"anthropic",
true,
&json!({ "model": "claude-sonnet-4-6" }),
);
assert_eq!(endpoint, "/chat/completions?x-id=1");
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
@@ -1841,12 +1991,60 @@ mod tests {
"/v1/messages?beta=true&x-id=1",
"openai_responses",
true,
&json!({ "model": "gpt-5.4" }),
);
assert_eq!(endpoint, "/v1/responses?x-id=1");
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
}
#[test]
fn rewrite_claude_transform_endpoint_maps_gemini_generate_content() {
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
"/v1/messages?beta=true&x-id=1",
"gemini_native",
false,
&json!({ "model": "gemini-2.5-pro" }),
);
assert_eq!(
endpoint,
"/v1beta/models/gemini-2.5-pro:generateContent?x-id=1"
);
assert_eq!(passthrough_query.as_deref(), Some("x-id=1"));
}
/// Regression: body.model arriving as the resource-name form
/// `models/gemini-2.5-pro` must not produce a doubled
/// `/v1beta/models/models/...` path.
#[test]
fn rewrite_claude_transform_endpoint_strips_gemini_model_resource_prefix() {
let (endpoint, _) = rewrite_claude_transform_endpoint(
"/v1/messages",
"gemini_native",
false,
&json!({ "model": "models/gemini-2.5-pro" }),
);
assert_eq!(endpoint, "/v1beta/models/gemini-2.5-pro:generateContent");
}
#[test]
fn rewrite_claude_transform_endpoint_maps_gemini_streaming() {
let (endpoint, passthrough_query) = rewrite_claude_transform_endpoint(
"/v1/messages?beta=true",
"gemini_native",
false,
&json!({ "model": "gemini-2.5-flash", "stream": true }),
);
assert_eq!(
endpoint,
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
assert_eq!(passthrough_query.as_deref(), Some("alt=sse"));
}
#[test]
fn append_query_to_full_url_preserves_existing_query_string() {
let url = append_query_to_full_url("https://relay.example/api?foo=bar", Some("x-id=1"));
@@ -1854,6 +2052,43 @@ mod tests {
assert_eq!(url, "https://relay.example/api?foo=bar&x-id=1");
}
#[test]
fn build_gemini_native_url_uses_origin_when_base_ends_with_v1beta() {
let url = crate::proxy::gemini_url::build_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta",
"/v1beta/models/gemini-2.5-pro:generateContent",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
);
}
#[test]
fn build_gemini_native_url_uses_origin_when_base_already_contains_models_prefix() {
let url = crate::proxy::gemini_url::build_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta/models",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn resolve_gemini_native_url_keeps_opaque_full_url_as_is() {
let url = crate::proxy::gemini_url::resolve_gemini_native_url(
"https://relay.example/custom/generate-content",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
}
#[test]
fn force_identity_for_stream_flag_requests() {
let headers = HeaderMap::new();
+665
View File
@@ -0,0 +1,665 @@
//! Gemini Native URL helpers.
//!
//! Normalizes legacy Gemini/OpenAI-compatible base URLs into the canonical
//! Gemini Native `models/*:generateContent` endpoints.
/// Normalize a Gemini model identifier to its bare form, stripping an
/// optional leading `models/` (and any leading `/`) so that the value can
/// be safely interpolated into a URL template like
/// `/v1beta/models/{model}:generateContent`.
///
/// Gemini SDKs and documentation commonly surface model ids as
/// `models/gemini-2.5-pro` (the resource-name form). Passing that value
/// through to the format string would otherwise yield a doubled prefix
/// like `/v1beta/models/models/gemini-2.5-pro:generateContent`, which is
/// rejected by the upstream API and turns any health check or live
/// request into a false negative.
pub fn normalize_gemini_model_id(model: &str) -> &str {
let trimmed = model.strip_prefix('/').unwrap_or(model);
trimmed.strip_prefix("models/").unwrap_or(trimmed)
}
pub fn resolve_gemini_native_url(base_url: &str, endpoint: &str, is_full_url: bool) -> String {
if !is_full_url || should_normalize_gemini_full_url(base_url) {
return build_gemini_native_url(base_url, endpoint);
}
let base_url = base_url
.split_once('#')
.map_or(base_url, |(base, _)| base)
.trim_end_matches('/');
let (base_without_query, base_query) = split_query(base_url);
let (_, endpoint_query) = split_query(endpoint);
let mut url = base_without_query.to_string();
if let Some(query) = merge_queries(base_query, endpoint_query) {
url.push('?');
url.push_str(&query);
}
url
}
pub fn build_gemini_native_url(base_url: &str, endpoint: &str) -> String {
let base_url = base_url
.split_once('#')
.map_or(base_url, |(base, _)| base)
.trim_end_matches('/');
let (base_without_query, base_query) = split_query(base_url);
let (endpoint_without_query, endpoint_query) = split_query(endpoint);
let endpoint_path = format!("/{}", endpoint_without_query.trim_start_matches('/'));
let (origin, raw_path) = split_origin_and_path(base_without_query);
let prefix_path = normalize_gemini_base_path(raw_path);
let mut url = if prefix_path.is_empty() {
format!("{origin}{endpoint_path}")
} else {
format!("{origin}{prefix_path}{endpoint_path}")
};
if let Some(query) = merge_queries(base_query, endpoint_query) {
url.push('?');
url.push_str(&query);
}
url
}
fn should_normalize_gemini_full_url(base_url: &str) -> bool {
let base_url = base_url
.split_once('#')
.map_or(base_url, |(base, _)| base)
.trim_end_matches('/');
let (base_without_query, _) = split_query(base_url);
let (origin, path) = split_origin_and_path(base_without_query);
if path.is_empty() || path == "/" {
return true;
}
let path = path.trim_end_matches('/');
let on_google_host = is_google_gemini_host(extract_host(origin));
// Unconditional layer: only paths whose grammar is *intrinsically*
// Gemini-specific — the `/models/...:generateContent` method-call
// shape and the deep OpenAI-compat endpoints (`/openai/chat/completions`,
// `/openai/responses`) that are implausibly used as a relay's fixed
// terminal path — get rewritten regardless of host.
if matches_structured_gemini_models_path(path)
|| path.ends_with("/v1beta/openai/chat/completions")
|| path.ends_with("/v1beta/openai/responses")
|| path.ends_with("/openai/chat/completions")
|| path.ends_with("/openai/responses")
|| path.ends_with("/v1/openai/chat/completions")
|| path.ends_with("/v1/openai/responses")
{
return true;
}
// All other version / resource-root suffixes — `/v1beta`, `/v1`,
// `/models`, `/openai`, and variants — could legitimately be an
// opaque relay's fixed endpoint (`https://relay.example/custom/v1beta`
// is a real deployment shape, even if uncommon outside Google's
// ecosystem). Only rewrite when the host itself is Google's Gemini
// or Vertex AI endpoint.
if on_google_host
&& (path.ends_with("/v1beta")
|| path.ends_with("/v1beta/models")
|| path.ends_with("/v1beta/openai")
|| path.ends_with("/v1")
|| path.ends_with("/v1/models")
|| path.ends_with("/models")
|| path.ends_with("/v1/openai")
|| path.ends_with("/openai"))
{
return true;
}
false
}
/// Extract the host portion of an origin like `https://host:port` or
/// `https://host`. Returns an empty string if no host can be found (e.g.
/// bare `http://`).
fn extract_host(origin: &str) -> &str {
let after_scheme = origin.split_once("://").map_or(origin, |(_, rest)| rest);
// authority may carry credentials (`user:pass@host`) and a port
// (`host:port`). Strip userinfo first, then port.
let without_userinfo = after_scheme
.rsplit_once('@')
.map_or(after_scheme, |(_, h)| h);
let without_port = without_userinfo
.split_once(':')
.map_or(without_userinfo, |(h, _)| h);
// Strip trailing `/` defensively (split_origin_and_path already handled
// it, but this helper may be reused elsewhere).
without_port.trim_end_matches('/')
}
/// Returns true when `host` is one of Google's Gemini / Vertex AI endpoints.
/// Case-insensitive. Requires exact match or a real `-aiplatform.googleapis.com`
/// subdomain suffix — not a substring match, so lookalikes like
/// `aiplatform.example.com` are rejected.
fn is_google_gemini_host(host: &str) -> bool {
if host.is_empty() {
return false;
}
let host_lower = host.to_ascii_lowercase();
host_lower == "generativelanguage.googleapis.com"
|| host_lower == "aiplatform.googleapis.com"
|| host_lower.ends_with("-aiplatform.googleapis.com")
}
fn split_query(input: &str) -> (&str, Option<&str>) {
input
.split_once('?')
.map_or((input, None), |(path, query)| (path, Some(query)))
}
fn split_origin_and_path(base_url: &str) -> (&str, &str) {
let Some(scheme_sep) = base_url.find("://") else {
return (base_url, "");
};
let authority_start = scheme_sep + 3;
let Some(path_start_rel) = base_url[authority_start..].find('/') else {
return (base_url, "");
};
let path_start = authority_start + path_start_rel;
(&base_url[..path_start], &base_url[path_start..])
}
fn normalize_gemini_base_path(path: &str) -> String {
let path = path.trim_end_matches('/');
if path.is_empty() || path == "/" {
return String::new();
}
for marker in ["/v1beta/models/", "/v1/models/", "/models/"] {
if let Some(index) = path.find(marker) {
return normalize_prefix(&path[..index]);
}
}
for suffix in [
"/v1beta/openai/chat/completions",
"/v1/openai/chat/completions",
"/openai/chat/completions",
"/v1beta/openai/responses",
"/v1/openai/responses",
"/openai/responses",
"/v1beta/openai",
"/v1/openai",
"/openai",
"/v1beta/models",
"/v1/models",
"/models",
"/v1beta",
"/v1",
] {
if path == suffix {
return String::new();
}
if let Some(prefix) = path.strip_suffix(suffix) {
return normalize_prefix(prefix);
}
}
path.to_string()
}
fn normalize_prefix(prefix: &str) -> String {
let prefix = prefix.trim_end_matches('/');
if prefix.is_empty() || prefix == "/" {
String::new()
} else {
prefix.to_string()
}
}
/// Returns true when `path` contains a `/models/` segment followed by a
/// canonical Gemini method call (`*:generateContent` or
/// `*:streamGenerateContent`). The `/models/` segment alone is not enough:
/// opaque relay routes such as `/v1/models/invoke` or `/custom/models/foo`
/// also contain `/models/` but are not Gemini-structured and must not be
/// rewritten.
fn matches_structured_gemini_models_path(path: &str) -> bool {
let mut cursor = path;
while let Some(idx) = cursor.find("/models/") {
let after = &cursor[idx + "/models/".len()..];
if after.contains(":generateContent") || after.contains(":streamGenerateContent") {
return true;
}
// Advance past this `/models/` occurrence so a later Gemini-style
// segment in the same path (unusual but cheap to handle) can still
// match.
cursor = &cursor[idx + "/models/".len()..];
}
false
}
fn merge_queries(base_query: Option<&str>, endpoint_query: Option<&str>) -> Option<String> {
let parts: Vec<&str> = [base_query, endpoint_query]
.into_iter()
.flatten()
.flat_map(|query| query.split('&'))
.filter(|part| !part.is_empty())
.collect();
if parts.is_empty() {
None
} else {
Some(parts.join("&"))
}
}
#[cfg(test)]
mod tests {
use super::{build_gemini_native_url, normalize_gemini_model_id, resolve_gemini_native_url};
#[test]
fn strips_version_root_for_official_base() {
let url = build_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta",
"/v1beta/models/gemini-2.5-pro:generateContent",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
);
}
#[test]
fn strips_openai_compat_path_for_official_base() {
let url = build_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
"/v1beta/models/gemini-2.5-pro:generateContent",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent"
);
}
#[test]
fn preserves_custom_proxy_prefix_while_stripping_openai_suffix() {
let url = build_gemini_native_url(
"https://proxy.example.com/google/v1beta/openai/chat/completions",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
);
assert_eq!(
url,
"https://proxy.example.com/google/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn strips_model_method_path_from_full_url_base() {
let url = build_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn resolves_structured_full_url_by_normalizing_to_requested_method() {
let url = resolve_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn resolves_opaque_full_url_without_appending_gemini_models_path() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/generate-content",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
}
#[test]
fn preserves_opaque_full_url_containing_models_segment() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/models/invoke",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/models/invoke?alt=sse");
}
/// Regression: a relay whose fixed path starts with `/v1/models/` is an
/// opaque route, not a Gemini-structured endpoint. The previous
/// heuristic matched any `contains("/v1/models/")` and rewrote it to
/// `/v1beta/models/{model}:generateContent`, dropping the relay's own
/// route component (`/invoke`) and sending traffic to the wrong place.
#[test]
fn preserves_opaque_full_url_with_v1_models_prefix() {
let url = resolve_gemini_native_url(
"https://relay.example/v1/models/invoke",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/v1/models/invoke?alt=sse");
}
/// Same regression, `/v1beta/models/` variant — relays may use Google's
/// path layout defensively for routing while still being opaque.
#[test]
fn preserves_opaque_full_url_with_v1beta_models_prefix() {
let url = resolve_gemini_native_url(
"https://relay.example/v1beta/models/route",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/v1beta/models/route?alt=sse");
}
/// Counter-case: a full URL that *does* carry a genuine Gemini method
/// segment (`:generateContent`) under `/v1/models/` should still be
/// recognized as structured and normalized to the requested model.
#[test]
fn normalizes_structured_v1_models_path_with_method_segment() {
let url = resolve_gemini_native_url(
"https://relay.example/v1/models/gemini-2.5-pro:generateContent",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://relay.example/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
// ------------------------------------------------------------------
// Google-host whitelist tests (generic REST suffix handling)
//
// Generic REST conventions like `/v1`, `/models`, `/openai` legitimately
// appear on opaque relays. `should_normalize_gemini_full_url` only
// treats these as structured Gemini endpoints when the host itself is
// Google's Gemini or Vertex AI endpoint.
// ------------------------------------------------------------------
/// Regression: a relay whose fixed path ends with `/v1` (a ubiquitous
/// REST convention) used to be rewritten to
/// `/v1beta/models/{model}:generateContent`, dropping the relay's own
/// `/v1` endpoint.
#[test]
fn preserves_opaque_full_url_with_v1_suffix() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/v1?alt=sse");
}
/// Companion case: bare `/models` suffix on a non-Google host is a
/// generic REST path, not a Gemini-structured endpoint.
#[test]
fn preserves_opaque_full_url_with_models_suffix() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/models",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/models?alt=sse");
}
/// Companion case: `/v1/models` — same ambiguity as `/models`, with the
/// version prefix. Must stay as-is on non-Google hosts.
#[test]
fn preserves_opaque_full_url_with_v1_models_suffix() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1/models",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/v1/models?alt=sse");
}
/// Companion case: a relay that exposes an `/openai` compatibility
/// surface without the deep `/openai/chat/completions` path. Must stay
/// as-is on non-Google hosts.
#[test]
fn preserves_opaque_full_url_with_openai_suffix_on_non_google_host() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/openai",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/openai?alt=sse");
}
/// Counter-case: `/v1` on the official Gemini host must still be
/// normalized to the full `/v1beta/models/...` endpoint — users who
/// paste `https://generativelanguage.googleapis.com/v1` as their base
/// URL expect the proxy to resolve the method path.
#[test]
fn normalizes_google_host_with_v1_suffix() {
let url = resolve_gemini_native_url(
"https://generativelanguage.googleapis.com/v1",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
/// Counter-case: `/models` on the official Gemini host is recognized
/// and normalized.
#[test]
fn normalizes_google_host_with_models_suffix() {
let url = resolve_gemini_native_url(
"https://generativelanguage.googleapis.com/models",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
/// Counter-case: Vertex AI regional endpoints live under
/// `*-aiplatform.googleapis.com`. Those should also be treated as
/// Google-host for the whitelist.
#[test]
fn normalizes_vertex_aiplatform_host_with_v1_suffix() {
let url = resolve_gemini_native_url(
"https://us-central1-aiplatform.googleapis.com/v1",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://us-central1-aiplatform.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
/// Safety: the Google-host whitelist must do an exact/suffix match, not
/// a `contains`. A lookalike host like `aiplatform.example.com` must
/// NOT be treated as Google.
#[test]
fn preserves_non_google_aiplatform_lookalike_host() {
let url = resolve_gemini_native_url(
"https://aiplatform.example.com/v1",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://aiplatform.example.com/v1?alt=sse");
}
/// Regression: `/v1beta` by itself is Google-conventional but not
/// literally impossible on other hosts. An opaque relay fronting a
/// non-Gemini service at `https://relay.example/custom/v1beta` would
/// be silently rewritten if `/v1beta` were classified as unconditional
/// structured Gemini. Require the Google-host whitelist instead.
#[test]
fn preserves_opaque_full_url_with_bare_v1beta_suffix() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1beta",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/v1beta?alt=sse");
}
/// Companion case: `/v1beta/models` (no method segment) on a non-Google
/// host stays as-is too.
#[test]
fn preserves_opaque_full_url_with_v1beta_models_suffix_no_method() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1beta/models",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(url, "https://relay.example/custom/v1beta/models?alt=sse");
}
/// Counter-case: `/v1beta` on the official Gemini host must still
/// normalize — this is the canonical base URL shape users paste from
/// AI Studio documentation.
#[test]
fn normalizes_google_host_with_v1beta_suffix() {
let url = resolve_gemini_native_url(
"https://generativelanguage.googleapis.com/v1beta",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
true,
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
/// Regression guard: in non-full-URL mode, a versioned third-party
/// relay base must have its `/v1beta` suffix **stripped** so the
/// appended standard endpoint (`/v1beta/models/{model}:method`) does
/// not produce a doubled `/v1beta/v1beta/models/...` path. Non-full
/// mode's contract is "base URL + cc-switch appends the canonical
/// Gemini endpoint" — a user who wants a relay's custom namespace
/// (e.g. `/v1/models/...`) must use full-URL mode instead.
///
/// This test pins the intentional asymmetry with
/// `preserves_opaque_full_url_with_bare_v1beta_suffix` (full-URL
/// preserves, non-full strips) so nobody "fixes" one side into
/// breaking the other.
#[test]
fn strips_versioned_relay_base_suffix_in_non_full_url_mode() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1beta",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
false,
);
assert_eq!(
url,
"https://relay.example/custom/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
/// Companion case: `/v1` base suffix also stripped in non-full-URL
/// mode regardless of host.
#[test]
fn strips_v1_relay_base_suffix_in_non_full_url_mode() {
let url = resolve_gemini_native_url(
"https://relay.example/custom/v1",
"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
false,
);
assert_eq!(
url,
"https://relay.example/custom/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
// ------------------------------------------------------------------
// Model ID normalization tests.
//
// Gemini SDKs and documentation commonly surface model identifiers as
// `models/gemini-2.5-pro` (resource-name form). If that value flows
// straight into our URL builder, the format string
// `/v1beta/models/{model}:generateContent` produces a doubled prefix
// `/v1beta/models/models/gemini-2.5-pro:generateContent`, which is
// rejected upstream. `normalize_gemini_model_id` is the single source
// of truth callers should run the model through first.
// ------------------------------------------------------------------
#[test]
fn normalize_model_id_strips_models_prefix() {
assert_eq!(
normalize_gemini_model_id("models/gemini-2.5-pro"),
"gemini-2.5-pro"
);
}
#[test]
fn normalize_model_id_leaves_bare_id_unchanged() {
assert_eq!(
normalize_gemini_model_id("gemini-2.5-pro"),
"gemini-2.5-pro"
);
}
#[test]
fn normalize_model_id_preserves_nested_slashes_after_prefix() {
// e.g. tuned model resource like `models/gemini-2.5-pro/tunedModels/xxx`
// — the caller asked for a specific tuned model resource, keep its
// identity intact after stripping only the single leading prefix.
assert_eq!(
normalize_gemini_model_id("models/tunedModels/my-tuned"),
"tunedModels/my-tuned"
);
}
#[test]
fn normalize_model_id_tolerates_leading_slash() {
assert_eq!(
normalize_gemini_model_id("/models/gemini-2.5-flash"),
"gemini-2.5-flash"
);
}
#[test]
fn normalize_model_id_preserves_empty_input() {
// Edge: caller has no model at all. Pass through so the URL error
// surfaces at the request layer rather than producing a misleading
// empty segment here.
assert_eq!(normalize_gemini_model_id(""), "");
}
}
+6
View File
@@ -57,6 +57,8 @@ pub struct RequestContext {
pub app_type: AppType,
/// Session ID(从客户端请求提取或新生成)
pub session_id: String,
/// Session ID 是否由客户端提供。生成的 UUID 不能作为上游缓存 key,否则每个请求都会换 key。
pub session_client_provided: bool,
/// 整流器配置
pub rectifier_config: RectifierConfig,
/// 优化器配置
@@ -161,6 +163,7 @@ impl RequestContext {
app_type_str,
app_type,
session_id,
session_client_provided: session_result.client_provided,
rectifier_config,
optimizer_config,
copilot_optimizer_config,
@@ -218,9 +221,12 @@ impl RequestContext {
non_streaming_timeout,
state.status.clone(),
state.current_providers.clone(),
state.gemini_shadow.clone(),
state.failover_manager.clone(),
state.app_handle.clone(),
self.current_provider_id.clone(),
self.session_id.clone(),
self.session_client_provided,
first_byte_timeout,
idle_timeout,
self.rectifier_config.clone(),
+226 -7
View File
@@ -15,8 +15,9 @@ use super::{
handler_context::RequestContext,
providers::{
get_adapter, get_claude_api_format, streaming::create_anthropic_sse_stream,
streaming_gemini::create_anthropic_sse_stream_from_gemini,
streaming_responses::create_anthropic_sse_stream_from_responses, transform,
transform_responses,
transform_gemini, transform_responses,
},
response_processor::{
create_logged_passthrough_stream, process_response, read_decoded_body,
@@ -24,6 +25,7 @@ use super::{
SseUsageCollector,
},
server::ProxyState,
sse::{strip_sse_field, take_sse_block},
types::*,
usage::parser::TokenUsage,
ProxyError,
@@ -145,19 +147,52 @@ async fn handle_claude_transform(
response: super::hyper_client::ProxyResponse,
ctx: &RequestContext,
state: &ProxyState,
_original_body: &Value,
original_body: &Value,
is_stream: bool,
api_format: &str,
) -> Result<axum::response::Response, ProxyError> {
let status = response.status();
let is_codex_oauth = ctx
.provider
.meta
.as_ref()
.and_then(|meta| meta.provider_type.as_deref())
== Some("codex_oauth");
// Codex OAuth 会把 openai_responses 响应强制升级为 SSE,即使客户端发的是 stream:false。
// should_use_claude_transform_streaming 默认会把这个组合路由到流式转换器——虽然能避免
// JSON parse 报 422,但会让非流客户端收到 text/event-stream,违反 Anthropic 非流语义。
// 这里为这个特定组合打开 override:把上游 SSE 聚合成 Anthropic JSON 回给客户端,其它
// 场景(任意上游 is_sse、非 Codex OAuth 等)仍沿用原有流式兜底。
let aggregate_codex_oauth_responses_sse =
!is_stream && is_codex_oauth && api_format == "openai_responses";
let use_streaming = if aggregate_codex_oauth_responses_sse {
false
} else {
should_use_claude_transform_streaming(
is_stream,
response.is_sse(),
api_format,
is_codex_oauth,
)
};
let tool_schema_hints = transform_gemini::extract_anthropic_tool_schema_hints(original_body);
let tool_schema_hints = (!tool_schema_hints.is_empty()).then_some(tool_schema_hints);
if is_stream {
if use_streaming {
// 根据 api_format 选择流式转换器
let stream = response.bytes_stream();
let sse_stream: Box<
dyn futures::Stream<Item = Result<Bytes, std::io::Error>> + Send + Unpin,
> = if api_format == "openai_responses" {
Box::new(Box::pin(create_anthropic_sse_stream_from_responses(stream)))
} else if api_format == "gemini_native" {
Box::new(Box::pin(create_anthropic_sse_stream_from_gemini(
stream,
Some(state.gemini_shadow.clone()),
Some(ctx.provider.id.clone()),
Some(ctx.session_id.clone()),
tool_schema_hints.clone(),
)))
} else {
Box::new(Box::pin(create_anthropic_sse_stream(stream)))
};
@@ -234,14 +269,26 @@ async fn handle_claude_transform(
let body_str = String::from_utf8_lossy(&body_bytes);
let upstream_response: Value = serde_json::from_slice(&body_bytes).map_err(|e| {
log::error!("[Claude] 解析上游响应失败: {e}, body: {body_str}");
ProxyError::TransformError(format!("Failed to parse upstream response: {e}"))
})?;
let upstream_response: Value = if aggregate_codex_oauth_responses_sse {
responses_sse_to_response_value(&body_str)?
} else {
serde_json::from_slice(&body_bytes).map_err(|e| {
log::error!("[Claude] 解析上游响应失败: {e}, body: {body_str}");
ProxyError::TransformError(format!("Failed to parse upstream response: {e}"))
})?
};
// 根据 api_format 选择非流式转换器
let anthropic_response = if api_format == "openai_responses" {
transform_responses::responses_to_anthropic(upstream_response)
} else if api_format == "gemini_native" {
transform_gemini::gemini_to_anthropic_with_shadow_and_hints(
upstream_response,
Some(state.gemini_shadow.as_ref()),
Some(&ctx.provider.id),
Some(&ctx.session_id),
tool_schema_hints.as_ref(),
)
} else {
transform::openai_to_anthropic(upstream_response)
}
@@ -542,6 +589,87 @@ pub async fn handle_gemini(
process_response(response, &ctx, &state, &GEMINI_PARSER_CONFIG).await
}
fn should_use_claude_transform_streaming(
requested_streaming: bool,
upstream_is_sse: bool,
api_format: &str,
is_codex_oauth: bool,
) -> bool {
requested_streaming || upstream_is_sse || (is_codex_oauth && api_format == "openai_responses")
}
/// 把 OpenAI Responses SSE 流聚合成一个完整的 Responses JSON 对象,供下游转成 Anthropic
/// 非流响应。仅在 Codex OAuth 把 `stream:false` 强制升级为 SSE 的场景下调用。
///
/// 复用 `proxy::sse` 的 `take_sse_block`/`strip_sse_field``take_sse_block` 同时支持
/// `\n\n` 与 `\r\n\r\n` 两种分隔符,`strip_sse_field` 兼容带/不带空格的字段写法。
fn responses_sse_to_response_value(body: &str) -> Result<Value, ProxyError> {
let mut buffer = body.to_string();
let mut completed_response: Option<Value> = None;
let mut output_items = Vec::new();
while let Some(block) = take_sse_block(&mut buffer) {
let mut event_name = "";
let mut data_lines: Vec<&str> = Vec::new();
for line in block.lines() {
if let Some(evt) = strip_sse_field(line, "event") {
event_name = evt.trim();
} else if let Some(d) = strip_sse_field(line, "data") {
data_lines.push(d);
}
}
if data_lines.is_empty() {
continue;
}
let data_str = data_lines.join("\n");
if data_str.trim() == "[DONE]" {
continue;
}
let data: Value = serde_json::from_str(&data_str).map_err(|e| {
ProxyError::TransformError(format!("Failed to parse upstream SSE event: {e}"))
})?;
match event_name {
"response.output_item.done" => {
if let Some(item) = data.get("item") {
output_items.push(item.clone());
}
}
"response.completed" => {
completed_response = Some(data.get("response").cloned().unwrap_or(data));
}
"response.failed" => {
let message = data
.pointer("/response/error/message")
.and_then(|v| v.as_str())
.unwrap_or("response.failed event received");
return Err(ProxyError::TransformError(message.to_string()));
}
_ => {}
}
}
let mut response = completed_response.ok_or_else(|| {
ProxyError::TransformError("No response.completed event in upstream SSE".to_string())
})?;
if !output_items.is_empty() {
if let Some(obj) = response.as_object_mut() {
obj.insert("output".to_string(), Value::Array(output_items));
} else {
return Err(ProxyError::TransformError(
"response.completed payload is not an object".to_string(),
));
}
}
Ok(response)
}
// ============================================================================
// 使用量记录(保留用于 Claude 转换逻辑)
// ============================================================================
@@ -622,3 +750,94 @@ async fn log_usage(
log::warn!("[USG-001] 记录使用量失败: {e}");
}
}
#[cfg(test)]
mod tests {
use super::{responses_sse_to_response_value, should_use_claude_transform_streaming};
use crate::proxy::ProxyError;
#[test]
fn codex_oauth_responses_force_streaming_even_if_client_sent_false() {
assert!(should_use_claude_transform_streaming(
false,
false,
"openai_responses",
true,
));
}
#[test]
fn upstream_sse_response_always_uses_streaming_path() {
assert!(should_use_claude_transform_streaming(
false,
true,
"openai_chat",
false,
));
}
#[test]
fn non_streaming_response_stays_non_streaming_for_regular_openai_responses() {
assert!(!should_use_claude_transform_streaming(
false,
false,
"openai_responses",
false,
));
}
#[test]
fn responses_sse_to_response_value_collects_output_items() {
let sse = r#"event: response.output_item.done
data: {"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]}}
event: response.completed
data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","model":"gpt-5.4","output":[],"usage":{"input_tokens":10,"output_tokens":2}}}
"#;
let response = responses_sse_to_response_value(sse).unwrap();
assert_eq!(response["id"], "resp_1");
assert_eq!(response["output"][0]["type"], "message");
assert_eq!(response["output"][0]["content"][0]["text"], "hello");
}
#[test]
fn responses_sse_to_response_value_handles_crlf_delimiters() {
// 真实 HTTP SSE 按规范使用 \r\n\r\n 分隔事件;take_sse_block 必须同时处理两种分隔符,
// 否则此路径在任何标准上游(含 Codex OAuth HTTPS 后端)下都会 TransformError。
let sse = "event: response.output_item.done\r\n\
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"hi\"}]}}\r\n\
\r\n\
event: response.completed\r\n\
data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_crlf\",\"status\":\"completed\",\"model\":\"gpt-5.4\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":1}}}\r\n\
\r\n";
let response = responses_sse_to_response_value(sse).unwrap();
assert_eq!(response["id"], "resp_crlf");
assert_eq!(response["output"][0]["type"], "message");
assert_eq!(response["output"][0]["content"][0]["text"], "hi");
}
#[test]
fn responses_sse_to_response_value_returns_err_on_response_failed() {
let sse = "event: response.failed\n\
data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"upstream blew up\"}}}\n\n";
let err = responses_sse_to_response_value(sse).unwrap_err();
match err {
ProxyError::TransformError(msg) => assert!(msg.contains("upstream blew up")),
other => panic!("expected TransformError, got {other:?}"),
}
}
#[test]
fn responses_sse_to_response_value_errors_when_no_completed_event() {
let sse = "event: response.output_item.done\n\
data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\"}}\n\n";
assert!(responses_sse_to_response_value(sse).is_err());
}
}
+1
View File
@@ -10,6 +10,7 @@ pub mod error;
pub mod error_mapper;
pub(crate) mod failover_switch;
mod forwarder;
pub mod gemini_url;
pub mod handler_config;
pub mod handler_context;
mod handlers;
+16 -107
View File
@@ -11,7 +11,6 @@ pub struct ModelMapping {
pub sonnet_model: Option<String>,
pub opus_model: Option<String>,
pub default_model: Option<String>,
pub reasoning_model: Option<String>,
}
impl ModelMapping {
@@ -40,11 +39,6 @@ impl ModelMapping {
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
reasoning_model: env
.and_then(|e| e.get("ANTHROPIC_REASONING_MODEL"))
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(String::from),
}
}
@@ -54,21 +48,13 @@ impl ModelMapping {
|| self.sonnet_model.is_some()
|| self.opus_model.is_some()
|| self.default_model.is_some()
|| self.reasoning_model.is_some()
}
/// 根据原始模型名称获取映射后的模型
pub fn map_model(&self, original_model: &str, has_thinking: bool) -> String {
pub fn map_model(&self, original_model: &str) -> String {
let model_lower = original_model.to_lowercase();
// 1. thinking 模式优先使用推理模型
if has_thinking {
if let Some(ref m) = self.reasoning_model {
return m.clone();
}
}
// 2. 按模型类型匹配
// 1. 按模型类型匹配
if model_lower.contains("haiku") {
if let Some(ref m) = self.haiku_model {
return m.clone();
@@ -85,35 +71,16 @@ impl ModelMapping {
}
}
// 3. 默认模型
// 2. 默认模型
if let Some(ref m) = self.default_model {
return m.clone();
}
// 4. 无映射,保持原样
// 3. 无映射,保持原样
original_model.to_string()
}
}
/// 检测请求是否启用了 thinking 模式
pub fn has_thinking_enabled(body: &Value) -> bool {
match body
.get("thinking")
.and_then(|v| v.as_object())
.and_then(|o| o.get("type"))
.and_then(|t| t.as_str())
{
Some("enabled") | Some("adaptive") => true,
Some("disabled") | None => false,
Some(other) => {
log::warn!(
"[ModelMapper] 未知 thinking.type='{other}',按 disabled 处理以避免误路由 reasoning 模型"
);
false
}
}
}
/// 对请求体应用模型映射
///
/// 返回 (映射后的请求体, 原始模型名, 映射后模型名)
@@ -133,8 +100,7 @@ pub fn apply_model_mapping(
let original_model = body.get("model").and_then(|m| m.as_str()).map(String::from);
if let Some(ref original) = original_model {
let has_thinking = has_thinking_enabled(&body);
let mapped = mapping.map_model(original, has_thinking);
let mapped = mapping.map_model(original);
if mapped != *original {
log::debug!("[ModelMapper] 模型映射: {original} → {mapped}");
@@ -160,8 +126,7 @@ mod tests {
"ANTHROPIC_MODEL": "default-model",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-mapped",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-mapped",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped",
"ANTHROPIC_REASONING_MODEL": "reasoning-model"
"ANTHROPIC_DEFAULT_OPUS_MODEL": "opus-mapped"
}
}),
website_url: None,
@@ -193,27 +158,6 @@ mod tests {
}
}
fn create_provider_with_reasoning_only() -> Provider {
Provider {
id: "test".to_string(),
name: "Test".to_string(),
settings_config: json!({
"env": {
"ANTHROPIC_REASONING_MODEL": "reasoning-only-model"
}
}),
website_url: None,
category: None,
created_at: None,
sort_index: None,
notes: None,
meta: None,
icon: None,
icon_color: None,
in_failover_queue: false,
}
}
#[test]
fn test_sonnet_mapping() {
let provider = create_provider_with_mapping();
@@ -243,40 +187,29 @@ mod tests {
}
#[test]
fn test_thinking_mode() {
fn test_thinking_does_not_affect_model_mapping() {
// Issue #2081: thinking 参数不应影响模型映射
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "enabled"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "reasoning-model");
assert_eq!(mapped, Some("reasoning-model".to_string()));
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
}
#[test]
fn test_reasoning_only_mapping_in_thinking_mode() {
let provider = create_provider_with_reasoning_only();
fn test_thinking_adaptive_does_not_affect_model_mapping() {
// Issue #2081: adaptive thinking 也不应影响模型映射
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "enabled"}
"thinking": {"type": "adaptive"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "reasoning-only-model");
assert_eq!(mapped, Some("reasoning-only-model".to_string()));
}
#[test]
fn test_reasoning_only_mapping_does_not_affect_non_thinking() {
let provider = create_provider_with_reasoning_only();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "disabled"}
});
let (result, original, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "claude-sonnet-4-5");
assert_eq!(original, Some("claude-sonnet-4-5".to_string()));
assert!(mapped.is_none());
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
}
#[test]
@@ -310,30 +243,6 @@ mod tests {
assert!(mapped.is_none());
}
#[test]
fn test_thinking_adaptive() {
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "adaptive"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "reasoning-model");
assert_eq!(mapped, Some("reasoning-model".to_string()));
}
#[test]
fn test_thinking_unknown_type() {
let provider = create_provider_with_mapping();
let body = json!({
"model": "claude-sonnet-4-5",
"thinking": {"type": "some_future_type"}
});
let (result, _, mapped) = apply_model_mapping(body, &provider);
assert_eq!(result["model"], "sonnet-mapped");
assert_eq!(mapped, Some("sonnet-mapped".to_string()));
}
#[test]
fn test_case_insensitive() {
let provider = create_provider_with_mapping();
+518 -29
View File
@@ -6,6 +6,7 @@
//! - **anthropic** (默认): Anthropic Messages API 格式,直接透传
//! - **openai_chat**: OpenAI Chat Completions 格式,需要 Anthropic ↔ OpenAI 转换
//! - **openai_responses**: OpenAI Responses API 格式,需要 Anthropic ↔ Responses 转换
//! - **gemini_native**: Google Gemini Native generateContent 格式,需要 Anthropic ↔ Gemini 转换
//!
//! ## 认证模式
//! - **Claude**: Anthropic 官方 API (x-api-key + anthropic-version)
@@ -35,6 +36,7 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
return match api_format {
"openai_chat" => "openai_chat",
"openai_responses" => "openai_responses",
"gemini_native" => "gemini_native",
_ => "anthropic",
};
}
@@ -49,6 +51,7 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
return match api_format {
"openai_chat" => "openai_chat",
"openai_responses" => "openai_responses",
"gemini_native" => "gemini_native",
_ => "anthropic",
};
}
@@ -73,14 +76,21 @@ pub fn get_claude_api_format(provider: &Provider) -> &'static str {
}
pub fn claude_api_format_needs_transform(api_format: &str) -> bool {
matches!(api_format, "openai_chat" | "openai_responses")
matches!(
api_format,
"openai_chat" | "openai_responses" | "gemini_native"
)
}
pub fn transform_claude_request_for_api_format(
body: serde_json::Value,
provider: &Provider,
api_format: &str,
session_id: Option<&str>,
shadow_store: Option<&super::gemini_shadow::GeminiShadowStore>,
) -> Result<serde_json::Value, ProxyError> {
let is_codex_oauth = provider.is_codex_oauth();
// Copilot 场景:优先从 metadata.user_id 提取 session ID 作为 cache key
// 格式: "uuid_sessionId" → 提取 "_" 后面的部分作为 session 标识
// 同一会话的请求共享 cache key,提升 Copilot 缓存命中率
@@ -110,35 +120,59 @@ pub fn transform_claude_request_for_api_format(
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
})
} else if is_codex_oauth {
session_id
.map(str::trim)
.filter(|s| !s.is_empty())
.map(ToString::to_string)
} else {
None
};
let cache_key = session_cache_key
.as_deref()
.or_else(|| {
provider
.meta
.as_ref()
.and_then(|m| m.prompt_cache_key.as_deref())
})
.unwrap_or(&provider.id);
let explicit_cache_key = provider
.meta
.as_ref()
.and_then(|m| m.prompt_cache_key.as_deref());
let cache_key = if is_codex_oauth {
explicit_cache_key
.or(session_cache_key.as_deref())
.unwrap_or(&provider.id)
} else {
session_cache_key
.as_deref()
.or(explicit_cache_key)
.unwrap_or(&provider.id)
};
match api_format {
"openai_responses" => {
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要在请求体里强制 store: false
// + include: ["reasoning.encrypted_content"],由 transform 层统一处理。
let is_codex_oauth = provider
.meta
.as_ref()
.and_then(|m| m.provider_type.as_deref())
== Some("codex_oauth");
let codex_fast_mode = provider.codex_fast_mode_enabled();
super::transform_responses::anthropic_to_responses(
body,
Some(cache_key),
is_codex_oauth,
codex_fast_mode,
)
}
"openai_chat" => super::transform::anthropic_to_openai(body),
"openai_chat" => {
let mut result = super::transform::anthropic_to_openai(body)?;
// Inject prompt_cache_key only if explicitly configured in meta
if let Some(key) = provider
.meta
.as_ref()
.and_then(|m| m.prompt_cache_key.as_deref())
{
result["prompt_cache_key"] = serde_json::json!(key);
}
Ok(result)
}
"gemini_native" => super::transform_gemini::anthropic_to_gemini_with_shadow(
body,
shadow_store,
Some(&provider.id),
session_id,
),
_ => Ok(body),
}
}
@@ -160,6 +194,16 @@ impl ClaudeAdapter {
/// - ClaudeAuth: auth_mode 为 bearer_only
/// - Claude: 默认 Anthropic 官方
pub fn provider_type(&self, provider: &Provider) -> ProviderType {
// 检测 Gemini Native 格式
if self.get_api_format(provider) == "gemini_native" {
return match self.extract_key(provider) {
Some(key) if key.starts_with("ya29.") || key.starts_with('{') => {
ProviderType::GeminiCli
}
_ => ProviderType::Gemini,
};
}
// 检测 Codex OAuth (ChatGPT Plus/Pro)
if self.is_codex_oauth(provider) {
return ProviderType::CodexOAuth;
@@ -262,6 +306,7 @@ impl ClaudeAdapter {
if let Some(key) = env
.get("ANTHROPIC_AUTH_TOKEN")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
log::debug!("[Claude] 使用 ANTHROPIC_AUTH_TOKEN");
@@ -270,6 +315,7 @@ impl ClaudeAdapter {
if let Some(key) = env
.get("ANTHROPIC_API_KEY")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
log::debug!("[Claude] 使用 ANTHROPIC_API_KEY");
@@ -279,6 +325,7 @@ impl ClaudeAdapter {
if let Some(key) = env
.get("OPENROUTER_API_KEY")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
log::debug!("[Claude] 使用 OPENROUTER_API_KEY");
@@ -288,6 +335,7 @@ impl ClaudeAdapter {
if let Some(key) = env
.get("OPENAI_API_KEY")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
log::debug!("[Claude] 使用 OPENAI_API_KEY");
@@ -301,6 +349,7 @@ impl ClaudeAdapter {
.get("apiKey")
.or_else(|| provider.settings_config.get("api_key"))
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
log::debug!("[Claude] 使用 apiKey/api_key");
@@ -388,14 +437,43 @@ impl ProviderAdapter for ClaudeAdapter {
));
}
let strategy = match provider_type {
ProviderType::OpenRouter => AuthStrategy::Bearer,
ProviderType::ClaudeAuth => AuthStrategy::ClaudeAuth,
_ => AuthStrategy::Anthropic,
};
let key = self.extract_key(provider)?;
self.extract_key(provider)
.map(|key| AuthInfo::new(key, strategy))
match provider_type {
ProviderType::GeminiCli => {
// Parse stored OAuth JSON and only attach access_token when
// it's actually usable. `parse_oauth_credentials` accepts
// refresh-token-only JSON (which is legitimate before the
// first refresh) and also surfaces `{"access_token": "", ...}`
// for expired credentials. In both cases we would otherwise
// send `Authorization: Bearer ` to upstream and get a 401.
//
// CC Switch does not currently exchange the refresh_token for
// a fresh access_token. Until that path exists, degrade to
// plain GoogleOAuth strategy (which still sends the raw key
// as a fallback) and log loudly so users know to refresh
// their `~/.gemini/oauth_creds.json`.
match super::gemini::GeminiAdapter::new().parse_oauth_credentials(&key) {
Some(creds) if !creds.access_token.is_empty() => {
Some(AuthInfo::with_access_token(key, creds.access_token))
}
Some(_) => {
log::warn!(
"[Gemini OAuth] access_token missing or empty for provider `{}`; \
bearer auth will likely fail with 401. Refresh \
~/.gemini/oauth_creds.json via the gemini CLI to obtain a new token.",
provider.id
);
Some(AuthInfo::new(key, AuthStrategy::GoogleOAuth))
}
None => Some(AuthInfo::new(key, AuthStrategy::GoogleOAuth)),
}
}
ProviderType::Gemini => Some(AuthInfo::new(key, AuthStrategy::Google)),
ProviderType::OpenRouter => Some(AuthInfo::new(key, AuthStrategy::Bearer)),
ProviderType::ClaudeAuth => Some(AuthInfo::new(key, AuthStrategy::ClaudeAuth)),
_ => Some(AuthInfo::new(key, AuthStrategy::Anthropic)),
}
}
fn build_url(&self, base_url: &str, endpoint: &str) -> String {
@@ -437,6 +515,23 @@ impl ProviderAdapter for ClaudeAdapter {
HeaderValue::from_str(&bearer).unwrap(),
)]
}
AuthStrategy::Google => vec![(
HeaderName::from_static("x-goog-api-key"),
HeaderValue::from_str(&auth.api_key).unwrap(),
)],
AuthStrategy::GoogleOAuth => {
let token = auth.access_token.as_ref().unwrap_or(&auth.api_key);
vec![
(
HeaderName::from_static("authorization"),
HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
),
(
HeaderName::from_static("x-goog-api-client"),
HeaderValue::from_static("GeminiCLI/1.0"),
),
]
}
AuthStrategy::CodexOAuth => {
// 注意:bearer token 由 forwarder 动态注入到 auth.api_key
// ChatGPT-Account-Id 由 forwarder 注入额外 header
@@ -507,7 +602,6 @@ impl ProviderAdapter for ClaudeAdapter {
),
]
}
_ => vec![],
}
}
@@ -528,7 +622,7 @@ impl ProviderAdapter for ClaudeAdapter {
// - "openai_responses": 需要 Anthropic ↔ OpenAI Responses API 格式转换
matches!(
self.get_api_format(provider),
"openai_chat" | "openai_responses"
"openai_chat" | "openai_responses" | "gemini_native"
)
}
@@ -537,7 +631,13 @@ impl ProviderAdapter for ClaudeAdapter {
body: serde_json::Value,
provider: &Provider,
) -> Result<serde_json::Value, ProxyError> {
transform_claude_request_for_api_format(body, provider, self.get_api_format(provider))
transform_claude_request_for_api_format(
body,
provider,
self.get_api_format(provider),
None,
None,
)
}
fn transform_response(&self, body: serde_json::Value) -> Result<serde_json::Value, ProxyError> {
@@ -546,7 +646,9 @@ impl ProviderAdapter for ClaudeAdapter {
// config, so we can't check api_format here. Instead we rely on the fact that
// Responses API always returns "output" while Chat Completions returns "choices".
// This is safe because the two formats are structurally disjoint.
if body.get("output").is_some() {
if body.get("candidates").is_some() || body.get("promptFeedback").is_some() {
super::transform_gemini::gemini_to_anthropic(body)
} else if body.get("output").is_some() {
super::transform_responses::responses_to_anthropic(body)
} else {
super::transform::openai_to_anthropic(body)
@@ -684,6 +786,146 @@ mod tests {
assert_eq!(auth.strategy, AuthStrategy::ClaudeAuth);
}
/// Regression: a Gemini OAuth credential JSON that carries only a
/// refresh_token (no active access_token) must not be surfaced as an
/// `AuthInfo` whose bearer would be empty. Without the guard, downstream
/// header injection produces `Authorization: Bearer ` and a deterministic
/// 401 from upstream.
#[test]
fn test_extract_auth_gemini_cli_refresh_only_json_does_not_expose_empty_bearer() {
let adapter = ClaudeAdapter::new();
let refresh_only_json =
r#"{"refresh_token":"rt-abc","client_id":"cid","client_secret":"cs"}"#;
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": refresh_only_json
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
let auth = adapter.extract_auth(&provider).unwrap();
// access_token must not be surfaced as `Some("")` — the OAuth header
// builder uses `access_token.as_ref().unwrap_or(&api_key)`, so a
// `Some("")` would win over the raw key and emit `Bearer `.
assert!(
auth.access_token.as_deref().is_none_or(|t| !t.is_empty()),
"empty access_token leaked into AuthInfo"
);
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
}
/// Companion case: a JSON credential with an empty-string `access_token`
/// field (the shape an expired credential can take after partial writes)
/// must degrade the same way.
#[test]
fn test_extract_auth_gemini_cli_empty_access_token_degrades_to_raw_key() {
let adapter = ClaudeAdapter::new();
let expired_json = r#"{"access_token":"","refresh_token":"rt-abc","client_id":"cid","client_secret":"cs"}"#;
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": expired_json
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
let auth = adapter.extract_auth(&provider).unwrap();
assert!(
auth.access_token.as_deref().is_none_or(|t| !t.is_empty()),
"empty access_token leaked into AuthInfo"
);
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
}
/// Counter-case: a well-formed JSON credential with a non-empty
/// access_token must still flow through the OAuth path unchanged.
#[test]
fn test_extract_auth_gemini_cli_valid_json_keeps_access_token() {
let adapter = ClaudeAdapter::new();
let valid_json = r#"{"access_token":"ya29.valid","refresh_token":"rt"}"#;
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": valid_json
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
let auth = adapter.extract_auth(&provider).unwrap();
assert_eq!(auth.access_token.as_deref(), Some("ya29.valid"));
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
}
/// 回归:从 oauth_creds.json 复制时常带前导换行/空格。未 trim 时
/// `starts_with('{')` 会落空,导致误分类为 `ProviderType::Gemini`,再
/// 以 raw JSON 当 `x-goog-api-key` 发出去触发 401。trim 应在 provider
/// 类型判定和 OAuth 解析前统一生效。
#[test]
fn test_extract_auth_gemini_cli_json_with_leading_whitespace_classifies_correctly() {
let adapter = ClaudeAdapter::new();
let valid_json = r#"{"access_token":"ya29.valid","refresh_token":"rt"}"#;
let key_with_whitespace = format!("\n {valid_json}\n");
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": key_with_whitespace
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
assert_eq!(adapter.provider_type(&provider), ProviderType::GeminiCli);
let auth = adapter.extract_auth(&provider).unwrap();
assert_eq!(auth.access_token.as_deref(), Some("ya29.valid"));
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
}
/// 回归:裸 `ya29.` access_token 若带前导换行,也应被 trim 后识别为
/// Gemini CLI OAuth,避免前导空白把 `starts_with("ya29.")` 检查顶穿。
#[test]
fn test_extract_auth_gemini_cli_access_token_with_leading_newline_classifies_correctly() {
let adapter = ClaudeAdapter::new();
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": "\nya29.raw-token-value\n"
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
assert_eq!(adapter.provider_type(&provider), ProviderType::GeminiCli);
let auth = adapter.extract_auth(&provider).unwrap();
assert_eq!(auth.access_token.as_deref(), Some("ya29.raw-token-value"));
assert_eq!(auth.strategy, AuthStrategy::GoogleOAuth);
}
#[test]
fn test_provider_type_detection() {
let adapter = ClaudeAdapter::new();
@@ -850,6 +1092,24 @@ mod tests {
);
assert!(adapter.needs_transform(&openai_responses_provider));
let gemini_native_provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": "test-key"
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
assert!(adapter.needs_transform(&gemini_native_provider));
assert_eq!(
adapter.provider_type(&gemini_native_provider),
ProviderType::Gemini
);
// meta takes precedence over legacy settings_config fields
let meta_precedence_over_settings = create_provider_with_meta(
json!({
@@ -957,11 +1217,240 @@ mod tests {
"max_tokens": 128
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "openai_responses").unwrap();
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
None,
None,
)
.unwrap();
assert_eq!(transformed["model"], "gpt-5.4");
assert!(transformed.get("input").is_some());
assert!(transformed.get("max_output_tokens").is_some());
}
#[test]
fn test_transform_claude_request_for_codex_oauth_uses_session_cache_key() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
Some("session-123"),
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], "session-123");
}
#[test]
fn test_transform_claude_request_for_codex_oauth_without_session_falls_back_to_provider_id() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
None,
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], provider.id);
}
#[test]
fn test_transform_claude_request_for_codex_oauth_keeps_explicit_cache_key() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
api_format: Some("openai_responses".to_string()),
provider_type: Some("codex_oauth".to_string()),
prompt_cache_key: Some("explicit-cache-key".to_string()),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
Some("session-123"),
None,
)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], "explicit-cache-key");
}
#[test]
fn test_transform_claude_request_for_api_format_codex_oauth_fast_mode_off() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://chatgpt.com/backend-api/codex"
}
}),
ProviderMeta {
provider_type: Some("codex_oauth".to_string()),
codex_fast_mode: Some(false),
..ProviderMeta::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 128
});
let transformed = transform_claude_request_for_api_format(
body,
&provider,
"openai_responses",
None,
None,
)
.unwrap();
assert_eq!(transformed["store"], json!(false));
assert!(transformed.get("service_tier").is_none());
assert_eq!(
transformed["include"],
json!(["reasoning.encrypted_content"])
);
}
#[test]
fn test_transform_claude_request_for_api_format_gemini_native() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://generativelanguage.googleapis.com",
"ANTHROPIC_API_KEY": "test-key"
}
}),
ProviderMeta {
api_format: Some("gemini_native".to_string()),
..Default::default()
},
);
let body = json!({
"model": "gemini-2.5-pro",
"system": "You are helpful.",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 64
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "gemini_native", None, None)
.unwrap();
assert!(transformed.get("contents").is_some());
assert_eq!(
transformed["systemInstruction"]["parts"][0]["text"],
"You are helpful."
);
assert_eq!(transformed["generationConfig"]["maxOutputTokens"], 64);
}
#[test]
fn test_transform_claude_request_for_api_format_openai_chat_skips_prompt_cache_key_by_default()
{
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://api.example.com",
"ANTHROPIC_API_KEY": "test-key"
}
}),
ProviderMeta {
api_format: Some("openai_chat".to_string()),
..Default::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 64
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
.unwrap();
assert!(transformed.get("prompt_cache_key").is_none());
}
#[test]
fn test_transform_claude_request_for_api_format_openai_chat_keeps_explicit_prompt_cache_key() {
let provider = create_provider_with_meta(
json!({
"env": {
"ANTHROPIC_BASE_URL": "https://api.example.com",
"ANTHROPIC_API_KEY": "test-key"
}
}),
ProviderMeta {
api_format: Some("openai_chat".to_string()),
prompt_cache_key: Some("claude-cache-route".to_string()),
..Default::default()
},
);
let body = json!({
"model": "gpt-5.4",
"messages": [{ "role": "user", "content": "hello" }],
"max_tokens": 64
});
let transformed =
transform_claude_request_for_api_format(body, &provider, "openai_chat", None, None)
.unwrap();
assert_eq!(transformed["prompt_cache_key"], "claude-cache-route");
}
}
@@ -203,6 +203,7 @@ impl From<&CodexAccountData> for GitHubAccount {
.unwrap_or_else(|| format!("ChatGPT ({})", &data.account_id)),
avatar_url: None,
authenticated_at: data.authenticated_at,
github_domain: "github.com".to_string(),
}
}
}
+328 -54
View File
@@ -24,26 +24,114 @@ use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{Mutex, RwLock};
/// GitHub OAuth 客户端 IDVS Code 使用的 ID
/// GitHub OAuth 客户端 IDVS Code- 用于 github.com
const GITHUB_CLIENT_ID: &str = "Iv1.b507a08c87ecfe98";
/// GitHub OAuth 客户端 ID(与 OpenCode 相同)- 在所有 GHES Copilot 实例上预注册
const GITHUB_CLIENT_ID_GHES: &str = "Ov23li8tweQw6odWQebz";
/// 默认 GitHub 域名
const DEFAULT_GITHUB_DOMAIN: &str = "github.com";
/// 根据域名选择 OAuth 客户端 ID
fn github_client_id(domain: &str) -> &'static str {
if domain == DEFAULT_GITHUB_DOMAIN {
GITHUB_CLIENT_ID
} else {
GITHUB_CLIENT_ID_GHES
}
}
fn default_github_domain() -> String {
DEFAULT_GITHUB_DOMAIN.to_string()
}
/// GitHub 设备码 URL
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
fn github_device_code_url(domain: &str) -> String {
format!("https://{domain}/login/device/code")
}
/// GitHub OAuth Token URL
const GITHUB_OAUTH_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
fn github_oauth_token_url(domain: &str) -> String {
format!("https://{domain}/login/oauth/access_token")
}
/// GitHub API 基础 URLgithub.com 用 api.github.comGHES 用 {domain}/api/v3
fn github_api_base(domain: &str) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
"https://api.github.com".to_string()
} else {
format!("https://{domain}/api/v3")
}
}
/// Copilot Token URL
const COPILOT_TOKEN_URL: &str = "https://api.github.com/copilot_internal/v2/token";
fn copilot_token_url(domain: &str) -> String {
format!("{}/copilot_internal/v2/token", github_api_base(domain))
}
/// GitHub User API URL
const GITHUB_USER_URL: &str = "https://api.github.com/user";
fn github_user_url(domain: &str) -> String {
format!("{}/user", github_api_base(domain))
}
/// Copilot 使用量 API URL
fn copilot_usage_url(domain: &str) -> String {
format!("{}/copilot_internal/user", github_api_base(domain))
}
/// Copilot API 基础地址(github.com 用 api.githubcopilot.comGHES 用 copilot-api.{domain}
fn copilot_api_base(domain: &str) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
"https://api.githubcopilot.com".to_string()
} else {
format!("https://copilot-api.{domain}")
}
}
/// Token 刷新提前量(秒)
const TOKEN_REFRESH_BUFFER_SECONDS: i64 = 60;
/// Copilot API 端点
const COPILOT_MODELS_URL: &str = "https://api.githubcopilot.com/models";
/// 判断是否为 GitHub Enterprise Server(非 github.com
fn is_ghes(domain: &str) -> bool {
domain != DEFAULT_GITHUB_DOMAIN
}
/// 归一化 GitHub 域名(SSOT):
/// - 小写化
/// - 剥离协议(https:// http://
/// - 剥离尾斜杠、path、query、fragment
/// - 拒绝包含 userinfo@)的输入
/// - 保留端口号(如有)
fn normalize_github_domain(raw: &str) -> Result<String, CopilotAuthError> {
let s = raw.trim();
// 剥离协议
let s = s
.strip_prefix("https://")
.or_else(|| s.strip_prefix("http://"))
.unwrap_or(s);
// 取 host 部分(到第一个 / 或 ? 或 #)
let host = s.split(&['/', '?', '#'][..]).next().unwrap_or(s);
// 拒绝 userinfo
if host.contains('@') {
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
}
let normalized = host.to_lowercase();
if normalized.is_empty() {
return Err(CopilotAuthError::InvalidDomain(raw.to_string()));
}
Ok(normalized)
}
/// 生成复合账号 ID,确保不同 GHES 实例的 user ID 不会冲突。
/// github.com 账号保持原格式(向后兼容),GHES 账号使用 `domain:user_id` 格式。
fn composite_account_id(domain: &str, user_id: u64) -> String {
if domain == DEFAULT_GITHUB_DOMAIN {
user_id.to_string()
} else {
format!("{}:{}", domain, user_id)
}
}
/// Copilot API Header 常量
pub const COPILOT_EDITOR_VERSION: &str = "vscode/1.110.1";
@@ -52,12 +140,6 @@ pub const COPILOT_USER_AGENT: &str = "GitHubCopilotChat/0.38.2";
pub const COPILOT_API_VERSION: &str = "2025-10-01";
pub const COPILOT_INTEGRATION_ID: &str = "vscode-chat";
/// Copilot 使用量 API URL
const COPILOT_USAGE_URL: &str = "https://api.github.com/copilot_internal/user";
/// 默认 Copilot API 端点
const DEFAULT_COPILOT_API_ENDPOINT: &str = "https://api.githubcopilot.com";
/// Copilot 使用量响应
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CopilotUsageResponse {
@@ -169,6 +251,9 @@ pub enum CopilotAuthError {
#[error("账号不存在: {0}")]
AccountNotFound(String),
#[error("无效的 GitHub 域名: {0}")]
InvalidDomain(String),
}
impl From<reqwest::Error> for CopilotAuthError {
@@ -253,15 +338,19 @@ pub struct GitHubAccount {
pub avatar_url: Option<String>,
/// 认证时间戳
pub authenticated_at: i64,
/// GitHub 域名(github.com 或 GHES 域名)
#[serde(default = "default_github_domain")]
pub github_domain: String,
}
impl From<&GitHubAccountData> for GitHubAccount {
fn from(data: &GitHubAccountData) -> Self {
GitHubAccount {
id: data.user.id.to_string(),
id: composite_account_id(&data.github_domain, data.user.id),
login: data.user.login.clone(),
avatar_url: data.user.avatar_url.clone(),
authenticated_at: data.authenticated_at,
github_domain: data.github_domain.clone(),
}
}
}
@@ -295,6 +384,9 @@ struct GitHubAccountData {
pub user: GitHubUser,
/// 认证时间戳
pub authenticated_at: i64,
/// GitHub 域名(github.com 或 GHES 域名)
#[serde(default = "default_github_domain")]
pub github_domain: String,
}
/// 持久化存储结构(v3 多账号 + 默认账号格式)
@@ -437,14 +529,16 @@ impl CopilotAuthManager {
&self,
github_token: String,
user: GitHubUser,
github_domain: String,
) -> Result<GitHubAccount, CopilotAuthError> {
let account_id = user.id.to_string();
let account_id = composite_account_id(&github_domain, user.id);
let now = chrono::Utc::now().timestamp();
let account_data = GitHubAccountData {
github_token,
user: user.clone(),
authenticated_at: now,
github_domain: github_domain.clone(),
};
let account = GitHubAccount {
@@ -452,6 +546,7 @@ impl CopilotAuthManager {
login: user.login.clone(),
avatar_url: user.avatar_url.clone(),
authenticated_at: now,
github_domain,
};
{
@@ -497,15 +592,25 @@ impl CopilotAuthManager {
// ==================== 设备码流程 ====================
/// 启动设备码流程
pub async fn start_device_flow(&self) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
log::info!("[CopilotAuth] 启动设备码流程");
pub async fn start_device_flow(
&self,
github_domain: Option<&str>,
) -> Result<GitHubDeviceCodeResponse, CopilotAuthError> {
let domain = match github_domain {
Some(d) => normalize_github_domain(d)?,
None => DEFAULT_GITHUB_DOMAIN.to_string(),
};
log::info!("[CopilotAuth] 启动设备码流程 (domain: {domain})");
let response = self
.http_client
.post(GITHUB_DEVICE_CODE_URL)
.post(github_device_code_url(&domain))
.header("Accept", "application/json")
.header("User-Agent", COPILOT_USER_AGENT)
.form(&[("client_id", GITHUB_CLIENT_ID), ("scope", "read:user")])
.form(&[
("client_id", github_client_id(&domain)),
("scope", "read:user"),
])
.send()
.await?;
@@ -534,16 +639,21 @@ impl CopilotAuthManager {
pub async fn poll_for_token(
&self,
device_code: &str,
github_domain: Option<&str>,
) -> Result<Option<GitHubAccount>, CopilotAuthError> {
log::debug!("[CopilotAuth] 轮询 OAuth Token");
let domain = match github_domain {
Some(d) => normalize_github_domain(d)?,
None => DEFAULT_GITHUB_DOMAIN.to_string(),
};
log::debug!("[CopilotAuth] 轮询 OAuth Token (domain: {domain})");
let response = self
.http_client
.post(GITHUB_OAUTH_TOKEN_URL)
.post(github_oauth_token_url(&domain))
.header("Accept", "application/json")
.header("User-Agent", COPILOT_USER_AGENT)
.form(&[
("client_id", GITHUB_CLIENT_ID),
("client_id", github_client_id(&domain)),
("device_code", device_code),
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
])
@@ -578,14 +688,28 @@ impl CopilotAuthManager {
log::info!("[CopilotAuth] OAuth Token 获取成功");
// 获取用户信息
let user = self.fetch_user_info_with_token(&access_token).await?;
// 验证 Copilot 订阅(获取 Copilot Token
self.fetch_copilot_token_with_github_token(&access_token, &user.id.to_string())
let user = self
.fetch_user_info_with_token(&access_token, &domain)
.await?;
// GHES 无需换取 Copilot Token,直接使用 OAuth token 作为 Bearer
// 参考 OpenCode 的实现:GHE Copilot 直接用 OAuth token 调用 copilot-api.{domain}
if !is_ghes(&domain) {
// github.com:验证 Copilot 订阅(获取 Copilot Token
self.fetch_copilot_token_with_github_token(
&access_token,
&user.id.to_string(),
&domain,
)
.await?;
} else {
log::info!("[CopilotAuth] GHES 账号,跳过 Copilot Token 兑换,直接使用 OAuth token");
}
// 添加账号
let account = self.add_account_internal(access_token, user).await?;
let account = self
.add_account_internal(access_token, user, domain)
.await?;
Ok(Some(account))
}
@@ -600,6 +724,16 @@ impl CopilotAuthManager {
// 确保迁移完成
self.ensure_migration_complete().await?;
// GHES 账号直接使用 GitHub OAuth token,无需 Copilot token 交换
let domain = self.get_account_domain(account_id).await;
if is_ghes(&domain) {
let accounts = self.accounts.read().await;
return accounts
.get(account_id)
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()));
}
// 检查缓存的 token
{
let tokens = self.copilot_tokens.read().await;
@@ -627,16 +761,16 @@ impl CopilotAuthManager {
}
// 获取账号的 GitHub token
let github_token = {
let (github_token, domain) = {
let accounts = self.accounts.read().await;
accounts
let account = accounts
.get(account_id)
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
};
// 刷新 Copilot token
self.fetch_copilot_token_with_github_token(&github_token, account_id)
self.fetch_copilot_token_with_github_token(&github_token, account_id, &domain)
.await?;
// 返回新 token
@@ -687,11 +821,19 @@ impl CopilotAuthManager {
) -> Result<Vec<CopilotModel>, CopilotAuthError> {
let copilot_token = self.get_valid_token_for_account(account_id).await?;
// 使用 get_api_endpoint() 动态解析 Copilot API 基础 URL。
// 对于 github.com 账号,会查询 /copilot_internal/user 获取 endpoints.api 字段。
// 对于 GHES 账号,/copilot_internal/user 可能不返回 endpoints——此时
// get_api_endpoint() 会回退到 copilot_api_base(&domain),与之前的静态 URL
// 拼接结果一致。该回退行为是安全且符合预期的。
let api_base = self.get_api_endpoint(account_id).await;
let models_url = format!("{}/models", api_base);
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 可用模型");
let response = self
.http_client
.get(COPILOT_MODELS_URL)
.get(&models_url)
.header("Authorization", format!("Bearer {copilot_token}"))
.header("Content-Type", "application/json")
.header("copilot-integration-id", "vscode-chat")
@@ -767,19 +909,19 @@ impl CopilotAuthManager {
&self,
account_id: &str,
) -> Result<CopilotUsageResponse, CopilotAuthError> {
let github_token = {
let (github_token, domain) = {
let accounts = self.accounts.read().await;
accounts
let account = accounts
.get(account_id)
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
};
log::info!("[CopilotAuth] 获取账号 {account_id} 的 Copilot 使用量");
let response = self
.http_client
.get(COPILOT_USAGE_URL)
.get(copilot_usage_url(&domain))
.header("Authorization", format!("token {github_token}"))
.header("Content-Type", "application/json")
.header("editor-version", COPILOT_EDITOR_VERSION)
@@ -862,7 +1004,8 @@ impl CopilotAuthManager {
log::debug!(
"[CopilotAuth] 获取账号 {account_id} 动态 API 端点失败: {e},使用默认值"
);
DEFAULT_COPILOT_API_ENDPOINT.to_string()
let domain = self.get_account_domain(account_id).await;
copilot_api_base(&domain)
}
}
}
@@ -873,24 +1016,27 @@ impl CopilotAuthManager {
match self.resolve_default_account_id().await {
Some(id) => self.get_api_endpoint(&id).await,
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
None => {
// 无账号时回退到 github.com 的默认端点
copilot_api_base(DEFAULT_GITHUB_DOMAIN)
}
}
}
async fn fetch_and_cache_endpoint(&self, account_id: &str) -> Result<String, CopilotAuthError> {
let github_token = {
let (github_token, domain) = {
let accounts = self.accounts.read().await;
accounts
let account = accounts
.get(account_id)
.map(|a| a.github_token.clone())
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?
.ok_or_else(|| CopilotAuthError::AccountNotFound(account_id.to_string()))?;
(account.github_token.clone(), account.github_domain.clone())
};
log::debug!("[CopilotAuth] 为账号 {account_id} 惰性拉取动态 API 端点");
let response = self
.http_client
.get(COPILOT_USAGE_URL)
.get(copilot_usage_url(&domain))
.header("Authorization", format!("token {github_token}"))
.header("Content-Type", "application/json")
.header("editor-version", COPILOT_EDITOR_VERSION)
@@ -918,7 +1064,7 @@ impl CopilotAuthManager {
let endpoint = match usage.endpoints {
Some(endpoints) => endpoints.api.clone(),
None => DEFAULT_COPILOT_API_ENDPOINT.to_string(),
None => copilot_api_base(&domain),
};
// 缓存端点(包括默认值),避免重复请求
@@ -1075,6 +1221,15 @@ impl CopilotAuthManager {
Self::fallback_default_account_id(&accounts)
}
/// 获取指定账号的 GitHub 域名
async fn get_account_domain(&self, account_id: &str) -> String {
let accounts = self.accounts.read().await;
accounts
.get(account_id)
.map(|a| a.github_domain.clone())
.unwrap_or_else(|| DEFAULT_GITHUB_DOMAIN.to_string())
}
async fn get_refresh_lock(&self, account_id: &str) -> Arc<Mutex<()>> {
{
let refresh_locks = self.refresh_locks.read().await;
@@ -1155,10 +1310,11 @@ impl CopilotAuthManager {
async fn fetch_user_info_with_token(
&self,
github_token: &str,
domain: &str,
) -> Result<GitHubUser, CopilotAuthError> {
let response = self
.http_client
.get(GITHUB_USER_URL)
.get(github_user_url(domain))
.header("Authorization", format!("token {github_token}"))
.header("User-Agent", COPILOT_USER_AGENT)
.header("Editor-Version", COPILOT_EDITOR_VERSION)
@@ -1185,12 +1341,13 @@ impl CopilotAuthManager {
&self,
github_token: &str,
account_id: &str,
domain: &str,
) -> Result<(), CopilotAuthError> {
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token");
log::debug!("[CopilotAuth] 获取账号 {account_id} 的 Copilot Token (domain: {domain})");
let response = self
.http_client
.get(COPILOT_TOKEN_URL)
.get(copilot_token_url(domain))
.header("Authorization", format!("token {github_token}"))
.header("User-Agent", COPILOT_USER_AGENT)
.header("Editor-Version", COPILOT_EDITOR_VERSION)
@@ -1284,20 +1441,32 @@ impl CopilotAuthManager {
log::info!("[CopilotAuth] 执行旧格式迁移");
// 获取用户信息
match self.fetch_user_info_with_token(&legacy_token).await {
match self
.fetch_user_info_with_token(&legacy_token, DEFAULT_GITHUB_DOMAIN)
.await
{
Ok(user) => {
let account_id = user.id.to_string();
let account_id = composite_account_id(DEFAULT_GITHUB_DOMAIN, user.id);
// 尝试获取 Copilot token 验证订阅
if let Err(e) = self
.fetch_copilot_token_with_github_token(&legacy_token, &account_id)
.fetch_copilot_token_with_github_token(
&legacy_token,
&account_id,
DEFAULT_GITHUB_DOMAIN,
)
.await
{
log::warn!("[CopilotAuth] 迁移时验证 Copilot 订阅失败: {e}");
}
// 添加账号
self.add_account_internal(legacy_token, user).await?;
self.add_account_internal(
legacy_token,
user,
DEFAULT_GITHUB_DOMAIN.to_string(),
)
.await?;
self.set_migration_error(None).await;
log::info!("[CopilotAuth] 旧格式迁移完成");
@@ -1387,6 +1556,7 @@ mod tests {
login: "testuser".to_string(),
avatar_url: Some("https://example.com/avatar.png".to_string()),
authenticated_at: 1234567890,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
}],
default_account_id: Some("12345".to_string()),
migration_error: None,
@@ -1420,6 +1590,7 @@ mod tests {
avatar_url: Some("https://example.com/alice.png".to_string()),
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
accounts.insert(
@@ -1432,6 +1603,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000001,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
@@ -1479,6 +1651,7 @@ mod tests {
avatar_url: Some("https://example.com/avatar.png".to_string()),
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
};
let account = GitHubAccount::from(&data);
@@ -1504,6 +1677,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
accounts.insert(
@@ -1516,6 +1690,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000001,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
@@ -1546,6 +1721,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1630,6 +1806,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1664,6 +1841,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1746,6 +1924,7 @@ mod tests {
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: DEFAULT_GITHUB_DOMAIN.to_string(),
},
);
}
@@ -1801,7 +1980,7 @@ mod tests {
let manager = CopilotAuthManager::new(temp_dir.path().to_path_buf());
let endpoint = manager.get_api_endpoint("12345").await;
assert_eq!(endpoint, DEFAULT_COPILOT_API_ENDPOINT);
assert_eq!(endpoint, copilot_api_base(DEFAULT_GITHUB_DOMAIN));
}
#[tokio::test]
@@ -1817,4 +1996,99 @@ mod tests {
other => panic!("期望 AccountNotFound 错误,实际: {other:?}"),
}
}
#[test]
fn test_normalize_github_domain() {
// 基本用法
assert_eq!(normalize_github_domain("github.com").unwrap(), "github.com");
assert_eq!(
normalize_github_domain("company.ghe.com").unwrap(),
"company.ghe.com"
);
// 剥离协议
assert_eq!(
normalize_github_domain("https://company.ghe.com").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("http://company.ghe.com").unwrap(),
"company.ghe.com"
);
// 小写化
assert_eq!(normalize_github_domain("GitHub.COM").unwrap(), "github.com");
assert_eq!(
normalize_github_domain("Company.GHE.Com").unwrap(),
"company.ghe.com"
);
// 剥离尾斜杠和 path
assert_eq!(
normalize_github_domain("company.ghe.com/").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("company.ghe.com/api/v3").unwrap(),
"company.ghe.com"
);
// 剥离 query 和 fragment
assert_eq!(
normalize_github_domain("company.ghe.com?foo=bar").unwrap(),
"company.ghe.com"
);
assert_eq!(
normalize_github_domain("company.ghe.com#section").unwrap(),
"company.ghe.com"
);
// 保留端口
assert_eq!(
normalize_github_domain("company.ghe.com:8443").unwrap(),
"company.ghe.com:8443"
);
// 拒绝 userinfo
assert!(normalize_github_domain("user@company.ghe.com").is_err());
// 拒绝空输入
assert!(normalize_github_domain("").is_err());
assert!(normalize_github_domain(" ").is_err());
}
#[test]
fn test_composite_account_id() {
// github.com 保持原格式(向后兼容)
assert_eq!(composite_account_id("github.com", 12345), "12345");
// GHES 使用复合格式
assert_eq!(
composite_account_id("company.ghe.com", 12345),
"company.ghe.com:12345"
);
// 不同 GHES 实例,相同 user ID,不冲突
assert_ne!(
composite_account_id("a.ghe.com", 1),
composite_account_id("b.ghe.com", 1)
);
}
#[test]
fn test_github_account_from_data_ghes_uses_composite_id() {
let data = GitHubAccountData {
github_token: "gho_test".to_string(),
user: GitHubUser {
login: "testuser".to_string(),
id: 99999,
avatar_url: None,
},
authenticated_at: 1700000000,
github_domain: "company.ghe.com".to_string(),
};
let account = GitHubAccount::from(&data);
assert_eq!(account.id, "company.ghe.com:99999");
}
}
+13 -1
View File
@@ -70,6 +70,11 @@ impl GeminiAdapter {
/// 解析 OAuth 凭证
pub fn parse_oauth_credentials(&self, key: &str) -> Option<OAuthCredentials> {
// 防御性 trim:前端在 input 事件中会 trim,但 JSON 编辑器 / deeplink
// 导入 / live 回填等路径会绕过。带前导换行的 oauth_creds.json 粘贴
// 是常见场景,此处统一兜底。
let key = key.trim();
// 直接是 access_token
if key.starts_with("ya29.") {
return Some(OAuthCredentials {
@@ -120,7 +125,12 @@ impl GeminiAdapter {
fn extract_key_raw(&self, provider: &Provider) -> Option<String> {
if let Some(env) = provider.settings_config.get("env") {
// 使用 GEMINI_API_KEY
if let Some(key) = env.get("GEMINI_API_KEY").and_then(|v| v.as_str()) {
if let Some(key) = env
.get("GEMINI_API_KEY")
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
return Some(key.to_string());
}
}
@@ -131,6 +141,8 @@ impl GeminiAdapter {
.get("apiKey")
.or_else(|| provider.settings_config.get("api_key"))
.and_then(|v| v.as_str())
.map(str::trim)
.filter(|s| !s.is_empty())
{
return Some(key.to_string());
}
@@ -0,0 +1,338 @@
//! Gemini tool schema helpers.
//!
//! Gemini `FunctionDeclaration` supports two schema channels:
//! - `parameters`: a restricted `Schema` subset
//! - `parametersJsonSchema`: richer JSON Schema via arbitrary JSON `Value`
//!
//! Anthropic tool schemas are closer to JSON Schema, so we choose the richer
//! channel when unsupported `Schema` fields are present.
use serde_json::{json, Map, Value};
#[derive(Debug, Clone, PartialEq)]
pub enum GeminiFunctionParameters {
Schema(Value),
JsonSchema(Value),
}
pub fn build_gemini_function_parameters(input_schema: Value) -> GeminiFunctionParameters {
let schema = ensure_object_schema(normalize_json_schema(input_schema));
if requires_parameters_json_schema(&schema) {
GeminiFunctionParameters::JsonSchema(schema)
} else {
GeminiFunctionParameters::Schema(to_gemini_schema(schema))
}
}
/// Vertex AI rejects FunctionDeclarations whose `parameters` schema lacks an
/// explicit `type: "object"`, returning:
///
/// > functionDeclaration parameters schema should be of type OBJECT.
///
/// Anthropic tools sometimes arrive with empty or type-less `input_schema`
/// (e.g. no-argument tools like Claude Code's `TodoRead`). Normalize those to
/// `{type: "object", properties: {}}` so the Gemini upstream accepts them.
///
/// References: google-gemini/generative-ai-python#423, BerriAI/litellm#5055.
fn ensure_object_schema(schema: Value) -> Value {
match schema {
Value::Object(mut obj) => {
obj.entry("type".to_string())
.or_insert_with(|| json!("object"));
if obj.get("type").and_then(|v| v.as_str()) == Some("object") {
obj.entry("properties".to_string())
.or_insert_with(|| json!({}));
}
Value::Object(obj)
}
other => other,
}
}
fn normalize_json_schema(schema: Value) -> Value {
match schema {
Value::Object(mut obj) => {
obj.remove("$schema");
obj.remove("$id");
if let Some(properties) = obj
.get_mut("properties")
.and_then(|value| value.as_object_mut())
{
for value in properties.values_mut() {
*value = normalize_json_schema(value.clone());
}
}
if let Some(items) = obj.get_mut("items") {
*items = normalize_json_schema(items.clone());
}
for key in ["anyOf", "oneOf", "allOf", "prefixItems"] {
if let Some(values) = obj.get_mut(key).and_then(|value| value.as_array_mut()) {
for value in values.iter_mut() {
*value = normalize_json_schema(value.clone());
}
}
}
for key in ["not", "if", "then", "else", "additionalProperties"] {
if let Some(value) = obj.get_mut(key) {
*value = normalize_json_schema(value.clone());
}
}
Value::Object(obj)
}
Value::Array(values) => {
Value::Array(values.into_iter().map(normalize_json_schema).collect())
}
other => other,
}
}
fn requires_parameters_json_schema(schema: &Value) -> bool {
match schema {
Value::Object(obj) => object_requires_parameters_json_schema(obj),
Value::Array(values) => values.iter().any(requires_parameters_json_schema),
_ => false,
}
}
fn object_requires_parameters_json_schema(obj: &Map<String, Value>) -> bool {
for (key, value) in obj {
match key.as_str() {
"type" => {
if value.is_array() {
return true;
}
}
"format" | "title" | "description" | "nullable" | "enum" | "maxItems" | "minItems"
| "required" | "minProperties" | "maxProperties" | "minLength" | "maxLength"
| "pattern" | "example" | "propertyOrdering" | "default" | "minimum" | "maximum" => {}
"properties" => {
let Some(properties) = value.as_object() else {
return true;
};
if properties.values().any(requires_parameters_json_schema) {
return true;
}
}
"items" => {
if !value.is_object() || requires_parameters_json_schema(value) {
return true;
}
}
"anyOf" => {
let Some(values) = value.as_array() else {
return true;
};
if values.iter().any(requires_parameters_json_schema) {
return true;
}
}
// JSON Schema keywords that Gemini `parameters` does not accept.
"$ref"
| "$defs"
| "definitions"
| "additionalProperties"
| "unevaluatedProperties"
| "patternProperties"
| "oneOf"
| "allOf"
| "const"
| "not"
| "if"
| "then"
| "else"
| "dependentRequired"
| "dependentSchemas"
| "contains"
| "minContains"
| "maxContains"
| "prefixItems"
| "exclusiveMinimum"
| "exclusiveMaximum"
| "multipleOf"
| "examples" => return true,
// Be conservative for unknown keywords.
_ => return true,
}
}
false
}
fn to_gemini_schema(schema: Value) -> Value {
match schema {
Value::Object(obj) => {
let mut result = Map::new();
for (key, value) in obj {
match key.as_str() {
"type" | "format" | "title" | "description" | "nullable" | "enum"
| "maxItems" | "minItems" | "required" | "minProperties" | "maxProperties"
| "minLength" | "maxLength" | "pattern" | "example" | "propertyOrdering"
| "default" | "minimum" | "maximum" => {
result.insert(key, value);
}
"properties" => {
if let Some(properties) = value.as_object() {
let converted = properties
.iter()
.map(|(name, property_schema)| {
(name.clone(), to_gemini_schema(property_schema.clone()))
})
.collect();
result.insert("properties".to_string(), Value::Object(converted));
}
}
"items" if value.is_object() => {
result.insert("items".to_string(), to_gemini_schema(value));
}
"anyOf" => {
if let Some(values) = value.as_array() {
result.insert(
"anyOf".to_string(),
Value::Array(
values
.iter()
.map(|value| to_gemini_schema(value.clone()))
.collect(),
),
);
}
}
_ => {}
}
}
Value::Object(result)
}
other => other,
}
}
pub fn build_gemini_function_declaration(
name: &str,
description: Option<&str>,
input_schema: Value,
) -> Value {
let mut declaration = Map::new();
declaration.insert("name".to_string(), json!(name));
declaration.insert("description".to_string(), json!(description.unwrap_or("")));
match build_gemini_function_parameters(input_schema) {
GeminiFunctionParameters::Schema(schema) => {
declaration.insert("parameters".to_string(), schema);
}
GeminiFunctionParameters::JsonSchema(schema) => {
declaration.insert("parametersJsonSchema".to_string(), schema);
}
}
Value::Object(declaration)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn uses_schema_for_simple_openapi_subset() {
let schema = json!({
"type": "object",
"properties": {
"city": { "type": "string", "description": "Target city" }
},
"required": ["city"]
});
let result = build_gemini_function_declaration("weather", Some("Weather lookup"), schema);
assert!(result.get("parameters").is_some());
assert!(result.get("parametersJsonSchema").is_none());
assert_eq!(result["parameters"]["properties"]["city"]["type"], "string");
}
#[test]
fn uses_parameters_json_schema_for_additional_properties() {
let schema = json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"city": { "type": "string" }
},
"required": ["city"],
"additionalProperties": false
});
let result = build_gemini_function_declaration("weather", Some("Weather lookup"), schema);
assert!(result.get("parameters").is_none());
assert!(result.get("parametersJsonSchema").is_some());
assert!(result["parametersJsonSchema"].get("$schema").is_none());
assert_eq!(
result["parametersJsonSchema"]["additionalProperties"],
false
);
}
#[test]
fn uses_parameters_json_schema_for_one_of() {
let schema = json!({
"type": "object",
"properties": {
"target": {
"oneOf": [
{ "type": "string" },
{ "type": "integer" }
]
}
}
});
let result = build_gemini_function_declaration("search", Some("Search"), schema);
assert!(result.get("parameters").is_none());
assert!(result.get("parametersJsonSchema").is_some());
}
/// Regression for P2 (Vertex AI rejecting empty schemas): zero-argument
/// Anthropic tools (no `input_schema`) must produce `parameters` with an
/// explicit `type: "object"` and an empty `properties` map so the Gemini
/// upstream does not return `schema should be of type OBJECT`.
#[test]
fn empty_input_schema_produces_explicit_object_type() {
let result = build_gemini_function_declaration("ping", Some("no-arg"), json!({}));
assert_eq!(result["parameters"]["type"], "object");
assert!(result["parameters"]["properties"].is_object());
}
/// A schema that carries descriptive fields but no `type` is still a
/// zero-arg object for Gemini purposes — promote it explicitly.
#[test]
fn input_schema_missing_type_is_promoted_to_object() {
let result = build_gemini_function_declaration(
"noop",
None,
json!({ "description": "does nothing" }),
);
assert_eq!(result["parameters"]["type"], "object");
assert!(result["parameters"]["properties"].is_object());
}
/// Defensive: an atomic (non-object) schema is left untouched, because
/// forcing `type: "object"` here would corrupt primitive parameter types
/// that happen to flow through this path.
#[test]
fn non_object_schema_is_not_mutated() {
let result = build_gemini_function_declaration("bare", None, json!({ "type": "string" }));
assert_eq!(result["parameters"]["type"], "string");
assert!(result["parameters"].get("properties").is_none());
}
}
@@ -0,0 +1,389 @@
//! Gemini Native shadow state
//!
//! Keeps provider/session-scoped assistant content snapshots and tool call metadata
//! so Gemini thought signatures and tool turns can be replayed without bloating
//! the main proxy files.
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use std::sync::RwLock;
/// Composite key for a Gemini shadow session.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct GeminiShadowKey {
pub provider_id: String,
pub session_id: String,
}
impl GeminiShadowKey {
pub fn new(provider_id: impl Into<String>, session_id: impl Into<String>) -> Self {
Self {
provider_id: provider_id.into(),
session_id: session_id.into(),
}
}
}
/// Gemini function call metadata captured from an assistant turn.
#[derive(Debug, Clone, PartialEq)]
pub struct GeminiToolCallMeta {
pub id: Option<String>,
pub name: String,
pub args: Value,
pub thought_signature: Option<String>,
}
impl GeminiToolCallMeta {
pub fn new(
id: Option<impl Into<String>>,
name: impl Into<String>,
args: Value,
thought_signature: Option<impl Into<String>>,
) -> Self {
Self {
id: id.map(Into::into),
name: name.into(),
args,
thought_signature: thought_signature.map(Into::into),
}
}
}
/// Stored assistant turn snapshot.
#[derive(Debug, Clone, PartialEq)]
pub struct GeminiAssistantTurn {
pub assistant_content: Value,
pub tool_calls: Vec<GeminiToolCallMeta>,
}
impl GeminiAssistantTurn {
pub fn new(assistant_content: Value, tool_calls: Vec<GeminiToolCallMeta>) -> Self {
Self {
assistant_content,
tool_calls,
}
}
}
/// Session snapshot returned by read APIs.
#[derive(Debug, Clone, PartialEq)]
pub struct GeminiShadowSessionSnapshot {
pub provider_id: String,
pub session_id: String,
pub turns: Vec<GeminiAssistantTurn>,
}
#[derive(Debug, Clone)]
struct GeminiShadowSession {
turns: VecDeque<GeminiAssistantTurn>,
}
impl GeminiShadowSession {
fn new() -> Self {
Self {
turns: VecDeque::new(),
}
}
}
#[derive(Debug, Clone)]
struct GeminiShadowInner {
sessions: HashMap<GeminiShadowKey, GeminiShadowSession>,
session_order: VecDeque<GeminiShadowKey>,
}
impl GeminiShadowInner {
fn new() -> Self {
Self {
sessions: HashMap::new(),
session_order: VecDeque::new(),
}
}
}
/// Thread-safe shadow store for Gemini Native replay state.
///
/// The store is intentionally small and explicit:
/// - sessions are keyed by `(provider_id, session_id)`
/// - each session keeps only a bounded number of recent assistant turns
/// - the oldest session is evicted first when the store is full
#[derive(Debug)]
pub struct GeminiShadowStore {
max_sessions: usize,
max_turns_per_session: usize,
inner: RwLock<GeminiShadowInner>,
}
impl Default for GeminiShadowStore {
fn default() -> Self {
Self::with_limits(200, 64)
}
}
impl GeminiShadowStore {
#[allow(dead_code)]
pub fn new() -> Self {
Self::default()
}
pub fn with_limits(max_sessions: usize, max_turns_per_session: usize) -> Self {
Self {
max_sessions: max_sessions.max(1),
max_turns_per_session: max_turns_per_session.max(1),
inner: RwLock::new(GeminiShadowInner::new()),
}
}
/// Record a Gemini assistant turn for later replay.
pub fn record_assistant_turn(
&self,
provider_id: impl Into<String>,
session_id: impl Into<String>,
assistant_content: Value,
tool_calls: Vec<GeminiToolCallMeta>,
) -> GeminiShadowSessionSnapshot {
let key = GeminiShadowKey::new(provider_id, session_id);
let turn = GeminiAssistantTurn::new(assistant_content, tool_calls);
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
Self::touch_session_order(&mut inner.session_order, &key);
let snapshot = {
let session = inner
.sessions
.entry(key.clone())
.or_insert_with(GeminiShadowSession::new);
session.turns.push_back(turn);
while session.turns.len() > self.max_turns_per_session {
session.turns.pop_front();
}
Self::snapshot_session(&key, session)
};
Self::prune_sessions(&mut inner, self.max_sessions);
snapshot
}
/// Get the latest assistant content for a provider/session pair.
#[allow(dead_code)]
pub fn latest_assistant_content(&self, provider_id: &str, session_id: &str) -> Option<Value> {
self.get_session(provider_id, session_id)
.and_then(|snapshot| {
snapshot
.turns
.last()
.map(|turn| turn.assistant_content.clone())
})
}
/// Get the latest tool calls for a provider/session pair.
#[allow(dead_code)]
pub fn latest_tool_calls(
&self,
provider_id: &str,
session_id: &str,
) -> Option<Vec<GeminiToolCallMeta>> {
self.get_session(provider_id, session_id)
.and_then(|snapshot| snapshot.turns.last().map(|turn| turn.tool_calls.clone()))
}
/// Read a full session snapshot.
pub fn get_session(
&self,
provider_id: &str,
session_id: &str,
) -> Option<GeminiShadowSessionSnapshot> {
let key = GeminiShadowKey::new(provider_id, session_id);
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
let snapshot = inner
.sessions
.get(&key)
.map(|session| Self::snapshot_session(&key, session));
if snapshot.is_some() {
Self::touch_session_order(&mut inner.session_order, &key);
}
snapshot
}
/// Remove a single session from the store.
#[allow(dead_code)]
pub fn clear_session(&self, provider_id: &str, session_id: &str) -> bool {
let key = GeminiShadowKey::new(provider_id, session_id);
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
let removed = inner.sessions.remove(&key).is_some();
if removed {
Self::remove_key_from_order(&mut inner.session_order, &key);
}
removed
}
/// Remove all sessions for a provider.
#[allow(dead_code)]
pub fn clear_provider(&self, provider_id: &str) -> usize {
let mut inner = self.inner.write().expect("gemini shadow lock poisoned");
let keys: Vec<_> = inner
.sessions
.keys()
.filter(|key| key.provider_id == provider_id)
.cloned()
.collect();
for key in &keys {
inner.sessions.remove(key);
Self::remove_key_from_order(&mut inner.session_order, key);
}
keys.len()
}
/// Number of tracked sessions.
#[allow(dead_code)]
pub fn session_count(&self) -> usize {
self.inner
.read()
.expect("gemini shadow lock poisoned")
.sessions
.len()
}
fn snapshot_session(
key: &GeminiShadowKey,
session: &GeminiShadowSession,
) -> GeminiShadowSessionSnapshot {
GeminiShadowSessionSnapshot {
provider_id: key.provider_id.clone(),
session_id: key.session_id.clone(),
turns: session.turns.iter().cloned().collect(),
}
}
fn touch_session_order(order: &mut VecDeque<GeminiShadowKey>, key: &GeminiShadowKey) {
if let Some(pos) = order.iter().position(|existing| existing == key) {
order.remove(pos);
}
order.push_back(key.clone());
}
#[allow(dead_code)]
fn remove_key_from_order(order: &mut VecDeque<GeminiShadowKey>, key: &GeminiShadowKey) {
if let Some(pos) = order.iter().position(|existing| existing == key) {
order.remove(pos);
}
}
fn prune_sessions(inner: &mut GeminiShadowInner, max_sessions: usize) {
while inner.sessions.len() > max_sessions {
let Some(evicted_key) = inner.session_order.pop_front() else {
break;
};
inner.sessions.remove(&evicted_key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn record_and_read_latest_turn() {
let store = GeminiShadowStore::with_limits(8, 4);
let snapshot = store.record_assistant_turn(
"provider-a",
"session-1",
json!({"parts": [{"text": "hello", "thoughtSignature": "sig-1"}]}),
vec![GeminiToolCallMeta::new(
Some("call-1"),
"get_weather",
json!({"location": "Tokyo"}),
Some("sig-1"),
)],
);
assert_eq!(snapshot.provider_id, "provider-a");
assert_eq!(snapshot.session_id, "session-1");
assert_eq!(snapshot.turns.len(), 1);
let content = store
.latest_assistant_content("provider-a", "session-1")
.expect("content");
assert_eq!(content["parts"][0]["text"], "hello");
assert_eq!(content["parts"][0]["thoughtSignature"], "sig-1");
let tool_calls = store
.latest_tool_calls("provider-a", "session-1")
.expect("tool calls");
assert_eq!(tool_calls.len(), 1);
assert_eq!(tool_calls[0].id.as_deref(), Some("call-1"));
assert_eq!(tool_calls[0].name, "get_weather");
assert_eq!(tool_calls[0].args["location"], "Tokyo");
assert_eq!(tool_calls[0].thought_signature.as_deref(), Some("sig-1"));
}
#[test]
fn sessions_are_isolated_by_provider_and_session_id() {
let store = GeminiShadowStore::with_limits(8, 4);
store.record_assistant_turn("provider-a", "session-1", json!({"text": "a"}), vec![]);
store.record_assistant_turn("provider-b", "session-1", json!({"text": "b"}), vec![]);
store.record_assistant_turn("provider-a", "session-2", json!({"text": "c"}), vec![]);
assert_eq!(store.session_count(), 3);
assert_eq!(
store.latest_assistant_content("provider-a", "session-1"),
Some(json!({"text": "a"}))
);
assert_eq!(
store.latest_assistant_content("provider-b", "session-1"),
Some(json!({"text": "b"}))
);
assert_eq!(
store.latest_assistant_content("provider-a", "session-2"),
Some(json!({"text": "c"}))
);
}
#[test]
fn retains_only_latest_turns_per_session() {
let store = GeminiShadowStore::with_limits(8, 2);
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 2}), vec![]);
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 3}), vec![]);
let snapshot = store
.get_session("provider-a", "session-1")
.expect("snapshot");
assert_eq!(snapshot.turns.len(), 2);
assert_eq!(snapshot.turns[0].assistant_content, json!({"idx": 2}));
assert_eq!(snapshot.turns[1].assistant_content, json!({"idx": 3}));
}
#[test]
fn evicts_oldest_session_when_capacity_is_exceeded() {
let store = GeminiShadowStore::with_limits(2, 2);
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
store.record_assistant_turn("provider-a", "session-2", json!({"idx": 2}), vec![]);
store.record_assistant_turn("provider-a", "session-3", json!({"idx": 3}), vec![]);
assert!(store.get_session("provider-a", "session-1").is_none());
assert!(store.get_session("provider-a", "session-2").is_some());
assert!(store.get_session("provider-a", "session-3").is_some());
}
#[test]
fn clear_session_and_provider_work() {
let store = GeminiShadowStore::with_limits(8, 4);
store.record_assistant_turn("provider-a", "session-1", json!({"idx": 1}), vec![]);
store.record_assistant_turn("provider-a", "session-2", json!({"idx": 2}), vec![]);
store.record_assistant_turn("provider-b", "session-3", json!({"idx": 3}), vec![]);
assert!(store.clear_session("provider-a", "session-1"));
assert!(store.get_session("provider-a", "session-1").is_none());
let removed = store.clear_provider("provider-a");
assert_eq!(removed, 1);
assert!(store.get_session("provider-a", "session-2").is_none());
assert!(store.get_session("provider-b", "session-3").is_some());
}
}
+17 -13
View File
@@ -18,10 +18,14 @@ mod codex;
pub mod codex_oauth_auth;
pub mod copilot_auth;
mod gemini;
pub(crate) mod gemini_schema;
pub mod gemini_shadow;
pub mod models;
pub mod streaming;
pub mod streaming_gemini;
pub mod streaming_responses;
pub mod transform;
pub mod transform_gemini;
pub mod transform_responses;
use crate::app_config::AppType;
@@ -101,6 +105,14 @@ impl ProviderType {
pub fn from_app_type_and_config(app_type: &AppType, provider: &Provider) -> Self {
match app_type {
AppType::Claude => {
if get_claude_api_format(provider) == "gemini_native" {
let adapter = ClaudeAdapter::new();
return match adapter.extract_auth(provider).map(|auth| auth.strategy) {
Some(AuthStrategy::GoogleOAuth) => ProviderType::GeminiCli,
_ => ProviderType::Gemini,
};
}
// 检测是否为 GitHub Copilot
if let Some(meta) = provider.meta.as_ref() {
if meta.provider_type.as_deref() == Some("github_copilot") {
@@ -162,13 +174,9 @@ impl ProviderType {
}
ProviderType::Gemini
}
AppType::OpenCode => {
// OpenCode doesn't support proxy, but return a default type for completeness
ProviderType::Codex // Fallback to Codex-like type
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy, but return a default type for completeness
ProviderType::Codex // Fallback to Codex-like type
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy, fallback to Codex-like type
ProviderType::Codex
}
}
}
@@ -220,12 +228,8 @@ pub fn get_adapter(app_type: &AppType) -> Box<dyn ProviderAdapter> {
AppType::Claude => Box::new(ClaudeAdapter::new()),
AppType::Codex => Box::new(CodexAdapter::new()),
AppType::Gemini => Box::new(GeminiAdapter::new()),
AppType::OpenCode => {
// OpenCode doesn't support proxy, fallback to Codex adapter
Box::new(CodexAdapter::new())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy, fallback to Codex adapter
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy, fallback to Codex adapter
Box::new(CodexAdapter::new())
}
}
+2 -5
View File
@@ -2,7 +2,7 @@
//!
//! 实现 OpenAI SSE → Anthropic SSE 格式转换
use crate::proxy::sse::strip_sse_field;
use crate::proxy::sse::{strip_sse_field, take_sse_block};
use bytes::Bytes;
use futures::stream::{Stream, StreamExt};
use serde::{Deserialize, Serialize};
@@ -118,10 +118,7 @@ pub fn create_anthropic_sse_stream<E: std::error::Error + Send + 'static>(
Ok(bytes) => {
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
while let Some(pos) = buffer.find("\n\n") {
let line = buffer[..pos].to_string();
buffer = buffer[pos + 2..].to_string();
while let Some(line) = take_sse_block(&mut buffer) {
if line.trim().is_empty() {
continue;
}
File diff suppressed because it is too large Load Diff
@@ -9,7 +9,7 @@
//! 与 Chat Completions 的 delta chunk 模型完全不同,需要独立的状态机处理。
use super::transform_responses::{build_anthropic_usage_from_responses, map_responses_stop_reason};
use crate::proxy::sse::strip_sse_field;
use crate::proxy::sse::{strip_sse_field, take_sse_block};
use bytes::Bytes;
use futures::stream::{Stream, StreamExt};
use serde_json::{json, Value};
@@ -122,10 +122,7 @@ pub fn create_anthropic_sse_stream_from_responses<E: std::error::Error + Send +
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
// SSE 事件由 \n\n 分隔
while let Some(pos) = buffer.find("\n\n") {
let block = buffer[..pos].to_string();
buffer = buffer[pos + 2..].to_string();
while let Some(block) = take_sse_block(&mut buffer) {
if block.trim().is_empty() {
continue;
}
File diff suppressed because it is too large Load Diff
@@ -17,10 +17,13 @@ use serde_json::{json, Value};
/// `is_codex_oauth`: 当目标后端是 ChatGPT Plus/Pro 反代 (`chatgpt.com/backend-api/codex`) 时为 true。
/// 该后端强制要求 `store: false`,并要求 `include` 包含 `reasoning.encrypted_content`
/// 以便在无服务端状态下保持多轮 reasoning 上下文。
/// `codex_fast_mode`: 仅在 `is_codex_oauth` 为 true 时生效,控制是否注入
/// `service_tier = "priority"`。
pub fn anthropic_to_responses(
body: Value,
cache_key: Option<&str>,
is_codex_oauth: bool,
codex_fast_mode: bool,
) -> Result<Value, ProxyError> {
let mut result = json!({});
@@ -125,10 +128,15 @@ pub fn anthropic_to_responses(
// (codex-rs 结构体根本没有这三个字段,OpenAI 自己的客户端不发它们)
// - instructions / tools / parallel_tool_calls: 必填字段,缺则兜底默认值
// cc-switch 的 transform 当前是"条件写入",可能产生缺失)
// - service_tier: 仅在 FAST mode 开启时写入 "priority"
// (与 OpenAI 官方 codex-rs 当前请求结构保持一致)
// - stream: 必须永远 truecodex-rs 硬编码 true,且 cc-switch 的
// SSE 解析层只处理流式响应,强制覆盖避免客户端误传 false)
if is_codex_oauth {
result["store"] = json!(false);
if codex_fast_mode {
result["service_tier"] = json!("priority");
}
const REASONING_MARKER: &str = "reasoning.encrypted_content";
let mut includes: Vec<Value> = body
@@ -194,24 +202,16 @@ pub(crate) fn map_responses_stop_reason(
incomplete_reason: Option<&str>,
) -> Option<&'static str> {
status.map(|s| match s {
"completed" => {
if has_tool_use {
"tool_use"
} else {
"end_turn"
}
}
"incomplete" => {
"completed" if has_tool_use => "tool_use",
"incomplete"
if matches!(
incomplete_reason,
Some("max_output_tokens") | Some("max_tokens")
) || incomplete_reason.is_none()
{
"max_tokens"
} else {
"end_turn"
}
) || incomplete_reason.is_none() =>
{
"max_tokens"
}
"incomplete" => "end_turn",
_ => "end_turn",
})
}
@@ -528,7 +528,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["model"], "gpt-4o");
assert_eq!(result["max_output_tokens"], 1024);
assert_eq!(result["input"][0]["role"], "user");
@@ -547,7 +547,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["instructions"], "You are a helpful assistant.");
// system should not appear in input
assert_eq!(result["input"].as_array().unwrap().len(), 1);
@@ -565,7 +565,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["instructions"], "Part 1\n\nPart 2");
}
@@ -582,7 +582,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tools"][0]["type"], "function");
assert_eq!(result["tools"][0]["name"], "get_weather");
assert!(result["tools"][0].get("parameters").is_some());
@@ -599,7 +599,7 @@ mod tests {
"tool_choice": {"type": "any"}
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tool_choice"], "required");
}
@@ -612,7 +612,7 @@ mod tests {
"tool_choice": {"type": "tool", "name": "get_weather"}
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["tool_choice"]["type"], "function");
assert_eq!(result["tool_choice"]["name"], "get_weather");
}
@@ -631,7 +631,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// Should produce: assistant message (text) + function_call item
@@ -661,7 +661,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// Should produce: function_call_output item (lifted)
@@ -685,7 +685,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
let input_arr = result["input"].as_array().unwrap();
// thinking should be discarded, only text remains
@@ -708,7 +708,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
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_text");
@@ -866,7 +866,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["model"], "o3-mini");
}
@@ -878,7 +878,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, Some("my-provider-id"), false).unwrap();
let result = anthropic_to_responses(input, Some("my-provider-id"), false, false).unwrap();
assert_eq!(result["prompt_cache_key"], "my-provider-id");
}
@@ -896,7 +896,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result["tools"][0].get("cache_control").is_none());
}
@@ -913,7 +913,7 @@ mod tests {
}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result["input"][0]["content"][0]
.get("cache_control")
.is_none());
@@ -975,7 +975,7 @@ mod tests {
"max_tokens": 4096,
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["max_output_tokens"], 4096);
assert!(result.get("max_completion_tokens").is_none());
}
@@ -989,7 +989,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "xhigh");
}
@@ -1003,7 +1003,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "low");
}
@@ -1016,7 +1016,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "low");
}
@@ -1029,7 +1029,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "medium");
}
@@ -1042,7 +1042,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "high");
}
@@ -1055,7 +1055,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["reasoning"]["effort"], "xhigh");
}
@@ -1068,7 +1068,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result.get("reasoning").is_none());
}
@@ -1082,10 +1082,11 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
// store 必须显式为 falseChatGPT 后端拒绝 true
assert_eq!(result["store"], json!(false));
assert_eq!(result["service_tier"], json!("priority"));
// include 必须包含 reasoning.encrypted_content(无服务端状态下保持多轮 reasoning)
assert_eq!(result["include"], json!(["reasoning.encrypted_content"]));
@@ -1101,9 +1102,10 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(result.get("store").is_none());
assert!(result.get("service_tier").is_none());
assert!(result.get("include").is_none());
}
@@ -1117,7 +1119,7 @@ mod tests {
"include": ["something.else", "reasoning.encrypted_content"]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
let includes = result["include"]
.as_array()
.expect("include should be array");
@@ -1138,6 +1140,21 @@ mod tests {
assert_eq!(marker_count, 1, "marker 不应被重复添加(idempotent 失败)");
}
#[test]
fn test_anthropic_to_responses_codex_oauth_fast_mode_can_be_disabled() {
let input = json!({
"model": "gpt-5-codex",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true, false).unwrap();
assert_eq!(result["store"], json!(false));
assert!(result.get("service_tier").is_none());
assert_eq!(result["include"], json!(["reasoning.encrypted_content"]));
}
#[test]
fn test_anthropic_to_responses_codex_oauth_strips_max_output_tokens() {
// ChatGPT Plus/Pro 反代不接受 max_output_tokensOpenAI 官方 codex-rs 的
@@ -1149,7 +1166,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("max_output_tokens").is_none(),
@@ -1167,7 +1184,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["max_output_tokens"], json!(1024));
}
@@ -1185,7 +1202,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("temperature").is_none(),
@@ -1203,7 +1220,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert!(
result.get("top_p").is_none(),
@@ -1220,7 +1237,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["instructions"],
@@ -1254,7 +1271,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["instructions"],
@@ -1278,7 +1295,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, true).unwrap();
let result = anthropic_to_responses(input, None, true, true).unwrap();
assert_eq!(
result["stream"],
@@ -1299,7 +1316,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert_eq!(result["temperature"], json!(0.7));
assert_eq!(result["top_p"], json!(0.9));
@@ -1315,7 +1332,7 @@ mod tests {
"messages": [{"role": "user", "content": "Hello"}]
});
let result = anthropic_to_responses(input, None, false).unwrap();
let result = anthropic_to_responses(input, None, false, false).unwrap();
assert!(
result.get("parallel_tool_calls").is_none(),
+2 -5
View File
@@ -5,7 +5,7 @@
use super::session::ProxySession;
use super::usage::parser::TokenUsage;
use super::ProxyError;
use crate::proxy::sse::strip_sse_field;
use crate::proxy::sse::{strip_sse_field, take_sse_block};
use bytes::Bytes;
use futures::stream::{Stream, StreamExt};
use serde_json::Value;
@@ -86,10 +86,7 @@ impl StreamHandler {
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
// 提取完整事件
while let Some(pos) = buffer.find("\n\n") {
let event_text = buffer[..pos].to_string();
buffer = buffer[pos + 2..].to_string();
while let Some(event_text) = take_sse_block(&mut buffer) {
for line in event_text.lines() {
if let Some(data) = strip_sse_field(line, "data") {
if data.trim() != "[DONE]" {
+4 -5
View File
@@ -7,7 +7,7 @@ use super::{
handler_context::{RequestContext, StreamingTimeoutConfig},
hyper_client::ProxyResponse,
server::ProxyState,
sse::strip_sse_field,
sse::{strip_sse_field, take_sse_block},
usage::parser::TokenUsage,
ProxyError,
};
@@ -662,10 +662,7 @@ pub fn create_logged_passthrough_stream(
crate::proxy::sse::append_utf8_safe(&mut buffer, &mut utf8_remainder, &bytes);
// 尝试解析并记录完整的 SSE 事件
while let Some(pos) = buffer.find("\n\n") {
let event_text = buffer[..pos].to_string();
buffer = buffer[pos + 2..].to_string();
while let Some(event_text) = take_sse_block(&mut buffer) {
if !event_text.trim().is_empty() {
// 提取 data 部分并尝试解析为 JSON
for line in event_text.lines() {
@@ -726,6 +723,7 @@ mod tests {
use crate::provider::ProviderMeta;
use crate::proxy::failover_switch::FailoverSwitchManager;
use crate::proxy::provider_router::ProviderRouter;
use crate::proxy::providers::gemini_shadow::GeminiShadowStore;
use crate::proxy::types::{ProxyConfig, ProxyStatus};
use rust_decimal::Decimal;
use std::collections::HashMap;
@@ -846,6 +844,7 @@ mod tests {
start_time: Arc::new(RwLock::new(None)),
current_providers: Arc::new(RwLock::new(HashMap::new())),
provider_router: Arc::new(ProviderRouter::new(db.clone())),
gemini_shadow: Arc::new(GeminiShadowStore::default()),
app_handle: None,
failover_manager: Arc::new(FailoverSwitchManager::new(db)),
}
+5 -1
View File
@@ -10,7 +10,8 @@
use super::{
failover_switch::FailoverSwitchManager, handlers, log_codes::srv as log_srv,
provider_router::ProviderRouter, types::*, ProxyError,
provider_router::ProviderRouter, providers::gemini_shadow::GeminiShadowStore, types::*,
ProxyError,
};
use crate::database::Database;
use axum::{
@@ -35,6 +36,8 @@ pub struct ProxyState {
pub current_providers: Arc<RwLock<std::collections::HashMap<String, (String, String)>>>,
/// 共享的 ProviderRouter(持有熔断器状态,跨请求保持)
pub provider_router: Arc<ProviderRouter>,
/// Gemini Native shadow state,用于 thoughtSignature / tool call 回放
pub gemini_shadow: Arc<GeminiShadowStore>,
/// AppHandle,用于发射事件和更新托盘菜单
pub app_handle: Option<tauri::AppHandle>,
/// 故障转移切换管理器
@@ -68,6 +71,7 @@ impl ProxyServer {
start_time: Arc::new(RwLock::new(None)),
current_providers: Arc::new(RwLock::new(std::collections::HashMap::new())),
provider_router,
gemini_shadow: Arc::new(GeminiShadowStore::default()),
app_handle,
failover_manager,
};
+69
View File
@@ -242,6 +242,12 @@ pub fn extract_session_id(
body: &serde_json::Value,
client_format: &str,
) -> SessionIdResult {
if client_format == "claude" {
if let Some(result) = extract_claude_session(headers, body) {
return result;
}
}
// Codex 请求特殊处理
if client_format == "codex" || client_format == "openai" {
if let Some(result) = extract_codex_session(headers, body) {
@@ -258,6 +264,28 @@ pub fn extract_session_id(
generate_new_session_id()
}
/// 提取 Claude Session ID
fn extract_claude_session(
headers: &HeaderMap,
body: &serde_json::Value,
) -> Option<SessionIdResult> {
for header_name in &["x-claude-code-session-id", "claude-code-session-id"] {
if let Some(value) = headers.get(*header_name) {
if let Ok(session_id) = value.to_str() {
if !session_id.is_empty() {
return Some(SessionIdResult {
session_id: session_id.to_string(),
source: SessionIdSource::Header,
client_provided: true,
});
}
}
}
}
extract_from_metadata(body)
}
/// 提取 Codex Session ID
fn extract_codex_session(headers: &HeaderMap, body: &serde_json::Value) -> Option<SessionIdResult> {
// 1. 从 headers 提取
@@ -515,6 +543,47 @@ mod tests {
assert!(result.client_provided);
}
#[test]
fn test_extract_session_from_claude_header() {
let mut headers = HeaderMap::new();
headers.insert(
"x-claude-code-session-id",
"d937243f-2702-4f20-97b6-c9682235ab81".parse().unwrap(),
);
let body = json!({
"model": "claude-3-5-sonnet",
"messages": [{"role": "user", "content": "Hello"}]
});
let result = extract_session_id(&headers, &body, "claude");
assert_eq!(result.session_id, "d937243f-2702-4f20-97b6-c9682235ab81");
assert_eq!(result.source, SessionIdSource::Header);
assert!(result.client_provided);
}
#[test]
fn test_extract_session_from_claude_header_precedes_metadata() {
let mut headers = HeaderMap::new();
headers.insert(
"x-claude-code-session-id",
"header-session-123".parse().unwrap(),
);
let body = json!({
"model": "claude-3-5-sonnet",
"messages": [{"role": "user", "content": "Hello"}],
"metadata": {
"session_id": "my-session-123"
}
});
let result = extract_session_id(&headers, &body, "claude");
assert_eq!(result.session_id, "header-session-123");
assert_eq!(result.source, SessionIdSource::Header);
assert!(result.client_provided);
}
#[test]
fn test_extract_session_from_codex_previous_response_id() {
let headers = HeaderMap::new();
+41 -1
View File
@@ -4,6 +4,24 @@ pub(crate) fn strip_sse_field<'a>(line: &'a str, field: &str) -> Option<&'a str>
.or_else(|| line.strip_prefix(&format!("{field}:")))
}
#[inline]
pub(crate) fn take_sse_block(buffer: &mut String) -> Option<String> {
let mut best: Option<(usize, usize)> = None;
for (delimiter, len) in [("\r\n\r\n", 4usize), ("\n\n", 2usize)] {
if let Some(pos) = buffer.find(delimiter) {
if best.is_none_or(|(best_pos, _)| pos < best_pos) {
best = Some((pos, len));
}
}
}
let (pos, len) = best?;
let block = buffer[..pos].to_string();
buffer.drain(..pos + len);
Some(block)
}
/// Append raw bytes to a UTF-8 `String` buffer, correctly handling multi-byte
/// characters that are split across chunk boundaries.
///
@@ -68,7 +86,7 @@ pub(crate) fn append_utf8_safe(buffer: &mut String, remainder: &mut Vec<u8>, new
#[cfg(test)]
mod tests {
use super::{append_utf8_safe, strip_sse_field};
use super::{append_utf8_safe, strip_sse_field, take_sse_block};
#[test]
fn strip_sse_field_accepts_optional_space() {
@@ -91,6 +109,28 @@ mod tests {
assert_eq!(strip_sse_field("id:1", "data"), None);
}
#[test]
fn take_sse_block_supports_lf_delimiters() {
let mut buffer = "data: {\"ok\":true}\n\nrest".to_string();
assert_eq!(
take_sse_block(&mut buffer),
Some("data: {\"ok\":true}".to_string())
);
assert_eq!(buffer, "rest");
}
#[test]
fn take_sse_block_supports_crlf_delimiters() {
let mut buffer = "data: {\"ok\":true}\r\n\r\nrest".to_string();
assert_eq!(
take_sse_block(&mut buffer),
Some("data: {\"ok\":true}".to_string())
);
assert_eq!(buffer, "rest");
}
// ------------------------------------------------------------------
// append_utf8_safe tests
// ------------------------------------------------------------------
+2 -2
View File
@@ -7,7 +7,7 @@ use serde_json::{json, Value};
///
/// 三路径分发:
/// - skip: haiku 模型直接跳过
/// - adaptive: opus-4-6 / sonnet-4-6 使用 adaptive thinking
/// - adaptive: opus-4-7 / opus-4-6 / sonnet-4-6 使用 adaptive thinking
/// - legacy: 其他模型注入 enabled thinking + budget_tokens
pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
if !config.thinking_optimizer {
@@ -24,7 +24,7 @@ pub fn optimize(body: &mut Value, config: &OptimizerConfig) {
return;
}
if model.contains("opus-4-6") || model.contains("sonnet-4-6") {
if model.contains("opus-4-7") || model.contains("opus-4-6") || model.contains("sonnet-4-6") {
log::info!("[OPT] thinking: adaptive({model})");
body["thinking"] = json!({"type": "adaptive"});
body["output_config"] = json!({"effort": "max"});
+27
View File
@@ -52,6 +52,14 @@ pub fn should_rectify_thinking_signature(
return true;
}
// 场景1b: Gemini/第三方渠道返回 "Thought signature is not valid"
// 错误示例: "Unable to submit request because Thought signature is not valid"
if lower.contains("thought signature")
&& (lower.contains("not valid") || lower.contains("invalid"))
{
return true;
}
// 场景2: assistant 消息必须以 thinking block 开头
// 错误示例: "must start with a thinking block"
if lower.contains("must start with a thinking block") {
@@ -280,6 +288,16 @@ mod tests {
));
}
#[test]
fn test_detect_invalid_thought_signature_message() {
assert!(should_rectify_thinking_signature(
Some(
"Unable to submit request because Thought signature is not valid.. Learn more: https://example.com/help"
),
&enabled_config()
));
}
#[test]
fn test_detect_invalid_signature_nested_json() {
// 测试嵌套 JSON 格式的错误消息(第三方渠道常见格式)
@@ -290,6 +308,15 @@ mod tests {
));
}
#[test]
fn test_detect_invalid_thought_signature_nested_json() {
let nested_error = r#"{"error":{"message":"Unable to submit request because Thought signature is not valid.. Learn more: https://example.com/help","type":"upstream_error","param":"","code":400}}"#;
assert!(should_rectify_thinking_signature(
Some(nested_error),
&enabled_config()
));
}
#[test]
fn test_detect_thinking_expected() {
assert!(should_rectify_thinking_signature(
+9 -2
View File
@@ -298,9 +298,15 @@ pub struct CopilotOptimizerConfig {
/// Warmup 小模型降级(默认开启 — 与参考实现对齐,避免探针请求消耗 premium quota
#[serde(default = "default_true")]
pub warmup_downgrade: bool,
/// Warmup 降级使用的模型(默认 "gpt-4o-mini"
/// Warmup 降级使用的模型(默认 "gpt-5-mini"
#[serde(default = "default_warmup_model")]
pub warmup_model: String,
/// 请求前主动剥离 assistant 消息里的 thinking / redacted_thinking block
///
/// Copilot 走 OpenAI 兼容端点,thinking block 会被上游拒绝并触发 rectifier 反应式
/// 重试,那时第一次请求已经消耗了一次 premium quota。主动剥离避免这次浪费。
#[serde(default = "default_true")]
pub strip_thinking: bool,
}
fn default_warmup_model() -> String {
@@ -317,7 +323,8 @@ impl Default for CopilotOptimizerConfig {
deterministic_request_id: true,
subagent_detection: true,
warmup_downgrade: true,
warmup_model: "gpt-4o-mini".to_string(),
warmup_model: "gpt-5-mini".to_string(),
strip_thinking: true,
}
}
}
+3
View File
@@ -130,6 +130,9 @@ impl ConfigService {
// OpenClaw uses additive mode, no live sync needed
// OpenClaw providers are managed directly in the config file
}
AppType::Hermes => {
// Hermes uses additive mode, no live sync needed
}
}
Ok(())
+47
View File
@@ -40,6 +40,9 @@ impl McpService {
if prev_apps.opencode && !server.apps.opencode {
Self::remove_server_from_app(state, &server.id, &AppType::OpenCode)?;
}
if prev_apps.hermes && !server.apps.hermes {
Self::remove_server_from_app(state, &server.id, &AppType::Hermes)?;
}
// 同步到各个启用的应用
Self::sync_server_to_apps(state, &server)?;
@@ -128,6 +131,9 @@ impl McpService {
// Skip for now
log::debug!("OpenClaw MCP support is still in development, skipping sync");
}
AppType::Hermes => {
mcp::sync_single_server_to_hermes(&Default::default(), &server.id, &server.server)?;
}
}
Ok(())
}
@@ -157,6 +163,9 @@ impl McpService {
// OpenClaw MCP support is still in development
log::debug!("OpenClaw MCP support is still in development, skipping remove");
}
AppType::Hermes => {
mcp::remove_server_from_hermes(id)?;
}
}
Ok(())
}
@@ -381,4 +390,42 @@ impl McpService {
Ok(new_count)
}
/// 从 Hermes 导入 MCP
pub fn import_from_hermes(state: &AppState) -> Result<usize, AppError> {
// 创建临时 MultiAppConfig 用于导入
let mut temp_config = crate::app_config::MultiAppConfig::default();
// 调用导入逻辑(从 mcp/hermes.rs
let count = crate::mcp::import_from_hermes(&mut temp_config)?;
let mut new_count = 0;
// 如果有导入的服务器,保存到数据库
if count > 0 {
if let Some(servers) = &temp_config.mcp.servers {
let mut existing = state.db.get_all_mcp_servers()?;
for server in servers.values() {
// 已存在:仅启用 Hermes,不覆盖其他字段(与导入模块语义保持一致)
let to_save = if let Some(existing_server) = existing.get(&server.id) {
let mut merged = existing_server.clone();
merged.apps.hermes = true;
merged
} else {
// 真正的新服务器
new_count += 1;
server.clone()
};
state.db.save_mcp_server(&to_save)?;
existing.insert(to_save.id.clone(), to_save.clone());
// 同步到对应应用 live 配置
Self::sync_server_to_apps(state, &to_save)?;
}
}
}
Ok(new_count)
}
}
+2
View File
@@ -16,6 +16,7 @@ pub mod skill;
pub mod speedtest;
pub mod stream_check;
pub mod subscription;
pub mod usage_cache;
pub mod usage_stats;
pub mod webdav;
pub mod webdav_auto_sync;
@@ -30,6 +31,7 @@ pub use proxy::ProxyService;
#[allow(unused_imports)]
pub use skill::{DiscoverableSkill, Skill, SkillRepo, SkillService};
pub use speedtest::{EndpointLatency, SpeedtestService};
pub use usage_cache::UsageCache;
#[allow(unused_imports)]
pub use usage_stats::{
DailyStats, LogFilters, ModelStats, PaginatedLogs, ProviderLimitStatus, ProviderStats,
+1 -1
View File
@@ -27,7 +27,7 @@ pub fn get_custom_endpoints(
}
let mut result: Vec<_> = meta.custom_endpoints.values().cloned().collect();
result.sort_by(|a, b| b.added_at.cmp(&a.added_at));
result.sort_by_key(|ep| std::cmp::Reverse(ep.added_at));
Ok(result)
}
+92 -5
View File
@@ -42,6 +42,8 @@ pub(crate) fn provider_exists_in_live_config(
.map(|providers| providers.contains_key(provider_id)),
AppType::OpenClaw => crate::openclaw_config::get_providers()
.map(|providers| providers.contains_key(provider_id)),
AppType::Hermes => crate::hermes_config::get_providers()
.map(|providers| providers.contains_key(provider_id)),
_ => Ok(false),
}
}
@@ -345,7 +347,7 @@ fn settings_contain_common_config(app_type: &AppType, settings: &Value, snippet:
}
_ => false,
},
AppType::OpenCode | AppType::OpenClaw => false,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => false,
}
}
@@ -415,7 +417,7 @@ pub(crate) fn remove_common_config_from_settings(
}
Ok(result)
}
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
}
}
@@ -470,7 +472,7 @@ fn apply_common_config_to_settings(
}
Ok(result)
}
AppType::OpenCode | AppType::OpenClaw => Ok(settings.clone()),
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => Ok(settings.clone()),
}
}
@@ -790,6 +792,10 @@ pub(crate) fn write_live_snapshot(app_type: &AppType, provider: &Provider) -> Re
}
}
}
AppType::Hermes => {
crate::hermes_config::set_provider(&provider.id, provider.settings_config.clone())?;
log::debug!("Hermes provider '{}' written to live config", provider.id);
}
}
Ok(())
}
@@ -985,6 +991,19 @@ pub fn read_live_settings(app_type: AppType) -> Result<Value, AppError> {
let config = read_openclaw_config()?;
Ok(config)
}
AppType::Hermes => {
let config_path = crate::hermes_config::get_hermes_config_path();
if !config_path.exists() {
return Err(AppError::localized(
"hermes.config.missing",
"Hermes 配置文件不存在",
"Hermes configuration file not found",
));
}
let yaml_config = crate::hermes_config::read_hermes_config()?;
let config = crate::hermes_config::yaml_to_json(&yaml_config)?;
Ok(config)
}
}
}
@@ -1067,8 +1086,8 @@ pub fn import_default_config(state: &AppState, app_type: AppType) -> Result<bool
"config": config_obj
})
}
// OpenCode and OpenClaw use additive mode and are handled by early return above
AppType::OpenCode | AppType::OpenClaw => {
// OpenCode, OpenClaw and Hermes use additive mode and are handled by early return above
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
unreachable!("additive mode apps are handled by early return")
}
};
@@ -1316,6 +1335,74 @@ pub fn import_openclaw_providers_from_live(state: &AppState) -> Result<usize, Ap
Ok(imported)
}
/// Import all providers from Hermes live config to database
///
/// This imports existing providers from ~/.hermes/config.yaml
/// into the CC Switch database. Each provider found will be added to the
/// database with is_current set to false.
pub fn import_hermes_providers_from_live(state: &AppState) -> Result<usize, AppError> {
use crate::hermes_config;
let providers = hermes_config::get_providers()?;
if providers.is_empty() {
return Ok(0);
}
let mut imported = 0;
let existing_ids = state.db.get_provider_ids("hermes")?;
for (name, config) in providers {
// Validate: skip entries with empty name
if name.trim().is_empty() {
log::warn!("Skipping Hermes provider with empty name");
continue;
}
// Skip if already exists in database
if existing_ids.contains(&name) {
log::debug!("Hermes provider '{name}' already exists in database, skipping");
continue;
}
// Create provider
let mut provider = Provider::with_id(name.clone(), name.clone(), config, None);
provider.meta = Some(crate::provider::ProviderMeta {
live_config_managed: Some(true),
..Default::default()
});
// Save to database
if let Err(e) = state.db.save_provider("hermes", &provider) {
log::warn!("Failed to import Hermes provider '{name}': {e}");
continue;
}
imported += 1;
log::info!("Imported Hermes provider '{name}' from live config");
}
Ok(imported)
}
/// Remove a Hermes provider from live config
///
/// This removes a specific provider from ~/.hermes/config.yaml
/// without affecting other providers in the file.
pub fn remove_hermes_provider_from_live(provider_id: &str) -> Result<(), AppError> {
use crate::hermes_config;
// Check if Hermes config directory exists
if !hermes_config::get_hermes_dir().exists() {
log::debug!("Hermes config directory doesn't exist, skipping removal of '{provider_id}'");
return Ok(());
}
hermes_config::remove_provider(provider_id)?;
log::info!("Hermes provider '{provider_id}' removed from live config");
Ok(())
}
/// Remove an OpenClaw provider from live config
///
/// This removes a specific provider from ~/.openclaw/openclaw.json
+43 -6
View File
@@ -21,7 +21,7 @@ use crate::store::AppState;
// Re-export sub-module functions for external access
pub use live::{
import_default_config, import_openclaw_providers_from_live,
import_default_config, import_hermes_providers_from_live, import_openclaw_providers_from_live,
import_opencode_providers_from_live, read_live_settings, sync_current_to_live,
};
@@ -35,7 +35,8 @@ pub(crate) use live::{
// Internal re-exports
use live::{
remove_openclaw_provider_from_live, remove_opencode_provider_from_live, write_gemini_live,
remove_hermes_provider_from_live, remove_openclaw_provider_from_live,
remove_opencode_provider_from_live, write_gemini_live,
};
use usage::validate_usage_script;
@@ -1282,6 +1283,7 @@ impl ProviderService {
match app_type {
AppType::OpenCode => remove_opencode_provider_from_live(id)?,
AppType::OpenClaw => remove_openclaw_provider_from_live(id)?,
AppType::Hermes => remove_hermes_provider_from_live(id)?,
_ => {}
}
}
@@ -1344,6 +1346,9 @@ impl ProviderService {
AppType::OpenClaw => {
remove_openclaw_provider_from_live(id)?;
}
AppType::Hermes => {
remove_hermes_provider_from_live(id)?;
}
_ => {
return Err(AppError::Message(format!(
"App {} does not support remove from live config",
@@ -1518,6 +1523,25 @@ impl ProviderService {
// Sync to live (write_gemini_live handles security flag internally for Gemini)
write_live_with_common_config(state.db.as_ref(), &app_type, provider)?;
// Hermes is additive, so "switching" doesn't overwrite a live config file
// — we instead update the top-level `model:` section to point at this
// provider's first declared model. Without this, clicking "switch" would
// only shuffle entries in custom_providers[] while Hermes keeps using
// whatever `model.provider` was set before.
if matches!(app_type, AppType::Hermes) {
if let Err(e) =
crate::hermes_config::apply_switch_defaults(&provider.id, &provider.settings_config)
{
log::warn!(
"Failed to update Hermes model defaults after switching to '{}': {e}",
provider.id
);
result
.warnings
.push(format!("hermes_model_defaults_failed:{}", provider.id));
}
}
// For additive-mode providers that were DB-only (live_config_managed == Some(false)),
// flip the flag to true now that the provider has been successfully written to the live
// file. This ensures sync_all_providers_to_live() will include it on future syncs.
@@ -1532,6 +1556,7 @@ impl ProviderService {
let rollback_result = match app_type {
AppType::OpenCode => remove_opencode_provider_from_live(&provider.id),
AppType::OpenClaw => remove_openclaw_provider_from_live(&provider.id),
AppType::Hermes => remove_hermes_provider_from_live(&provider.id),
_ => Ok(()),
};
@@ -1708,6 +1733,7 @@ impl ProviderService {
AppType::Gemini => Self::extract_gemini_common_config(&provider.settings_config),
AppType::OpenCode => Self::extract_opencode_common_config(&provider.settings_config),
AppType::OpenClaw => Self::extract_openclaw_common_config(&provider.settings_config),
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
}
}
@@ -1722,6 +1748,7 @@ impl ProviderService {
AppType::Gemini => Self::extract_gemini_common_config(settings_config),
AppType::OpenCode => Self::extract_opencode_common_config(settings_config),
AppType::OpenClaw => Self::extract_openclaw_common_config(settings_config),
AppType::Hermes => Ok(String::new()), // Hermes doesn't use common config snippets
}
}
@@ -1734,9 +1761,9 @@ impl ProviderService {
// Auth
"ANTHROPIC_API_KEY",
"ANTHROPIC_AUTH_TOKEN",
// Models (5 fields)
// Models (4 fields + 1 legacy)
"ANTHROPIC_MODEL",
"ANTHROPIC_REASONING_MODEL",
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
@@ -2087,6 +2114,16 @@ impl ProviderService {
));
}
}
AppType::Hermes => {
// Hermes: accept any JSON object for now
if !provider.settings_config.is_object() {
return Err(AppError::localized(
"provider.hermes.settings.not_object",
"Hermes 配置必须是 JSON 对象",
"Hermes configuration must be a JSON object",
));
}
}
}
// Validate and clean UsageScript configuration (common for all app types)
@@ -2258,8 +2295,8 @@ impl ProviderService {
Ok((api_key, base_url))
}
AppType::OpenClaw => {
// OpenClaw uses apiKey and baseUrl directly on the object
AppType::OpenClaw | AppType::Hermes => {
// OpenClaw/Hermes use apiKey and baseUrl directly on the object
let api_key = provider
.settings_config
.get("apiKey")
+24 -57
View File
@@ -27,7 +27,7 @@ const PROXY_TOKEN_PLACEHOLDER: &str = "PROXY_MANAGED";
/// Claude Code 会继续以旧模型名发起请求,导致新供应商不支持时失败。
const CLAUDE_MODEL_OVERRIDE_ENV_KEYS: [&str; 6] = [
"ANTHROPIC_MODEL",
"ANTHROPIC_REASONING_MODEL",
"ANTHROPIC_REASONING_MODEL", // legacy: 已废弃,但旧配置可能残留
"ANTHROPIC_DEFAULT_HAIKU_MODEL",
"ANTHROPIC_DEFAULT_SONNET_MODEL",
"ANTHROPIC_DEFAULT_OPUS_MODEL",
@@ -466,13 +466,9 @@ impl ProxyService {
AppType::Claude => self.read_claude_live()?,
AppType::Codex => self.read_codex_live()?,
AppType::Gemini => self.read_gemini_live()?,
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
}
};
@@ -687,11 +683,8 @@ impl ProxyService {
}
}
}
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
}
}
@@ -871,13 +864,9 @@ impl ProxyService {
AppType::Claude => ("claude", self.read_claude_live()?),
AppType::Codex => ("codex", self.read_codex_live()?),
AppType::Gemini => ("gemini", self.read_gemini_live()?),
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
}
};
@@ -1019,13 +1008,9 @@ impl ProxyService {
self.write_gemini_live(&live_config)?;
log::info!("Gemini Live 配置已接管,代理地址: {proxy_url}");
}
AppType::OpenCode => {
// OpenCode doesn't support proxy features
return Err("OpenCode 不支持代理功能".to_string());
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
return Err("OpenClaw 不支持代理功能".to_string());
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
return Err("该应用不支持代理功能".to_string());
}
}
@@ -1076,11 +1061,8 @@ impl ProxyService {
let _ = self.write_gemini_live(&live_config);
}
}
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
}
}
@@ -1119,11 +1101,8 @@ impl ProxyService {
log::info!("Gemini Live 配置已恢复");
}
}
AppType::OpenCode => {
// OpenCode doesn't support proxy features, skip silently
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features, skip silently
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features, skip silently
}
}
@@ -1213,13 +1192,9 @@ impl ProxyService {
AppType::Claude => self.write_claude_live(config),
AppType::Codex => self.write_codex_live(config),
AppType::Gemini => self.write_gemini_live(config),
AppType::OpenCode => {
// OpenCode doesn't support proxy features
Err("OpenCode 不支持代理功能".to_string())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
Err("OpenClaw 不支持代理功能".to_string())
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
Err("该应用不支持代理功能".to_string())
}
}
}
@@ -1238,12 +1213,8 @@ impl ProxyService {
Ok(config) => Self::is_gemini_live_taken_over(&config),
Err(_) => false,
},
AppType::OpenCode => {
// OpenCode doesn't support proxy takeover
false
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy takeover
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy takeover
false
}
}
@@ -1285,12 +1256,8 @@ impl ProxyService {
AppType::Claude => self.cleanup_claude_takeover_placeholders_in_live(),
AppType::Codex => self.cleanup_codex_takeover_placeholders_in_live(),
AppType::Gemini => self.cleanup_gemini_takeover_placeholders_in_live(),
AppType::OpenCode => {
// OpenCode doesn't support proxy features
Ok(())
}
AppType::OpenClaw => {
// OpenClaw doesn't support proxy features
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// These apps don't support proxy features
Ok(())
}
}
@@ -1540,7 +1507,7 @@ impl ProxyService {
serde_json::to_string(&env_backup)
.map_err(|e| format!("序列化 Gemini 配置失败: {e}"))?
}
AppType::OpenCode | AppType::OpenClaw => {
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
return Err(format!("未知的应用类型: {app_type}"));
}
};
+10 -12
View File
@@ -297,18 +297,16 @@ fn sync_single_codex_file(db: &Database, file_path: &Path) -> Result<(u32, u32),
};
match event_type {
"session_meta" => {
if state.session_id.is_none() {
let payload = value.get("payload");
state.session_id = payload
.and_then(|p| {
p.get("session_id")
.or_else(|| p.get("sessionId"))
.or_else(|| p.get("id"))
})
.and_then(|v| v.as_str())
.map(|s| s.to_string());
}
"session_meta" if state.session_id.is_none() => {
let payload = value.get("payload");
state.session_id = payload
.and_then(|p| {
p.get("session_id")
.or_else(|| p.get("sessionId"))
.or_else(|| p.get("id"))
})
.and_then(|v| v.as_str())
.map(|s| s.to_string());
}
"turn_context" => {
if let Some(payload) = value.get("payload") {
+129 -45
View File
@@ -529,6 +529,11 @@ impl SkillService {
return Ok(custom.join("skills"));
}
}
AppType::Hermes => {
if let Some(custom) = crate::settings::get_hermes_override_dir() {
return Ok(custom.join("skills"));
}
}
}
// 默认路径:回退到用户主目录下的标准位置
@@ -544,6 +549,7 @@ impl SkillService {
AppType::Gemini => home.join(".gemini").join("skills"),
AppType::OpenCode => home.join(".config").join("opencode").join("skills"),
AppType::OpenClaw => home.join(".openclaw").join("skills"),
AppType::Hermes => crate::hermes_config::get_hermes_dir().join("skills"),
})
}
@@ -666,36 +672,16 @@ impl SkillService {
repo_branch = used_branch;
// 复制到 SSOT
let mut source = temp_dir.join(&source_rel);
if !source.exists() {
// 回退:在 temp_dir 中递归查找名称匹配的目录(含 SKILL.md)
let target_name = source_rel
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default();
if let Some(found) = Self::find_skill_dir_by_name(&temp_dir, &target_name) {
log::info!(
"Skill directory '{}' not found at direct path, using fallback: {}",
target_name,
found.display()
);
source = found;
} else if temp_dir.join("SKILL.md").exists() {
// 根级 Skill:仓库本身就是 skillSKILL.md 直接在解压根目录
log::info!(
"Skill directory '{}' not found, but SKILL.md exists at root, using temp_dir",
target_name,
);
source = temp_dir.clone();
} else {
let source =
Self::resolve_skill_source_dir(&temp_dir, &skill.directory).ok_or_else(|| {
let missing = temp_dir.join(&source_rel).display().to_string();
let _ = fs::remove_dir_all(&temp_dir);
return Err(anyhow!(format_skill_error(
anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &source.display().to_string())],
&[("path", &missing)],
Some("checkRepoUrl"),
)));
}
}
))
})?;
let canonical_temp = temp_dir.canonicalize().unwrap_or_else(|_| temp_dir.clone());
let canonical_source = source.canonicalize().map_err(|_| {
@@ -948,14 +934,13 @@ impl SkillService {
});
let remote_skill_dir = match remote_match {
Some(rs) => temp_dir.join(&rs.directory),
Some(rs) => match Self::resolve_skill_source_dir(&temp_dir, &rs.directory) {
Some(path) => path,
None => continue,
},
None => continue,
};
if !remote_skill_dir.exists() {
continue;
}
let remote_hash = match Self::compute_dir_hash(&remote_skill_dir) {
Ok(h) => h,
Err(e) => {
@@ -1059,15 +1044,16 @@ impl SkillService {
))
})?;
let source = temp_dir.join(&remote_match.directory);
if !source.exists() {
let _ = fs::remove_dir_all(&temp_dir);
return Err(anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &source.display().to_string())],
Some("checkRepoUrl"),
)));
}
let source = Self::resolve_skill_source_dir(&temp_dir, &remote_match.directory)
.ok_or_else(|| {
let missing = temp_dir.join(&remote_match.directory).display().to_string();
let _ = fs::remove_dir_all(&temp_dir);
anyhow!(format_skill_error(
"SKILL_DIR_NOT_FOUND",
&[("path", &missing)],
Some("checkRepoUrl"),
))
})?;
// 备份旧文件
let _ = Self::create_uninstall_backup(&skill);
@@ -1268,7 +1254,7 @@ impl SkillService {
}
}
entries.sort_by(|a, b| b.created_at.cmp(&a.created_at));
entries.sort_by_key(|entry| std::cmp::Reverse(entry.created_at));
Ok(entries)
}
@@ -1549,6 +1535,20 @@ impl SkillService {
// 保存到数据库
db.save_skill(&skill)?;
// 同步到已启用的应用目录(创建 symlink 或复制文件)
for app in AppType::all() {
if skill.apps.is_enabled_for(&app) {
if let Err(e) = Self::sync_to_app_dir(&skill.directory, &app) {
log::warn!(
"导入后同步 Skill '{}' 到 {:?} 失败: {e:#}",
skill.directory,
app
);
}
}
}
imported.push(skill);
}
@@ -1772,7 +1772,7 @@ impl SkillService {
let results: Vec<Result<Vec<DiscoverableSkill>>> =
futures::future::join_all(fetch_tasks).await;
for (repo, result) in enabled_repos.into_iter().zip(results.into_iter()) {
for (repo, result) in enabled_repos.into_iter().zip(results) {
match result {
Ok(repo_skills) => skills.extend(repo_skills),
Err(e) => log::warn!("获取仓库 {}/{} 技能失败: {}", repo.owner, repo.name, e),
@@ -1781,7 +1781,7 @@ impl SkillService {
// 去重并排序
Self::deduplicate_discoverable_skills(&mut skills);
skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
skills.sort_by_key(|skill| skill.name.to_lowercase());
Ok(skills)
}
@@ -1848,7 +1848,7 @@ impl SkillService {
}
}
skills.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
skills.sort_by_key(|skill| skill.name.to_lowercase());
Ok(skills)
}
@@ -2088,6 +2088,40 @@ impl SkillService {
walk(root, target_name, 0)
}
/// 将 discoverable skill 的目录信息重新解析为解压目录中的真实源目录。
///
/// 兼容三种情况:
/// 1. `skills/foo` 这类直接相对路径;
/// 2. 仅持有安装名 `foo`,需要在仓库中递归查找真实目录;
/// 3. 仓库根目录本身就是 skill,此时回退到解压根目录。
fn resolve_skill_source_dir(root: &Path, raw_directory: &str) -> Option<PathBuf> {
let source_rel = Self::sanitize_skill_source_path(raw_directory)?;
let direct = root.join(&source_rel);
if direct.is_dir() {
return Some(direct);
}
let target_name = source_rel.file_name()?.to_string_lossy().to_string();
if let Some(found) = Self::find_skill_dir_by_name(root, &target_name) {
log::info!(
"Skill directory '{}' not found at direct path, using fallback: {}",
target_name,
found.display()
);
return Some(found);
}
if root.is_dir() && root.join("SKILL.md").exists() {
log::info!(
"Skill directory '{}' not found, but SKILL.md exists at root, using repo root",
target_name,
);
return Some(root.to_path_buf());
}
None
}
/// 去重技能列表(基于完整 key,不同仓库的同名 skill 分开显示)
fn deduplicate_discoverable_skills(skills: &mut Vec<DiscoverableSkill>) {
let mut seen = HashMap::new();
@@ -2955,3 +2989,53 @@ pub fn migrate_skills_to_ssot(db: &Arc<Database>) -> Result<usize> {
Ok(count)
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
fn write_skill(dir: &Path, name: &str) {
fs::create_dir_all(dir).expect("create skill dir");
fs::write(
dir.join("SKILL.md"),
format!("---\nname: {name}\ndescription: Test skill\n---\n"),
)
.expect("write SKILL.md");
}
#[test]
fn resolve_skill_source_dir_returns_repo_root_for_root_level_skill() {
let temp = tempdir().expect("tempdir");
write_skill(temp.path(), "Root Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "last30days-skill-cn")
.expect("root-level skill should resolve to the extracted repo root");
assert_eq!(resolved, temp.path());
}
#[test]
fn resolve_skill_source_dir_returns_direct_nested_directory_when_present() {
let temp = tempdir().expect("tempdir");
let nested = temp.path().join("skills").join("nested-skill");
write_skill(&nested, "Nested Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "skills/nested-skill")
.expect("nested skill should resolve from its relative source path");
assert_eq!(resolved, nested);
}
#[test]
fn resolve_skill_source_dir_falls_back_to_matching_install_name() {
let temp = tempdir().expect("tempdir");
let nested = temp.path().join("skills").join("nested-skill");
write_skill(&nested, "Nested Skill");
let resolved = SkillService::resolve_skill_source_dir(temp.path(), "nested-skill")
.expect("install name should fall back to the matching discovered skill directory");
assert_eq!(resolved, nested);
}
}
+269 -31
View File
@@ -3,7 +3,6 @@
//! 使用流式 API 进行快速健康检查,只需接收首个 chunk 即判定成功。
use futures::StreamExt;
use regex::Regex;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -12,8 +11,10 @@ use std::time::Instant;
use crate::app_config::AppType;
use crate::error::AppError;
use crate::provider::Provider;
use crate::proxy::gemini_url::{normalize_gemini_model_id, resolve_gemini_native_url};
use crate::proxy::providers::copilot_auth;
use crate::proxy::providers::transform::anthropic_to_openai;
use crate::proxy::providers::transform_gemini::anthropic_to_gemini;
use crate::proxy::providers::transform_responses::anthropic_to_responses;
use crate::proxy::providers::{get_adapter, AuthInfo, AuthStrategy};
@@ -205,7 +206,10 @@ impl StreamCheckService {
// OpenCode / OpenClaw 的 settings_config 结构与 Claude/Codex/Gemini 不同
// baseUrl / apiKey 直接作为根字段而非嵌套在 env),并且协议由 `api`
// 或 `npm` 字段显式指定。它们不走 get_adapter 路径,而是直接分发。
if matches!(app_type, AppType::OpenCode | AppType::OpenClaw) {
if matches!(
app_type,
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes
) {
return Self::check_once_without_adapter(app_type, provider, config, start).await;
}
@@ -268,9 +272,9 @@ impl StreamCheckService {
)
.await
}
AppType::OpenCode | AppType::OpenClaw => {
AppType::OpenCode | AppType::OpenClaw | AppType::Hermes => {
// Already handled via early dispatch above
unreachable!("OpenCode/OpenClaw 已通过 check_once_without_adapter 处理")
unreachable!("OpenCode/OpenClaw/Hermes 已通过 check_once_without_adapter 处理")
}
};
@@ -288,6 +292,8 @@ impl StreamCheckService {
/// 根据供应商的 api_format 选择请求格式:
/// - "anthropic" (默认): Anthropic Messages API (/v1/messages)
/// - "openai_chat": OpenAI Chat Completions API (/v1/chat/completions)
/// - "openai_responses": OpenAI Responses API (/v1/responses)
/// - "gemini_native": Gemini Native streamGenerateContent
///
/// `extra_headers` 是一个可选的供应商级自定义 header 集合(从 OpenClaw
/// 的 `settings_config.headers` 或 OpenCode 的 `settings_config.options.headers`
@@ -329,8 +335,14 @@ impl StreamCheckService {
.unwrap_or(false);
let is_openai_chat = effective_api_format == "openai_chat";
let is_openai_responses = effective_api_format == "openai_responses";
let url =
Self::resolve_claude_stream_url(base, auth.strategy, effective_api_format, is_full_url);
let is_gemini_native = effective_api_format == "gemini_native";
let url = Self::resolve_claude_stream_url(
base,
auth.strategy,
effective_api_format,
is_full_url,
model,
);
let max_tokens = if is_openai_responses { 16 } else { 1 };
@@ -343,14 +355,19 @@ impl StreamCheckService {
});
// Codex OAuth (ChatGPT Plus/Pro 反代) 需要 store:false + include 标记,
// 否则 Stream Check 会和生产路径一样被服务端 400 拒绝。
let is_codex_oauth = provider
.meta
.as_ref()
.and_then(|m| m.provider_type.as_deref())
== Some("codex_oauth");
let is_codex_oauth = provider.is_codex_oauth();
let codex_fast_mode = provider.codex_fast_mode_enabled();
let body = if is_openai_responses {
anthropic_to_responses(anthropic_body, Some(&provider.id), is_codex_oauth)
anthropic_to_responses(
anthropic_body,
Some(&provider.id),
is_codex_oauth,
codex_fast_mode,
)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
} else if is_gemini_native {
anthropic_to_gemini(anthropic_body)
.map_err(|e| AppError::Message(format!("Failed to build test request: {e}")))?
} else if is_openai_chat {
anthropic_to_openai(anthropic_body)
@@ -387,6 +404,23 @@ impl StreamCheckService {
.header("x-vscode-user-agent-library-version", "electron-fetch")
.header("x-request-id", &request_id)
.header("x-agent-task-id", &request_id);
} else if is_gemini_native {
request_builder = match auth.strategy {
AuthStrategy::GoogleOAuth => {
let token = auth.access_token.as_ref().unwrap_or(&auth.api_key);
request_builder
.header("authorization", format!("Bearer {token}"))
.header("x-goog-api-client", "GeminiCLI/1.0")
.header("content-type", "application/json")
.header("accept", "text/event-stream")
.header("accept-encoding", "identity")
}
_ => request_builder
.header("x-goog-api-key", &auth.api_key)
.header("content-type", "application/json")
.header("accept", "text/event-stream")
.header("accept-encoding", "identity"),
};
} else if is_openai_chat || is_openai_responses {
// OpenAI-compatible targets: Bearer auth + SSE headers only
request_builder = request_builder
@@ -568,13 +602,16 @@ impl StreamCheckService {
extra_headers: Option<&serde_json::Map<String, serde_json::Value>>,
) -> Result<(u16, String), AppError> {
let base = base_url.trim_end_matches('/');
// Strip `models/` resource-name prefix from the model id — see
// `normalize_gemini_model_id` for rationale.
let normalized_model = normalize_gemini_model_id(model);
// Gemini 原生 API: /v1beta/models/{model}:streamGenerateContent?alt=sse
// 智能处理 /v1beta 路径:如果 base_url 不包含版本路径,则添加 /v1beta
// alt=sse 参数使 API 返回 SSE 格式(text/event-stream)而非 JSON 数组
let url = if base.contains("/v1beta") || base.contains("/v1/") {
format!("{base}/models/{model}:streamGenerateContent?alt=sse")
format!("{base}/models/{normalized_model}:streamGenerateContent?alt=sse")
} else {
format!("{base}/v1beta/models/{model}:streamGenerateContent?alt=sse")
format!("{base}/v1beta/models/{normalized_model}:streamGenerateContent?alt=sse")
};
// Gemini 原生请求体格式
@@ -648,7 +685,7 @@ impl StreamCheckService {
let result = match app_type {
AppType::OpenClaw => {
Self::check_openclaw_stream(
Self::check_additive_app_stream(
&client,
provider,
&model_to_test,
@@ -667,7 +704,17 @@ impl StreamCheckService {
)
.await
}
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw"),
AppType::Hermes => {
Self::check_hermes_stream(
&client,
provider,
&model_to_test,
test_prompt,
request_timeout,
)
.await
}
_ => unreachable!("check_once_without_adapter 只处理 OpenCode/OpenClaw/Hermes"),
};
let response_time = start.elapsed().as_millis() as u64;
@@ -772,7 +819,7 @@ impl StreamCheckService {
/// - `anthropic-messages` → check_claude_stream + api_format="anthropic" (ClaudeAuth 策略)
/// - `google-generative-ai` → check_gemini_stream (Google API Key 策略)
/// - `bedrock-converse-stream` → 不支持(需要 AWS SigV4 签名)
async fn check_openclaw_stream(
async fn check_additive_app_stream(
client: &Client,
provider: &Provider,
model: &str,
@@ -782,7 +829,7 @@ impl StreamCheckService {
// 自定义认证头(如 Longcat 的 `apikey` 头)不走标准 Bearer
// 具体头名由 OpenClaw 网关内部决定,cc-switch 无法准确构造,
// 因此直接返回友好错误而不是让用户看到一个误导性的 401。
if Self::openclaw_uses_auth_header(provider) {
if Self::additive_app_uses_auth_header(provider) {
return Err(AppError::localized(
"openclaw_auth_header_not_supported",
"该供应商使用自定义认证头,暂不支持流式健康检查。建议直接通过 OpenClaw 测试。",
@@ -875,8 +922,8 @@ impl StreamCheckService {
}
}
/// 判断 OpenClaw 供应商是否使用自定义认证头(`authHeader: true`
fn openclaw_uses_auth_header(provider: &Provider) -> bool {
/// 判断 additive-mode 供应商是否使用自定义认证头(`authHeader: true`
fn additive_app_uses_auth_header(provider: &Provider) -> bool {
provider
.settings_config
.get("authHeader")
@@ -936,6 +983,112 @@ impl StreamCheckService {
.filter(|s| !s.is_empty())
}
// Hermes 的 settings_config 用 snake_casebase_url / api_key / api_mode),
// 与 OpenClaw 的 camelCasebaseUrl / apiKey / api)是两套独立命名。
// 见 src/config/hermesProviderPresets.ts 的 HermesProviderSettingsConfig。
fn extract_hermes_base_url(provider: &Provider) -> Result<String, AppError> {
provider
.settings_config
.get("base_url")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
AppError::localized(
"hermes_base_url_missing",
"Hermes 供应商缺少 base_url",
"Hermes provider is missing `base_url`",
)
})
}
fn extract_hermes_api_key(provider: &Provider) -> Result<String, AppError> {
provider
.settings_config
.get("api_key")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.ok_or_else(|| {
AppError::localized(
"hermes_api_key_missing",
"Hermes 供应商缺少 api_key",
"Hermes provider is missing `api_key`",
)
})
}
fn extract_hermes_api_mode(provider: &Provider) -> Option<String> {
provider
.settings_config
.get("api_mode")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Hermes 流式检查分发器
///
/// Hermes 以 `api_mode` 字段显式指定协议,取值来自
/// `HermesApiMode`hermesProviderPresets.ts):
/// - `chat_completions` → check_claude_stream + api_format="openai_chat"Bearer
/// - `anthropic_messages` → check_claude_stream + api_format="anthropic"ClaudeAuth,与 OpenClaw 的 anthropic-messages 同策略)
/// - `codex_responses` → check_claude_stream + api_format="openai_responses"Bearer
/// - `bedrock_converse` → 不支持(需要 AWS SigV4 签名)
async fn check_hermes_stream(
client: &Client,
provider: &Provider,
model: &str,
test_prompt: &str,
timeout: std::time::Duration,
) -> Result<(u16, String), AppError> {
// 先把 api_mode 路由出协议格式与认证策略。
// 纯错误路径(bedrock / 未知 / 缺失)直接 return,避免在用户
// 选了 bedrock_converse 时被"缺 base_url"的二级错误盖住真正原因。
let (api_format, auth_strategy) = match Self::extract_hermes_api_mode(provider).as_deref() {
Some("chat_completions") => ("openai_chat", AuthStrategy::Bearer),
Some("anthropic_messages") => ("anthropic", AuthStrategy::ClaudeAuth),
Some("codex_responses") => ("openai_responses", AuthStrategy::Bearer),
Some("bedrock_converse") => {
return Err(AppError::localized(
"hermes_bedrock_not_supported",
"AWS Bedrock 需要 SigV4 签名,当前不支持健康检查。",
"AWS Bedrock requires SigV4 signing and is not supported by stream health check.",
));
}
Some(other) => {
return Err(AppError::localized(
"hermes_protocol_not_yet_supported",
format!("Hermes 暂不支持协议: {other}"),
format!("Hermes protocol not yet supported: {other}"),
));
}
None => {
return Err(AppError::localized(
"hermes_api_mode_missing",
"Hermes 供应商缺少 api_mode 字段",
"Hermes provider is missing the `api_mode` field",
));
}
};
let base_url = Self::extract_hermes_base_url(provider)?;
let api_key = Self::extract_hermes_api_key(provider)?;
let auth = AuthInfo::new(api_key, auth_strategy);
Self::check_claude_stream(
client,
&base_url,
&auth,
model,
test_prompt,
timeout,
provider,
Some(api_format),
None,
)
.await
}
/// OpenCode 流式检查分发器
///
/// OpenCode 用 `npm` 字段(AI SDK 包名)隐式指定协议。映射关系参见
@@ -993,7 +1146,7 @@ impl StreamCheckService {
.await
}
Some("@ai-sdk/anthropic") => {
// 见 check_openclaw_stream 对 anthropic-messages 的注释
// 见 check_additive_app_stream 对 anthropic-messages 的处理
// 用 ClaudeAuthBearer-only)兼容中转服务。
let auth = AuthInfo::new(api_key, AuthStrategy::ClaudeAuth);
Self::check_claude_stream(
@@ -1208,8 +1361,8 @@ impl StreamCheckService {
// Try to extract first model from the models object
Self::extract_opencode_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
}
AppType::OpenClaw => {
// OpenClaw uses models array in settings_config
AppType::OpenClaw | AppType::Hermes => {
// OpenClaw/Hermes use models array in settings_config
// Try to extract first model from the models array
Self::extract_openclaw_model(provider).unwrap_or_else(|| "gpt-4o".to_string())
}
@@ -1260,10 +1413,11 @@ impl StreamCheckService {
return None;
}
let re = Regex::new(r#"^model\s*=\s*["']([^"']+)["']"#).ok()?;
re.captures(config_text)
.and_then(|caps| caps.get(1))
.map(|m| m.as_str().trim().to_string())
let table = toml::from_str::<toml::Table>(config_text).ok()?;
table
.get("model")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|value| !value.is_empty())
}
@@ -1292,7 +1446,19 @@ impl StreamCheckService {
auth_strategy: AuthStrategy,
api_format: &str,
is_full_url: bool,
model: &str,
) -> String {
if api_format == "gemini_native" {
// Strip an optional `models/` resource-name prefix so that model
// identifiers copied from Gemini SDK outputs (e.g.
// `models/gemini-2.5-pro`) don't produce a doubled
// `/v1beta/models/models/...` URL.
let normalized_model = normalize_gemini_model_id(model);
let endpoint =
format!("/v1beta/models/{normalized_model}:streamGenerateContent?alt=sse");
return resolve_gemini_native_url(base_url, &endpoint, is_full_url);
}
if is_full_url {
return base_url.to_string();
}
@@ -1361,24 +1527,24 @@ mod tests {
}
#[test]
fn test_openclaw_uses_auth_header_true() {
fn test_additive_app_uses_auth_header_true() {
let p = make_provider(serde_json::json!({
"baseUrl": "https://api.longcat.chat/v1",
"apiKey": "k",
"api": "openai-completions",
"authHeader": true,
}));
assert!(StreamCheckService::openclaw_uses_auth_header(&p));
assert!(StreamCheckService::additive_app_uses_auth_header(&p));
}
#[test]
fn test_openclaw_uses_auth_header_default_false() {
fn test_additive_app_uses_auth_header_default_false() {
let p = make_provider(serde_json::json!({
"baseUrl": "https://api.deepseek.com/v1",
"apiKey": "k",
"api": "openai-completions",
}));
assert!(!StreamCheckService::openclaw_uses_auth_header(&p));
assert!(!StreamCheckService::additive_app_uses_auth_header(&p));
}
#[test]
@@ -1621,6 +1787,7 @@ mod tests {
AuthStrategy::Bearer,
"openai_chat",
true,
"gpt-5.4",
);
assert_eq!(url, "https://relay.example/v1/chat/completions");
@@ -1633,6 +1800,7 @@ mod tests {
AuthStrategy::GitHubCopilot,
"openai_chat",
false,
"gpt-5.4",
);
assert_eq!(url, "https://api.githubcopilot.com/chat/completions");
@@ -1645,6 +1813,7 @@ mod tests {
AuthStrategy::GitHubCopilot,
"openai_responses",
false,
"gpt-5.4",
);
assert_eq!(url, "https://api.githubcopilot.com/v1/responses");
@@ -1657,6 +1826,7 @@ mod tests {
AuthStrategy::Bearer,
"openai_chat",
false,
"gpt-5.4",
);
assert_eq!(url, "https://example.com/v1/chat/completions");
@@ -1669,6 +1839,7 @@ mod tests {
AuthStrategy::Bearer,
"openai_responses",
false,
"gpt-5.4",
);
assert_eq!(url, "https://example.com/v1/responses");
@@ -1681,11 +1852,78 @@ mod tests {
AuthStrategy::Anthropic,
"anthropic",
false,
"claude-sonnet-4-6",
);
assert_eq!(url, "https://api.anthropic.com/v1/messages");
}
#[test]
fn test_resolve_claude_stream_url_for_gemini_native() {
let url = StreamCheckService::resolve_claude_stream_url(
"https://generativelanguage.googleapis.com",
AuthStrategy::Google,
"gemini_native",
false,
"gemini-2.5-flash",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn test_resolve_claude_stream_url_for_gemini_native_full_url_openai_compat_base() {
let url = StreamCheckService::resolve_claude_stream_url(
"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions",
AuthStrategy::Google,
"gemini_native",
true,
"gemini-2.5-flash",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse"
);
}
#[test]
fn test_resolve_claude_stream_url_for_gemini_native_opaque_full_url() {
let url = StreamCheckService::resolve_claude_stream_url(
"https://relay.example/custom/generate-content",
AuthStrategy::Google,
"gemini_native",
true,
"gemini-2.5-flash",
);
assert_eq!(url, "https://relay.example/custom/generate-content?alt=sse");
}
/// Regression: Gemini SDK outputs commonly surface model ids as the
/// resource-name form `models/gemini-2.5-pro`. Interpolating that raw
/// value used to produce `/v1beta/models/models/gemini-2.5-pro:...`
/// which the upstream rejects and the health check records as a
/// false-negative for an otherwise valid provider.
#[test]
fn test_resolve_claude_stream_url_for_gemini_native_strips_models_prefix() {
let url = StreamCheckService::resolve_claude_stream_url(
"https://generativelanguage.googleapis.com",
AuthStrategy::Google,
"gemini_native",
false,
"models/gemini-2.5-pro",
);
assert_eq!(
url,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse"
);
}
#[test]
fn test_resolve_codex_stream_urls_for_full_url_mode() {
let urls = StreamCheckService::resolve_codex_stream_urls(
+25 -11
View File
@@ -291,12 +291,26 @@ struct ApiExtraUsage {
currency: Option<String>,
}
/// 已知的 Claude 用量窗口名称
/// 已知的 Claude 用量窗口名称。`QuotaTier::name` 会是其中之一。
pub const TIER_FIVE_HOUR: &str = "five_hour";
pub const TIER_SEVEN_DAY: &str = "seven_day";
pub const TIER_SEVEN_DAY_OPUS: &str = "seven_day_opus";
pub const TIER_SEVEN_DAY_SONNET: &str = "seven_day_sonnet";
/// Coding PlanKimi / MiniMax)的周窗口 tier 名。与 `coding_plan::query_*`
/// 写入、tray 渲染、commands::provider 扁平化三处共用同一标识。
pub const TIER_WEEKLY_LIMIT: &str = "weekly_limit";
/// Gemini 用量分组名称(按模型而非时间窗口)。`classify_gemini_model` 输出。
pub const TIER_GEMINI_PRO: &str = "gemini_pro";
pub const TIER_GEMINI_FLASH: &str = "gemini_flash";
pub const TIER_GEMINI_FLASH_LITE: &str = "gemini_flash_lite";
const KNOWN_TIERS: &[&str] = &[
"five_hour",
"seven_day",
"seven_day_opus",
"seven_day_sonnet",
TIER_FIVE_HOUR,
TIER_SEVEN_DAY,
TIER_SEVEN_DAY_OPUS,
TIER_SEVEN_DAY_SONNET,
];
/// 查询 Claude 官方订阅额度
@@ -993,11 +1007,11 @@ fn extract_project_id(value: &serde_json::Value) -> Option<String> {
/// 将 Gemini 模型 ID 分类为 Pro / Flash / Flash Lite
fn classify_gemini_model(model_id: &str) -> &str {
if model_id.contains("flash-lite") {
"gemini_flash_lite"
TIER_GEMINI_FLASH_LITE
} else if model_id.contains("flash") {
"gemini_flash"
TIER_GEMINI_FLASH
} else if model_id.contains("pro") {
"gemini_pro"
TIER_GEMINI_PRO
} else {
model_id
}
@@ -1152,9 +1166,9 @@ async fn query_gemini_quota(access_token: &str) -> SubscriptionQuota {
// 转换为 tiersremainingFraction → utilization: 已用百分比)
let sort_order = |name: &str| -> usize {
match name {
"gemini_pro" => 0,
"gemini_flash" => 1,
"gemini_flash_lite" => 2,
TIER_GEMINI_PRO => 0,
TIER_GEMINI_FLASH => 1,
TIER_GEMINI_FLASH_LITE => 2,
_ => 3,
}
};
+143
View File
@@ -0,0 +1,143 @@
//! 托盘展示用的用量缓存(进程内、写穿式)。
//!
//! 各 usage 查询命令成功时写入;系统托盘构建菜单时读取。不持久化,
//! 进程重启即空,由下一次自动查询或托盘悬停触发的刷新重新填充。
use std::collections::HashMap;
use std::sync::RwLock;
use crate::app_config::AppType;
use crate::provider::UsageResult;
use crate::services::subscription::SubscriptionQuota;
#[derive(Default)]
pub struct UsageCache {
subscription: RwLock<HashMap<AppType, SubscriptionQuota>>,
script: RwLock<HashMap<(AppType, String), UsageResult>>,
}
impl UsageCache {
pub fn new() -> Self {
Self::default()
}
pub fn put_subscription(&self, app_type: AppType, quota: SubscriptionQuota) {
if let Ok(mut w) = self.subscription.write() {
w.insert(app_type, quota);
}
}
pub fn put_script(&self, app_type: AppType, provider_id: String, result: UsageResult) {
if let Ok(mut w) = self.script.write() {
w.insert((app_type, provider_id), result);
}
}
/// 以借用形式暴露订阅快照,避免托盘每次重建时深拷贝整个 `SubscriptionQuota`。
pub fn with_subscription<R>(
&self,
app_type: &AppType,
f: impl FnOnce(&SubscriptionQuota) -> R,
) -> Option<R> {
self.subscription
.read()
.ok()
.and_then(|r| r.get(app_type).map(f))
}
/// 以借用形式暴露脚本型用量结果,同上。
pub fn with_script<R>(
&self,
app_type: &AppType,
provider_id: &str,
f: impl FnOnce(&UsageResult) -> R,
) -> Option<R> {
self.script
.read()
.ok()
.and_then(|r| r.get(&(app_type.clone(), provider_id.to_string())).map(f))
}
pub fn invalidate_script(&self, app_type: &AppType, provider_id: &str) {
// 热路径会对每个禁用脚本的 provider 在托盘重建时调用一次:先走读锁
// `contains_key` 快速放行"本来就不在缓存里"的常见情况,避免无谓的写锁升级。
let key = (app_type.clone(), provider_id.to_string());
if !self.script.read().is_ok_and(|r| r.contains_key(&key)) {
return;
}
if let Ok(mut w) = self.script.write() {
w.remove(&key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::services::subscription::CredentialStatus;
fn fake_quota() -> SubscriptionQuota {
SubscriptionQuota {
tool: "claude".to_string(),
credential_status: CredentialStatus::Valid,
credential_message: None,
success: true,
tiers: vec![],
extra_usage: None,
error: None,
queried_at: Some(0),
}
}
fn fake_result() -> UsageResult {
UsageResult {
success: true,
data: None,
error: None,
}
}
#[test]
fn subscription_round_trip() {
let cache = UsageCache::new();
assert!(cache
.with_subscription(&AppType::Claude, |q| q.success)
.is_none());
cache.put_subscription(AppType::Claude, fake_quota());
let got = cache
.with_subscription(&AppType::Claude, |q| q.success)
.unwrap();
assert!(got);
assert!(cache
.with_subscription(&AppType::Codex, |q| q.success)
.is_none());
}
#[test]
fn script_round_trip_and_invalidate() {
let cache = UsageCache::new();
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_none());
cache.put_script(AppType::Codex, "pid".to_string(), fake_result());
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_some());
cache.invalidate_script(&AppType::Codex, "pid");
assert!(cache
.with_script(&AppType::Codex, "pid", |r| r.success)
.is_none());
}
#[test]
fn script_keys_isolated_by_app_type() {
let cache = UsageCache::new();
cache.put_script(AppType::Claude, "same".to_string(), fake_result());
assert!(cache
.with_script(&AppType::Claude, "same", |r| r.success)
.is_some());
assert!(cache
.with_script(&AppType::Codex, "same", |r| r.success)
.is_none());
}
}
File diff suppressed because it is too large Load Diff
+1 -4
View File
@@ -173,10 +173,7 @@ async fn run_worker_loop(
let started_at = Instant::now();
let mut merged_count = 1usize;
loop {
let Some(wait_for) = auto_sync_wait_duration(started_at, Instant::now()) else {
break;
};
while let Some(wait_for) = auto_sync_wait_duration(started_at, Instant::now()) {
let timeout = tokio::time::timeout(wait_for, rx.recv()).await;
match timeout {
+16 -4
View File
@@ -4,7 +4,7 @@ pub mod terminal;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use providers::{claude, codex, gemini, openclaw, opencode};
use providers::{claude, codex, gemini, hermes, openclaw, opencode};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -56,18 +56,20 @@ pub struct DeleteSessionOutcome {
}
pub fn scan_sessions() -> Vec<SessionMeta> {
let (r1, r2, r3, r4, r5) = std::thread::scope(|s| {
let (r1, r2, r3, r4, r5, r6) = std::thread::scope(|s| {
let h1 = s.spawn(codex::scan_sessions);
let h2 = s.spawn(claude::scan_sessions);
let h3 = s.spawn(opencode::scan_sessions);
let h4 = s.spawn(openclaw::scan_sessions);
let h5 = s.spawn(gemini::scan_sessions);
let h6 = s.spawn(hermes::scan_sessions);
(
h1.join().unwrap_or_default(),
h2.join().unwrap_or_default(),
h3.join().unwrap_or_default(),
h4.join().unwrap_or_default(),
h5.join().unwrap_or_default(),
h6.join().unwrap_or_default(),
)
});
@@ -77,6 +79,7 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
sessions.extend(r3);
sessions.extend(r4);
sessions.extend(r5);
sessions.extend(r6);
sessions.sort_by(|a, b| {
let a_ts = a.last_active_at.or(a.created_at).unwrap_or(0);
@@ -88,10 +91,13 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
}
pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<SessionMessage>, String> {
// OpenCode SQLite sessions use a "sqlite:" prefixed source_path
// SQLite sessions use a "sqlite:" prefixed source_path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::load_messages_sqlite(source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::load_messages_sqlite(source_path);
}
let path = Path::new(source_path);
match provider_id {
@@ -100,6 +106,7 @@ pub fn load_messages(provider_id: &str, source_path: &str) -> Result<Vec<Session
"opencode" => opencode::load_messages(path),
"openclaw" => openclaw::load_messages(path),
"gemini" => gemini::load_messages(path),
"hermes" => hermes::load_messages(path),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
@@ -109,10 +116,13 @@ pub fn delete_session(
session_id: &str,
source_path: &str,
) -> Result<bool, String> {
// OpenCode SQLite sessions bypass the file-based deletion path
// SQLite sessions bypass the file-based deletion path
if provider_id == "opencode" && source_path.starts_with("sqlite:") {
return opencode::delete_session_sqlite(session_id, source_path);
}
if provider_id == "hermes" && source_path.starts_with("sqlite:") {
return hermes::delete_session_sqlite(session_id, source_path);
}
let root = provider_root(provider_id)?;
delete_session_with_root(provider_id, session_id, Path::new(source_path), &root)
@@ -150,6 +160,7 @@ fn delete_session_with_root(
"opencode" => opencode::delete_session(&validated_root, &validated_source, session_id),
"openclaw" => openclaw::delete_session(&validated_root, &validated_source, session_id),
"gemini" => gemini::delete_session(&validated_root, &validated_source, session_id),
"hermes" => hermes::delete_session(&validated_root, &validated_source, session_id),
_ => Err(format!("Unsupported provider: {provider_id}")),
}
}
@@ -161,6 +172,7 @@ fn provider_root(provider_id: &str) -> Result<PathBuf, String> {
"opencode" => opencode::get_opencode_data_dir(),
"openclaw" => crate::openclaw_config::get_openclaw_dir().join("agents"),
"gemini" => crate::gemini_config::get_gemini_dir().join("tmp"),
"hermes" => crate::hermes_config::get_hermes_dir().join("sessions"),
_ => return Err(format!("Unsupported provider: {provider_id}")),
};
@@ -17,7 +17,7 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
let mut sessions = Vec::new();
// Iterate over project hash directories: tmp/<project_hash>/chats/session-*.json
// Iterate over project directories: tmp/<project_name>/chats/session-*.json
let project_dirs = match std::fs::read_dir(&tmp_dir) {
Ok(entries) => entries,
Err(_) => return Vec::new(),
@@ -34,13 +34,19 @@ pub fn scan_sessions() -> Vec<SessionMeta> {
Err(_) => continue,
};
let project_root_file = entry.path().join(".project_root");
let project_dir = std::fs::read_to_string(project_root_file).ok();
for file_entry in chat_files.flatten() {
let path = file_entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("json") {
continue;
}
if let Some(meta) = parse_session(&path) {
sessions.push(meta);
sessions.push(SessionMeta {
project_dir: project_dir.clone(),
..meta
});
}
}
}
@@ -159,7 +165,7 @@ fn parse_session(path: &Path) -> Option<SessionMeta> {
session_id: session_id.clone(),
title: title.clone(),
summary: title,
project_dir: None, // project hash is not reversible
project_dir: None, // (optionally) populated later
created_at,
last_active_at: last_active_at.or(created_at),
source_path: Some(source_path),
@@ -0,0 +1,603 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use rusqlite::Connection;
use serde_json::Value;
use crate::hermes_config::get_hermes_dir;
use crate::session_manager::{SessionMessage, SessionMeta};
use super::utils::{
extract_text, parse_timestamp_to_ms, read_head_tail_lines, truncate_summary, TITLE_MAX_CHARS,
};
const PROVIDER_ID: &str = "hermes";
fn get_hermes_db_path() -> PathBuf {
get_hermes_dir().join("state.db")
}
fn get_hermes_sessions_dir() -> PathBuf {
get_hermes_dir().join("sessions")
}
/// Scan sessions from both SQLite database and JSONL transcript files,
/// with SQLite taking precedence on ID conflicts.
pub fn scan_sessions() -> Vec<SessionMeta> {
let sqlite_sessions = scan_sessions_sqlite();
let jsonl_sessions = scan_sessions_jsonl();
if sqlite_sessions.is_empty() {
return jsonl_sessions;
}
if jsonl_sessions.is_empty() {
return sqlite_sessions;
}
let sqlite_ids: std::collections::HashSet<String> = sqlite_sessions
.iter()
.map(|s| s.session_id.clone())
.collect();
let mut merged = sqlite_sessions;
for s in jsonl_sessions {
if !sqlite_ids.contains(&s.session_id) {
merged.push(s);
}
}
merged
}
// ── SQLite scanning ─────────────────────────────────────────────────
fn scan_sessions_sqlite() -> Vec<SessionMeta> {
let db_path = get_hermes_db_path();
if !db_path.exists() {
return Vec::new();
}
let conn = match Connection::open_with_flags(
&db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
) {
Ok(c) => c,
Err(_) => return Vec::new(),
};
// Check if sessions table exists
let has_sessions: bool = conn
.query_row(
"SELECT COUNT(*) > 0 FROM sqlite_master WHERE type='table' AND name='sessions'",
[],
|row| row.get(0),
)
.unwrap_or(false);
if !has_sessions {
return Vec::new();
}
// Query sessions — use flexible column access via pragma
let columns = get_table_columns(&conn, "sessions");
let query = "SELECT * FROM sessions ORDER BY rowid DESC LIMIT 500";
let mut stmt = match conn.prepare(query) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let mut sessions = Vec::new();
let rows = match stmt.query_map([], |row| Ok(row_to_json(row, &columns))) {
Ok(r) => r,
Err(_) => return Vec::new(),
};
let db_source = format!("sqlite:{}", db_path.display());
for row_result in rows.flatten() {
if let Some(meta) = sqlite_row_to_session_meta(&row_result, &db_source) {
sessions.push(meta);
}
}
sessions
}
fn sqlite_row_to_session_meta(row: &Value, db_source: &str) -> Option<SessionMeta> {
let obj = row.as_object()?;
let session_id = obj.get("id").and_then(Value::as_str)?.to_string();
let title = obj
.get("title")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| truncate_summary(s, TITLE_MAX_CHARS).to_string());
let cwd = obj
.get("cwd")
.or_else(|| obj.get("directory"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
let started_at = obj
.get("started_at")
.or_else(|| obj.get("created_at"))
.and_then(parse_timestamp_to_ms);
let ended_at = obj
.get("ended_at")
.or_else(|| obj.get("updated_at"))
.and_then(parse_timestamp_to_ms);
let source_path = format!("{}#{}", db_source, session_id);
Some(SessionMeta {
provider_id: PROVIDER_ID.to_string(),
session_id,
title,
summary: None,
project_dir: cwd,
created_at: started_at,
last_active_at: ended_at.or(started_at),
source_path: Some(source_path),
resume_command: None,
})
}
/// Get column names for a table.
fn get_table_columns(conn: &Connection, table: &str) -> Vec<String> {
let query = format!("PRAGMA table_info({table})");
let mut stmt = match conn.prepare(&query) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let rows = match stmt.query_map([], |row| {
let name: String = row.get(1)?;
Ok(name)
}) {
Ok(r) => r,
Err(_) => return Vec::new(),
};
rows.flatten().collect()
}
/// Convert a SQLite row to a JSON Value using known column names.
fn row_to_json(row: &rusqlite::Row, columns: &[String]) -> Value {
let mut map = serde_json::Map::new();
for (i, col) in columns.iter().enumerate() {
// Try string first, then integer, then float, then null
if let Ok(val) = row.get::<_, String>(i) {
map.insert(col.clone(), Value::String(val));
} else if let Ok(val) = row.get::<_, i64>(i) {
map.insert(col.clone(), Value::Number(val.into()));
} else if let Ok(val) = row.get::<_, f64>(i) {
if let Some(n) = serde_json::Number::from_f64(val) {
map.insert(col.clone(), Value::Number(n));
}
} else {
map.insert(col.clone(), Value::Null);
}
}
Value::Object(map)
}
/// Load messages from the Hermes SQLite database.
pub fn load_messages_sqlite(source: &str) -> Result<Vec<SessionMessage>, String> {
let (db_path, session_id) = parse_sqlite_source(source)
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
let conn = Connection::open_with_flags(
&db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
)
.map_err(|e| format!("Failed to open Hermes database: {e}"))?;
// Try querying with common column names
let query =
"SELECT role, content, created_at FROM messages WHERE session_id = ?1 ORDER BY created_at ASC";
let mut stmt = conn
.prepare(query)
.map_err(|e| format!("Failed to prepare messages query: {e}"))?;
let rows = stmt
.query_map([session_id.as_str()], |row| {
let role: String = row.get(0)?;
let content: String = row.get(1)?;
let ts: Option<i64> = row.get(2).ok();
Ok((role, content, ts))
})
.map_err(|e| format!("Failed to query messages: {e}"))?;
let mut messages = Vec::new();
for row in rows.flatten() {
let (role, content, ts) = row;
if content.trim().is_empty() {
continue;
}
let ts_ms = ts.and_then(|v| parse_timestamp_to_ms(&Value::Number(v.into())));
messages.push(SessionMessage {
role,
content,
ts: ts_ms,
});
}
Ok(messages)
}
/// Delete a session from the Hermes SQLite database.
pub fn delete_session_sqlite(session_id: &str, source: &str) -> Result<bool, String> {
let (db_path, ref_session_id) = parse_sqlite_source(source)
.ok_or_else(|| format!("Invalid SQLite source reference: {source}"))?;
let db_path = db_path
.canonicalize()
.map_err(|e| format!("Failed to canonicalize Hermes database path: {e}"))?;
let expected_db_path = get_hermes_db_path()
.canonicalize()
.map_err(|e| format!("Failed to canonicalize expected Hermes database path: {e}"))?;
if ref_session_id != session_id {
return Err(format!(
"Hermes SQLite session ID mismatch: expected {session_id}, found {ref_session_id}"
));
}
if db_path != expected_db_path {
return Err("SQLite path does not match expected Hermes database".to_string());
}
let conn =
Connection::open(&db_path).map_err(|e| format!("Failed to open Hermes database: {e}"))?;
let tx = conn
.unchecked_transaction()
.map_err(|e| format!("Failed to begin transaction: {e}"))?;
// Delete messages first (child records)
let _ = tx.execute("DELETE FROM messages WHERE session_id = ?1", [session_id]);
let deleted = tx
.execute("DELETE FROM sessions WHERE id = ?1", [session_id])
.map_err(|e| format!("Failed to delete Hermes session: {e}"))?;
tx.commit()
.map_err(|e| format!("Failed to commit session deletion: {e}"))?;
Ok(deleted > 0)
}
fn parse_sqlite_source(source: &str) -> Option<(PathBuf, String)> {
let rest = source.strip_prefix("sqlite:")?;
let hash_pos = rest.rfind('#')?;
let db_path = PathBuf::from(&rest[..hash_pos]);
let session_id = rest[hash_pos + 1..].to_string();
if session_id.is_empty() {
return None;
}
Some((db_path, session_id))
}
// ── JSONL scanning ──────────────────────────────────────────────────
fn scan_sessions_jsonl() -> Vec<SessionMeta> {
let sessions_dir = get_hermes_sessions_dir();
if !sessions_dir.exists() {
return Vec::new();
}
let entries = match std::fs::read_dir(&sessions_dir) {
Ok(e) => e,
Err(_) => return Vec::new(),
};
let mut sessions = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
let ext = path.extension().and_then(|e| e.to_str());
if ext != Some("jsonl") && ext != Some("json") {
continue;
}
if let Some(meta) = parse_jsonl_session(&path) {
sessions.push(meta);
}
}
sessions
}
fn parse_jsonl_session(path: &Path) -> Option<SessionMeta> {
// Read head (metadata + first user message) and tail (last timestamp)
let (head, tail) = read_head_tail_lines(path, 30, 10).ok()?;
let mut first_user_msg: Option<String> = None;
let mut first_ts: Option<i64> = None;
let mut last_ts: Option<i64> = None;
let mut session_id: Option<String> = None;
let mut title: Option<String> = None;
let mut cwd: Option<String> = None;
// Process head lines for metadata and first user message
for line in &head {
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let ts = value
.get("timestamp")
.or_else(|| value.get("ts"))
.and_then(parse_timestamp_to_ms);
if first_ts.is_none() {
first_ts = ts;
}
last_ts = ts.or(last_ts);
let line_type = value.get("type").and_then(Value::as_str).unwrap_or("");
// Extract session metadata from session-type lines
if line_type == "session" || line_type == "init" {
if session_id.is_none() {
session_id = value
.get("id")
.or_else(|| value.get("sessionId"))
.and_then(Value::as_str)
.map(|s| s.to_string());
}
if title.is_none() {
title = value
.get("title")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
}
if cwd.is_none() {
cwd = value
.get("cwd")
.or_else(|| value.get("directory"))
.and_then(Value::as_str)
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
}
}
if first_user_msg.is_none() {
let role = value
.get("role")
.or_else(|| value.get("message").and_then(|m| m.get("role")))
.and_then(Value::as_str);
if role == Some("user") {
let content = value
.get("content")
.or_else(|| value.get("message").and_then(|m| m.get("content")));
if let Some(c) = content {
let text = extract_text(c);
if !text.trim().is_empty() {
first_user_msg = Some(truncate_summary(&text, TITLE_MAX_CHARS).to_string());
}
}
}
}
}
// Process tail lines for the most recent timestamp
for line in tail.iter().rev() {
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(_) => continue,
};
let ts = value
.get("timestamp")
.or_else(|| value.get("ts"))
.and_then(parse_timestamp_to_ms);
if let Some(t) = ts {
last_ts = Some(t);
break;
}
}
// Fall back to filename as session ID
let session_id = session_id.unwrap_or_else(|| {
path.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown")
.to_string()
});
let source_path = path.to_string_lossy().to_string();
Some(SessionMeta {
provider_id: PROVIDER_ID.to_string(),
session_id,
title: title.or_else(|| first_user_msg.clone()),
summary: first_user_msg,
project_dir: cwd,
created_at: first_ts,
last_active_at: last_ts.or(first_ts),
source_path: Some(source_path),
resume_command: None,
})
}
/// Load messages from a Hermes JSONL transcript file.
pub fn load_messages(path: &Path) -> Result<Vec<SessionMessage>, String> {
let file = File::open(path).map_err(|e| format!("Failed to open session file: {e}"))?;
let reader = BufReader::new(file);
let mut messages = Vec::new();
for line in reader.lines() {
let line = match line {
Ok(l) => l,
Err(_) => continue,
};
if line.trim().is_empty() {
continue;
}
let value: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(_) => continue,
};
// Support both flat messages and nested {type:"message", message:{...}} format
let (role_val, content_val, ts_val) =
if value.get("type").and_then(Value::as_str) == Some("message") {
let msg = match value.get("message") {
Some(m) => m,
None => continue,
};
(
msg.get("role"),
msg.get("content"),
value.get("timestamp").or_else(|| msg.get("ts")),
)
} else {
(
value.get("role"),
value.get("content"),
value.get("timestamp").or_else(|| value.get("ts")),
)
};
let role = match role_val.and_then(Value::as_str) {
Some(r) => r.to_string(),
None => continue,
};
let content = content_val.map(extract_text).unwrap_or_default();
if content.trim().is_empty() {
continue;
}
let ts = ts_val.and_then(parse_timestamp_to_ms);
messages.push(SessionMessage { role, content, ts });
}
Ok(messages)
}
/// Delete a Hermes JSONL session file.
pub fn delete_session(_root: &Path, path: &Path, _session_id: &str) -> Result<bool, String> {
std::fs::remove_file(path).map_err(|e| {
format!(
"Failed to delete Hermes session file {}: {e}",
path.display()
)
})?;
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::tempdir;
#[test]
fn parse_sqlite_source_valid() {
let (path, id) = parse_sqlite_source("sqlite:/home/user/.hermes/state.db#session-123")
.expect("should parse");
assert_eq!(path, PathBuf::from("/home/user/.hermes/state.db"));
assert_eq!(id, "session-123");
}
#[test]
fn parse_sqlite_source_invalid() {
assert!(parse_sqlite_source("not-sqlite").is_none());
assert!(parse_sqlite_source("sqlite:").is_none());
assert!(parse_sqlite_source("sqlite:/path#").is_none());
}
#[test]
fn parse_jsonl_session_extracts_metadata() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("test-session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(
f,
r#"{{"type":"session","id":"s1","title":"My Session","cwd":"/home/user/project"}}"#
)
.unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello world"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi there"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
f.flush().unwrap();
let meta = parse_jsonl_session(&path).expect("should parse");
assert_eq!(meta.session_id, "s1");
assert_eq!(meta.title.as_deref(), Some("My Session"));
assert_eq!(meta.project_dir.as_deref(), Some("/home/user/project"));
assert!(meta.created_at.is_some());
assert!(meta.last_active_at.is_some());
}
#[test]
fn parse_jsonl_session_fallback_to_filename() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("my-session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(f, r#"{{"role":"user","content":"Hello","ts":1700000000}}"#).unwrap();
f.flush().unwrap();
let meta = parse_jsonl_session(&path).expect("should parse");
assert_eq!(meta.session_id, "my-session");
assert!(meta.title.is_some()); // Falls back to first user message
}
#[test]
fn load_messages_flat_format() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(
f,
r#"{{"role":"user","content":"What is Rust?","ts":1700000000}}"#
)
.unwrap();
writeln!(
f,
r#"{{"role":"assistant","content":"A systems programming language.","ts":1700000001}}"#
)
.unwrap();
f.flush().unwrap();
let msgs = load_messages(&path).expect("should load");
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[0].role, "user");
assert_eq!(msgs[1].role, "assistant");
}
#[test]
fn load_messages_nested_format() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
let mut f = File::create(&path).expect("create");
writeln!(f, r#"{{"type":"session","id":"s1"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"user","content":"Hello"}},"timestamp":"2026-01-01T00:00:00Z"}}"#).unwrap();
writeln!(f, r#"{{"type":"message","message":{{"role":"assistant","content":"Hi"}},"timestamp":"2026-01-01T00:01:00Z"}}"#).unwrap();
f.flush().unwrap();
let msgs = load_messages(&path).expect("should load");
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[0].role, "user");
assert!(msgs[0].ts.is_some());
}
#[test]
fn delete_session_removes_file() {
let dir = tempdir().expect("tempdir");
let path = dir.path().join("session.jsonl");
File::create(&path).expect("create");
assert!(path.exists());
delete_session(dir.path(), &path, "session").expect("should delete");
assert!(!path.exists());
}
}
@@ -1,6 +1,7 @@
pub mod claude;
pub mod codex;
pub mod gemini;
pub mod hermes;
pub mod openclaw;
pub mod opencode;
mod utils;
+36 -66
View File
@@ -78,22 +78,7 @@ end tell"#
}
fn launch_ghostty(command: &str, cwd: Option<&str>) -> Result<(), String> {
let args = build_ghostty_args(command, cwd);
let status = Command::new("open")
.args(args.iter().map(String::as_str))
.status()
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
if status.success() {
Ok(())
} else {
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
}
}
fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
let input = ghostty_raw_input(command);
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".to_string());
let mut args = vec![
"-na".to_string(),
@@ -108,22 +93,22 @@ fn build_ghostty_args(command: &str, cwd: Option<&str>) -> Vec<String> {
}
}
args.push(format!("--input={input}"));
args
}
args.push("-e".to_string());
args.push(shell);
args.push("-l".to_string());
args.push("-c".to_string());
args.push(command.to_string());
fn ghostty_raw_input(command: &str) -> String {
let mut escaped = String::from("raw:");
for ch in command.chars() {
match ch {
'\\' => escaped.push_str("\\\\"),
'\n' => escaped.push_str("\\n"),
'\r' => escaped.push_str("\\r"),
_ => escaped.push(ch),
}
let status = Command::new("open")
.args(&args)
.status()
.map_err(|e| format!("Failed to launch Ghostty: {e}"))?;
if status.success() {
Ok(())
} else {
Err("Failed to launch Ghostty. Make sure it is installed.".to_string())
}
escaped.push_str("\\n");
escaped
}
fn launch_kitty(command: &str, cwd: Option<&str>) -> Result<(), String> {
@@ -300,43 +285,10 @@ mod tests {
use super::*;
#[test]
fn ghostty_uses_shell_mode_for_resume_commands() {
let args = build_ghostty_args("claude --resume abc-123", Some("/tmp/project dir"));
fn build_shell_command_keeps_command_without_cwd_prefix_when_not_provided() {
assert_eq!(
args,
vec![
"-na",
"Ghostty",
"--args",
"--quit-after-last-window-closed=true",
"--working-directory=/tmp/project dir",
"--input=raw:claude --resume abc-123\\n",
]
);
}
#[test]
fn ghostty_keeps_command_without_cwd_prefix_when_not_provided() {
let args = build_ghostty_args("claude --resume abc-123", None);
assert_eq!(
args,
vec![
"-na",
"Ghostty",
"--args",
"--quit-after-last-window-closed=true",
"--input=raw:claude --resume abc-123\\n",
]
);
}
#[test]
fn ghostty_escapes_newlines_and_backslashes_in_input() {
assert_eq!(
ghostty_raw_input("echo foo\\\\bar\npwd"),
"raw:echo foo\\\\\\\\bar\\npwd\\n"
build_shell_command("claude --resume abc-123", None),
"claude --resume abc-123"
);
}
@@ -365,4 +317,22 @@ mod tests {
]
);
}
#[test]
fn ghostty_uses_working_directory_arg_for_cwd() {
// cwd should be passed as --working-directory, not embedded in the shell command string
// This avoids shell expansion of special characters in directory paths
let cwd = "/tmp/project dir";
let command = "claude --resume abc-123";
// Verify build_shell_command does NOT include cwd when used in ghostty context
// (ghostty passes cwd via --working-directory flag instead)
assert_eq!(
build_shell_command(command, None),
"claude --resume abc-123"
);
// Verify shell_escape works correctly for paths with spaces
assert_eq!(shell_escape(cwd), "\"/tmp/project dir\"");
}
}
+28
View File
@@ -36,6 +36,8 @@ pub struct VisibleApps {
pub opencode: bool,
#[serde(default = "default_true")]
pub openclaw: bool,
#[serde(default)]
pub hermes: bool,
}
impl Default for VisibleApps {
@@ -46,6 +48,7 @@ impl Default for VisibleApps {
gemini: true,
opencode: true,
openclaw: true,
hermes: false, // 默认不显示,需用户手动启用
}
}
}
@@ -59,6 +62,7 @@ impl VisibleApps {
AppType::Gemini => self.gemini,
AppType::OpenCode => self.opencode,
AppType::OpenClaw => self.openclaw,
AppType::Hermes => self.hermes,
}
}
}
@@ -231,6 +235,8 @@ pub struct AppSettings {
pub opencode_config_dir: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub openclaw_config_dir: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hermes_config_dir: Option<String>,
// ===== 当前供应商 ID(设备级)=====
/// 当前 Claude 供应商 ID(本地存储,优先于数据库 is_current
@@ -248,6 +254,9 @@ pub struct AppSettings {
/// 当前 OpenClaw 供应商 ID(本地存储,对 OpenClaw 可能无意义,但保持结构一致)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_provider_openclaw: Option<String>,
/// 当前 Hermes 供应商 ID(本地存储,保持结构一致)
#[serde(default, skip_serializing_if = "Option::is_none")]
pub current_provider_hermes: Option<String>,
// ===== Skill 同步设置 =====
/// Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
@@ -315,11 +324,13 @@ impl Default for AppSettings {
gemini_config_dir: None,
opencode_config_dir: None,
openclaw_config_dir: None,
hermes_config_dir: None,
current_provider_claude: None,
current_provider_codex: None,
current_provider_gemini: None,
current_provider_opencode: None,
current_provider_openclaw: None,
current_provider_hermes: None,
skill_sync_method: SyncMethod::default(),
skill_storage_location: SkillStorageLocation::default(),
webdav_sync: None,
@@ -377,6 +388,13 @@ impl AppSettings {
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
self.hermes_config_dir = self
.hermes_config_dir
.as_ref()
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
self.language = self
.language
.as_ref()
@@ -577,6 +595,14 @@ pub fn get_openclaw_override_dir() -> Option<PathBuf> {
.map(|p| resolve_override_path(p))
}
pub fn get_hermes_override_dir() -> Option<PathBuf> {
let settings = settings_store().read().ok()?;
settings
.hermes_config_dir
.as_ref()
.map(|p| resolve_override_path(p))
}
// ===== 当前供应商管理函数 =====
/// 获取指定应用类型的当前供应商 ID(从本地 settings 读取)
@@ -591,6 +617,7 @@ pub fn get_current_provider(app_type: &AppType) -> Option<String> {
AppType::Gemini => settings.current_provider_gemini.clone(),
AppType::OpenCode => settings.current_provider_opencode.clone(),
AppType::OpenClaw => settings.current_provider_openclaw.clone(),
AppType::Hermes => settings.current_provider_hermes.clone(),
}
}
@@ -606,6 +633,7 @@ pub fn set_current_provider(app_type: &AppType, id: Option<&str>) -> Result<(),
AppType::Gemini => settings.current_provider_gemini = id_owned.clone(),
AppType::OpenCode => settings.current_provider_opencode = id_owned.clone(),
AppType::OpenClaw => settings.current_provider_openclaw = id_owned.clone(),
AppType::Hermes => settings.current_provider_hermes = id_owned.clone(),
})
}
+7 -2
View File
@@ -1,11 +1,12 @@
use crate::database::Database;
use crate::services::ProxyService;
use crate::services::{ProxyService, UsageCache};
use std::sync::Arc;
/// 全局应用状态
pub struct AppState {
pub db: Arc<Database>,
pub proxy_service: ProxyService,
pub usage_cache: Arc<UsageCache>,
}
impl AppState {
@@ -13,6 +14,10 @@ impl AppState {
pub fn new(db: Arc<Database>) -> Self {
let proxy_service = ProxyService::new(db.clone());
Self { db, proxy_service }
Self {
db,
proxy_service,
usage_cache: Arc::new(UsageCache::new()),
}
}
}

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