zag-agent 0.12.4

Core library for zag — a unified interface for AI coding agents
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Configuration management for the zag CLI.
//!
//! Configuration is stored in `~/.zag/projects/<sanitized-path>/zag.toml`,
//! where the sanitized path is derived from the git repository root or explicit `--root`.

use anyhow::{Context, Result};
use log::debug;
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Agent-specific model configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AgentModels {
    pub claude: Option<String>,
    pub codex: Option<String>,
    pub gemini: Option<String>,
    pub copilot: Option<String>,
    pub ollama: Option<String>,
}

/// Ollama-specific configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OllamaConfig {
    /// Default model name (default: "qwen3.5")
    pub model: Option<String>,
    /// Default parameter size (default: "9b")
    pub size: Option<String>,
    /// Parameter size for small alias
    pub size_small: Option<String>,
    /// Parameter size for medium alias
    pub size_medium: Option<String>,
    /// Parameter size for large alias
    pub size_large: Option<String>,
}

/// Default settings applied when not overridden by CLI flags.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Defaults {
    /// Auto-approve all actions (skip permission prompts)
    pub auto_approve: Option<bool>,
    /// Default model size for all agents (small, medium, large)
    pub model: Option<String>,
    /// Default provider (claude, codex, gemini, copilot)
    pub provider: Option<String>,
    /// Default maximum number of agentic turns
    pub max_turns: Option<u32>,
    /// Default system prompt for all agents
    pub system_prompt: Option<String>,
}

/// Auto-selection configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AutoConfig {
    /// Provider used for auto-selection (default: "claude")
    pub provider: Option<String>,
    /// Model used for auto-selection (default: "sonnet")
    pub model: Option<String>,
}

/// Listen command configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ListenConfig {
    /// Default output format: "text", "json", or "rich-text"
    pub format: Option<String>,
    /// strftime-style format for timestamps (default: "%H:%M:%S")
    pub timestamp_format: Option<String>,
}

/// Root configuration structure.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    /// Default settings
    #[serde(default)]
    pub defaults: Defaults,
    /// Per-agent model defaults
    #[serde(default)]
    pub models: AgentModels,
    /// Auto-selection settings
    #[serde(default)]
    pub auto: AutoConfig,
    /// Ollama-specific settings
    #[serde(default)]
    pub ollama: OllamaConfig,
    /// Listen command settings
    #[serde(default)]
    pub listen: ListenConfig,
}

impl Config {
    /// Load configuration from `~/.zag/projects/<id>/zag.toml`.
    ///
    /// The project ID is derived from the git repo root or explicit `--root`.
    /// Returns default config if file doesn't exist.
    pub fn load(root: Option<&str>) -> Result<Self> {
        let path = Self::config_path(root);
        debug!("Loading config from {}", path.display());
        if !path.exists() {
            debug!("Config file not found, using defaults");
            return Ok(Self::default());
        }

        let content = std::fs::read_to_string(&path)
            .with_context(|| format!("Failed to read config: {}", path.display()))?;
        let config: Config = toml::from_str(&content)
            .with_context(|| format!("Failed to parse config: {}", path.display()))?;
        debug!("Config loaded successfully from {}", path.display());
        Ok(config)
    }

    /// Save configuration to `~/.zag/projects/<id>/zag.toml`.
    ///
    /// Creates the directory if it doesn't exist.
    pub fn save(&self, root: Option<&str>) -> Result<()> {
        let path = Self::config_path(root);
        debug!("Saving config to {}", path.display());
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        let content = toml::to_string_pretty(self).context("Failed to serialize config")?;
        std::fs::write(&path, content)
            .with_context(|| format!("Failed to write config: {}", path.display()))?;
        debug!("Config saved to {}", path.display());
        Ok(())
    }

    /// Initialize config file with defaults if it doesn't exist.
    ///
    /// Returns true if a new config was created, false if it already existed.
    pub fn init(root: Option<&str>) -> Result<bool> {
        let path = Self::config_path(root);
        if path.exists() {
            debug!("Config already exists at {}", path.display());
            return Ok(false);
        }

        debug!("Initializing new config at {}", path.display());
        let config = Self::default_with_comments();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        std::fs::write(&path, config)
            .with_context(|| format!("Failed to write config: {}", path.display()))?;

        Ok(true)
    }

    /// Detect git repository root from a given directory.
    /// Returns None if not in a git repository.
    fn find_git_root(start_dir: &Path) -> Option<PathBuf> {
        let output = Command::new("git")
            .arg("rev-parse")
            .arg("--show-toplevel")
            .current_dir(start_dir)
            .output()
            .ok()?;

        if output.status.success() {
            let root = String::from_utf8(output.stdout).ok()?;
            Some(PathBuf::from(root.trim()))
        } else {
            None
        }
    }

    /// Get the global base directory (~/.zag).
    pub fn global_base_dir() -> PathBuf {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".zag")
    }

    /// Sanitize an absolute path into a directory name.
    /// Strips leading `/` and replaces `/` with `-`.
    pub fn sanitize_path(path: &str) -> String {
        path.trim_start_matches('/').replace('/', "-")
    }

    /// Resolve the project directory for config/session storage.
    ///
    /// All state is stored under `~/.zag/`:
    /// - Per-project: `~/.zag/projects/<sanitized-path>/`
    /// - Global (no repo): `~/.zag/`
    fn resolve_project_dir(root: Option<&str>) -> PathBuf {
        let base = Self::global_base_dir();

        // Keep this helper free of logging. It is used by config/session path
        // resolution on hot paths, and debug logging here can re-enter the same
        // resolution flow through logger setup and formatting.
        if let Some(r) = root {
            let sanitized = Self::sanitize_path(r);
            return base.join("projects").join(sanitized);
        }

        let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

        // Try to find git root
        if let Some(git_root) = Self::find_git_root(&current_dir) {
            let sanitized = Self::sanitize_path(&git_root.to_string_lossy());
            return base.join("projects").join(sanitized);
        }

        // Fall back to global base directory (no project subdir)
        base
    }

    /// Get the path to the config file.
    pub fn config_path(root: Option<&str>) -> PathBuf {
        Self::resolve_project_dir(root).join("zag.toml")
    }

    /// Get the project directory path (for sessions, etc.).
    #[allow(dead_code)]
    pub fn agent_dir(root: Option<&str>) -> PathBuf {
        Self::resolve_project_dir(root)
    }

    /// Get the global logs directory path.
    pub fn global_logs_dir() -> PathBuf {
        Self::global_base_dir().join("logs")
    }

    /// Get the default model for a specific agent, if configured.
    /// Checks agent-specific model first, then falls back to defaults.model.
    pub fn get_model(&self, agent: &str) -> Option<&str> {
        // First check agent-specific model
        let agent_model = match agent {
            "claude" => self.models.claude.as_deref(),
            "codex" => self.models.codex.as_deref(),
            "gemini" => self.models.gemini.as_deref(),
            "copilot" => self.models.copilot.as_deref(),
            "ollama" => self.models.ollama.as_deref(),
            _ => None,
        };

        // Return agent-specific model if set, otherwise fall back to default
        agent_model.or(self.defaults.model.as_deref())
    }

    /// Get the global default model (without agent-specific override).
    #[allow(dead_code)]
    pub fn default_model(&self) -> Option<&str> {
        self.defaults.model.as_deref()
    }

    /// Get the ollama model name (default: "qwen3.5").
    pub fn ollama_model(&self) -> &str {
        self.ollama.model.as_deref().unwrap_or("qwen3.5")
    }

    /// Get the ollama default size (default: "9b").
    pub fn ollama_size(&self) -> &str {
        self.ollama.size.as_deref().unwrap_or("9b")
    }

    /// Get the ollama size for a model size alias, with config override.
    pub fn ollama_size_for<'a>(&'a self, size: &'a str) -> &'a str {
        match size {
            "small" | "s" => self.ollama.size_small.as_deref().unwrap_or("2b"),
            "medium" | "m" | "default" => self.ollama.size_medium.as_deref().unwrap_or("9b"),
            "large" | "l" | "max" => self.ollama.size_large.as_deref().unwrap_or("35b"),
            _ => size, // passthrough for explicit sizes like "27b"
        }
    }

    /// Check if auto-approve is enabled by default.
    pub fn auto_approve(&self) -> bool {
        self.defaults.auto_approve.unwrap_or(false)
    }

    /// Get the default max turns, if configured.
    pub fn max_turns(&self) -> Option<u32> {
        self.defaults.max_turns
    }

    /// Get the default system prompt, if configured.
    pub fn system_prompt(&self) -> Option<&str> {
        self.defaults.system_prompt.as_deref()
    }

    /// Get the default provider, if configured.
    pub fn provider(&self) -> Option<&str> {
        self.defaults.provider.as_deref()
    }

    /// Get the auto-selection provider, if configured.
    pub fn auto_provider(&self) -> Option<&str> {
        self.auto.provider.as_deref()
    }

    /// Get the auto-selection model, if configured.
    pub fn auto_model(&self) -> Option<&str> {
        self.auto.model.as_deref()
    }

    /// Get the listen output format, if configured.
    pub fn listen_format(&self) -> Option<&str> {
        self.listen.format.as_deref()
    }

    /// Get the listen timestamp format (strftime-style, default: "%H:%M:%S").
    pub fn listen_timestamp_format(&self) -> &str {
        self.listen
            .timestamp_format
            .as_deref()
            .unwrap_or("%H:%M:%S")
    }

    /// Valid provider names (including "auto").
    #[cfg(not(test))]
    pub const VALID_PROVIDERS: &'static [&'static str] =
        &["claude", "codex", "gemini", "copilot", "ollama", "auto"];

    /// Valid provider names (including "auto" and "mock" for testing).
    #[cfg(test)]
    pub const VALID_PROVIDERS: &'static [&'static str] = &[
        "claude", "codex", "gemini", "copilot", "ollama", "auto", "mock",
    ];

    /// All valid config keys for listing/discovery.
    pub const VALID_KEYS: &'static [&'static str] = &[
        "provider",
        "model",
        "auto_approve",
        "max_turns",
        "system_prompt",
        "model.claude",
        "model.codex",
        "model.gemini",
        "model.copilot",
        "model.ollama",
        "auto.provider",
        "auto.model",
        "ollama.model",
        "ollama.size",
        "ollama.size_small",
        "ollama.size_medium",
        "ollama.size_large",
        "listen.format",
        "listen.timestamp_format",
    ];

    /// Get a config value by dot-notation key.
    /// Get a config value by dot-notation key.
    pub fn get_value(&self, key: &str) -> Option<String> {
        match key {
            "provider" => self.defaults.provider.clone(),
            "model" => self.defaults.model.clone(),
            "auto_approve" => self.defaults.auto_approve.map(|v| v.to_string()),
            "max_turns" => self.defaults.max_turns.map(|v| v.to_string()),
            "system_prompt" => self.defaults.system_prompt.clone(),
            "model.claude" => self.models.claude.clone(),
            "model.codex" => self.models.codex.clone(),
            "model.gemini" => self.models.gemini.clone(),
            "model.copilot" => self.models.copilot.clone(),
            "model.ollama" => self.models.ollama.clone(),
            "auto.provider" => self.auto.provider.clone(),
            "auto.model" => self.auto.model.clone(),
            "ollama.model" => self.ollama.model.clone(),
            "ollama.size" => self.ollama.size.clone(),
            "ollama.size_small" => self.ollama.size_small.clone(),
            "ollama.size_medium" => self.ollama.size_medium.clone(),
            "ollama.size_large" => self.ollama.size_large.clone(),
            "listen.format" => self.listen.format.clone(),
            "listen.timestamp_format" => self.listen.timestamp_format.clone(),
            _ => None,
        }
    }

    /// Set a config value by dot-notation key. Validates inputs.
    pub fn set_value(&mut self, key: &str, value: &str) -> Result<()> {
        debug!("Setting config: {} = {}", key, value);
        match key {
            "provider" => {
                let v = value.to_lowercase();
                if !Self::VALID_PROVIDERS.contains(&v.as_str()) {
                    anyhow::bail!(
                        "Invalid provider '{}'. Available: {}",
                        value,
                        Self::VALID_PROVIDERS.join(", ")
                    );
                }
                self.defaults.provider = Some(v);
            }
            "model" => {
                self.defaults.model = Some(value.to_string());
            }
            "max_turns" => {
                let turns: u32 = value.parse().map_err(|_| {
                    anyhow::anyhow!(
                        "Invalid value '{}' for max_turns. Must be a positive integer.",
                        value
                    )
                })?;
                self.defaults.max_turns = Some(turns);
            }
            "system_prompt" => {
                self.defaults.system_prompt = Some(value.to_string());
            }
            "auto_approve" => match value.to_lowercase().as_str() {
                "true" | "1" | "yes" => self.defaults.auto_approve = Some(true),
                "false" | "0" | "no" => self.defaults.auto_approve = Some(false),
                _ => anyhow::bail!(
                    "Invalid value '{}' for auto_approve. Use true or false.",
                    value
                ),
            },
            "model.claude" => self.models.claude = Some(value.to_string()),
            "model.codex" => self.models.codex = Some(value.to_string()),
            "model.gemini" => self.models.gemini = Some(value.to_string()),
            "model.copilot" => self.models.copilot = Some(value.to_string()),
            "model.ollama" => self.models.ollama = Some(value.to_string()),
            "auto.provider" => self.auto.provider = Some(value.to_string()),
            "auto.model" => self.auto.model = Some(value.to_string()),
            "ollama.model" => self.ollama.model = Some(value.to_string()),
            "ollama.size" => self.ollama.size = Some(value.to_string()),
            "ollama.size_small" => self.ollama.size_small = Some(value.to_string()),
            "ollama.size_medium" => self.ollama.size_medium = Some(value.to_string()),
            "ollama.size_large" => self.ollama.size_large = Some(value.to_string()),
            "listen.format" => {
                let v = value.to_lowercase();
                if !["text", "json", "rich-text"].contains(&v.as_str()) {
                    anyhow::bail!(
                        "Invalid listen format '{}'. Available: text, json, rich-text",
                        value
                    );
                }
                self.listen.format = Some(v);
            }
            "listen.timestamp_format" => {
                self.listen.timestamp_format = Some(value.to_string());
            }
            _ => anyhow::bail!(
                "Unknown config key '{}'. Available: provider, model, auto_approve, max_turns, system_prompt, model.claude, model.codex, model.gemini, model.copilot, model.ollama, auto.provider, auto.model, ollama.model, ollama.size, ollama.size_small, ollama.size_medium, ollama.size_large, listen.format, listen.timestamp_format",
                key
            ),
        }
        Ok(())
    }

    /// Unset a config value by dot-notation key (revert to default).
    pub fn unset_value(&mut self, key: &str) -> Result<()> {
        debug!("Unsetting config: {}", key);
        match key {
            "provider" => self.defaults.provider = None,
            "model" => self.defaults.model = None,
            "auto_approve" => self.defaults.auto_approve = None,
            "max_turns" => self.defaults.max_turns = None,
            "system_prompt" => self.defaults.system_prompt = None,
            "model.claude" => self.models.claude = None,
            "model.codex" => self.models.codex = None,
            "model.gemini" => self.models.gemini = None,
            "model.copilot" => self.models.copilot = None,
            "model.ollama" => self.models.ollama = None,
            "auto.provider" => self.auto.provider = None,
            "auto.model" => self.auto.model = None,
            "ollama.model" => self.ollama.model = None,
            "ollama.size" => self.ollama.size = None,
            "ollama.size_small" => self.ollama.size_small = None,
            "ollama.size_medium" => self.ollama.size_medium = None,
            "ollama.size_large" => self.ollama.size_large = None,
            "listen.format" => self.listen.format = None,
            "listen.timestamp_format" => self.listen.timestamp_format = None,
            _ => anyhow::bail!(
                "Unknown config key '{}'. Run 'zag config list' to see available keys.",
                key
            ),
        }
        Ok(())
    }

    /// Generate default config content with comments.
    fn default_with_comments() -> String {
        r#"# Zag CLI Configuration
# This file configures default behavior for the zag CLI.
# Settings here can be overridden by command-line flags.

[defaults]
# Default provider (claude, codex, gemini, copilot)
# provider = "claude"

# Auto-approve all actions (skip permission prompts)
# auto_approve = false

# Default model size for all agents (small, medium, large)
# Can be overridden per-agent in [models] section
model = "medium"

# Default maximum number of agentic turns
# max_turns = 10

# Default system prompt for all agents
# system_prompt = ""

[models]
# Default models for each agent (overrides defaults.model)
# Use size aliases (small, medium, large) or specific model names
# claude = "opus"
# codex = "gpt-5.4"
# gemini = "auto"
# copilot = "claude-sonnet-4.6"

[auto]
# Settings for auto provider/model selection (-p auto / -m auto)
# provider = "claude"
# model = "haiku"

[ollama]
# Ollama-specific settings
# model = "qwen3.5"
# size = "9b"
# size_small = "2b"
# size_medium = "9b"
# size_large = "35b"

[listen]
# Default output format for listen command: "text", "json", or "rich-text"
# format = "text"
# Timestamp format for --timestamps flag (strftime-style, default: "%H:%M:%S")
# timestamp_format = "%H:%M:%S"
"#
        .to_string()
    }
}

/// Resolve the provider name from a CLI flag, config default, or hardcoded fallback.
///
/// Validates the provider name against [`Config::VALID_PROVIDERS`].
pub fn resolve_provider(flag: Option<&str>, root: Option<&str>) -> anyhow::Result<String> {
    if let Some(p) = flag {
        let p = p.to_lowercase();
        if !Config::VALID_PROVIDERS.contains(&p.as_str()) {
            anyhow::bail!(
                "Invalid provider '{}'. Available: {}",
                p,
                Config::VALID_PROVIDERS.join(", ")
            );
        }
        return Ok(p);
    }

    let config = Config::load(root).unwrap_or_default();
    if let Some(p) = config.provider() {
        return Ok(p.to_string());
    }

    Ok("claude".to_string())
}

#[cfg(test)]
#[path = "config_tests.rs"]
mod tests;