Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

38.2 KB
Raw Blame
export type ProviderCategory =
  | "official" // 官方
  | "cn_official" // 开源官方(原"国产官方")
  | "cloud_provider" // 云服务商(AWS Bedrock 等)
  | "aggregator" // 聚合网站
  | "third_party" // 第三方供应商
  | "custom" // 自定义
  | "local" // 本机推理服务(Ollama、LM Studio 等)
  | "omo" // Oh My OpenCode
  | "omo-slim"; // Oh My OpenCode Slim

/** 库里有、但存的数据读不出来的一条记录:只能删除,原始数据保持不动。 */
export interface UnreadableEntry {
  id: string;
  name: string;
  /** 后端的解析错误,点名是哪一列 */
  error: string;
}

export interface Provider {
  id: string;
  name: string;
  settingsConfig: Record<string, any>; // 应用配置对象:Claude 为 settings.json;Codex 为 { auth, config }
  websiteUrl?: string;
  // 新增:供应商分类(用于差异化提示/能力开关)
  category?: ProviderCategory;
  createdAt?: number; // 添加时间戳(毫秒)
  sortIndex?: number; // 排序索引(用于自定义拖拽排序)
  // 备注信息
  notes?: string;
  // 新增:是否为商业合作伙伴
  isPartner?: boolean;
  // 可选:供应商元数据(仅存于 ~/.cc-switch/config.json,不写入 live 配置)
  meta?: ProviderMeta;
  // 图标配置
  icon?: string; // 图标名称(如 "openai", "anthropic")
  iconColor?: string; // 图标颜色(Hex 格式,如 "#00A67E")
  // 是否加入故障转移队列
  inFailoverQueue?: boolean;
}

// 自定义端点配置
export interface CustomEndpoint {
  url: string;
  addedAt: number;
  lastUsed?: number;
}

// 端点候选项(用于端点测速弹窗)
export interface EndpointCandidate {
  id?: string;
  url: string;
  isCustom?: boolean;
}

import type { AppId } from "./lib/api/types";
import type { TemplateType } from "./config/constants";
import type { Language } from "./i18n/languages";

// 用量查询脚本配置
export interface UsageScript {
  enabled: boolean; // 是否启用用量查询
  language: "javascript"; // 脚本语言
  code: string; // 脚本代码(JSON 格式配置)
  timeout?: number; // 超时时间(秒,默认 10)
  templateType?: TemplateType; // 模板类型(用于后端判断验证规则)
  apiKey?: string; // 用量查询专用的 API Key(通用模板使用)
  baseUrl?: string; // 用量查询专用的 Base URL(通用和 NewAPI 模板使用)
  accessToken?: string; // 访问令牌(NewAPI 模板使用)
  userId?: string; // 用户ID(NewAPI 模板使用)
  accessKeyId?: string; // 火山方舟 AccessKey ID(用量查询签名用,与推理 Key 分离)
  secretAccessKey?: string; // 火山方舟 SecretAccessKey
  teamOrganizationId?: string; // 智谱团队套餐组织 ID(请求头 bigmodel-organization)
  teamProjectId?: string; // 智谱团队套餐项目 ID(请求头 bigmodel-project)
  codingPlanProvider?: string; // Coding Plan 供应商标识(如 "kimi", "zhipu", "minimax")
  autoQueryInterval?: number; // 自动查询间隔(单位:分钟,0 表示禁用)
  autoIntervalMinutes?: number; // 自动查询间隔(分钟)- 别名字段
  request?: {
    // 请求配置
    url?: string; // 请求 URL
    method?: string; // HTTP 方法
    headers?: Record<string, string>; // 请求头
    body?: any; // 请求体
  };
}

const DEFAULT_USAGE_SCRIPT: UsageScript = {
  enabled: false,
  language: "javascript",
  code: "",
  timeout: 10,
  autoQueryInterval: 5,
};

export function createUsageScript(
  overrides?: Partial<UsageScript>,
): UsageScript {
  return { ...DEFAULT_USAGE_SCRIPT, ...overrides };
}

// 单个套餐用量数据
export interface UsageData {
  planName?: string; // 套餐名称(可选)
  extra?: string; // 扩展字段,可自由补充需要展示的文本(可选)
  isValid?: boolean; // 套餐是否有效(可选)
  invalidMessage?: string; // 失效原因说明(可选,当 isValid 为 false 时显示)
  total?: number; // 总额度(可选)
  used?: number; // 已用额度(可选)
  remaining?: number; // 剩余额度(可选)
  unit?: string; // 单位(可选)
}

// 用量查询结果(支持多套餐)
export interface UsageResult {
  success: boolean;
  data?: UsageData[]; // 改为数组,支持返回多个套餐
  error?: string;
}

export type AuthBindingSource = "provider_config" | "managed_account";

export interface AuthBinding {
  source: AuthBindingSource;
  authProvider?: string;
  accountId?: string;
}

export interface ClaudeDesktopModelRoute {
  model: string;
  labelOverride?: string;
  supports1m?: boolean;
}

export type CodexChatThinkingParam =
  | "none"
  | "thinking"
  | "enable_thinking"
  | "reasoning_split";

export type CodexChatEffortParam =
  | "none"
  | "reasoning_effort"
  // OpenRouter 原生归一化对象 reasoning:{effort}(区别于顶层 OpenAI 别名 reasoning_effort)
  | "reasoning.effort";

export type CodexChatEffortValueMode =
  | "passthrough"
  | "low_high"
  | "deepseek"
  // OpenRouter effort 枚举 xhigh|high|medium|low|minimal(无 max,max 钳到 xhigh)
  | "openrouter"
  // OpenCode Zen 网关:合法档位逐模型,见 modelCatalog 各条目 reasoningLevels
  // (镜像 models.dev);代理转换层按请求模型查表钳制,无表不发 effort 字段
  | "zen";

export type CodexChatReasoningOutputFormat =
  | "auto"
  | "reasoning_content"
  | "reasoning"
  | "reasoning_details"
  | "think_tags";

export interface CodexChatReasoning {
  supportsThinking?: boolean;
  supportsEffort?: boolean;
  thinkingParam?: CodexChatThinkingParam;
  effortParam?: CodexChatEffortParam;
  effortValueMode?: CodexChatEffortValueMode;
  // 声明性字段:标注上游 reasoning 回传位置。当前提取靠穷举字段,未读取此值(think_tags 尚未接线)。
  outputFormat?: CodexChatReasoningOutputFormat;
}

export type PromptCacheRoutingMode = "auto" | "enabled" | "disabled";

export interface LocalProxyRequestOverrides {
  headers?: Record<string, string>;
  body?: Record<string, unknown>;
}

// 供应商元数据(字段名与后端一致,保持 snake_case)
export interface ProviderMeta {
  /** Explicit multiplier for future local-proxy reference costs; absent means 1. */
  billingMultiplier?: string;
  // 自定义端点:以 URL 为键,值为端点信息
  custom_endpoints?: Record<string, CustomEndpoint>;
  // 是否在切换/同步到 live 时应用通用配置片段
  commonConfigEnabled?: boolean;
  // Claude Desktop 3P 配置写入模式
  claudeDesktopMode?: "direct" | "proxy";
  // Claude Desktop 本地路由模式:Claude-safe route -> upstream model
  claudeDesktopModelRoutes?: Record<string, ClaudeDesktopModelRoute>;
  // 用量查询脚本配置
  usage_script?: UsageScript;
  // 请求地址管理:测速后自动选择最佳端点
  endpointAutoSelect?: boolean;
  // 是否为官方合作伙伴
  isPartner?: boolean;
  // 合作伙伴促销 key(用于后端识别 PackyCode 等)
  partnerPromotionKey?: string;
  // API 格式(Claude / Codex 供应商使用)
  // - "anthropic": 原生 Anthropic Messages API 格式,直接透传
  // - "openai_chat": OpenAI Chat Completions 格式,需要格式转换
  // - "openai_responses": OpenAI Responses API 格式,需要格式转换
  // - "gemini_native": Gemini Native generateContent API 格式,需要格式转换
  apiFormat?:
    | "anthropic"
    | "openai_chat"
    | "openai_responses"
    | "gemini_native";
  // Managed Codex Copilot uses this instead of apiFormat. Missing/unknown means auto.
  // Keep the raw string so selections from newer versions survive an edit/save.
  codexCopilotApiFormat?: string;
  // 通用认证绑定
  authBinding?: AuthBinding;
  // Claude 认证字段名
  apiKeyField?: ClaudeApiKeyField;
  // 是否将 base_url 视为完整 API 端点(代理直接使用此 URL,不拼接路径)
  isFullUrl?: boolean;
  // Prompt cache key for OpenAI Responses-compatible endpoints (improves cache hit rate)
  promptCacheKey?: string;
  // Session-based prompt-cache routing for Codex Responses -> Chat conversions.
  // auto enables only for known-compatible upstreams; enabled/disabled are user overrides.
  promptCacheRouting?: PromptCacheRoutingMode;
  // Codex OAuth FAST mode: injects service_tier="priority" on ChatGPT Codex requests
  codexFastMode?: boolean;
  // Codex Responses -> Chat Completions reasoning capability metadata
  codexChatReasoning?: CodexChatReasoning;
  // Claude route → OpenAI Chat / Responses: how the client's thinking effort is sent upstream (absent = auto)
  claudeReasoningEffort?: ClaudeReasoningEffortMode;
  // Codex → Anthropic path: emulate the Claude Code client (disabled by default; only an explicit true enables it)
  impersonateClaudeCode?: boolean;
  // Codex → Anthropic path: override the Anthropic max_tokens (output ceiling).
  // Codex does not forward model_max_output_tokens in the request body; without
  // this the path falls back to a 32000 default (DEFAULT_CODEX_ANTHROPIC_MAX_TOKENS),
  // which a low-ceiling gateway may reject. When set (>0) it takes precedence over the
  // request value and the default.
  maxOutputTokens?: number;
  // Custom User-Agent for local proxy routing. Only applied by the local proxy.
  customUserAgent?: string;
  // Local proxy request overrides. Only applied by the local proxy after route transforms.
  localProxyRequestOverrides?: LocalProxyRequestOverrides;
  // Whether this provider is currently projected into an additive app's live config.
  liveConfigManaged?: boolean;
  // Source format is needed for package-less OpenCode built-in overrides.
  opencodeConfigFormat?: "v1" | "v2";
  // 供应商类型(用于识别 Copilot 等特殊供应商)
  providerType?: string;
  // GitHub Copilot 关联账号 ID(旧字段,保留兼容读取)
  githubAccountId?: string;
  // Stack 模式下这家 Claude Code 供应商发布的模型;没有时按模型映射发布,空列表什么都不发布
  stackModels?: ClaudeStackModel[];
}

// Stack 模式下 Claude Code 供应商发布的一个模型
export interface ClaudeStackModel {
  // 发往上游的模型名(不带 1M 标记)
  model: string;
  // 选择器里的显示名,没有时用模型名
  displayName?: string;
  // 上游是 1M 窗口
  oneM?: boolean;
}

// Skill 同步方式
export type SkillSyncMethod = "auto" | "symlink" | "copy";

// Skill 存储位置
export type SkillStorageLocation = "cc_switch" | "unified";

// Claude API 格式类型
// - "anthropic": 原生 Anthropic Messages API 格式,直接透传
// - "openai_chat": OpenAI Chat Completions 格式,需要格式转换
// - "openai_responses": OpenAI Responses API 格式,需要格式转换
// - "gemini_native": Gemini Native generateContent API 格式,需要格式转换
export type ClaudeApiFormat =
  | "anthropic"
  | "openai_chat"
  | "openai_responses"
  | "gemini_native";

// Claude 路由经 OpenAI Chat / Responses 转发时思考档位的发法;缺省 = 自动
export type ClaudeReasoningEffortMode = "off" | "passthrough";

// Codex API 格式类型
// - "openai_responses": OpenAI Responses API 格式,直接透传
// - "openai_chat": OpenAI Chat Completions 格式,需要本地路由转换
// - "anthropic": native Anthropic Messages format, needs local routing to convert to Responses
export type CodexApiFormat = "openai_responses" | "openai_chat" | "anthropic";

export type CodexCopilotApiFormat = "auto" | "openai_responses" | "openai_chat";

export interface CodexCatalogModel {
  model: string;
  displayName?: string;
  contextWindow?: string | number;
  fast?: boolean;
  lite?: boolean;
  // Hidden provider capability metadata for the generated model catalog.
  // supportsParallelToolCalls is native-profile-only; inputModalities wins over
  // automatic text-only model detection for every profile.
  supportsParallelToolCalls?: boolean;
  inputModalities?: string[];
  // Vendor's OFFICIAL base_instructions (model identity / system preamble).
  // Codex requires this field in every catalog entry; when omitted the backend
  // falls back to a neutral default. e.g. MiMo "developed by Xiaomi".
  baseInstructions?: string;
  // Per-model reasoning effort levels exposed in the generated Codex catalog
  // (e.g. ["none", "low", "medium", "high", "xhigh", "max"]). When omitted the
  // backend keeps the template's conservative none/high default.
  reasoningLevels?: string[];
  // Per-model default reasoning effort. Only meaningful together with
  // reasoningLevels; when omitted the backend keeps the template default if it
  // is still in the list, otherwise the highest declared level.
  defaultReasoningLevel?: string;
}

// Claude 认证字段类型
export type ClaudeApiKeyField = "ANTHROPIC_AUTH_TOKEN" | "ANTHROPIC_API_KEY";

// 主页面显示的应用配置
export type VisibleApps = Record<AppId, boolean>;

// WebDAV 同步状态
export interface WebDavSyncStatus {
  lastSyncAt?: number | null;
  lastError?: string | null;
  lastErrorSource?: string | null;
  lastRemoteEtag?: string | null;
  lastLocalManifestHash?: string | null;
  lastRemoteManifestHash?: string | null;
}

// WebDAV 同步配置
export interface WebDavSyncSettings {
  enabled?: boolean;
  autoSync?: boolean;
  baseUrl?: string;
  username?: string;
  password?: string;
  remoteRoot?: string;
  profile?: string;
  encryptionKey?: string;
  status?: WebDavSyncStatus;
}

// S3 同步配置
export interface S3SyncSettings {
  enabled?: boolean;
  autoSync?: boolean;
  region?: string;
  bucket?: string;
  accessKeyId?: string;
  secretAccessKey?: string;
  endpoint?: string;
  remoteRoot?: string;
  profile?: string;
  /** Selected S3 provider preset id; presentational, persisted so it survives reopening. */
  preset?: string;
  encryptionKey?: string;
  status?: WebDavSyncStatus;
}

export type RemoteSnapshotLayout = "current" | "legacy";

export type RemoteEncryptionStatus =
  | "none"
  | "matched"
  | "missing_key"
  | "key_mismatch"
  | "unsupported_version"
  | "malformed";

// 远端快照信息(下载前预览)
export interface RemoteSnapshotInfo {
  deviceName: string;
  createdAt: string;
  snapshotId: string;
  version: number;
  protocolVersion: number;
  dbCompatVersion?: number | null;
  compatible: boolean;
  artifacts: string[];
  layout: RemoteSnapshotLayout;
  remotePath: string;
  encrypted?: boolean;
  encryptionStatus?: RemoteEncryptionStatus;
}

/** 用量金额的显示方式;对应 Rust `UsageDisplaySettings`。值由前端校验兜底。 */
export interface UsageDisplaySettings {
  /** 显示币种(见 `DISPLAY_CURRENCIES`),缺省为 USD */
  currency?: string;
  /** 1 美元折多少目标币种,按币种存 */
  exchangeRates?: Record<string, number>;
  /** 侧栏「今日」显示哪几项(见 `SIDEBAR_TODAY_ITEMS`),缺省只显示金额;空列表=不显示 */
  sidebarTodayItems?: string[];
  /** 请求日志列显隐:只存用户改过的列(列 id → 是否显示) */
  requestLogColumns?: Record<string, boolean>;
  /** 用量趋势图的样式(见 `TREND_CHART_TYPES`),缺省为柱形图 */
  trendChartType?: string;
  /** 汇率来源("auto" 自动获取 / "manual" 手动填写),缺省为 manual,只有用户主动选自动才联网 */
  rateSource?: string;
  /** 自动获取到的汇率,按币种存;与手填的 `exchangeRates` 分开,切回手动不丢手填值 */
  autoExchangeRates?: Record<string, number>;
  /** 上次成功取到汇率的时间(毫秒时间戳) */
  rateFetchedAt?: number;
  /** 上次取到汇率的实际数据源(后端返回的 source),用于界面署名 */
  rateProvider?: string;
}

/** 后端 `fetch_exchange_rates` 的返回:1 美元折多少目标币种 */
export interface FetchedExchangeRates {
  rates: Record<string, number>;
  fetchedAt: number;
  /** 实际取到数据的源,界面标注用 */
  source: string;
}

// 应用设置类型(用于设置对话框与 Tauri API)
// 存储在本地 ~/.cc-switch/settings.json,不随数据库同步
export interface Settings {
  // ===== 设备级 UI 设置 =====
  // 是否在系统托盘(macOS 菜单栏)显示图标
  showInTray: boolean;
  // 点击关闭按钮时是否最小化到托盘而不是关闭应用
  minimizeToTrayOnClose: boolean;
  // 是否启用应用级窗口控制按钮(最小化/最大化/关闭)
  useAppWindowControls?: boolean;
  // 启用 Claude 插件联动(写入 ~/.claude/config.json 的 primaryApiKey)
  enableClaudePluginIntegration?: boolean;
  copilotVscode?: { enabled: boolean; targets: string[] };
  // 跳过 Claude Code 初次安装确认(写入 ~/.claude.json 的 hasCompletedOnboarding)
  skipClaudeOnboarding?: boolean;
  // 是否开机自启
  launchOnStartup?: boolean;
  // 静默启动(程序启动时不显示主窗口)
  silentStartup?: boolean;
  // 是否启用主页面本地代理功能(默认关闭)
  enableLocalProxy?: boolean;
  // 是否在主页面显示 Stack 模式开关(默认关闭)。和 enableLocalProxy 二选一,只影响 Claude Code、Codex
  enableStackMode?: boolean;
  // User has confirmed the local proxy first-run notice
  proxyConfirmed?: boolean;
  // User has confirmed the usage query first-run notice
  usageConfirmed?: boolean;
  usageDashboardRefreshIntervalMs?: number;
  // 用量金额的显示币种与汇率(只影响显示,库里一律存美元)
  usageDisplay?: UsageDisplaySettings;
  // 会话用量自动扫描开关(默认开启=自动模式;关闭后仅手动同步时扫描会话日志,代理记账不受影响)
  sessionAutoSyncEnabled?: boolean;
  // 会话页搜索消息正文(默认关闭;开启后在本地建 session-index.db 索引,关闭时删除索引)
  sessionContentSearchEnabled?: boolean;
  // Whether to show the failover toggle independently on the main page
  enableFailoverToggle?: boolean;
  // Whether to show the project profile switcher on the main page header
  showProfileSwitcher?: boolean;
  // 供应商页页头显示搜索按钮(默认开;关掉后 ⌘F 仍可用)
  showProviderSearch?: boolean;
  // 启动时检查已安装的命令行应用有没有新版本(默认关)
  checkToolUpdatesOnStartup?: boolean;
  // 自动下载 CC Switch 新版本,下好后问要不要安装(默认关;设备级,不随云同步)
  autoUpdateEnabled?: boolean;
  // 点托盘图标出原生菜单,不出托盘面板(macOS / Windows;Linux 一律原生菜单;默认关,没写过视为关,即用托盘面板)
  nativeTrayMenu?: boolean;
  // Preserve Codex ChatGPT login in auth.json when switching third-party providers
  preserveCodexOfficialAuthOnSwitch?: boolean;
  codexQuotaProtection?: {
    enabled: boolean;
    fiveHourThreshold: number;
    weeklyThreshold: number;
  };
  // 路由 / 聚合模式下暂停使用 Codex 官方登录(官方额度用完、发送键被锁时的应急开关;默认关)
  codexProxyWithoutOfficialLogin?: boolean;
  // Run official Codex under the shared "custom" provider id so future
  // sessions share one resume-history bucket with third-party providers
  unifyCodexSessionHistory?: boolean;
  // User opted in (enable dialog checkbox) to migrate existing official sessions
  unifyCodexMigrateExisting?: boolean;
  // Codex aggregation: every catalog row uses the classic (v1) sub-agent tools,
  // so a sub-agent on another provider can read its task (on by default)
  codexStackClassicTools?: boolean;
  // Codex aggregation: default sub-agent model (a published `ccs-<key>/<model>` id)
  // and its reasoning effort. Unset = sub-agents follow the main model.
  codexStackSubagentModel?: string;
  codexStackSubagentReasoningEffort?: string;
  // Codex aggregation: Auto Review (approval reviewer) model, a published
  // `ccs-<key>/<model>` id. Unset = Codex's default reviewer.
  codexStackAutoReviewModel?: string;
  // User has confirmed the failover toggle first-run notice
  failoverConfirmed?: boolean;
  // User has confirmed the first-run welcome notice
  firstRunNoticeConfirmed?: boolean;
  // User has finished or skipped the onboarding tour (shown once to every user,
  // including those who dismissed the old welcome dialog)
  onboardingTourSeen?: boolean;
  // User has confirmed the one-time "new layout" dialog shown to upgrading users
  newLayoutNoticeConfirmed?: boolean;
  // Highest app version whose "what's new" summary the user has seen on this device
  whatsNewSeenVersion?: string;
  // User has confirmed the auto-sync traffic warning
  autoSyncConfirmed?: boolean;
  // User has confirmed the common config first-run notice
  commonConfigConfirmed?: boolean;
  // 首选语言(可选,默认中文)
  language?: Language;
  // Qoder CLI 用哪个版本(设备级):没设时中文界面默认国内版,其余默认国际版
  qoderEdition?: "global" | "cn";
  // 按档的额度百分比写剩余还是已用(默认剩余;余额、Credits 不受影响)
  quotaDisplay?: "left" | "used";
  // 官方账号额度只在手动刷新时查询(授权中心开关,#8990;默认自动查询)
  officialQuotaManualOnly?: boolean;

  // 主页面显示的应用(默认全部显示)
  visibleApps?: VisibleApps;
  // 应用页和侧栏的应用顺序(应用 ID,拖动排序后写入;缺的应用按默认顺序插回)
  appOrder?: string[];

  // ===== 设备级目录覆盖 =====
  // 覆盖 Claude Code 配置目录(可选)
  claudeConfigDir?: string;
  // 覆盖 Claude Desktop 配置目录(可选)
  claudeDesktopConfigDir?: string;
  // 覆盖 Codex 配置目录(可选)
  codexConfigDir?: string;
  // 覆盖 Gemini 配置目录(可选)
  geminiConfigDir?: string;
  // 覆盖 Grok Build 配置目录(可选)
  grokConfigDir?: string;
  // 覆盖 OpenCode 配置目录(可选)
  opencodeConfigDir?: string;
  // 覆盖 OpenClaw 配置目录(可选)
  openclawConfigDir?: string;
  // 覆盖 Hermes 配置目录(可选)
  hermesConfigDir?: string;
  // 覆盖 Pi agent 配置目录(可选)
  piConfigDir?: string;
  // 覆盖 MiniMax Code 数据目录(可选)
  mcodeConfigDir?: string;
  // 覆盖 Kimi Code 主目录(可选)
  kimiConfigDir?: string;
  // 覆盖 Oh My Pi agent 配置目录(可选)
  ompConfigDir?: string;
  // 覆盖 DeepSeek Harness 主目录(相当于 DSH_HOME,可选)
  dshConfigDir?: string;
  // 覆盖 Antigravity 配置根目录(可选)
  agyConfigDir?: string;
  // 覆盖 GitHub Copilot CLI 配置目录(可选)
  copilotConfigDir?: string;
  // 覆盖 WorkBuddy 数据目录(可选)
  workbuddyConfigDir?: string;
  // 覆盖 CodeBuddy 配置目录(可选)
  codebuddyConfigDir?: string;
  // 覆盖 ZCode 配置目录(可选)
  zcodeConfigDir?: string;
  // 覆盖 Qoder CLI(国际版)配置目录(可选)
  qoderConfigDir?: string;
  // 覆盖 Qoder CLI(国内版)配置目录(可选)
  qoderCnConfigDir?: string;

  // ===== 当前供应商 ID(设备级)=====
  // 当前 Claude 供应商 ID(优先于数据库 is_current)
  currentProviderClaude?: string;
  // 当前 Claude Desktop 供应商 ID(优先于数据库 is_current)
  currentProviderClaudeDesktop?: string;
  // 当前 Codex 供应商 ID(优先于数据库 is_current)
  currentProviderCodex?: string;
  // 当前 Gemini 供应商 ID(优先于数据库 is_current)
  currentProviderGemini?: string;

  // ===== Skill 同步设置 =====
  // Skill 同步方式:auto(默认,优先 symlink)、symlink、copy
  skillSyncMethod?: SkillSyncMethod;
  // Skill 存储位置:cc_switch(默认)或 unified(~/.agents/skills/)
  skillStorageLocation?: SkillStorageLocation;

  // ===== WebDAV v2 同步设置 =====
  webdavSync?: WebDavSyncSettings;

  // ===== S3 同步设置 =====
  s3Sync?: S3SyncSettings;

  // ===== 备份策略设置 =====
  // Auto-backup interval in hours (0=disabled, default 24)
  backupIntervalHours?: number;
  // Maximum backup files to retain (default 10)
  backupRetainCount?: number;
  // Total size limit for the backups folder in MB (unset or 0 = unlimited, default)
  backupMaxTotalMb?: number;

  // ===== 终端设置 =====
  // 首选终端应用(可选,默认使用系统默认终端)
  // macOS: "terminal" | "iterm2" | "warp" | "alacritty" | "kitty" | "ghostty" | "otty" | "wezterm" | "kaku"
  // Windows: "cmd" | "powershell" | "wt"
  // Linux: "gnome-terminal" | "konsole" | "xfce4-terminal" | "alacritty" | "kitty" | "ghostty"
  preferredTerminal?: string;

  // ===== 本机自动迁移状态 =====
  localMigrations?: {
    codexThirdPartyHistoryProviderBucketV1?: {
      completedAt: string;
      targetProviderId: string;
      sourceProviderIds?: string[];
      migratedJsonlFiles?: number;
      migratedStateRows?: number;
    };
  };
}

/** 原文 UTF-16 坐标,左闭右开;不得切开代理对。 */
export interface SessionTextRange {
  start: number;
  end: number;
}

/** 一条命中消息的摘录 */
export interface SessionContentSnippet {
  /** 摘录所在消息在会话里的序号 */
  messageIndex: number;
  /** 命中词附近的纯文本,空白已压缩 */
  text: string;
  /** 按完整消息匹配后映射到最终 text 的位置,避免截断改变上下文小写规则。 */
  highlights: SessionTextRange[];
}

/** 会话正文搜索的命中(search_session_content):最多 3 条摘录,第一条最相关 */
export interface SessionContentHit {
  providerId: string;
  sourcePath: string;
  snippets: SessionContentSnippet[];
  /** 命中的消息条数 */
  matchCount: number;
}

/** 正文索引的进度;running 为 false 且 processed === total 时索引已是最新 */
export interface SessionIndexStatus {
  running: boolean;
  processed: number;
  total: number;
}

export interface SessionContentSearchResult {
  hits: SessionContentHit[];
  status: SessionIndexStatus;
}

export interface SessionMeta {
  providerId: string;
  sessionId: string;
  title?: string;
  summary?: string;
  projectDir?: string | null;
  createdAt?: number;
  lastActiveAt?: number;
  sourcePath?: string;
  resumeCommand?: string;
}

// ─── 会话阅读页数据模型(对应 Rust session_manager/model.rs) ───

export type ToolKind =
  | "shell"
  | "read"
  | "search"
  | "edit"
  | "write"
  | "web"
  | "mcp"
  | "agent"
  | "ask"
  | "todo"
  | "other";

export type ToolStatus =
  | "success"
  | "error"
  | "interrupted"
  | "pending"
  | "unknown";

export type EventKind =
  | "aborted"
  | "compaction"
  | "model_change"
  | "thinking_level"
  | "hook"
  | "pr_link"
  | "slash_command"
  | "info"
  | "error"
  | "sub_agent"
  | "goal"
  | "other";

/** 大内容的「按需取」引用:前端不解析,原样回传给后端 */
export type ContentRef =
  | { kind: "jsonl"; offset: number; len: number; pointer: string }
  | {
      kind: "sqlite";
      table: string;
      id: string;
      column: string;
      pointer: string;
    }
  | { kind: "file"; relPath: string; pointer: string }
  | { kind: "sidecar"; relPath: string };

export type ImageSource =
  | { kind: "inline"; content: ContentRef }
  | { kind: "local_file"; path: string };

export interface ImageRef {
  source: ImageSource;
  mediaType: string;
  /** 解码后的字节数估算 */
  size: number;
  alt?: string;
}

export interface DiffFile {
  path: string;
  op: "add" | "update" | "delete" | "rename";
  added: number;
  removed: number;
}

export interface DiffSummary {
  files: DiffFile[];
  added: number;
  removed: number;
  full?: ContentRef;
}

export interface TextBlock {
  type: "text";
  /** 正文;带 full 时只是预览(超长注入文本) */
  text: string;
  full?: ContentRef;
}

export interface ThinkingBlock {
  type: "thinking";
  /** 可见正文的预览;可能为空(加密/只有签名) */
  text: string;
  summary?: string;
  redacted?: boolean;
  durationMs?: number;
  full?: ContentRef;
}

export interface ToolCallBlock {
  type: "tool_call";
  /** 与 ToolResultBlock.callId 配对 */
  id: string;
  rawName: string;
  kind: ToolKind;
  title: string;
  detail?: string;
  server?: string;
  inputPreview: string;
  inputTotalLen: number;
  inputFull?: ContentRef;
  diff?: DiffSummary;
  byUser?: boolean;
}

export interface ToolResultBlock {
  type: "tool_result";
  /** 为空串表示源数据没有配对信息,显示为通用「工具输出」 */
  callId: string;
  status: ToolStatus;
  preview: string;
  totalLen: number;
  lineCount: number;
  truncated: boolean;
  full?: ContentRef;
  exitCode?: number;
  durationMs?: number;
  images?: ImageRef[];
  savedPath?: string;
}

export interface ImageBlock {
  type: "image";
  image: ImageRef;
}

export interface EventBlock {
  type: "event";
  kind: EventKind;
  /** 说明;带 full 时只是预览(压缩摘要等长文本) */
  text?: string;
  url?: string;
  full?: ContentRef;
}

export interface StepBlock {
  type: "step";
  phase: "start" | "finish";
  tokens?: number;
  costUsd?: number;
  reason?: string;
}

export type SessionBlock =
  | TextBlock
  | ThinkingBlock
  | ToolCallBlock
  | ToolResultBlock
  | ImageBlock
  | EventBlock
  | StepBlock;

export interface MessageMeta {
  model?: string;
  inputTokens?: number;
  outputTokens?: number;
  cacheReadTokens?: number;
  cacheWriteTokens?: number;
  reasoningTokens?: number;
  costUsd?: number;
  durationMs?: number;
  stopReason?: string;
}

export interface SessionMessage {
  role: string;
  /**
   * 旧格式的纯文本内容:只有 blocks 缺失时(旧后端)才下发,
   * 有 blocks 时前端一律从 blocks 推导(见 reader/turns.ts `messageText`)
   */
  content?: string;
  ts?: number;
  id?: string;
  turnId?: string;
  injected?: boolean;
  /** 旧后端 / 尚未迁移的解析器会省略 → 前端按 content 兜底 */
  blocks?: SessionBlock[];
  meta?: MessageMeta;
}

export interface TurnIndex {
  turnId: string;
  firstMessageIndex: number;
  lastMessageIndex: number;
  questionPreview: string;
  ts?: number;
  stepCount: number;
  errorCount: number;
  hasFinalReply: boolean;
  aborted: boolean;
}

export type TranscriptChunk =
  | {
      type: "header";
      total: number;
      turns: TurnIndex[];
      cached: boolean;
      parseMs: number;
    }
  | { type: "messages"; start: number; messages: SessionMessage[] }
  | { type: "done"; payloadBytes: number }
  | { type: "error"; message: string };

// MCP 服务器连接参数(宽松:允许扩展字段)
export interface McpServerSpec {
  // 可选:社区常见 .mcp.json 中 stdio 配置可不写 type
  type?: "stdio" | "http" | "sse";
  // stdio 字段
  command?: string;
  args?: string[];
  env?: Record<string, string>;
  cwd?: string;
  // http 和 sse 字段
  url?: string;
  headers?: Record<string, string>;
  // 通用字段
  [key: string]: any;
}

// v3.7.0: MCP 服务器应用启用状态
export interface McpApps {
  mcode?: boolean;
  kimi?: boolean;
  codebuddy?: boolean;
  dsh?: boolean;
  workbuddy?: boolean;
  agy?: boolean;
  copilot?: boolean;
  claude: boolean;
  "claude-desktop"?: boolean;
  codex: boolean;
  gemini: boolean;
  grokbuild?: boolean;
  opencode: boolean;
  openclaw: boolean;
  hermes: boolean;
  pi?: boolean;
  omp?: boolean;
  zcode?: boolean;
  qoder?: boolean;
}

// MCP 服务器条目(v3.7.0 统一结构)
export interface McpServer {
  id: string;
  name: string;
  server: McpServerSpec;
  apps: McpApps; // v3.7.0: 标记应用到哪些客户端
  description?: string;
  tags?: string[];
  homepage?: string;
  docs?: string;
  // 兼容旧字段(v3.6.x 及以前)
  enabled?: boolean; // 已废弃,v3.7.0 使用 apps 字段
  source?: string;
  [key: string]: any;
}

// MCP 服务器映射(id -> McpServer)
export type McpServersMap = Record<string, McpServer>;

// ============================================================================
// 统一供应商(Universal Provider)- 跨应用共享配置
// ============================================================================

// 统一供应商的应用启用状态
export interface UniversalProviderApps {
  claude: boolean;
  codex: boolean;
  gemini: boolean;
}

// Claude 模型配置
export interface ClaudeModelConfig {
  model?: string;
  haikuModel?: string;
  sonnetModel?: string;
  opusModel?: string;
}

// Codex 模型配置
export interface CodexModelConfig {
  model?: string;
  reasoningEffort?: string;
}

// Gemini 模型配置
export interface GeminiModelConfig {
  model?: string;
}

// 各应用的模型配置
export interface UniversalProviderModels {
  claude?: ClaudeModelConfig;
  codex?: CodexModelConfig;
  gemini?: GeminiModelConfig;
}

// 统一供应商(跨应用共享配置)
export interface UniversalProvider {
  id: string;
  name: string;
  providerType: string; // "newapi" | "custom" 等
  apps: UniversalProviderApps;
  baseUrl: string;
  apiKey: string;
  models: UniversalProviderModels;
  websiteUrl?: string;
  notes?: string;
  icon?: string;
  iconColor?: string;
  meta?: ProviderMeta;
  createdAt?: number;
  sortIndex?: number;
}

// 统一供应商映射(id -> UniversalProvider)
export type UniversalProvidersMap = Record<string, UniversalProvider>;

// ============================================================================
// OpenCode 专属配置(v3.9.2+)
// ============================================================================

// OpenCode 模型配置
export interface OpenCodeModel {
  name: string;
  limit?: {
    context?: number;
    output?: number;
  };
  options?: Record<string, unknown>; // 模型级别额外选项(provider 路由等)
  // 支持任意额外字段(cost、modalities、thinking、variants 等)
  [key: string]: unknown;
}

// OpenCode 供应商选项
export interface OpenCodeProviderOptions {
  baseURL?: string;
  apiKey?: string;
  headers?: Record<string, string>;
  // 支持额外选项(timeout, setCacheKey 等)
  [key: string]: unknown;
}

// OpenCode 供应商配置(settings_config 结构)
export interface OpenCodeProviderConfig {
  npm: string; // AI SDK 包名,如 "@ai-sdk/openai-compatible"
  name?: string; // 供应商显示名称
  options: OpenCodeProviderOptions;
  models: Record<string, OpenCodeModel>;
}

// ============================================================================
// OpenClaw 专属配置(v3.11.0+)
// ============================================================================

// OpenClaw 模型配置
export interface OpenClawModel {
  id: string;
  name: string;
  alias?: string;
  reasoning?: boolean; // 是否支持推理模式(如 o1、DeepSeek R1)
  input?: string[]; // 支持的输入类型(如 ["text"]、["text", "image"])
  cost?: {
    input: number;
    output: number;
    cacheRead?: number; // 缓存读取价格
    cacheWrite?: number; // 缓存写入价格
  };
  contextWindow?: number;
  maxTokens?: number; // 最大输出 token 数
  compat?: {
    maxTokensField?: string; // 最大输出 token 请求字段名(如 "max_tokens")
    supportsTools?: boolean; // 自定义供应商声明模型支持工具调用
    toolSchemaProfile?: string; // 工具 schema 清理档案(如 llama-server 用 "llamacpp")
    supportsReasoningEffort?: boolean; // 接受 reasoning effort 参数
    supportedReasoningEfforts?: string[]; // 接口接受的 effort 档位
  };
}

// OpenClaw 默认模型配置(agents.defaults.model)
export interface OpenClawDefaultModel {
  primary: string;
  fallbacks?: string[];
}

// OpenClaw 模型目录条目(agents.defaults.models 中的值)
export interface OpenClawModelCatalogEntry {
  alias?: string;
  params?: { thinking?: string };
}

export interface OpenClawHealthWarning {
  code: string;
  message: string;
  path?: string;
}

export interface OpenClawWriteOutcome {
  backupPath?: string;
  warnings: OpenClawHealthWarning[];
}

export type OpenClawToolsProfile = "minimal" | "coding" | "messaging" | "full";

// OpenClaw 供应商配置(settings_config 结构)
// 对应 OpenClaw 的 models.providers.<provider-id> 配置
export interface OpenClawProviderConfig {
  baseUrl?: string; // API 端点
  apiKey?: string; // API 密钥
  api?: string; // API 协议类型(如 "openai-completions"、"anthropic")
  models?: OpenClawModel[]; // 可用模型列表
  headers?: Record<string, string>; // 自定义请求头(如 User-Agent)
  authHeader?: boolean; // 供应商自定义认证开关(如 Longcat)
}

// OpenClaw agents.defaults 完整配置
export interface OpenClawAgentsDefaults {
  model?: OpenClawDefaultModel;
  models?: Record<string, OpenClawModelCatalogEntry>;
  timeoutSeconds?: number;
  timeout?: number;
  [key: string]: unknown; // preserve unknown fields
}

// OpenClaw env 配置(openclaw.json 的 env 节点)
export interface OpenClawEnvConfig {
  [key: string]: unknown;
}

// OpenClaw tools 配置(openclaw.json 的 tools 节点)
export interface OpenClawToolsConfig {
  profile?: OpenClawToolsProfile | string;
  allow?: string[];
  deny?: string[];
  [key: string]: unknown; // preserve unknown fields
}

// ============================================================================
// Hermes Agent 专属配置
// ============================================================================

export interface HermesModelConfig {
  default?: string;
  provider?: string;
  base_url?: string;
  context_length?: number;
  max_tokens?: number;
  [key: string]: unknown;
}

export type HermesMemoryKind = "memory" | "user";

export interface HermesMemoryLimits {
  memory: number;
  user: number;
  memoryEnabled: boolean;
  userEnabled: boolean;
}

// ============================================================================
// ZCode Agent 专属配置
// 对应 ~/.zcode/v2/provider_config.json 的个人规则(providerConfigRules.providerRules[])
// ============================================================================

// ZCode 模型配置
export interface ZCodeModel {
  name?: string;
  limit?: {
    context?: number;
    output?: number;
  };
  modalities?: {
    input: string[];
    output: string[];
  };
  reasoning?: {
    enabled?: boolean;
    variants?: string[];
    defaultVariant?: string;
  };
  // 支持任意额外字段(cost 等)
  [key: string]: unknown;
}

// ZCode 供应商选项
export interface ZCodeProviderOptions {
  baseURL?: string;
  apiKey?: string;
  // 支持额外选项(headers 等)
  [key: string]: unknown;
}

// ZCode 供应商配置(settings_config 结构)
export interface ZCodeProviderConfig {
  name?: string;
  kind?: string; // "anthropic" | "openai-compatible" | "openai"
  options?: ZCodeProviderOptions;
  enabled?: boolean | null;
  source?: string;
  models?: Record<string, ZCodeModel>;
  // 支持任意额外字段
  [key: string]: unknown;
}