opencode-provider-manager 0.1.7-beta.4

TUI/CLI binary crate for managing OpenCode provider configs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Configuration file management for oh-my-openagent.
//!
//! Handles reading, writing, and path resolution for agent config files.
//!
//! Config file locations (matching oh-my-openagent conventions):
//! - Project: `.opencode/oh-my-opencode.json[c]` or `.opencode/oh-my-openagent.json[c]`
//! - Global:  `~/.config/opencode/oh-my-opencode.json[c]` (XDG) or `%APPDATA%\opencode\oh-my-opencode.json[c]` (Windows)

use crate::omo_config::error::{AgentConfigError, Result};
use crate::omo_config::types::OhMyOpencodeConfig;
use std::path::{Path, PathBuf};

/// Which configuration layer to operate on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ConfigLayer {
    /// Global config: `~/.config/opencode/oh-my-opencode.json`
    Global,
    /// Project config: `.opencode/oh-my-opencode.json`
    Project,
}

/// Manages agent configuration files.
#[derive(Debug, Clone, PartialEq)]
pub struct AgentConfigManager {
    /// Global config file path.
    pub global_path: PathBuf,
    /// Project config file path.
    pub project_path: Option<PathBuf>,
    /// Cached global config.
    pub global_config: Option<OhMyOpencodeConfig>,
    /// Cached project config.
    pub project_config: Option<OhMyOpencodeConfig>,
}

impl AgentConfigManager {
    /// Create a new manager with default paths.
    pub fn new() -> Result<Self> {
        let global_path = default_global_path()?;
        let project_path = find_project_path();

        Ok(Self {
            global_path,
            project_path,
            global_config: None,
            project_config: None,
        })
    }

    /// Load all configs (global + project).
    pub fn load_all(
        &mut self,
    ) -> Result<(&Option<OhMyOpencodeConfig>, &Option<OhMyOpencodeConfig>)> {
        self.global_config = self.load_layer(ConfigLayer::Global)?;
        self.project_config = self.load_layer(ConfigLayer::Project)?;
        Ok((&self.global_config, &self.project_config))
    }

    /// Load a single config layer.
    pub fn load_layer(&self, layer: ConfigLayer) -> Result<Option<OhMyOpencodeConfig>> {
        let path = match layer {
            ConfigLayer::Global => &self.global_path,
            ConfigLayer::Project => {
                let Some(ref path) = self.project_path else {
                    return Ok(None);
                };
                path
            }
        };

        if !path.exists() {
            return Ok(None);
        }

        let content = std::fs::read_to_string(path).map_err(|e| AgentConfigError::ReadError {
            path: path.clone(),
            source: e,
        })?;

        let config = parse_config_content(&content, path)?;
        Ok(Some(config))
    }

    /// Save a config layer to disk.
    pub fn save(&self, layer: ConfigLayer, config: &OhMyOpencodeConfig) -> Result<()> {
        let path = match layer {
            ConfigLayer::Global => &self.global_path,
            ConfigLayer::Project => {
                let Some(ref path) = self.project_path else {
                    return Err(AgentConfigError::InvalidLayer("project".to_string()));
                };
                path
            }
        };

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let json =
            serde_json::to_string_pretty(config).map_err(AgentConfigError::SerializeError)?;

        std::fs::write(path, json).map_err(|e| AgentConfigError::WriteError {
            path: path.clone(),
            source: e,
        })?;

        Ok(())
    }

    /// Get the path for a specific layer.
    pub fn path_for(&self, layer: ConfigLayer) -> &Path {
        match layer {
            ConfigLayer::Global => &self.global_path,
            ConfigLayer::Project => self
                .project_path
                .as_deref()
                .unwrap_or_else(|| Path::new(".opencode/oh-my-opencode.json")),
        }
    }
}

impl Default for AgentConfigManager {
    fn default() -> Self {
        Self::new().unwrap_or_else(|_| Self {
            global_path: default_global_path_fallback(),
            project_path: None,
            global_config: None,
            project_config: None,
        })
    }
}

/// Parse config content from various formats (JSON / JSONC / TOML / YAML).
fn parse_config_content(content: &str, path: &Path) -> Result<OhMyOpencodeConfig> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_lowercase();

    match ext.as_str() {
        "jsonc" => parse_jsonc(content, path),
        "json" | "" => {
            // Try JSONC first (handles comments if present), fall back to plain JSON
            if content.contains("//") || content.contains("/*") {
                parse_jsonc(content, path)
            } else {
                serde_json::from_str(content).map_err(|e| AgentConfigError::JsonParseError {
                    path: path.to_path_buf(),
                    source: e,
                })
            }
        }
        "toml" => toml::from_str(content).map_err(|e| AgentConfigError::TomlParseError {
            path: path.to_path_buf(),
            source: Box::new(e),
        }),
        "yaml" | "yml" => {
            serde_yaml::from_str(content).map_err(|e| AgentConfigError::YamlParseError {
                path: path.to_path_buf(),
                source: Box::new(e),
            })
        }
        other => Err(AgentConfigError::UnsupportedFormat {
            format: other.to_string(),
            path: path.to_path_buf(),
        }),
    }
}

/// Parse JSONC content using jsonc-parser crate.
fn parse_jsonc(content: &str, path: &Path) -> Result<OhMyOpencodeConfig> {
    let parsed = jsonc_parser::parse_to_value(content, &Default::default())
        .map_err(|e| AgentConfigError::Other(format!("JSONC parse error: {}", e)))?;

    let Some(value) = parsed else {
        return Err(AgentConfigError::Other(
            "JSONC parse returned None".to_string(),
        ));
    };

    let serde_value = jsonc_to_serde(value);
    serde_json::from_value(serde_value).map_err(|e| AgentConfigError::JsonParseError {
        path: path.to_path_buf(),
        source: e,
    })
}

/// Convert jsonc_parser::JsonValue to serde_json::Value.
fn jsonc_to_serde(value: jsonc_parser::JsonValue) -> serde_json::Value {
    match value {
        jsonc_parser::JsonValue::String(s) => serde_json::Value::String(s.into_owned()),
        jsonc_parser::JsonValue::Number(n) => {
            serde_json::Value::Number(n.parse().unwrap_or_else(|_| serde_json::Number::from(0)))
        }
        jsonc_parser::JsonValue::Boolean(b) => serde_json::Value::Bool(b),
        jsonc_parser::JsonValue::Object(obj) => {
            let map = obj
                .take_inner()
                .into_iter()
                .map(|(k, v)| (k, jsonc_to_serde(v)))
                .collect();
            serde_json::Value::Object(map)
        }
        jsonc_parser::JsonValue::Array(arr) => {
            serde_json::Value::Array(arr.take_inner().into_iter().map(jsonc_to_serde).collect())
        }
        jsonc_parser::JsonValue::Null => serde_json::Value::Null,
    }
}

/// Default global config path: `~/.config/opencode/oh-my-opencode.json`.
/// Prefers `.jsonc` if it exists.
///
/// Checks both platform config dir (e.g., `%APPDATA%\opencode` on Windows)
/// and `~/.config/opencode` (Unix-style, also used by oh-my-opencode on Windows).
fn default_global_path() -> Result<PathBuf> {
    let mut bases = Vec::new();

    // Platform config dir (e.g., %APPDATA%/opencode on Windows, ~/.config on Linux)
    if let Some(config_dir) = dirs::config_dir() {
        bases.push(config_dir.join("opencode"));
    }

    // Unix-style ~/.config/opencode (also used by oh-my-opencode on Windows)
    if let Some(home_dir) = dirs::home_dir() {
        let unix_style = home_dir.join(".config").join("opencode");
        if !bases.contains(&unix_style) {
            bases.push(unix_style);
        }
    }

    if bases.is_empty() {
        return Err(AgentConfigError::Other(
            "Could not determine config directory".to_string(),
        ));
    }

    // Prefer .jsonc, then .json; prefer oh-my-opencode, then oh-my-openagent
    for base in &bases {
        for filename in [
            "oh-my-opencode.jsonc",
            "oh-my-opencode.json",
            "oh-my-openagent.jsonc",
            "oh-my-openagent.json",
        ] {
            let path = base.join(filename);
            if path.exists() {
                return Ok(path);
            }
        }
    }

    // Default to oh-my-opencode.jsonc in the first available directory
    Ok(bases[0].join("oh-my-opencode.jsonc"))
}

/// Fallback global path for Default impl when dirs::config_dir() fails.
fn default_global_path_fallback() -> PathBuf {
    PathBuf::from("~/.config/opencode/oh-my-opencode.jsonc")
}

/// Find the project config by walking up from the current directory.
/// Looks in `.opencode/` for `oh-my-opencode.json[c]` or `oh-my-openagent.json[c]`.
fn find_project_path() -> Option<PathBuf> {
    let mut current = std::env::current_dir().ok()?;

    loop {
        let opencode_dir = current.join(".opencode");

        // Check .opencode/ directory first
        if opencode_dir.is_dir() {
            for filename in [
                "oh-my-opencode.jsonc",
                "oh-my-opencode.json",
                "oh-my-openagent.jsonc",
                "oh-my-openagent.json",
            ] {
                let path = opencode_dir.join(filename);
                if path.exists() {
                    return Some(path);
                }
            }
        }

        // Also check root-level fallback (legacy location)
        for filename in [
            "oh-my-opencode.jsonc",
            "oh-my-opencode.json",
            "oh-my-openagent.jsonc",
            "oh-my-openagent.json",
        ] {
            let path = current.join(filename);
            if path.exists() {
                return Some(path);
            }
        }

        // Stop at git root
        if current.join(".git").exists() {
            return None;
        }

        match current.parent() {
            Some(parent) => current = parent.to_path_buf(),
            None => return None,
        }
    }
}

/// Parse a config file directly from a path.
pub fn parse_config_file(path: &Path) -> Result<OhMyOpencodeConfig> {
    if !path.exists() {
        return Err(AgentConfigError::NotFound(path.to_path_buf()));
    }

    let content = std::fs::read_to_string(path).map_err(|e| AgentConfigError::ReadError {
        path: path.to_path_buf(),
        source: e,
    })?;

    parse_config_content(&content, path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_parse_json_config() {
        let json = r#"{
            "$schema": "https://example.com/schema.json",
            "newTaskSystemEnabled": true,
            "defaultRunAgent": "build",
            "agents": {
                "build": {
                    "model": "anthropic/claude-sonnet-4-5",
                    "temperature": 0.7
                }
            }
        }"#;

        let mut file = NamedTempFile::with_suffix(".json").unwrap();
        file.write_all(json.as_bytes()).unwrap();

        let config = parse_config_file(file.path()).unwrap();
        assert_eq!(config.new_task_system_enabled, Some(true));
        assert_eq!(config.default_run_agent.as_deref(), Some("build"));
        assert!(config.agents.is_some());
    }

    #[test]
    fn test_parse_jsonc_with_comments() {
        let jsonc = r#"{
            // This is a comment
            "$schema": "https://example.com/schema.json",
            /* multi-line
               comment */
            "newTaskSystemEnabled": true
        }"#;

        let mut file = NamedTempFile::with_suffix(".jsonc").unwrap();
        file.write_all(jsonc.as_bytes()).unwrap();

        let config = parse_config_file(file.path()).unwrap();
        assert_eq!(config.new_task_system_enabled, Some(true));
    }

    #[test]
    fn test_parse_jsonc_with_trailing_commas() {
        let jsonc = r#"{
            "newTaskSystemEnabled": true,
            "defaultRunAgent": "build",
        }"#;

        let mut file = NamedTempFile::with_suffix(".jsonc").unwrap();
        file.write_all(jsonc.as_bytes()).unwrap();

        let config = parse_config_file(file.path()).unwrap();
        assert_eq!(config.new_task_system_enabled, Some(true));
    }

    #[test]
    fn test_parse_toml_config() {
        let toml = r#"
newTaskSystemEnabled = true
defaultRunAgent = "plan"

[agents.build]
model = "openai/gpt-4o"
temperature = 0.5
"#;

        let mut file = NamedTempFile::with_suffix(".toml").unwrap();
        file.write_all(toml.as_bytes()).unwrap();

        let config = parse_config_file(file.path()).unwrap();
        assert_eq!(config.default_run_agent.as_deref(), Some("plan"));
        let agents = config.agents.unwrap();
        assert!(agents.build.is_some());
    }

    #[test]
    fn test_agent_config_manager_new() {
        let manager = AgentConfigManager::new();
        assert!(manager.is_ok());
    }
}