Skip to main content

corex_cli/
lib.rs

1use std::path::PathBuf;
2use anyhow::Result;
3use clap::{CommandFactory, Parser};
4use tokio_util::sync::CancellationToken;
5
6use corex_core::client::{get_sudo_password, LlmClient, StreamEvent};
7use corex_core::config::Config;
8use corex_core::session::Session;
9use corex_core::types::{Message, ToolCall};
10use corex_prompt::PromptBuilder;
11use corex_tools::registry::ToolRegistry;
12use corex_tools::types::ToolContext;
13use corex_tui::{run_tui, App};
14
15mod fleet_cli;
16
17#[derive(Parser, Debug, PartialEq)]
18#[command(
19    name = "cx",
20    version = env!("CARGO_PKG_VERSION"),
21    author = "sluisr <contact@sluisr.com>",
22    about = "Corex — High-Performance Autonomous Coding Agent"
23)]
24struct Cli {
25    /// Non-interactive headless prompt to execute directly (e.g. -p "..." or --prompt "...")
26    #[arg(short = 'p', long = "prompt", alias = "message")]
27    message: Option<String>,
28
29    /// Positional query (if provided without -p, runs headlessly)
30    #[arg(trailing_var_arg = true)]
31    query: Vec<String>,
32
33    /// Perform live web search (e.g. -w "query" or --web "query")
34    #[arg(short = 'w', long = "web")]
35    web: Option<String>,
36
37    /// Fetch and summarize a web page URL as Markdown (e.g. --fetch "https://...")
38    #[arg(long = "fetch")]
39    fetch: Option<String>,
40
41    /// Model name override (e.g. -m deepseek-flash, --model deepseek-v4-pro)
42    #[arg(short = 'm', short_alias = 'M', long = "model")]
43    model: Option<String>,
44
45    /// Custom API base URL (e.g. https://api.deepseek.com)
46    #[arg(long)]
47    base_url: Option<String>,
48
49    /// API Key override
50    #[arg(long)]
51    api_key: Option<String>,
52
53    /// Resume a previously saved conversation session by ID, tag, or index
54    #[arg(short = 'r', long)]
55    resume: Option<String>,
56
57    /// List available conversation sessions for this project
58    #[arg(short = 'l', long = "list-sessions")]
59    list_sessions: bool,
60
61    /// Automatically approve all tool executions (YOLO mode)
62    #[arg(short = 'y', long)]
63    yolo: bool,
64
65    /// Working directory (defaults to current working directory)
66    #[arg(short = 'C', long)]
67    directory: Option<PathBuf>,
68
69    /// Enable or disable local LLM assistant (--local, --no-local)
70    #[arg(long, default_missing_value = "true", num_args = 0..=1)]
71    local: Option<bool>,
72
73    /// Custom Local LLM URL (default: http://127.0.0.1:8080/v1)
74    #[arg(long)]
75    local_url: Option<String>,
76
77    /// Custom Local LLM model name
78    #[arg(long)]
79    local_model: Option<String>,
80
81    /// Update Corex to the latest release in-place (alias: --upgrade)
82    #[arg(long = "upgrade", alias = "update")]
83    upgrade: bool,
84
85    /// Force update or reinstallation even if already on the latest version
86    #[arg(long = "force", short = 'f')]
87    force: bool,
88
89    /// Generate shell autocompletion script (bash, zsh, fish, powershell, elvish)
90    #[arg(long = "completions", value_enum)]
91    completions: Option<clap_complete::Shell>,
92
93    /// Manage remote VPS servers and clusters (SysAdmin operations)
94    #[arg(long = "fleet", alias = "sysadmin")]
95    fleet: bool,
96}
97
98pub async fn run() -> Result<()> {
99    let mut cli = Cli::parse();
100    if let Some(arg0) = std::env::args().next() {
101        if (arg0.ends_with("cxs") || arg0.ends_with("cx-fleet")) && !cli.fleet {
102            cli.fleet = true;
103        }
104    }
105
106    let workspace_dir = cli
107        .directory
108        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
109
110    // Handle --list-sessions directly
111    if cli.list_sessions {
112        let ws_str = workspace_dir.display().to_string();
113        let sessions = Session::list_all(Some(&ws_str));
114        if sessions.is_empty() {
115            println!("No previous sessions found for this project.");
116        } else {
117            println!("\nAvailable sessions for this project ({}):", sessions.len());
118            for (i, s) in sessions.iter().enumerate() {
119                let rel_time = Session::format_relative_time(s.updated_at);
120                let tag_str = s.tag.as_ref().map(|t| format!(" [tag: {}]", t)).unwrap_or_default();
121                let model_display = if s.model == "deepseek-flash" || s.model == "deepseek-v4.1-flash" || s.model == "deepseek-v4-flash" || s.model == "deepseek-chat" {
122                    "DeepSeek-V4.1-Flash"
123                } else if s.model == "deepseek-v4.1-flash-1017" {
124                    "DeepSeek-V4.1-Flash-1017"
125                } else if s.model == "deepseek-v4-pro" || s.model == "deepseek-reasoner" {
126                    "DeepSeek-V4-Pro"
127                } else if s.model == "deepseek-v4-flash-vision-exp" {
128                    "DeepSeek-V4.1-Flash (Vision)"
129                } else {
130                    &s.model
131                };
132                println!("  {}. {} ({}){} · {} [{}]", i + 1, s.title, rel_time, tag_str, model_display, s.id);
133            }
134            println!("\nResume any session with: cx --resume <index | tag | id>\n");
135        }
136        return Ok(());
137    }
138
139    // Handle --completions or "cx completions <shell>"
140    let completions_shell = cli.completions.or_else(|| {
141        if cli.message.is_none() && !cli.query.is_empty() && cli.query[0] == "completions" {
142            cli.query.get(1).and_then(|s| s.parse::<clap_complete::Shell>().ok())
143        } else {
144            None
145        }
146    });
147
148    if let Some(shell) = completions_shell {
149        let mut cmd = Cli::command();
150        clap_complete::generate(shell, &mut cmd, "cx", &mut std::io::stdout());
151        return Ok(());
152    }
153
154    if cli.message.is_none() && !cli.query.is_empty() && cli.query[0] == "completions" && cli.query.len() == 1 {
155        println!("Usage: cx --completions <bash|zsh|fish|powershell|elvish>");
156        return Ok(());
157    }
158
159    // Handle "cx fleet ...", "cx sysadmin ...", "cxs ...", or "cx --fleet"
160    let is_fleet_cmd = cli.fleet
161        || (cli.message.is_none()
162            && !cli.query.is_empty()
163            && (cli.query[0] == "fleet" || cli.query[0] == "sysadmin"));
164
165    if is_fleet_cmd {
166        cli.fleet = true;
167        let fleet_args: Vec<String> = if !cli.query.is_empty() && (cli.query[0] == "fleet" || cli.query[0] == "sysadmin") {
168            cli.query[1..].to_vec()
169        } else {
170            cli.query.clone()
171        };
172
173        let is_headless_subcommand = fleet_args.first().map(|s| {
174            matches!(
175                s.as_str(),
176                "status" | "list" | "ls" | "nodes" | "ping" | "top" | "telemetry" | "metrics" | "init" | "run" | "broadcast" | "all" | "help" | "--help" | "-h"
177            )
178        }).unwrap_or(false);
179
180        if is_headless_subcommand {
181            return fleet_cli::handle_fleet_cli(&workspace_dir, &fleet_args).await;
182        }
183
184        // If the invocation was "cx fleet" or "cx sysadmin" without subcommands, consume the command word
185        if !cli.query.is_empty() && (cli.query[0] == "fleet" || cli.query[0] == "sysadmin") {
186            cli.query.remove(0);
187        }
188    }
189
190    // Handle in-place self-update: "cx update", "cx upgrade", "cx --upgrade", "cx --update"
191    let is_update_cmd = cli.upgrade
192        || (cli.message.is_none()
193            && !cli.query.is_empty()
194            && (cli.query[0] == "update" || cli.query[0] == "upgrade" || cli.query[0] == "--update" || cli.query[0] == "--upgrade"));
195
196    if is_update_cmd {
197        let current = env!("CARGO_PKG_VERSION");
198        let force = cli.force || cli.query.iter().any(|q| q == "--force" || q == "-f");
199        println!("Corex In-Place Self-Updater (v{})", current);
200        match corex_core::update::perform_self_update(current, force, |msg| {
201            println!("  › {}", msg);
202        }).await {
203            Ok(summary) => {
204                println!(
205                    "\n✓ Successfully updated Corex from v{} to v{}!\n  Binary: {}\n  Target: {}\n",
206                    summary.previous_version,
207                    summary.updated_version,
208                    summary.binary_path.display(),
209                    summary.target_triple
210                );
211            }
212            Err(e) => {
213                eprintln!("\nNotice: {}", e);
214                if !force && e.contains("already on the latest version") {
215                    println!("To force re-download the latest release, run:\n  cx update --force\n");
216                }
217            }
218        }
219        return Ok(());
220    }
221
222    // Initialize forensic audit log system (~/.corex/logs/corex-forensic-YYYY-MM-DD.log)
223    let log_path = corex_core::ForensicLogger::init(Some(&workspace_dir));
224    tracing::debug!("Forensic audit logger initialized at {:?}", log_path);
225
226    let mut config = Config::load_with_workspace(Some(&workspace_dir));
227    let mut headless_prompt = cli.message.clone();
228    let mut explicit_model = false;
229
230    if let Some(m) = cli.model {
231        // Smart fallback: Only if a multi-word string with spaces was passed to --model, treat as headless prompt!
232        if m.contains(' ') && headless_prompt.is_none() {
233            headless_prompt = Some(m);
234        } else {
235            config.model = m;
236            explicit_model = true;
237        }
238    }
239    if let Some(u) = cli.base_url {
240        config.base_url = u;
241    }
242    if let Some(k) = cli.api_key {
243        config.api_key = k;
244    }
245    if let Some(loc_en) = cli.local {
246        config.local_llm_enabled = loc_en;
247    }
248    if let Some(loc_url) = cli.local_url {
249        config.local_llm_url = loc_url;
250    }
251    if let Some(loc_m) = cli.local_model {
252        config.local_llm_model = loc_m;
253    }
254    if cli.yolo {
255        config.yolo_mode = true;
256    }
257
258    let mut resumed_session: Option<Session> = None;
259    if let Some(ref session_id) = cli.resume {
260        match Session::load_by_id_or_tag(session_id) {
261            Ok(loaded) => {
262                if !explicit_model {
263                    config.model = loaded.model.clone();
264                }
265                if let Some(t) = loaded.temperature {
266                    config.temperature = t;
267                }
268                if let Some(ref r) = loaded.reasoning_effort {
269                    config.reasoning_effort = r.clone();
270                }
271                resumed_session = Some(loaded);
272            }
273            Err(e) => {
274                eprintln!(
275                    "Warning: Could not resume session {}: {}. Starting new session.",
276                    session_id, e
277                );
278            }
279        }
280    }
281
282    let llm_client = LlmClient::new(config.clone());
283    corex_tools::subagent::set_subagent_llm_client(std::sync::Arc::new(llm_client.clone()));
284
285    let make_session = |resumed: Option<Session>| -> Session {
286        resumed.unwrap_or_else(|| {
287            Session::new_with_params(
288                &config.model,
289                config.temperature,
290                &config.reasoning_effort,
291                Some(&workspace_dir),
292            )
293        })
294    };
295
296    // Handle standalone --web / -w or `cx web <query>` search query
297    let web_search_query = cli.web.or_else(|| {
298        if cli.message.is_none() && !cli.query.is_empty() && (cli.query[0] == "web" || cli.query[0] == "/web" || cli.query[0] == "search" || cli.query[0] == "/search") {
299            let q = cli.query[1..].join(" ");
300            if !q.is_empty() {
301                Some(q)
302            } else {
303                None
304            }
305        } else {
306            None
307        }
308    });
309
310    if let Some(query) = web_search_query {
311        let prompt = format!(
312            "Please search the web using the web_search tool and synthesize a clear, direct, and well-structured answer with source links for: {}",
313            query
314        );
315        let display = format!("/web {}", query);
316        let session = make_session(resumed_session);
317        run_headless(llm_client, workspace_dir, prompt, Some(display), config.yolo_mode, session).await?;
318        return Ok(());
319    }
320
321    // Handle standalone --fetch or `cx fetch <url>`
322    let web_fetch_url = cli.fetch.or_else(|| {
323        if cli.message.is_none() && !cli.query.is_empty() && (cli.query[0] == "fetch" || cli.query[0] == "/fetch") {
324            let u = cli.query[1..].join(" ");
325            if !u.is_empty() {
326                Some(u)
327            } else {
328                None
329            }
330        } else {
331            None
332        }
333    });
334
335    if let Some(url) = web_fetch_url {
336        let prompt = format!(
337            "Please fetch the URL '{}' using the web_fetch tool and synthesize a clear, comprehensive summary and analysis of its content.",
338            url
339        );
340        let display = format!("/fetch {}", url);
341        let session = make_session(resumed_session);
342        run_headless(llm_client, workspace_dir, prompt, Some(display), config.yolo_mode, session).await?;
343        return Ok(());
344    }
345
346    // Check if headless mode requested via -m, -p, or positional args
347    if headless_prompt.is_none() && !cli.query.is_empty() {
348        headless_prompt = Some(cli.query.join(" "));
349    }
350
351    if let Some(prompt_text) = headless_prompt {
352        let session = make_session(resumed_session);
353        run_headless(llm_client, workspace_dir, prompt_text, None, config.yolo_mode, session).await?;
354        return Ok(());
355    }
356
357    // Launch interactive TUI
358    let mut app = App::new(llm_client, workspace_dir.clone(), cli.yolo);
359    let _ = app.reload_mcp_servers().await;
360    if cli.fleet {
361        app.enter_fleet_mode();
362        app.fleet_dialog.open_async(&workspace_dir).await;
363    }
364    if let Some(loaded) = resumed_session {
365        app.session = loaded;
366    }
367
368    run_tui(app).await?;
369    Ok(())
370}
371
372async fn run_headless(
373    client: LlmClient,
374    workspace_dir: PathBuf,
375    user_prompt: String,
376    display_prompt: Option<String>,
377    yolo: bool,
378    mut session: Session,
379) -> Result<()> {
380    let mut tool_registry = ToolRegistry::new();
381    corex_fleet::register_fleet_tools(&mut tool_registry);
382    let (mcp_tools, _) = corex_tools::load_mcp_servers(&client.get_config().mcp_servers).await;
383    for t in mcp_tools {
384        tool_registry.register(t);
385    }
386    let prompt_builder = PromptBuilder::new(&workspace_dir)
387        .with_sudo_password(get_sudo_password().is_some());
388
389    session.add_message(Message::user(user_prompt.clone()));
390
391    let mut messages = Vec::with_capacity(session.messages.len() + 1);
392    messages.push(Message::system(prompt_builder.build()));
393    for m in &session.messages {
394        if m.role != "system" {
395            messages.push(m.clone());
396        }
397    }
398
399    use colored::Colorize;
400    let you_badge = format!(
401        "{}{}{}",
402        "[".truecolor(95, 95, 95),
403        "You".bold().truecolor(130, 215, 160),
404        "]".truecolor(95, 95, 95),
405    );
406    println!("{} {}", you_badge, display_prompt.as_deref().unwrap_or(&user_prompt));
407
408    let tools = tool_registry.list_definitions();
409    let context = ToolContext {
410        workspace_dir: workspace_dir.clone(),
411        yolo_mode: yolo,
412        sudo_password: get_sudo_password(),
413        allowed_commands: client.get_config().allowed_commands.clone(),
414    };
415
416    use std::io::IsTerminal;
417    let is_tty = std::io::stdout().is_terminal();
418    let term_width = crossterm::terminal::size().map(|(w, _)| w as usize).unwrap_or(80);
419
420    struct StatusSpinner {
421        stop_tx: Option<tokio::sync::oneshot::Sender<()>>,
422        handle: Option<tokio::task::JoinHandle<()>>,
423    }
424
425    impl StatusSpinner {
426        fn start(is_tty: bool, prefix_color: &'static str, message: String) -> Self {
427            if !is_tty {
428                return Self { stop_tx: None, handle: None };
429            }
430            let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
431            let handle = tokio::spawn(async move {
432                let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
433                let mut i = 0;
434                loop {
435                    print!("\r\x1b[2K{}{}\x1b[0m {}", prefix_color, frames[i], message);
436                    use std::io::Write;
437                    let _ = std::io::stdout().flush();
438                    i = (i + 1) % frames.len();
439                    tokio::select! {
440                        _ = &mut rx => break,
441                        _ = tokio::time::sleep(tokio::time::Duration::from_millis(70)) => {}
442                    }
443                }
444                print!("\r\x1b[2K");
445                use std::io::Write;
446                let _ = std::io::stdout().flush();
447            });
448            Self {
449                stop_tx: Some(tx),
450                handle: Some(handle),
451            }
452        }
453
454        async fn stop(&mut self) {
455            if let Some(tx) = self.stop_tx.take() {
456                let _ = tx.send(());
457            }
458            if let Some(handle) = self.handle.take() {
459                let _ = handle.await;
460            }
461            print!("\r\x1b[2K");
462            use std::io::Write;
463            let _ = std::io::stdout().flush();
464        }
465    }
466
467    const MAX_HEADLESS_TURNS: usize = 35;
468    let mut turn_count = 0;
469
470    loop {
471        turn_count += 1;
472        if turn_count > MAX_HEADLESS_TURNS {
473            eprintln!("\n[WARNING] Maximum headless tool iteration limit ({}) reached. Terminating loop to protect budget.", MAX_HEADLESS_TURNS);
474            break;
475        }
476
477        let cancel_token = CancellationToken::new();
478        let mut rx = client
479            .stream_chat(messages.clone(), Some(tools.clone()), cancel_token.clone())
480            .await?;
481
482        let mut current_tool_calls: Vec<ToolCall> = Vec::new();
483        let mut assistant_text = String::new();
484        let mut reasoning_text = String::new();
485        let mut current_extra_content: Option<serde_json::Value> = None;
486        let mut active_spinner: Option<StatusSpinner> = None;
487        let mut current_stage: u8 = 0; // 0 = idle, 1 = reasoning, 2 = content
488
489        while let Some(event) = rx.recv().await {
490            match event {
491                StreamEvent::ReasoningDelta(delta) => {
492                    reasoning_text.push_str(&delta);
493                    if current_stage != 1 {
494                        if let Some(mut s) = active_spinner.take() {
495                            s.stop().await;
496                        }
497                        active_spinner = Some(StatusSpinner::start(
498                            is_tty,
499                            "\x1b[90m",
500                            "Thinking...".to_string(),
501                        ));
502                        current_stage = 1;
503                    }
504                }
505                StreamEvent::ContentDelta(delta) => {
506                    assistant_text.push_str(&delta);
507                    if current_stage != 2 {
508                        if let Some(mut s) = active_spinner.take() {
509                            s.stop().await;
510                        }
511                        active_spinner = Some(StatusSpinner::start(
512                            is_tty,
513                            "\x1b[36m",
514                            "Generating response...".to_string(),
515                        ));
516                        current_stage = 2;
517                    }
518                }
519                StreamEvent::ToolCallDelta { index, id, name, arguments, extra_content } => {
520                    if index > 64 {
521                        continue;
522                    }
523                    while current_tool_calls.len() <= index {
524                        current_tool_calls.push(ToolCall {
525                            id: String::new(),
526                            call_type: "function".to_string(),
527                            function: corex_core::types::FunctionCall {
528                                name: String::new(),
529                                arguments: String::new(),
530                            },
531                            extra_content: None,
532                        });
533                    }
534                    if let Some(i) = id {
535                        current_tool_calls[index].id.push_str(&i);
536                    }
537                    if let Some(n) = name {
538                        current_tool_calls[index].function.name.push_str(&n);
539                    }
540                    if let Some(a) = arguments {
541                        current_tool_calls[index].function.arguments.push_str(&a);
542                    }
543                    if let Some(ec) = extra_content {
544                        current_tool_calls[index].extra_content = Some(ec);
545                    }
546                }
547                StreamEvent::ExtraContentDelta(ec) => {
548                    current_extra_content = Some(ec);
549                }
550                StreamEvent::Notice(msg) => {
551                    if let Some(mut s) = active_spinner.take() {
552                        s.stop().await;
553                    }
554                    println!("\n[INFO] {}\n", msg);
555                }
556                StreamEvent::ContextCompacted { compacted_messages, notice } => {
557                    if let Some(mut s) = active_spinner.take() {
558                        s.stop().await;
559                    }
560                    session.messages = compacted_messages;
561                    println!("\n[INFO] {}\n", notice);
562                }
563                StreamEvent::UsageUpdate(usage) => {
564                    session.update_usage(&usage);
565                }
566                StreamEvent::Completed { .. } => {}
567                StreamEvent::Error(err) => {
568                    if let Some(mut s) = active_spinner.take() {
569                        s.stop().await;
570                    }
571                    eprintln!("\nError: {}", err);
572                    let _ = session.save();
573                    return Ok(());
574                }
575                _ => {}
576            }
577        }
578
579        if let Some(mut s) = active_spinner.take() {
580            s.stop().await;
581        }
582
583        let user_cjk = corex_core::language::user_has_requested_cjk(&messages);
584        if corex_core::language::is_unwanted_cjk_drift(&assistant_text, user_cjk) {
585            assistant_text = corex_core::language::clean_cjk_drift_from_text(&assistant_text);
586        }
587
588        if !assistant_text.trim().is_empty() {
589            if is_tty {
590                let theme = corex_tui::Theme::default();
591                let rendered = corex_tui::render_markdown_to_ansi(&assistant_text, &theme, term_width);
592                println!("{}\n", rendered);
593            } else {
594                println!("{}\n", assistant_text);
595            }
596        }
597
598        if !current_tool_calls.is_empty() {
599            let text_opt = if assistant_text.is_empty() { None } else { Some(assistant_text) };
600            let cot_opt = if reasoning_text.is_empty() { None } else { Some(reasoning_text) };
601
602            for call in &mut current_tool_calls {
603                if call.extra_content.is_none() {
604                    call.extra_content = current_extra_content.clone();
605                }
606            }
607
608            let assistant_msg = Message::assistant_with_tools(
609                text_opt,
610                cot_opt,
611                current_tool_calls.clone(),
612            );
613            messages.push(assistant_msg.clone());
614            session.add_message(assistant_msg);
615
616            for call in &current_tool_calls {
617                let args_json = corex_core::parse_lenient_json(&call.function.arguments)
618                    .unwrap_or(serde_json::Value::Null);
619
620                let (action_label, target_detail) = if call.function.name == "run_shell_command" || call.function.name == "shell" || call.function.name == "run_command" {
621                    let cmd = args_json.get("command").and_then(|c| c.as_str()).unwrap_or("").trim();
622                    ("Running command", cmd)
623                } else if call.function.name == "read_file" {
624                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
625                    ("Reading file", p)
626                } else if call.function.name == "write_file" {
627                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
628                    ("Writing file", p)
629                } else if call.function.name == "edit" || call.function.name == "apply_patch" {
630                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
631                    ("Editing file", p)
632                } else if call.function.name == "glob" || call.function.name == "ls" || call.function.name == "list_directory" {
633                    let p = args_json.get("path").or_else(|| args_json.get("dir")).and_then(|c| c.as_str()).unwrap_or(".");
634                    ("Exploring directory", p)
635                } else if call.function.name == "web_search" || call.function.name == "google_web_search" {
636                    let q = args_json.get("query").and_then(|c| c.as_str()).unwrap_or("");
637                    ("Searching web", q)
638                } else if call.function.name == "web_fetch" {
639                    let u = args_json.get("url").and_then(|c| c.as_str()).unwrap_or("");
640                    ("Fetching web page", u)
641                } else {
642                    ("Running tool", call.function.name.as_str())
643                };
644
645                let display_detail = corex_core::truncate_ellipsis(&corex_core::sanitize_for_terminal(target_detail), 70);
646
647                // Prompt user for confirmation on potentially mutating/dangerous actions unless YOLO mode is enabled
648                if !context.yolo_mode {
649                    if let Some(tool) = tool_registry.get(&call.function.name) {
650                        if tool.needs_confirmation(&args_json, &context) {
651                            if is_tty {
652                                print!("\r\x1b[2K");
653                                use std::io::Write;
654                                let _ = std::io::stdout().flush();
655                            }
656                            println!("\n[WARNING] Action requires confirmation: [{}]", call.function.name);
657                            if let Some(diff) = tool.format_diff(&args_json, &context.workspace_dir) {
658                                println!("{}", diff);
659                            } else if let Some(cmd) = args_json.get("command").and_then(|c| c.as_str()) {
660                                println!("  Command: {}", corex_core::sanitize_for_terminal(cmd));
661                            } else {
662                                println!("  Arguments: {}", corex_core::sanitize_for_terminal(&serde_json::to_string_pretty(&args_json).unwrap_or_default()));
663                            }
664
665                            print!("Allow execution? [y/N]: ");
666                            use std::io::Write;
667                            let _ = std::io::stdout().flush();
668
669                            let mut input = String::new();
670                            let _ = std::io::stdin().read_line(&mut input);
671                            let trimmed = input.trim().to_lowercase();
672                            if trimmed != "y" && trimmed != "yes" {
673                                println!("Execution cancelled by user.");
674                                let denied_msg = Message::tool_response(call.id.clone(), "Execution denied by user.");
675                                messages.push(denied_msg.clone());
676                                session.add_message(denied_msg);
677                                continue;
678                            }
679                        }
680                    }
681                }
682
683                // Show real-time animated spinner while the tool executes
684                let mut tool_spinner = StatusSpinner::start(
685                    is_tty,
686                    "\x1b[33m",
687                    format!("\x1b[1m{}:\x1b[0m \x1b[36m{}\x1b[0m", action_label, display_detail),
688                );
689
690                let output = match tool_registry
691                    .execute(&call.function.name, args_json, &context)
692                    .await
693                {
694                    Ok(o) => {
695                        tool_spinner.stop().await;
696                        if is_tty {
697                            println!("\x1b[32m✓\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m", action_label, display_detail);
698                        }
699                        o.output
700                    }
701                    Err(e) => {
702                        tool_spinner.stop().await;
703                        if is_tty {
704                            println!("\x1b[31m✗\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m ({})", action_label, display_detail, e);
705                        }
706                        let msg = format!("Error executing {}: {}", call.function.name, e);
707                        eprintln!("{}", msg);
708                        msg
709                    }
710                };
711                let tool_msg = Message::tool_response(call.id.clone(), output);
712                messages.push(tool_msg.clone());
713                session.add_message(tool_msg);
714            }
715
716            // Feed the tool results back and continue the agent loop
717            continue;
718        }
719
720        // No tool calls: record final assistant turn in session and finish
721        if !assistant_text.is_empty() || !reasoning_text.is_empty() {
722            let cot_opt = if reasoning_text.is_empty() { None } else { Some(reasoning_text) };
723            let final_msg = Message::assistant(assistant_text, cot_opt);
724            session.add_message(final_msg);
725        }
726        break;
727    }
728
729    let _ = session.save();
730    Ok(())
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736
737    #[test]
738    fn test_cli_command_factory_debug_assert() {
739        // Validates clap internal consistency, non-colliding flags, and value parsers.
740        Cli::command().debug_assert();
741    }
742
743    #[test]
744    fn test_cli_default_args() {
745        let cli = Cli::try_parse_from(["cx"]).expect("Should parse empty invocation");
746        assert_eq!(cli.message, None);
747        assert!(cli.query.is_empty());
748        assert_eq!(cli.model, None);
749        assert_eq!(cli.web, None);
750        assert_eq!(cli.fetch, None);
751        assert!(!cli.yolo);
752        assert!(!cli.fleet);
753        assert!(!cli.list_sessions);
754        assert_eq!(cli.resume, None);
755        assert_eq!(cli.local, None);
756    }
757
758    #[test]
759    fn test_cli_prompt_flags() {
760        let short = Cli::try_parse_from(["cx", "-p", "Refactor main.rs"]).unwrap();
761        assert_eq!(short.message.as_deref(), Some("Refactor main.rs"));
762
763        let long = Cli::try_parse_from(["cx", "--prompt", "Explain this"]).unwrap();
764        assert_eq!(long.message.as_deref(), Some("Explain this"));
765
766        let alias = Cli::try_parse_from(["cx", "--message", "Alias test"]).unwrap();
767        assert_eq!(alias.message.as_deref(), Some("Alias test"));
768    }
769
770    #[test]
771    fn test_cli_model_selection_flags() {
772        let short = Cli::try_parse_from(["cx", "-m", "gemini-3.8-flash"]).unwrap();
773        assert_eq!(short.model.as_deref(), Some("gemini-3.8-flash"));
774
775        let long = Cli::try_parse_from(["cx", "--model", "claude-3-7-sonnet"]).unwrap();
776        assert_eq!(long.model.as_deref(), Some("claude-3-7-sonnet"));
777
778        let short_alias = Cli::try_parse_from(["cx", "-M", "o3-mini"]).unwrap();
779        assert_eq!(short_alias.model.as_deref(), Some("o3-mini"));
780    }
781
782    #[test]
783    fn test_cli_yolo_mode_flags() {
784        let short = Cli::try_parse_from(["cx", "-y"]).unwrap();
785        assert!(short.yolo);
786
787        let long = Cli::try_parse_from(["cx", "--yolo"]).unwrap();
788        assert!(long.yolo);
789    }
790
791    #[test]
792    fn test_cli_web_and_fetch_flags() {
793        let web_short = Cli::try_parse_from(["cx", "-w", "tokio select"]).unwrap();
794        assert_eq!(web_short.web.as_deref(), Some("tokio select"));
795
796        let web_long = Cli::try_parse_from(["cx", "--web", "rust 2024 edition"]).unwrap();
797        assert_eq!(web_long.web.as_deref(), Some("rust 2024 edition"));
798
799        let fetch = Cli::try_parse_from(["cx", "--fetch", "https://docs.rs"]).unwrap();
800        assert_eq!(fetch.fetch.as_deref(), Some("https://docs.rs"));
801    }
802
803    #[test]
804    fn test_cli_session_management_flags() {
805        let list_short = Cli::try_parse_from(["cx", "-l"]).unwrap();
806        assert!(list_short.list_sessions);
807
808        let list_long = Cli::try_parse_from(["cx", "--list-sessions"]).unwrap();
809        assert!(list_long.list_sessions);
810
811        let resume_short = Cli::try_parse_from(["cx", "-r", "sess_abc123"]).unwrap();
812        assert_eq!(resume_short.resume.as_deref(), Some("sess_abc123"));
813
814        let resume_long = Cli::try_parse_from(["cx", "--resume", "tag-refactor"]).unwrap();
815        assert_eq!(resume_long.resume.as_deref(), Some("tag-refactor"));
816    }
817
818    #[test]
819    fn test_cli_local_llm_flags() {
820        let local_flag = Cli::try_parse_from(["cx", "--local"]).unwrap();
821        assert_eq!(local_flag.local, Some(true));
822
823        let local_config = Cli::try_parse_from([
824            "cx",
825            "--local",
826            "--local-url", "http://127.0.0.1:11434/v1",
827            "--local-model", "qwen2.5-coder:32b"
828        ]).unwrap();
829        assert_eq!(local_config.local, Some(true));
830        assert_eq!(local_config.local_url.as_deref(), Some("http://127.0.0.1:11434/v1"));
831        assert_eq!(local_config.local_model.as_deref(), Some("qwen2.5-coder:32b"));
832    }
833
834    #[test]
835    fn test_cli_directory_override() {
836        let short = Cli::try_parse_from(["cx", "-C", "/tmp/test-project"]).unwrap();
837        assert_eq!(short.directory, Some(PathBuf::from("/tmp/test-project")));
838
839        let long = Cli::try_parse_from(["cx", "--directory", "/home/user/code"]).unwrap();
840        assert_eq!(long.directory, Some(PathBuf::from("/home/user/code")));
841    }
842
843    #[test]
844    fn test_cli_fleet_flags() {
845        let fleet = Cli::try_parse_from(["cx", "--fleet"]).unwrap();
846        assert!(fleet.fleet);
847
848        let sysadmin = Cli::try_parse_from(["cx", "--sysadmin"]).unwrap();
849        assert!(sysadmin.fleet);
850    }
851
852    #[test]
853    fn test_cli_positional_query() {
854        let query = Cli::try_parse_from(["cx", "inspect", "src/lib.rs", "--verbose-details"]).unwrap();
855        assert_eq!(query.query, vec!["inspect", "src/lib.rs", "--verbose-details"]);
856    }
857
858    #[test]
859    fn test_cli_completions_flag() {
860        let bash = Cli::try_parse_from(["cx", "--completions", "bash"]).unwrap();
861        assert_eq!(bash.completions, Some(clap_complete::Shell::Bash));
862
863        let zsh = Cli::try_parse_from(["cx", "--completions", "zsh"]).unwrap();
864        assert_eq!(zsh.completions, Some(clap_complete::Shell::Zsh));
865    }
866
867    #[test]
868    fn test_cli_upgrade_flags() {
869        let upgrade = Cli::try_parse_from(["cx", "--upgrade"]).unwrap();
870        assert!(upgrade.upgrade);
871
872        let update_alias = Cli::try_parse_from(["cx", "--update", "-f"]).unwrap();
873        assert!(update_alias.upgrade);
874        assert!(update_alias.force);
875    }
876}