Skip to main content

yapi_core/
config.rs

1//! Where yapi keeps its state. Same layout as pi, under yapi's own directories.
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use crate::tools::path::{expand, home_dir};
7
8/// Application name in messages and paths.
9pub const APP_NAME: &str = "yapi";
10/// Project configuration directory name.
11pub const PROJECT_DIR: &str = ".yapi";
12/// Environment variable overriding the agent directory.
13pub const AGENT_DIR_ENV: &str = "YAPI_CODING_AGENT_DIR";
14/// Environment variable overriding the session directory. `--session-dir` wins.
15pub const SESSION_DIR_ENV: &str = "YAPI_CODING_AGENT_SESSION_DIR";
16
17/// Set once offline mode is on for the process.
18static OFFLINE: AtomicBool = AtomicBool::new(false);
19
20/// Environment variable that turns on project-only mode, as
21/// `--project-only` does. Child processes get it while the mode is on.
22pub const PROJECT_ONLY_ENV: &str = "YAPI_PROJECT_ONLY";
23
24/// Set once project-only mode is on for the process.
25static PROJECT_ONLY: AtomicBool = AtomicBool::new(false);
26
27/// Turns on project-only mode for the process: runs load the project's
28/// packages, skills and MCP servers, and of the user's only those the
29/// global `projectOnly` setting keeps. Every child's environment gets
30/// `YAPI_PROJECT_ONLY=1`, so a yapi it starts runs in the mode too.
31pub fn set_project_only() {
32    PROJECT_ONLY.store(true, Ordering::Relaxed);
33}
34
35/// Whether project-only mode is on for the process.
36pub fn project_only() -> bool {
37    PROJECT_ONLY.load(Ordering::Relaxed)
38}
39
40/// The variables pi sets on its own process in offline mode.
41const OFFLINE_ENV: [&str; 2] = ["PI_OFFLINE", "PI_SKIP_VERSION_CHECK"];
42
43/// Turns on offline mode for the process, as pi does for `--offline` or a
44/// true `PI_OFFLINE`: from then on `PI_OFFLINE` and `PI_SKIP_VERSION_CHECK`
45/// read as `1` here and in every child's environment.
46pub fn set_offline() {
47    OFFLINE.store(true, Ordering::Relaxed);
48}
49
50/// Environment variable `name`, with the values offline mode sets.
51pub fn env_var(name: &str) -> Option<String> {
52    if OFFLINE.load(Ordering::Relaxed) && OFFLINE_ENV.contains(&name) {
53        return Some("1".to_owned());
54    }
55    std::env::var(name).ok()
56}
57
58/// Whether environment variable `name` is set and not empty, as pi tests
59/// `process.env.PI_OFFLINE` and `PI_SKIP_VERSION_CHECK`.
60pub fn env_set(name: &str) -> bool {
61    env_var(name).is_some_and(|value| !value.is_empty())
62}
63
64/// Variables every child process gets, as pi sets them on its own process:
65/// the agent markers `PI_CODING_AGENT=true` and `AI_AGENT=yapi`, the offline
66/// variables in offline mode, `YAPI_PROJECT_ONLY=1` in project-only mode,
67/// and the proxy from the `httpProxy` setting where the environment has
68/// none.
69pub fn child_env() -> Vec<(&'static str, String)> {
70    let mut env = vec![
71        ("PI_CODING_AGENT", "true".to_owned()),
72        ("AI_AGENT", APP_NAME.to_owned()),
73    ];
74    if OFFLINE.load(Ordering::Relaxed) {
75        env.extend(OFFLINE_ENV.map(|name| (name, "1".to_owned())));
76    }
77    if project_only() {
78        env.push((PROJECT_ONLY_ENV, "1".to_owned()));
79    }
80    env.extend(yapi_ai::http::proxy_env());
81    env
82}
83
84/// The agent directory: `YAPI_CODING_AGENT_DIR`, else `~/.yapi/agent`.
85pub fn agent_dir() -> PathBuf {
86    match std::env::var(AGENT_DIR_ENV) {
87        Ok(dir) if !dir.is_empty() => PathBuf::from(expand(&dir)),
88        _ => home_dir().join(PROJECT_DIR).join("agent"),
89    }
90}
91
92/// Where sessions for `cwd` live by default:
93/// `<agent>/sessions/--<cwd with separators as dashes>--`, both resolved
94/// against the process directory.
95pub fn default_session_dir(agent_dir: &Path, cwd: &Path) -> PathBuf {
96    let base = std::env::current_dir().unwrap_or_default();
97    let resolve = |path: &Path| crate::tools::path::resolve_lexically(&base, path);
98    let cwd = resolve(cwd);
99    let text = cwd.to_string_lossy();
100    let trimmed = text.trim_start_matches(['/', '\\']);
101    let safe: String = trimmed
102        .chars()
103        .map(|c| {
104            if matches!(c, '/' | '\\' | ':') {
105                '-'
106            } else {
107                c
108            }
109        })
110        .collect();
111    resolve(agent_dir)
112        .join("sessions")
113        .join(format!("--{safe}--"))
114}
115
116/// Whether environment variable `name` is set to `1`, `true` or `yes`, as pi
117/// reads `PI_OFFLINE`.
118pub fn env_flag(name: &str) -> bool {
119    env_var(name).is_some_and(|value| {
120        value == "1" || matches!(value.to_lowercase().as_str(), "true" | "yes")
121    })
122}
123
124/// The documentation the model reads: yapi's pages, with pi's README, docs
125/// and examples under `pi/`. The installer or yapi's first run puts it here.
126pub fn docs_dir(agent_dir: &Path) -> PathBuf {
127    agent_dir.join("docs")
128}
129
130/// Executables the agent installs for its tools, prepended to `PATH` for commands.
131pub fn bin_dir(agent_dir: &Path) -> PathBuf {
132    agent_dir.join("bin")
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[test]
140    fn session_dirs_match_pi() {
141        assert_eq!(
142            default_session_dir(Path::new("/h/.yapi/agent"), Path::new("/home/user/project")),
143            PathBuf::from("/h/.yapi/agent/sessions/--home-user-project--")
144        );
145    }
146}