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