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

6.8 KB
Raw Blame
use std::path::{Path, PathBuf};

use crate::app_config::AppType;
use crate::codex_config::get_codex_auth_path;
use crate::config::get_claude_settings_path;
use crate::error::AppError;
use crate::gemini_config::get_gemini_dir;
use crate::openclaw_config::get_openclaw_dir;
use crate::opencode_config::get_opencode_dir;

pub(crate) fn validate_prompt_content(app: &AppType, content: &str) -> Result<(), AppError> {
    if matches!(app, AppType::Mcode) && content.len() > 32 * 1024 {
        return Err(AppError::InvalidInput(
            "MCode global instructions must not exceed 32 KiB".into(),
        ));
    }
    Ok(())
}

/// 返回指定应用所使用的提示词文件路径。
pub fn prompt_file_path(app: &AppType) -> Result<PathBuf, AppError> {
    if matches!(app, AppType::ClaudeDesktop) {
        return Err(AppError::localized(
            "app.prompts_unsupported",
            "当前应用暂不支持 Prompts",
            "This app does not support Prompts",
        ));
    }

    let base_dir: PathBuf = match app {
        AppType::Claude => get_base_dir_with_fallback(get_claude_settings_path(), ".claude"),
        AppType::Codex => get_base_dir_with_fallback(get_codex_auth_path(), ".codex"),
        AppType::Gemini => get_gemini_dir(),
        AppType::GrokBuild => crate::grok_config::get_grok_config_dir(),
        AppType::OpenCode => get_opencode_dir(),
        AppType::OpenClaw => get_openclaw_dir(),
        AppType::Hermes => crate::hermes_config::get_hermes_dir(),
        AppType::Pi => crate::pi_config::get_pi_agent_dir()?,
        AppType::Mcode => crate::mcode_config::data_dir(),
        AppType::Dsh => crate::dsh_config::data_dir(),
        AppType::Kimi => crate::kimi_config::data_dir(),
        AppType::Codebuddy => crate::codebuddy_config::data_dir(),
        // agy 只从各「定制根目录」读独立的 AGENTS.md;全局那一个是 ~/.gemini/config,Key 模式的
        // 私有 --gemini_dir 也经软链共享它。别用 ~/.gemini/GEMINI.md:那是 Gemini CLI 的。
        AppType::Agy => crate::agy_config::customizations_dir(),
        // omp 只读按 profile 切换的 agent 目录里的 AGENTS.md(上游 discovery/builtin.ts)
        AppType::Omp => crate::omp_config::get_omp_agent_dir()?,
        // Copilot CLI 的个人指令是 `~/.copilot/copilot-instructions.md`(`copilot instruction list`)。
        AppType::Copilot => crate::copilot_config::copilot_dir(),
        // WorkBuddy 桌面端关掉了引擎的 CODEBUDDY.md 注入(CODEBUDDY_DISABLE_SYSTEM_REMINDER_MD=1),
        // 用户级说明是当前账号目录下的 MEMORY.md(MemoryCollector 以 <user_instructions> 注入,
        // 每次最多 4000 字)。目录随登录的账号变,没登录时是数据目录本身。
        AppType::WorkBuddy => crate::services::workbuddy_account::user_data_dir(),
        // ZCode 的全局指令是 `$ZCODE_HOME/AGENTS.md`(cli/ 上一级)。
        AppType::ZCode => crate::zcode_config::get_zcode_dir(),
        // Qoder CLI 读数据目录下的 AGENTS.md,国际版 / 国内版各一个,按设置里选的版本。
        AppType::Qoder => crate::qoder_config::data_dir(crate::qoder_config::current_edition()),
        AppType::ClaudeDesktop => unreachable!("handled above"),
    };

    let filename = match app {
        AppType::Claude => "CLAUDE.md",
        AppType::Codex => "AGENTS.md",
        AppType::Gemini => "GEMINI.md",
        AppType::GrokBuild | AppType::OpenCode | AppType::OpenClaw => "AGENTS.md",
        AppType::Hermes => "SOUL.md",
        AppType::Codebuddy => "CODEBUDDY.md",
        AppType::Pi
        | AppType::Mcode
        | AppType::Agy
        | AppType::Kimi
        | AppType::Dsh
        | AppType::Omp => "AGENTS.md",
        AppType::Copilot => "copilot-instructions.md",
        AppType::WorkBuddy => "MEMORY.md",
        AppType::ZCode | AppType::Qoder => "AGENTS.md",
        AppType::ClaudeDesktop => unreachable!("handled above"),
    };

    Ok(base_dir.join(filename))
}

/// 把用户主目录前缀换成 `~`,给界面显示用(复制路径仍用完整路径)。
pub fn display_path(path: &Path) -> String {
    display_path_with_home(path, &crate::config::get_home_dir())
}

fn display_path_with_home(path: &Path, home: &Path) -> String {
    match path.strip_prefix(home) {
        Ok(rest) if rest.as_os_str().is_empty() => "~".to_string(),
        Ok(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()),
        Err(_) => path.display().to_string(),
    }
}

fn get_base_dir_with_fallback(primary_path: PathBuf, fallback_dir: &str) -> PathBuf {
    primary_path
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| crate::config::get_home_dir().join(fallback_dir))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn mcode_instructions_limit_counts_utf8_bytes() {
        assert!(validate_prompt_content(&AppType::Mcode, &"a".repeat(32768)).is_ok());
        assert!(validate_prompt_content(&AppType::Mcode, &"a".repeat(32769)).is_err());
        assert!(validate_prompt_content(&AppType::Mcode, &"中".repeat(10923)).is_err());
        assert!(validate_prompt_content(&AppType::OpenCode, &"中".repeat(10923)).is_ok());
    }

    #[test]
    fn display_path_shortens_the_home_prefix_only() {
        let home = Path::new("/Users/me");
        let sep = std::path::MAIN_SEPARATOR;
        assert_eq!(
            display_path_with_home(&home.join(".hermes").join("SOUL.md"), home),
            format!("~{sep}.hermes{sep}SOUL.md")
        );
        assert_eq!(display_path_with_home(home, home), "~");
        assert_eq!(
            display_path_with_home(Path::new("/opt/hermes/SOUL.md"), home),
            "/opt/hermes/SOUL.md"
        );
        // 只认整段目录前缀,不把 /Users/meow 当成 /Users/me 下面
        assert_eq!(
            display_path_with_home(Path::new("/Users/meow/SOUL.md"), home),
            "/Users/meow/SOUL.md"
        );
    }

    #[test]
    fn hermes_prompt_file_uses_soul_md() {
        let path = prompt_file_path(&AppType::Hermes).expect("Hermes prompt path");

        assert_eq!(
            path.file_name().and_then(|name| name.to_str()),
            Some("SOUL.md")
        );
    }

    #[test]
    fn pi_prompt_file_uses_agents_md() {
        let path = prompt_file_path(&AppType::Pi).expect("Pi prompt path");

        assert_eq!(
            path.file_name().and_then(|name| name.to_str()),
            Some("AGENTS.md")
        );
    }

    #[test]
    fn get_base_dir_with_fallback_uses_parent_or_home_fallback() {
        let primary = Path::new("custom").join("settings.json");
        assert_eq!(
            get_base_dir_with_fallback(primary, ".claude"),
            PathBuf::from("custom")
        );
        assert_eq!(
            get_base_dir_with_fallback(PathBuf::new(), ".claude"),
            crate::config::get_home_dir().join(".claude")
        );
    }
}