codetether-agent 4.0.0

A2A-native AI coding agent for the CodeTether ecosystem
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Configuration system
//!
//! Handles loading configuration from multiple sources:
//! - Global config (~/.config/codetether/config.toml)
//! - Project config (./codetether.toml or .codetether/config.toml)
//! - Environment variables (CODETETHER_*)

use anyhow::Result;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use tokio::fs;

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Default provider to use
    #[serde(default)]
    pub default_provider: Option<String>,

    /// Default model to use (provider/model format)
    #[serde(default)]
    pub default_model: Option<String>,

    /// Provider-specific configurations
    #[serde(default)]
    pub providers: HashMap<String, ProviderConfig>,

    /// Agent configurations
    #[serde(default)]
    pub agents: HashMap<String, AgentConfig>,

    /// Permission rules
    #[serde(default)]
    pub permissions: PermissionConfig,

    /// A2A worker settings
    #[serde(default)]
    pub a2a: A2aConfig,

    /// UI/TUI settings
    #[serde(default)]
    pub ui: UiConfig,

    /// Session settings
    #[serde(default)]
    pub session: SessionConfig,

    /// Telemetry and crash reporting settings
    #[serde(default)]
    pub telemetry: TelemetryConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            // Default to GLM-5 via Z.AI everywhere unless overridden.
            // Use provider/model format so provider selection is unambiguous.
            default_provider: Some("zai".to_string()),
            default_model: Some("zai/glm-5".to_string()),
            providers: HashMap::new(),
            agents: HashMap::new(),
            permissions: PermissionConfig::default(),
            a2a: A2aConfig::default(),
            ui: UiConfig::default(),
            session: SessionConfig::default(),
            telemetry: TelemetryConfig::default(),
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Default)]
pub struct ProviderConfig {
    /// API key (can also be set via env var)
    pub api_key: Option<String>,

    /// Base URL override
    pub base_url: Option<String>,

    /// Custom headers
    #[serde(default)]
    pub headers: HashMap<String, String>,

    /// Organization ID (for OpenAI)
    pub organization: Option<String>,
}

impl std::fmt::Debug for ProviderConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderConfig")
            .field("api_key", &self.api_key.as_ref().map(|_| "<REDACTED>"))
            .field("api_key_len", &self.api_key.as_ref().map(|k| k.len()))
            .field("base_url", &self.base_url)
            .field("organization", &self.organization)
            .field("headers_count", &self.headers.len())
            .finish()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
    /// Agent name
    pub name: String,

    /// Description
    #[serde(default)]
    pub description: Option<String>,

    /// Model override for this agent
    #[serde(default)]
    pub model: Option<String>,

    /// System prompt override
    #[serde(default)]
    pub prompt: Option<String>,

    /// Temperature setting
    #[serde(default)]
    pub temperature: Option<f32>,

    /// Top-p setting
    #[serde(default)]
    pub top_p: Option<f32>,

    /// Custom permissions for this agent
    #[serde(default)]
    pub permissions: HashMap<String, PermissionAction>,

    /// Whether this agent is disabled
    #[serde(default)]
    pub disabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PermissionConfig {
    /// Default permission rules
    #[serde(default)]
    pub rules: HashMap<String, PermissionAction>,

    /// Tool-specific permissions
    #[serde(default)]
    pub tools: HashMap<String, PermissionAction>,

    /// Path-specific permissions
    #[serde(default)]
    pub paths: HashMap<String, PermissionAction>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PermissionAction {
    Allow,
    Deny,
    Ask,
}

impl Default for PermissionAction {
    fn default() -> Self {
        Self::Ask
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct A2aConfig {
    /// Default A2A server URL
    pub server_url: Option<String>,

    /// Worker name
    pub worker_name: Option<String>,

    /// Auto-approve policy
    #[serde(default)]
    pub auto_approve: AutoApprovePolicy,

    /// Workspaces to register
    #[serde(default)]
    pub workspaces: Vec<PathBuf>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum AutoApprovePolicy {
    All,
    #[default]
    Safe,
    None,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiConfig {
    /// Theme name ("default", "marketing", "dark", "light", "solarized-dark", "solarized-light", or custom)
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Show line numbers in code
    #[serde(default = "default_true")]
    pub line_numbers: bool,

    /// Enable mouse support
    #[serde(default = "default_true")]
    pub mouse: bool,

    /// Custom theme configuration (overrides preset themes)
    #[serde(default)]
    pub custom_theme: Option<crate::tui::theme::Theme>,

    /// Enable theme hot-reloading (apply changes without restart)
    #[serde(default = "default_false")]
    pub hot_reload: bool,
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            line_numbers: true,
            mouse: true,
            custom_theme: None,
            hot_reload: false,
        }
    }
}

fn default_theme() -> String {
    "marketing".to_string()
}

fn default_true() -> bool {
    true
}

fn default_false() -> bool {
    false
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionConfig {
    /// Auto-compact sessions when they get too long
    #[serde(default = "default_true")]
    pub auto_compact: bool,

    /// Maximum context tokens before compaction
    #[serde(default = "default_max_tokens")]
    pub max_tokens: usize,

    /// Enable session persistence
    #[serde(default = "default_true")]
    pub persist: bool,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            auto_compact: true,
            max_tokens: default_max_tokens(),
            persist: true,
        }
    }
}

fn default_max_tokens() -> usize {
    100_000
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TelemetryConfig {
    /// Opt-in crash reporting. Disabled by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_reporting: Option<bool>,

    /// Whether we have already prompted the user about crash reporting consent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_reporting_prompted: Option<bool>,

    /// Endpoint for crash report ingestion.
    /// Defaults to the CodeTether telemetry endpoint when unset.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crash_report_endpoint: Option<String>,
}

impl TelemetryConfig {
    pub fn crash_reporting_enabled(&self) -> bool {
        self.crash_reporting.unwrap_or(false)
    }

    pub fn crash_reporting_prompted(&self) -> bool {
        self.crash_reporting_prompted.unwrap_or(false)
    }

    pub fn crash_report_endpoint(&self) -> String {
        self.crash_report_endpoint
            .clone()
            .unwrap_or_else(default_crash_report_endpoint)
    }
}

fn default_crash_report_endpoint() -> String {
    "https://api.codetether.run/v1/crash-reports".to_string()
}

impl Config {
    /// Load configuration from all sources (global, project, env)
    pub async fn load() -> Result<Self> {
        let mut config = Self::default();

        // Load global config
        if let Some(global_path) = Self::global_config_path() {
            if global_path.exists() {
                let content = fs::read_to_string(&global_path).await?;
                let global: Config = toml::from_str(&content)?;
                config = config.merge(global);
            }
        }

        // Load project config
        for name in ["codetether.toml", ".codetether/config.toml"] {
            let path = PathBuf::from(name);
            if path.exists() {
                let content = fs::read_to_string(&path).await?;
                let project: Config = toml::from_str(&content)?;
                config = config.merge(project);
            }
        }

        // Apply environment overrides
        config.apply_env();
        config.normalize_legacy_defaults();

        Ok(config)
    }

    /// Get the global config directory path
    pub fn global_config_path() -> Option<PathBuf> {
        ProjectDirs::from("ai", "codetether", "codetether-agent")
            .map(|dirs| dirs.config_dir().join("config.toml"))
    }

    /// Get the data directory path
    pub fn data_dir() -> Option<PathBuf> {
        ProjectDirs::from("ai", "codetether", "codetether-agent")
            .map(|dirs| dirs.data_dir().to_path_buf())
    }

    /// Initialize default configuration file
    pub async fn init_default() -> Result<()> {
        if let Some(path) = Self::global_config_path() {
            if let Some(parent) = path.parent() {
                fs::create_dir_all(parent).await?;
            }
            let default = Self::default();
            let content = toml::to_string_pretty(&default)?;
            fs::write(&path, content).await?;
            tracing::info!("Created config at {:?}", path);
        }
        Ok(())
    }

    /// Set a configuration value
    pub async fn set(key: &str, value: &str) -> Result<()> {
        let mut config = Self::load().await?;

        // Parse key path and set value
        match key {
            "default_provider" => config.default_provider = Some(value.to_string()),
            "default_model" => config.default_model = Some(value.to_string()),
            "a2a.server_url" => config.a2a.server_url = Some(value.to_string()),
            "a2a.worker_name" => config.a2a.worker_name = Some(value.to_string()),
            "ui.theme" => config.ui.theme = value.to_string(),
            "telemetry.crash_reporting" => {
                config.telemetry.crash_reporting = Some(parse_bool(value)?)
            }
            "telemetry.crash_reporting_prompted" => {
                config.telemetry.crash_reporting_prompted = Some(parse_bool(value)?)
            }
            "telemetry.crash_report_endpoint" => {
                config.telemetry.crash_report_endpoint = Some(value.to_string())
            }
            _ => anyhow::bail!("Unknown config key: {}", key),
        }

        // Save to global config
        if let Some(path) = Self::global_config_path() {
            let content = toml::to_string_pretty(&config)?;
            fs::write(&path, content).await?;
        }

        Ok(())
    }

    /// Merge two configs (other takes precedence)
    fn merge(mut self, other: Self) -> Self {
        if other.default_provider.is_some() {
            self.default_provider = other.default_provider;
        }
        if other.default_model.is_some() {
            self.default_model = other.default_model;
        }
        self.providers.extend(other.providers);
        self.agents.extend(other.agents);
        self.permissions.rules.extend(other.permissions.rules);
        self.permissions.tools.extend(other.permissions.tools);
        self.permissions.paths.extend(other.permissions.paths);
        if other.a2a.server_url.is_some() {
            self.a2a = other.a2a;
        }
        if other.telemetry.crash_reporting.is_some() {
            self.telemetry.crash_reporting = other.telemetry.crash_reporting;
        }
        if other.telemetry.crash_reporting_prompted.is_some() {
            self.telemetry.crash_reporting_prompted = other.telemetry.crash_reporting_prompted;
        }
        if other.telemetry.crash_report_endpoint.is_some() {
            self.telemetry.crash_report_endpoint = other.telemetry.crash_report_endpoint;
        }
        self
    }

    /// Load theme based on configuration
    pub fn load_theme(&self) -> crate::tui::theme::Theme {
        // Use custom theme if provided
        if let Some(custom) = &self.ui.custom_theme {
            return custom.clone();
        }

        // Use preset theme
        match self.ui.theme.as_str() {
            "marketing" | "default" => crate::tui::theme::Theme::marketing(),
            "dark" => crate::tui::theme::Theme::dark(),
            "light" => crate::tui::theme::Theme::light(),
            "solarized-dark" => crate::tui::theme::Theme::solarized_dark(),
            "solarized-light" => crate::tui::theme::Theme::solarized_light(),
            _ => {
                // Log warning and fallback to marketing theme
                tracing::warn!(theme = %self.ui.theme, "Unknown theme name, falling back to marketing");
                crate::tui::theme::Theme::marketing()
            }
        }
    }

    /// Apply environment variable overrides
    fn apply_env(&mut self) {
        if let Ok(val) = std::env::var("CODETETHER_DEFAULT_MODEL") {
            self.default_model = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_DEFAULT_PROVIDER") {
            self.default_provider = Some(val);
        }
        if let Ok(val) = std::env::var("OPENAI_API_KEY") {
            self.providers
                .entry("openai".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("ANTHROPIC_API_KEY") {
            self.providers
                .entry("anthropic".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("GOOGLE_API_KEY") {
            self.providers
                .entry("google".to_string())
                .or_default()
                .api_key = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_A2A_SERVER") {
            self.a2a.server_url = Some(val);
        }
        if let Ok(val) = std::env::var("CODETETHER_CRASH_REPORTING") {
            match parse_bool(&val) {
                Ok(enabled) => self.telemetry.crash_reporting = Some(enabled),
                Err(_) => tracing::warn!(
                    value = %val,
                    "Invalid CODETETHER_CRASH_REPORTING value; expected true/false"
                ),
            }
        }
        if let Ok(val) = std::env::var("CODETETHER_CRASH_REPORT_ENDPOINT") {
            self.telemetry.crash_report_endpoint = Some(val);
        }
    }

    /// Normalize legacy provider/model defaults from older releases.
    ///
    /// Historical versions defaulted to Moonshot Kimi K2.5. The current
    /// product default is Z.AI GLM-5, so we migrate only known legacy default
    /// values while preserving all other explicit user choices.
    fn normalize_legacy_defaults(&mut self) {
        if let Some(provider) = self.default_provider.as_deref()
            && provider.trim().eq_ignore_ascii_case("zhipuai")
        {
            self.default_provider = Some("zai".to_string());
        }

        if let Some(model) = self.default_model.as_deref() {
            let model_trimmed = model.trim();

            if model_trimmed.eq_ignore_ascii_case("zhipuai/glm-5") {
                self.default_model = Some("zai/glm-5".to_string());
                return;
            }

            let is_legacy_kimi_default = model_trimmed.eq_ignore_ascii_case("moonshotai/kimi-k2.5")
                || model_trimmed.eq_ignore_ascii_case("kimi-k2.5");

            if is_legacy_kimi_default {
                tracing::info!(
                    from = %model_trimmed,
                    to = "zai/glm-5",
                    "Migrating legacy default model to current Z.AI GLM-5 default"
                );
                self.default_model = Some("zai/glm-5".to_string());

                let should_update_provider = self.default_provider.as_deref().is_none_or(|p| {
                    let p = p.trim();
                    p.eq_ignore_ascii_case("moonshotai") || p.eq_ignore_ascii_case("zhipuai")
                });
                if should_update_provider {
                    self.default_provider = Some("zai".to_string());
                }
            }
        }
    }
}

fn parse_bool(value: &str) -> Result<bool> {
    let normalized = value.trim().to_ascii_lowercase();
    match normalized.as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "0" | "false" | "no" | "off" => Ok(false),
        _ => anyhow::bail!("Invalid boolean value: {}", value),
    }
}

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

    #[test]
    fn migrates_legacy_kimi_default_to_zai_glm5() {
        let mut cfg = Config {
            default_provider: Some("moonshotai".to_string()),
            default_model: Some("moonshotai/kimi-k2.5".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("zai"));
        assert_eq!(cfg.default_model.as_deref(), Some("zai/glm-5"));
    }

    #[test]
    fn preserves_explicit_non_legacy_default_model() {
        let mut cfg = Config {
            default_provider: Some("openai".to_string()),
            default_model: Some("openai/gpt-4o".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("openai"));
        assert_eq!(cfg.default_model.as_deref(), Some("openai/gpt-4o"));
    }

    #[test]
    fn normalizes_zhipuai_aliases_to_zai() {
        let mut cfg = Config {
            default_provider: Some("zhipuai".to_string()),
            default_model: Some("zhipuai/glm-5".to_string()),
            ..Default::default()
        };

        cfg.normalize_legacy_defaults();

        assert_eq!(cfg.default_provider.as_deref(), Some("zai"));
        assert_eq!(cfg.default_model.as_deref(), Some("zai/glm-5"));
    }
}