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