claux 20260907.0.1

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
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
mod api;
mod auth;
mod bootstrap;
mod checkpoint;
mod cli;
mod command_sandbox;
mod commands;
mod compact;
mod config;
mod context;
mod cost;
mod db;
#[cfg(test)]
mod evals;
mod image_input;
mod model;
mod model_catalog;
mod onboarding;
mod output;
mod permissions;
mod plugin;
mod query;
mod repl;
mod sandbox;
mod session;
mod shutdown;
#[cfg(test)]
mod test_support;
mod theme;
mod tokenizer_fingerprint;
mod tools;
mod tui;
mod usage;
mod utils;

use anyhow::Result;
use clap::Parser;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::process::ExitCode {
    match run().await {
        Ok(code) => code,
        Err(error) => {
            eprintln!("Error: {error:?}");
            std::process::ExitCode::from(1)
        }
    }
}

async fn run() -> Result<std::process::ExitCode> {
    use std::process::ExitCode;
    let args = cli::Cli::parse();

    if let Some(cli::CliCommand::SandboxExec { workspace, command }) = &args.command {
        return command_sandbox::run_helper(workspace, command).map(|()| ExitCode::SUCCESS);
    }
    if matches!(args.command, Some(cli::CliCommand::SandboxProbe)) {
        return command_sandbox::run_probe().map(|()| ExitCode::SUCCESS);
    }

    // Init logging
    let filter = if args.debug {
        "claux=debug"
    } else if args.verbose {
        "claux=info"
    } else {
        "claux=warn"
    };
    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr)
        .init();

    if let Some(command) = &args.command {
        match command {
            cli::CliCommand::Auth { command } => {
                match command {
                    cli::AuthCommand::Login {
                        provider: cli::AuthProvider::OpenRouter,
                        headless,
                        no_browser,
                    } => auth::login_openrouter(*headless, *no_browser).await?,
                    cli::AuthCommand::Status {
                        provider: cli::AuthProvider::OpenRouter,
                    } => auth::status_openrouter()?,
                    cli::AuthCommand::Logout {
                        provider: cli::AuthProvider::OpenRouter,
                    } => auth::logout_openrouter()?,
                    cli::AuthCommand::Token {
                        provider: cli::AuthProvider::OpenRouter,
                    } => auth::print_openrouter_token()?,
                    cli::AuthCommand::Login {
                        provider: cli::AuthProvider::OpenCodeGo,
                        ..
                    } => auth::login_api_key("opencode-go", "OpenCode Go")?,
                    cli::AuthCommand::Status {
                        provider: cli::AuthProvider::OpenCodeGo,
                    } => auth::status_provider("opencode-go", "OpenCode Go")?,
                    cli::AuthCommand::Logout {
                        provider: cli::AuthProvider::OpenCodeGo,
                    } => auth::logout_provider("opencode-go", "OpenCode Go")?,
                    cli::AuthCommand::Token {
                        provider: cli::AuthProvider::OpenCodeGo,
                    } => auth::print_provider_token("opencode-go", "OpenCode Go")?,
                    cli::AuthCommand::Login {
                        provider: cli::AuthProvider::Vercel,
                        ..
                    } => auth::login_api_key("vercel", "Vercel AI Gateway")?,
                    cli::AuthCommand::Status {
                        provider: cli::AuthProvider::Vercel,
                    } => auth::status_provider("vercel", "Vercel AI Gateway")?,
                    cli::AuthCommand::Logout {
                        provider: cli::AuthProvider::Vercel,
                    } => auth::logout_provider("vercel", "Vercel AI Gateway")?,
                    cli::AuthCommand::Token {
                        provider: cli::AuthProvider::Vercel,
                    } => auth::print_provider_token("vercel", "Vercel AI Gateway")?,
                }
                return Ok(ExitCode::SUCCESS);
            }
            cli::CliCommand::Config {
                command:
                    cli::ConfigCommand::Init {
                        provider,
                        model,
                        force,
                    },
            } => {
                let path = onboarding::init_config(*provider, model.as_deref(), *force)?;
                println!("Created {}", path.display());
                println!("Run `claux doctor` to verify the setup.");
                return Ok(ExitCode::SUCCESS);
            }
            cli::CliCommand::Doctor { offline } => {
                let config = config::Config::load(args.trust_project)?;
                let report = onboarding::doctor(&config, *offline).await;
                print!("{}", report.text);
                if !report.healthy {
                    anyhow::bail!("doctor found configuration errors");
                }
                return Ok(ExitCode::SUCCESS);
            }
            cli::CliCommand::Usage { command } => {
                match command {
                    cli::UsageCommand::Status { provider, json } => {
                        usage::status(provider.as_deref(), *json).await?
                    }
                }
                return Ok(ExitCode::SUCCESS);
            }
            cli::CliCommand::TokenizerFingerprint {
                models,
                format,
                json,
                report_output,
                resume_fingerprint,
            } => {
                let format = if *json {
                    cli::TokenizerOutputFormat::Json
                } else {
                    format.unwrap_or_default()
                };
                tokenizer_fingerprint::run(
                    models,
                    format,
                    report_output.as_deref(),
                    *resume_fingerprint,
                )
                .await?;
                return Ok(ExitCode::SUCCESS);
            }
            cli::CliCommand::SandboxExec { .. } | cli::CliCommand::SandboxProbe => {
                unreachable!("handled before logging")
            }
        }
    }

    // Load config (global + project)
    let mut config = config::Config::load(args.trust_project)?;
    command_sandbox::configure_child_environment(
        config.sensitive_environment_names(),
        config.strip_agent_sockets,
    );
    if let Some(ref mode) = args.permission_mode {
        config.permission_mode = serde_json::from_value(serde_json::Value::String(mode.clone()))
            .map_err(|_| {
                anyhow::anyhow!(
                    "Invalid permission mode {mode:?}; expected default, accept-edits, bypass, or plan"
                )
            })?;
    }

    // Build plugin registry
    let mut plugin_registry = plugin::PluginRegistry::new();
    for plugin_config in &config.plugins {
        plugin_registry.add(Box::new(plugin::CommandPlugin::new(
            &plugin_config.name,
            &plugin_config.command,
            &plugin_config.args,
            plugin_config.trigger.clone(),
        )));
    }
    if !plugin_registry.is_empty() {
        tracing::info!(
            "Loaded {} plugin(s): {} context, {} tool-start, {} tool-complete, {} session-start, {} turn-end, {} permission-request, {} permission-check",
            plugin_registry.len(),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnContextBuild),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnToolStart),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnToolComplete),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnSessionStart),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnTurnEnd),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnPermissionRequest),
            plugin_registry.get_by_trigger(&config::HookTrigger::OnPermissionCheck),
        );
    }
    let plugin_registry = Arc::new(plugin_registry);

    let requested_model = match args.model.as_deref() {
        Some(model) => config.resolve_model(model)?,
        None => config.default_resolved_model()?,
    };

    tracing::debug!(
        "Config loaded: openai_base_url={:?} openai_api_key_cmd={:?} model={}",
        config.openai_base_url,
        config.openai_api_key_cmd,
        config.model
    );

    // One-shot mode: --print / -p
    if let Some(ref prompt) = args.prompt {
        let mut engine = build_engine(&config, &requested_model, plugin_registry.clone()).await?;

        let system_prompt = context::build_system_prompt_for_model(
            &requested_model.binding.model,
            Some(&plugin_registry),
            &config::HookTrigger::OnContextBuild,
            requested_model.binding.provider_kind == config::ProviderKind::Anthropic,
            config.is_project_trusted(),
        )
        .await?;
        engine.set_system_prompt(system_prompt);
        if let Some(path) = args.transcript.as_ref() {
            engine.set_transcript_checkpoint(path.clone());
        }

        let cancel = shutdown::one_shot_cancellation_token()?;
        let response = if args.image.is_empty() {
            engine.submit(prompt, cancel.clone()).await
        } else {
            let images = image_input::load_images(&args.image)?;
            engine
                .submit_message(
                    api::types::Message::user_with_images(prompt, images),
                    cancel.clone(),
                )
                .await
        };
        let response = shutdown::classify_one_shot_response(response, cancel.is_cancelled());
        // Classify the failure for the transcript, the JSON output, and the
        // exit code. Cancellation wins because the engine reports a clean
        // interrupt rather than an error.
        let failure: Option<query::FailureRecord> = if response.is_ok() {
            None
        } else if cancel.is_cancelled() {
            Some(query::FailureRecord::cancelled(
                engine.last_failure().map(|f| f.attempts).unwrap_or(1),
            ))
        } else {
            Some(
                engine
                    .last_failure()
                    .cloned()
                    .unwrap_or_else(query::FailureRecord::unclassified),
            )
        };
        if let Some(path) = args.transcript.as_deref() {
            let error = response.as_ref().err().map(ToString::to_string);
            let outcome = match (&response, &error) {
                (Ok(result), _) => output::TranscriptOutcome::Completed { result },
                (Err(_), Some(message)) => output::TranscriptOutcome::Error {
                    message,
                    failure: failure.as_ref(),
                },
                (Err(_), None) => unreachable!("errors always render a message"),
            };
            let transcript = output::OneShotTranscript::new(
                engine.model(),
                &engine.cost,
                engine.messages(),
                engine.tool_trace(),
                engine.execution_timing(),
                outcome,
            );
            output::write_transcript(path, &transcript)?;
        }
        let json = matches!(
            args.output_format.unwrap_or_default(),
            cli::OutputFormat::Json
        );
        match response {
            Ok(response) => {
                if json {
                    let output =
                        output::OneShotOutput::new(&response, engine.model(), &engine.cost);
                    serde_json::to_writer(std::io::stdout().lock(), &output)?;
                    println!();
                } else {
                    print!("{response}");
                }
                return Ok(ExitCode::SUCCESS);
            }
            Err(error) => {
                let message = error.to_string();
                let failure = failure.expect("failed responses are classified");
                if json {
                    // Always give supervisors a machine-readable outcome, not
                    // just a stderr string and exit status.
                    let output = output::OneShotOutput::failed(
                        engine.model(),
                        &engine.cost,
                        &message,
                        Some(&failure),
                    );
                    serde_json::to_writer(std::io::stdout().lock(), &output)?;
                    println!();
                }
                eprintln!("Error: {error:?}");
                return Ok(ExitCode::from(failure.kind.exit_code()));
            }
        }
    }

    // Run session-start hooks
    plugin::PluginRegistry::execute_side_effects(
        &plugin_registry,
        &config::HookTrigger::OnSessionStart,
        None,
    )
    .await?;

    if args.tui {
        let mut models = config.selectable_models()?;
        if let Some(cli_model) = args.model.as_deref() {
            models.retain(|configured| {
                configured.binding.profile != cli_model && configured.binding.model != cli_model
            });
            models.insert(0, requested_model.clone());
        }
        return tui::run(&config, plugin_registry, models)
            .await
            .map(|()| ExitCode::SUCCESS);
    }

    // Resume a previous session if requested. The matched id is handed to
    // the REPL so it continues that session instead of forking a new one.
    let mut resumed_id: Option<String> = None;
    let mut resolved_model = requested_model;
    let mut resumed_messages = None;
    if let Some(ref session_id) = args.resume {
        match session::find_session(session_id)? {
            Some((sid, path)) => {
                let (meta, messages) = session::load_session(&path)?;
                resolved_model = match meta.model_binding.as_ref() {
                    Some(binding) => config.resolve_binding(binding)?,
                    None => config.resolve_model(&meta.model).map_err(|error| {
                        anyhow::anyhow!(
                            "Session {} uses legacy model '{}', which cannot be resolved: {error}. \
                             Add a matching model profile or start a new session.",
                            meta.id,
                            meta.model
                        )
                    })?,
                };
                eprintln!(
                    "Resumed session {} ({}, {} messages)",
                    meta.id,
                    meta.model,
                    messages.len()
                );
                resumed_messages = Some(messages);
                resumed_id = Some(sid);
            }
            None => {
                eprintln!("Session not found: {session_id}. Starting new session.");
            }
        }
    }

    let mut engine = build_engine(&config, &resolved_model, plugin_registry.clone()).await?;
    if let Some(messages) = resumed_messages {
        engine.set_messages(messages);
    }
    repl::run(engine, &config, plugin_registry, resumed_id, resolved_model)
        .await
        .map(|()| ExitCode::SUCCESS)
}

async fn build_engine(
    config: &config::Config,
    resolved: &config::ResolvedModel,
    plugins: Arc<plugin::PluginRegistry>,
) -> Result<query::Engine> {
    let model = &resolved.binding.model;
    let metadata = model_catalog::resolve(resolved).await;
    let provider = build_provider(resolved)?;
    tracing::info!(
        "Provider: {} ({}, profile {})",
        provider.name(),
        model,
        resolved.binding.profile
    );

    let resolved_for_factory = resolved.clone();
    let agent_factory: tools::agent::ProviderFactory = Box::new(move || {
        build_provider(&resolved_for_factory).expect("failed to build agent provider")
    });
    let sandbox_policy = Arc::new(sandbox::SandboxPolicy::from_native_tool_policy(
        config.native_tool_filesystem_policy,
        std::env::current_dir()?,
    )?);
    let command_sandbox = Arc::new(command_sandbox::CommandSandbox::new(
        config.bash_filesystem_policy,
        std::env::current_dir()?,
    )?);
    let permission_policy =
        permissions::PermissionPolicy::new(config.permission_mode, config.permission_rules()?);
    let mut tool_registry = tools::ToolRegistry::new_with_agent_factory(
        agent_factory,
        model.clone(),
        metadata,
        permission_policy.clone(),
        config.is_project_trusted(),
        sandbox_policy,
        command_sandbox,
    );
    tool_registry.add_tools(bootstrap::connect_mcp_tools(config).await);

    let permission_checker = permission_policy.checker();
    let mut engine = query::Engine::new(provider, tool_registry, permission_checker, model);
    engine.set_model_binding(resolved.binding.clone());
    engine.set_plugins(plugins);
    engine.set_auto_compact_threshold(config.auto_compact_threshold);
    engine.set_max_tokens(config.max_tokens);
    engine.set_model_metadata(metadata);
    Ok(engine)
}

/// Build a provider from config.
fn build_provider(resolved: &config::ResolvedModel) -> Result<Box<dyn api::Provider>> {
    let binding = &resolved.binding;
    let api_key = resolved.resolve_api_key().unwrap_or_default();
    if api_key.is_empty() && resolved.requires_api_key() {
        let login_hint = if binding.provider_name.eq_ignore_ascii_case("openrouter")
            || binding
                .base_url
                .as_deref()
                .is_some_and(|url| url.contains("openrouter.ai"))
        {
            " or run `claux auth login openrouter`"
        } else {
            ""
        };
        anyhow::bail!(
            "No API key found for profile '{}' (provider '{}'). Set {}{} or update \
             ~/.config/claux/config.toml.",
            binding.profile,
            binding.provider_name,
            binding.api_key_env,
            login_hint,
        );
    }
    match binding.provider_kind {
        config::ProviderKind::Openai => {
            let base_url = binding.base_url.as_deref().ok_or_else(|| {
                anyhow::anyhow!("saved provider '{}' has no base URL", binding.provider)
            })?;
            match binding.protocol {
                config::OpenAIProtocol::ChatCompletions => Ok(Box::new(
                    api::OpenAICompatProvider::new(
                        base_url,
                        &api_key,
                        &binding.model,
                        &binding.provider_name,
                        binding.reasoning_effort.as_deref(),
                    )
                    .with_prompt_caching(binding.prompt_caching)
                    .with_eof_without_finish_reason(binding.allow_eof_without_finish_reason),
                )),
                config::OpenAIProtocol::Responses => {
                    Ok(Box::new(api::OpenAIResponsesProvider::new(
                        base_url,
                        &api_key,
                        &binding.model,
                        &binding.provider_name,
                        binding.reasoning_effort.as_deref(),
                    )))
                }
            }
        }
        config::ProviderKind::Anthropic => {
            if api_key.is_empty() {
                anyhow::bail!(
                    "No authentication found for profile '{}'. Set {}.",
                    binding.profile,
                    binding.api_key_env
                );
            }
            let key = config::AnthropicApiKey::new(api_key);
            Ok(Box::new(match binding.base_url.as_deref() {
                Some(base_url) => {
                    api::AnthropicProvider::with_base_url(key, &binding.model, base_url)
                }
                None => api::AnthropicProvider::new(key, &binding.model),
            }))
        }
    }
}