claux 20260723.0.0

Terminal AI coding assistant with tool execution
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use crate::permissions::PermissionMode;

mod trust;

pub use trust::ProjectTrust;

/// How we authenticate with the API.
#[derive(Debug, Clone)]
pub enum AuthMethod {
    /// Direct API key (x-api-key header)
    ApiKey(String),
    /// OAuth access token from `claude login` (Authorization: Bearer header)
    OAuthToken(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default = "default_model")]
    pub model: String,

    #[serde(default)]
    pub api_key: Option<String>,

    #[serde(default = "default_api_key_env")]
    pub api_key_env: String,

    #[serde(default)]
    pub api_key_cmd: Option<String>,

    #[serde(default)]
    pub permission_mode: PermissionMode,

    #[serde(default = "default_max_tokens")]
    pub max_tokens: u32,

    /// Auto-compact threshold (0.0-1.0). If conversation exceeds this
    /// fraction of the context window, auto-compact before next request.
    /// Set to 0.0 to disable auto-compact.
    #[serde(default = "default_auto_compact_threshold")]
    pub auto_compact_threshold: f64,

    /// OpenAI-compatible endpoint (e.g. "http://localhost:11434/v1")
    #[serde(default)]
    pub openai_base_url: Option<String>,

    /// API key for the OpenAI-compatible endpoint
    #[serde(default)]
    pub openai_api_key: Option<String>,

    /// Shell command that returns the OpenAI-compatible API key
    #[serde(default)]
    pub openai_api_key_cmd: Option<String>,

    /// Display name for the provider (e.g. "ollama", "openai", "lmstudio")
    #[serde(default)]
    pub openai_provider_name: Option<String>,

    /// Plugin configuration
    #[serde(default)]
    pub plugins: Vec<PluginConfig>,

    /// MCP server configuration
    #[serde(default)]
    pub mcp_servers: Vec<McpServerConfig>,

    /// Project directories whose local configuration and MCP servers are
    /// explicitly trusted. This field is read only from the global config.
    #[serde(default)]
    pub trusted_projects: Vec<PathBuf>,

    /// Resolved trust for the current working directory. Runtime-only.
    #[serde(skip)]
    pub project_trust: Option<ProjectTrust>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    pub name: String,
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
}

/// The .mcp.json format matching Claude Code's schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpJsonConfig {
    #[serde(rename = "mcpServers")]
    pub mcp_servers: std::collections::HashMap<String, McpJsonServerEntry>,
}

/// A single server entry in .mcp.json (name comes from the key).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpJsonServerEntry {
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
}

impl McpJsonServerEntry {
    pub fn into_server_config(self, name: String) -> McpServerConfig {
        McpServerConfig {
            name,
            command: self.command,
            args: self.args,
            env: self.env,
        }
    }
}

/// Load MCP servers from .mcp.json in the current directory (CC format).
pub fn load_mcp_json(trust: &ProjectTrust) -> Vec<McpServerConfig> {
    if !trust.is_trusted() {
        return Vec::new();
    }

    let path = trust.project_file(".mcp.json");

    if !path.exists() {
        return Vec::new();
    }

    match std::fs::read_to_string(&path) {
        Ok(content) => match serde_json::from_str::<McpJsonConfig>(&content) {
            Ok(config) => config
                .mcp_servers
                .into_iter()
                .map(|(name, entry)| entry.into_server_config(name))
                .collect(),
            Err(e) => {
                tracing::warn!("Failed to parse .mcp.json: {e}");
                Vec::new()
            }
        },
        Err(e) => {
            tracing::warn!("Failed to read .mcp.json: {e}");
            Vec::new()
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
    pub name: String,
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default = "default_trigger")]
    pub trigger: HookTrigger,
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "snake_case")]
pub enum HookTrigger {
    #[default]
    OnContextBuild,
    OnToolStart,
    OnToolComplete,
    OnSessionStart,
}

fn default_trigger() -> HookTrigger {
    HookTrigger::OnContextBuild
}

fn default_model() -> String {
    "claude-sonnet-5".to_string()
}

fn default_api_key_env() -> String {
    "ANTHROPIC_API_KEY".to_string()
}

fn default_max_tokens() -> u32 {
    16384
}

fn default_auto_compact_threshold() -> f64 {
    0.8 // 80% of context window
}

impl Default for Config {
    fn default() -> Self {
        Self {
            model: default_model(),
            api_key: None,
            api_key_env: default_api_key_env(),
            api_key_cmd: None,
            permission_mode: PermissionMode::Default,
            max_tokens: default_max_tokens(),
            auto_compact_threshold: default_auto_compact_threshold(),
            openai_base_url: None,
            openai_api_key: None,
            openai_api_key_cmd: None,
            openai_provider_name: None,
            plugins: Vec::new(),
            mcp_servers: Vec::new(),
            trusted_projects: Vec::new(),
            project_trust: None,
        }
    }
}

impl Config {
    /// Returns true when using the native Anthropic API (not an OpenAI-compatible endpoint).
    pub fn is_anthropic(&self) -> bool {
        self.openai_base_url.is_none()
    }

    pub fn load(force_project_trust: bool) -> Result<Self> {
        let global_path = Self::global_path();

        let mut config = if global_path.exists() {
            let text = std::fs::read_to_string(&global_path)?;
            toml::from_str(&text)?
        } else {
            Self::default()
        };

        let trust = ProjectTrust::resolve(force_project_trust, &config.trusted_projects);

        // Layer project config on top
        let project_path = trust.project_file(".claux.toml");
        if project_path.exists() {
            let text = std::fs::read_to_string(project_path)?;
            let project: toml::Value = toml::from_str(&text)?;
            apply_project_overrides(&mut config, &project, trust.is_trusted());
        }
        config.project_trust = Some(trust);

        Ok(config)
    }

    /// Resolve authentication. Priority:
    /// 1. Direct API key in config
    /// 2. API key from command
    /// 3. ANTHROPIC_API_KEY env var
    /// 4. OAuth token from ~/.claude/.credentials.json (claude login)
    pub fn resolve_auth(&self) -> Option<AuthMethod> {
        // Direct value
        if let Some(ref key) = self.api_key {
            if !key.is_empty() {
                return Some(AuthMethod::ApiKey(key.clone()));
            }
        }

        // Command
        if let Some(ref cmd) = self.api_key_cmd {
            if let Ok(output) = std::process::Command::new("sh").arg("-c").arg(cmd).output() {
                if output.status.success() {
                    let key = String::from_utf8_lossy(&output.stdout).trim().to_string();
                    if !key.is_empty() {
                        return Some(AuthMethod::ApiKey(key));
                    }
                }
            }
        }

        // Environment variable
        if let Ok(key) = std::env::var(&self.api_key_env) {
            if !key.is_empty() {
                return Some(AuthMethod::ApiKey(key));
            }
        }

        // Fall back to Claude Code OAuth credentials
        if let Some(token) = Self::read_claude_oauth_token() {
            return Some(AuthMethod::OAuthToken(token));
        }

        None
    }

    /// Resolve the OpenAI API key: direct value, then command.
    pub fn resolve_openai_key(&self) -> Option<String> {
        if let Some(ref key) = self.openai_api_key {
            if !key.is_empty() {
                return Some(key.clone());
            }
        }

        if let Some(ref cmd) = self.openai_api_key_cmd {
            match std::process::Command::new("sh").arg("-c").arg(cmd).output() {
                Ok(output) => {
                    if output.status.success() {
                        let key = String::from_utf8_lossy(&output.stdout).trim().to_string();
                        if !key.is_empty() {
                            tracing::debug!("openai_api_key_cmd succeeded, key len={}", key.len());
                            return Some(key);
                        }
                        tracing::warn!("openai_api_key_cmd returned empty output");
                    } else {
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        tracing::warn!(
                            "openai_api_key_cmd failed ({}): {}",
                            output.status,
                            stderr.trim()
                        );
                    }
                }
                Err(e) => {
                    tracing::warn!("openai_api_key_cmd exec error: {}", e);
                }
            }
        }

        None
    }

    /// Read OAuth access token from ~/.claude/.credentials.json
    fn read_claude_oauth_token() -> Option<String> {
        let home = std::env::var("HOME").ok()?;
        let path = PathBuf::from(home)
            .join(".claude")
            .join(".credentials.json");

        let content = std::fs::read_to_string(&path).ok()?;
        let creds: serde_json::Value = serde_json::from_str(&content).ok()?;

        let oauth = creds.get("claudeAiOauth")?;

        // Check if token is expired (with 60s buffer)
        if let Some(expires_at) = oauth.get("expiresAt").and_then(|v| v.as_i64()) {
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .ok()?
                .as_millis() as i64;

            if now_ms > expires_at - 60_000 {
                tracing::warn!("Claude OAuth token is expired. Run `claude login` to refresh.");
                return None;
            }
        }

        oauth
            .get("accessToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    fn global_path() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("claux")
            .join("config.toml")
    }
}

fn apply_project_overrides(config: &mut Config, project: &toml::Value, trusted: bool) {
    if let Some(model) = project.get("model").and_then(|v| v.as_str()) {
        config.model = model.to_string();
    }
    if let Some(mode) = project.get("permission_mode").and_then(|v| v.as_str()) {
        if let Ok(requested) =
            serde_json::from_value::<PermissionMode>(serde_json::Value::String(mode.to_string()))
        {
            if trust::permits_permission_override(config.permission_mode, requested, trusted) {
                config.permission_mode = requested;
            } else {
                tracing::warn!(
                    "Ignoring project permission_mode={mode:?}: it would loosen the global policy; \
                     pass --trust-project or add this directory to trusted_projects"
                );
            }
        }
    }
}

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

    #[test]
    fn untrusted_project_permission_can_only_tighten() {
        let mut config = Config {
            permission_mode: PermissionMode::Default,
            ..Config::default()
        };
        let project: toml::Value =
            toml::from_str("permission_mode = \"bypass\"\nmodel = \"project-model\"").unwrap();

        apply_project_overrides(&mut config, &project, false);

        assert_eq!(config.permission_mode, PermissionMode::Default);
        assert_eq!(config.model, "project-model");

        let project: toml::Value = toml::from_str("permission_mode = \"plan\"").unwrap();
        apply_project_overrides(&mut config, &project, false);
        assert_eq!(config.permission_mode, PermissionMode::Plan);
    }

    #[test]
    fn trusted_project_permission_may_loosen() {
        let mut config = Config {
            permission_mode: PermissionMode::Plan,
            ..Config::default()
        };
        let project: toml::Value = toml::from_str("permission_mode = \"bypass\"").unwrap();

        apply_project_overrides(&mut config, &project, true);

        assert_eq!(config.permission_mode, PermissionMode::Bypass);
    }

    #[test]
    fn untrusted_project_does_not_load_mcp_json() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(
            temp.path().join(".mcp.json"),
            r#"{"mcpServers":{"evil":{"command":"false"}}}"#,
        )
        .unwrap();
        let trust = ProjectTrust::for_test(temp.path().to_path_buf(), false);

        assert!(load_mcp_json(&trust).is_empty());
    }

    #[test]
    fn trusted_project_loads_mcp_json() {
        let temp = tempfile::tempdir().unwrap();
        std::fs::write(
            temp.path().join(".mcp.json"),
            r#"{"mcpServers":{"safe":{"command":"true"}}}"#,
        )
        .unwrap();
        let trust = ProjectTrust::for_test(temp.path().to_path_buf(), true);

        let servers = load_mcp_json(&trust);
        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].name, "safe");
    }
}