Skip to main content

codetether_agent/cli/
run.rs

1//! Non-interactive run command
2
3use super::RunArgs;
4use crate::config::Config;
5use crate::session::Session;
6use anyhow::Result;
7
8pub async fn execute(args: RunArgs) -> Result<()> {
9    let message = args.message.trim();
10
11    if message.is_empty() {
12        anyhow::bail!("You must provide a message");
13    }
14
15    tracing::info!("Running with message: {}", message);
16
17    // Load configuration
18    let config = Config::load().await.unwrap_or_default();
19
20    // Create or continue session.
21    let mut session = if let Some(session_id) = args.session {
22        tracing::info!("Continuing session: {}", session_id);
23        Session::load(&session_id).await?
24    } else if args.continue_session {
25        let workspace_dir = std::env::current_dir().unwrap_or_default();
26        match Session::last_for_directory(Some(&workspace_dir)).await {
27            Ok(s) => {
28                tracing::info!(
29                    session_id = %s.id,
30                    workspace = %workspace_dir.display(),
31                    "Continuing last workspace session"
32                );
33                s
34            }
35            Err(_) => {
36                let s = Session::new().await?;
37                tracing::info!(
38                    session_id = %s.id,
39                    workspace = %workspace_dir.display(),
40                    "No workspace session found; created new session"
41                );
42                s
43            }
44        }
45    } else {
46        let s = Session::new().await?;
47        tracing::info!("Created new session: {}", s.id);
48        s
49    };
50
51    // Set model: CLI arg > env var > config default
52    let model = args
53        .model
54        .or_else(|| std::env::var("CODETETHER_DEFAULT_MODEL").ok())
55        .or(config.default_model);
56
57    if let Some(model) = model {
58        tracing::info!("Using model: {}", model);
59        session.metadata.model = Some(model);
60    }
61
62    // Execute the prompt
63    let result = session.prompt(message).await?;
64
65    // Output based on format
66    match args.format.as_str() {
67        "json" => {
68            println!("{}", serde_json::to_string_pretty(&result)?);
69        }
70        _ => {
71            println!("{}", result.text);
72            // Show session ID for continuation
73            eprintln!(
74                "\n[Session: {} | Continue with: codetether run -c \"...\"]",
75                session.id
76            );
77        }
78    }
79
80    Ok(())
81}