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        if let Err(e) = corex_core::config::validate_base_url(&u) {
242            anyhow::bail!("{}", e);
243        }
244        if cli.api_key.is_none()
245            && !corex_core::config::is_deepseek_base_url(&u)
246            && !corex_core::config::same_host(&u, &config.base_url)
247        {
248            config.api_key.clear();
249        }
250        config.base_url = u;
251    }
252    if let Some(k) = cli.api_key {
253        config.api_key = k;
254    }
255    if let Some(loc_en) = cli.local {
256        config.local_llm_enabled = loc_en;
257    }
258    if let Some(loc_url) = cli.local_url {
259        config.local_llm_url = loc_url;
260    }
261    if let Some(loc_m) = cli.local_model {
262        config.local_llm_model = loc_m;
263    }
264    if cli.yolo {
265        config.yolo_mode = true;
266    }
267
268    let mut resumed_session: Option<Session> = None;
269    if let Some(ref session_id) = cli.resume {
270        match Session::load_by_id_or_tag(session_id) {
271            Ok(loaded) => {
272                if !explicit_model {
273                    config.model = loaded.model.clone();
274                }
275                if let Some(t) = loaded.temperature {
276                    config.temperature = t;
277                }
278                if let Some(ref r) = loaded.reasoning_effort {
279                    config.reasoning_effort = r.clone();
280                }
281                resumed_session = Some(loaded);
282            }
283            Err(e) => {
284                eprintln!(
285                    "Warning: Could not resume session {}: {}. Starting new session.",
286                    session_id, e
287                );
288            }
289        }
290    }
291
292    let llm_client = LlmClient::new(config.clone());
293    corex_tools::subagent::set_subagent_llm_client(std::sync::Arc::new(llm_client.clone()));
294
295    let make_session = |resumed: Option<Session>| -> Session {
296        resumed.unwrap_or_else(|| {
297            Session::new_with_params(
298                &config.model,
299                config.temperature,
300                &config.reasoning_effort,
301                Some(&workspace_dir),
302            )
303        })
304    };
305
306    let web_search_query = cli.web.or_else(|| {
307        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") {
308            let q = cli.query[1..].join(" ");
309            if !q.is_empty() {
310                Some(q)
311            } else {
312                None
313            }
314        } else {
315            None
316        }
317    });
318
319    if let Some(query) = web_search_query {
320        let prompt = format!(
321            "Please search the web using the web_search tool and synthesize a clear, direct, and well-structured answer with source links for: {}",
322            query
323        );
324        let display = format!("/web {}", query);
325        let session = make_session(resumed_session);
326        run_headless(llm_client, workspace_dir, prompt, Some(display), config.yolo_mode, session).await?;
327        return Ok(());
328    }
329
330    let web_fetch_url = cli.fetch.or_else(|| {
331        if cli.message.is_none() && !cli.query.is_empty() && (cli.query[0] == "fetch" || cli.query[0] == "/fetch") {
332            let u = cli.query[1..].join(" ");
333            if !u.is_empty() {
334                Some(u)
335            } else {
336                None
337            }
338        } else {
339            None
340        }
341    });
342
343    if let Some(url) = web_fetch_url {
344        let prompt = format!(
345            "Please fetch the URL '{}' using the web_fetch tool and synthesize a clear, comprehensive summary and analysis of its content.",
346            url
347        );
348        let display = format!("/fetch {}", url);
349        let session = make_session(resumed_session);
350        run_headless(llm_client, workspace_dir, prompt, Some(display), config.yolo_mode, session).await?;
351        return Ok(());
352    }
353
354    if headless_prompt.is_none() && !cli.query.is_empty() {
355        headless_prompt = Some(cli.query.join(" "));
356    }
357
358    if let Some(prompt_text) = headless_prompt {
359        let session = make_session(resumed_session);
360        run_headless(llm_client, workspace_dir, prompt_text, None, config.yolo_mode, session).await?;
361        return Ok(());
362    }
363
364    let mut app = App::new(llm_client, workspace_dir.clone(), cli.yolo);
365    let _ = app.reload_mcp_servers().await;
366    if cli.fleet {
367        app.enter_fleet_mode();
368        app.fleet_dialog.open_async(&workspace_dir).await;
369    }
370    if let Some(loaded) = resumed_session {
371        app.session = loaded;
372    }
373
374    run_tui(app).await?;
375    Ok(())
376}
377
378/// Puts the ask_user questions to whoever is on stdin and returns their answers. With nobody to
379/// answer (stdin closed), says so plainly so the model goes on with a stated assumption instead
380/// of waiting for a reply that never comes in a one-shot run.
381fn ask_user_on_stdin(args: &serde_json::Value) -> String {
382    let questions: Vec<(String, Vec<String>)> = match args.get("questions").and_then(|q| q.as_array()) {
383        Some(list) => list
384            .iter()
385            .filter_map(|q| {
386                let text = q.get("question")?.as_str()?.to_string();
387                let options = q
388                    .get("options")
389                    .and_then(|o| o.as_array())
390                    .map(|o| o.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
391                    .unwrap_or_default();
392                Some((text, options))
393            })
394            .collect(),
395        None => args.get("question").and_then(|q| q.as_str()).map(|q| vec![(q.to_string(), Vec::new())]).unwrap_or_default(),
396    };
397    if questions.is_empty() {
398        return "ask_user was called without any question.".to_string();
399    }
400    let mut answers = Vec::new();
401    for (question, options) in &questions {
402        println!("\n\x1b[1m?\x1b[0m {}", corex_core::sanitize_for_terminal(question));
403        if !options.is_empty() {
404            println!("  ({})", corex_core::sanitize_for_terminal(&options.join(" / ")));
405        }
406        print!("> ");
407        use std::io::Write;
408        let _ = std::io::stdout().flush();
409        let mut line = String::new();
410        match std::io::stdin().read_line(&mut line) {
411            Ok(n) if n > 0 && !line.trim().is_empty() => answers.push(format!("- {}: {}", question, line.trim())),
412            _ => {
413                return "No user is available to answer (non-interactive run with no input). Do not wait for a reply: \
414                        choose the most reasonable option, say which one you assumed, and continue."
415                    .to_string()
416            }
417        }
418    }
419    format!("The user answered:\n{}", answers.join("\n"))
420}
421
422async fn run_headless(
423    client: LlmClient,
424    workspace_dir: PathBuf,
425    user_prompt: String,
426    display_prompt: Option<String>,
427    yolo: bool,
428    mut session: Session,
429) -> Result<()> {
430    let mut tool_registry = ToolRegistry::new();
431    corex_fleet::register_fleet_tools(&mut tool_registry);
432    let (mcp_tools, _) = corex_tools::load_mcp_servers(&client.get_config().mcp_servers).await;
433    for t in mcp_tools {
434        tool_registry.register(t);
435    }
436    let prompt_builder = PromptBuilder::new(&workspace_dir)
437        .with_sudo_password(get_sudo_password().is_some());
438
439    session.add_message(Message::user(user_prompt.clone()));
440
441    let mut messages = Vec::with_capacity(session.messages.len() + 1);
442    messages.push(Message::system(prompt_builder.build()));
443    for m in &session.messages {
444        let is_preserved_system = m.role == "system"
445            && m.content.as_ref().and_then(|c| c.as_text()).map_or(false, |c| {
446                c.contains("<CONTEXT_SUMMARY>")
447                    || c.starts_with("TASK_DONE|")
448                    || c.starts_with("SUBAGENT_DONE|")
449            });
450        if m.role != "system" || is_preserved_system {
451            messages.push(m.clone());
452        }
453    }
454
455    use colored::Colorize;
456    let you_badge = format!(
457        "{}{}{}",
458        "[".truecolor(95, 95, 95),
459        "You".bold().truecolor(130, 215, 160),
460        "]".truecolor(95, 95, 95),
461    );
462    println!("{} {}", you_badge, display_prompt.as_deref().unwrap_or(&user_prompt));
463
464    let tools = tool_registry.list_definitions();
465    let context = ToolContext {
466        workspace_dir: workspace_dir.clone(),
467        yolo_mode: yolo,
468        sudo_password: get_sudo_password(),
469        allowed_commands: client.get_config().allowed_commands.clone(),
470        extra_dirs: Vec::new(),
471    };
472
473    use std::io::IsTerminal;
474    let is_tty = std::io::stdout().is_terminal();
475    let term_width = crossterm::terminal::size().map(|(w, _)| w as usize).unwrap_or(80);
476
477    struct StatusSpinner {
478        stop_tx: Option<tokio::sync::oneshot::Sender<()>>,
479        handle: Option<tokio::task::JoinHandle<()>>,
480    }
481
482    impl StatusSpinner {
483        fn start(is_tty: bool, prefix_color: &'static str, message: String) -> Self {
484            if !is_tty {
485                return Self { stop_tx: None, handle: None };
486            }
487            let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
488            let handle = tokio::spawn(async move {
489                let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
490                let mut i = 0;
491                loop {
492                    print!("\r\x1b[2K{}{}\x1b[0m {}", prefix_color, frames[i], message);
493                    use std::io::Write;
494                    let _ = std::io::stdout().flush();
495                    i = (i + 1) % frames.len();
496                    tokio::select! {
497                        _ = &mut rx => break,
498                        _ = tokio::time::sleep(tokio::time::Duration::from_millis(70)) => {}
499                    }
500                }
501                print!("\r\x1b[2K");
502                use std::io::Write;
503                let _ = std::io::stdout().flush();
504            });
505            Self {
506                stop_tx: Some(tx),
507                handle: Some(handle),
508            }
509        }
510
511        async fn stop(&mut self) {
512            if let Some(tx) = self.stop_tx.take() {
513                let _ = tx.send(());
514            }
515            if let Some(handle) = self.handle.take() {
516                let _ = handle.await;
517            }
518            print!("\r\x1b[2K");
519            use std::io::Write;
520            let _ = std::io::stdout().flush();
521        }
522    }
523
524    const MAX_HEADLESS_TURNS: usize = 35;
525    let mut turn_count = 0;
526    let mut truncated_retries = 0u8;
527
528    loop {
529        turn_count += 1;
530        if turn_count > MAX_HEADLESS_TURNS {
531            eprintln!("\n[WARNING] Maximum headless tool iteration limit ({}) reached. Terminating loop to protect budget.", MAX_HEADLESS_TURNS);
532            break;
533        }
534
535        let cancel_token = CancellationToken::new();
536        let mut rx = client
537            .stream_chat(messages.clone(), Some(tools.clone()), cancel_token.clone())
538            .await?;
539
540        let mut current_tool_calls: Vec<ToolCall> = Vec::new();
541        let mut assistant_text = String::new();
542        let mut reasoning_text = String::new();
543        let mut current_extra_content: Option<serde_json::Value> = None;
544        let mut active_spinner: Option<StatusSpinner> = None;
545        let mut current_stage: u8 = 0; // 0 = idle, 1 = reasoning, 2 = content
546        let mut finish_reason: Option<String> = None;
547
548        while let Some(event) = rx.recv().await {
549            match event {
550                StreamEvent::ReasoningDelta(delta) => {
551                    reasoning_text.push_str(&delta);
552                    if current_stage != 1 {
553                        if let Some(mut s) = active_spinner.take() {
554                            s.stop().await;
555                        }
556                        active_spinner = Some(StatusSpinner::start(
557                            is_tty,
558                            "\x1b[90m",
559                            "Thinking...".to_string(),
560                        ));
561                        current_stage = 1;
562                    }
563                }
564                StreamEvent::ContentDelta(delta) => {
565                    assistant_text.push_str(&delta);
566                    if current_stage != 2 {
567                        if let Some(mut s) = active_spinner.take() {
568                            s.stop().await;
569                        }
570                        active_spinner = Some(StatusSpinner::start(
571                            is_tty,
572                            "\x1b[36m",
573                            "Generating response...".to_string(),
574                        ));
575                        current_stage = 2;
576                    }
577                }
578                StreamEvent::ToolCallDelta { index, id, name, arguments, extra_content } => {
579                    if index > 64 {
580                        continue;
581                    }
582                    while current_tool_calls.len() <= index {
583                        current_tool_calls.push(ToolCall {
584                            id: String::new(),
585                            call_type: "function".to_string(),
586                            function: corex_core::types::FunctionCall {
587                                name: String::new(),
588                                arguments: String::new(),
589                            },
590                            extra_content: None,
591                        });
592                    }
593                    if let Some(i) = id {
594                        current_tool_calls[index].id.push_str(&i);
595                    }
596                    if let Some(n) = name {
597                        current_tool_calls[index].function.name.push_str(&n);
598                    }
599                    if let Some(a) = arguments {
600                        current_tool_calls[index].function.arguments.push_str(&a);
601                    }
602                    if let Some(ec) = extra_content {
603                        current_tool_calls[index].extra_content = Some(ec);
604                    }
605                }
606                StreamEvent::ExtraContentDelta(ec) => {
607                    current_extra_content = Some(ec);
608                }
609                StreamEvent::Notice(msg) => {
610                    if let Some(mut s) = active_spinner.take() {
611                        s.stop().await;
612                    }
613                    println!("\n[INFO] {}\n", msg);
614                }
615                StreamEvent::ContextCompacted { compacted_messages, notice } => {
616                    if let Some(mut s) = active_spinner.take() {
617                        s.stop().await;
618                    }
619                    let sys_prompt = messages.first().cloned();
620                    let before = std::mem::replace(&mut session.messages, compacted_messages.clone());
621                    session.keep_history_before_compaction(&before);
622                    messages.clear();
623                    if let Some(sys) = sys_prompt {
624                        messages.push(sys);
625                    }
626                    for m in compacted_messages {
627                        if m.role != "system"
628                            || m.content.as_ref().and_then(|c| c.as_text()).map_or(false, |c| {
629                                c.contains("<CONTEXT_SUMMARY>")
630                                    || c.starts_with("TASK_DONE|")
631                                    || c.starts_with("SUBAGENT_DONE|")
632                            })
633                        {
634                            messages.push(m);
635                        }
636                    }
637                    println!("\n[INFO] {}\n", notice);
638                }
639                StreamEvent::UsageUpdate(usage) => {
640                    session.update_usage(&usage);
641                }
642                StreamEvent::Completed { finish_reason: reason } => {
643                    if reason.is_some() {
644                        finish_reason = reason;
645                    }
646                }
647                StreamEvent::Error(err) => {
648                    if let Some(mut s) = active_spinner.take() {
649                        s.stop().await;
650                    }
651                    eprintln!("\nError: {}", err);
652                    corex_tools::background::shutdown_all_tasks();
653                    let _ = session.save();
654                    return Ok(());
655                }
656                _ => {}
657            }
658        }
659
660        if let Some(mut s) = active_spinner.take() {
661            s.stop().await;
662        }
663
664        let user_cjk = corex_core::language::user_has_requested_cjk(&messages);
665        if corex_core::language::is_unwanted_cjk_drift(&assistant_text, user_cjk) {
666            assistant_text = corex_core::language::clean_cjk_drift_from_text(&assistant_text);
667        }
668
669        if !assistant_text.trim().is_empty() {
670            let safe_text = corex_core::sanitize_for_terminal(&assistant_text);
671            if is_tty {
672                let theme = corex_tui::Theme::default();
673                let rendered = corex_tui::render_markdown_to_ansi(&safe_text, &theme, term_width);
674                println!("{}\n", rendered);
675            } else {
676                println!("{}\n", safe_text);
677            }
678        }
679
680        // Providers that index tool calls by content block (Anthropic) leave empty placeholders.
681        current_tool_calls.retain(|c| !c.function.name.trim().is_empty());
682
683        if !current_tool_calls.is_empty() {
684            let text_opt = if assistant_text.is_empty() { None } else { Some(assistant_text) };
685            let cot_opt = if reasoning_text.is_empty() { None } else { Some(reasoning_text) };
686
687            for call in &mut current_tool_calls {
688                if call.extra_content.is_none() {
689                    call.extra_content = current_extra_content.clone();
690                }
691            }
692
693            let assistant_msg = Message::assistant_with_tools(
694                text_opt,
695                cot_opt,
696                current_tool_calls.clone(),
697            );
698            messages.push(assistant_msg.clone());
699            session.add_message(assistant_msg);
700
701            if corex_core::is_truncated_finish(finish_reason.as_deref()) {
702                // Arguments may be cut mid-file or mid-command: never run them.
703                for call in &current_tool_calls {
704                    let msg = Message::tool_response(call.id.clone(), corex_core::TRUNCATED_TOOL_CALL_ERROR);
705                    messages.push(msg.clone());
706                    session.add_message(msg);
707                }
708                truncated_retries += 1;
709                if truncated_retries > 1 {
710                    eprintln!("\n[WARNING] Response truncated twice by the output token limit; tool calls were not executed.");
711                    break;
712                }
713                eprintln!("\n[WARNING] Response truncated by the output token limit; asking the model to retry in smaller pieces.");
714                continue;
715            }
716            truncated_retries = 0;
717
718            for call in &current_tool_calls {
719                let args_json = corex_core::parse_lenient_json(&call.function.arguments)
720                    .unwrap_or(serde_json::Value::Null);
721
722                let (action_label, target_detail) = if call.function.name == "run_shell_command" || call.function.name == "shell" || call.function.name == "run_command" {
723                    let cmd = args_json.get("command").and_then(|c| c.as_str()).unwrap_or("").trim();
724                    ("Running command", cmd)
725                } else if call.function.name == "read_file" {
726                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
727                    ("Reading file", p)
728                } else if call.function.name == "write_file" {
729                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
730                    ("Writing file", p)
731                } else if call.function.name == "edit" || call.function.name == "apply_patch" {
732                    let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
733                    ("Editing file", p)
734                } else if call.function.name == "glob" || call.function.name == "ls" || call.function.name == "list_directory" {
735                    let p = args_json.get("path").or_else(|| args_json.get("dir")).and_then(|c| c.as_str()).unwrap_or(".");
736                    ("Exploring directory", p)
737                } else if call.function.name == "web_search" || call.function.name == "google_web_search" {
738                    let q = args_json.get("query").and_then(|c| c.as_str()).unwrap_or("");
739                    ("Searching web", q)
740                } else if call.function.name == "web_fetch" {
741                    let u = args_json.get("url").and_then(|c| c.as_str()).unwrap_or("");
742                    ("Fetching web page", u)
743                } else {
744                    ("Running tool", call.function.name.as_str())
745                };
746
747                let display_detail = corex_core::truncate_ellipsis(&corex_core::sanitize_for_terminal(target_detail), 70);
748
749                {
750                    if let Some(tool) = tool_registry.get(&call.function.name) {
751                        let must_ask = corex_tools::policy::verdict(&tool_registry, &call.function.name, &args_json, &context, false)
752                            == corex_tools::policy::Verdict::Ask;
753                        if must_ask {
754                            if is_tty {
755                                print!("\r\x1b[2K");
756                                use std::io::Write;
757                                let _ = std::io::stdout().flush();
758                            }
759                            println!("\n[WARNING] Action requires confirmation: [{}]", call.function.name);
760                            if let Some(diff) = tool.format_diff(&args_json, &context.workspace_dir) {
761                                println!("{}", corex_core::sanitize_for_terminal(&diff));
762                            } else if let Some(cmd) = args_json.get("command").and_then(|c| c.as_str()) {
763                                println!("  Command: {}", corex_core::sanitize_for_terminal(cmd));
764                            } else {
765                                println!("  Arguments: {}", corex_core::sanitize_for_terminal(&serde_json::to_string_pretty(&args_json).unwrap_or_default()));
766                            }
767
768                            print!("Allow execution? [y/N]: ");
769                            use std::io::Write;
770                            let _ = std::io::stdout().flush();
771
772                            let mut input = String::new();
773                            let _ = std::io::stdin().read_line(&mut input);
774                            let trimmed = input.trim().to_lowercase();
775                            if trimmed != "y" && trimmed != "yes" {
776                                println!("Execution cancelled by user.");
777                                let denied_msg = Message::tool_response(call.id.clone(), "Execution denied by user.");
778                                messages.push(denied_msg.clone());
779                                session.add_message(denied_msg);
780                                continue;
781                            }
782                        }
783                    }
784                }
785
786                if call.function.name == "ask_user" {
787                    let answer = ask_user_on_stdin(&args_json);
788                    let msg = Message::tool_response(call.id.clone(), answer);
789                    messages.push(msg.clone());
790                    session.add_message(msg);
791                    continue;
792                }
793
794                let mut tool_spinner = StatusSpinner::start(
795                    is_tty,
796                    "\x1b[33m",
797                    format!("\x1b[1m{}:\x1b[0m \x1b[36m{}\x1b[0m", action_label, display_detail),
798                );
799
800                let output = match tool_registry
801                    .execute(&call.function.name, args_json, &context)
802                    .await
803                {
804                    Ok(o) => {
805                        tool_spinner.stop().await;
806                        if is_tty {
807                            println!("\x1b[32m✓\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m", action_label, display_detail);
808                        }
809                        o.output
810                    }
811                    Err(e) => {
812                        tool_spinner.stop().await;
813                        if is_tty {
814                            println!("\x1b[31m✗\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m ({})", action_label, display_detail, e);
815                        }
816                        let msg = format!("Error executing {}: {}", call.function.name, e);
817                        eprintln!("{}", msg);
818                        msg
819                    }
820                };
821                // Huge output is cut to head + tail; the full text stays readable from a file.
822                let output = corex_core::spill_large_output(&call.function.name, output);
823                // Advisory nudge when the model keeps repeating the exact same call.
824                let output = match corex_core::observe_tool_call(&call.function.name, &call.function.arguments) {
825                    Some(reminder) => format!("{}\n\n{}", output, reminder),
826                    None => output,
827                };
828                let tool_msg = Message::tool_response(call.id.clone(), output);
829                messages.push(tool_msg.clone());
830                session.add_message(tool_msg);
831            }
832
833            if let Some(image_msg) = corex_core::drain_tool_images_message() {
834                messages.push(image_msg.clone());
835                session.add_message(image_msg);
836            }
837
838            continue;
839        }
840
841        if !assistant_text.is_empty() || !reasoning_text.is_empty() {
842            let cot_opt = if reasoning_text.is_empty() { None } else { Some(reasoning_text) };
843            let final_msg = Message::assistant(assistant_text, cot_opt);
844            session.add_message(final_msg);
845        }
846        break;
847    }
848
849    corex_tools::background::shutdown_all_tasks();
850    let _ = session.save();
851    Ok(())
852}
853
854#[cfg(test)]
855mod tests {
856    use super::*;
857
858    #[test]
859    fn test_cli_command_factory_debug_assert() {
860        // Validates clap internal consistency, non-colliding flags, and value parsers.
861        Cli::command().debug_assert();
862    }
863
864    #[test]
865    fn test_cli_default_args() {
866        let cli = Cli::try_parse_from(["cx"]).expect("Should parse empty invocation");
867        assert_eq!(cli.message, None);
868        assert!(cli.query.is_empty());
869        assert_eq!(cli.model, None);
870        assert_eq!(cli.web, None);
871        assert_eq!(cli.fetch, None);
872        assert!(!cli.yolo);
873        assert!(!cli.fleet);
874        assert!(!cli.list_sessions);
875        assert_eq!(cli.resume, None);
876        assert_eq!(cli.local, None);
877    }
878
879    #[test]
880    fn test_cli_prompt_flags() {
881        let short = Cli::try_parse_from(["cx", "-p", "Refactor main.rs"]).unwrap();
882        assert_eq!(short.message.as_deref(), Some("Refactor main.rs"));
883
884        let long = Cli::try_parse_from(["cx", "--prompt", "Explain this"]).unwrap();
885        assert_eq!(long.message.as_deref(), Some("Explain this"));
886
887        let alias = Cli::try_parse_from(["cx", "--message", "Alias test"]).unwrap();
888        assert_eq!(alias.message.as_deref(), Some("Alias test"));
889    }
890
891    #[test]
892    fn test_cli_model_selection_flags() {
893        let short = Cli::try_parse_from(["cx", "-m", "gemini-3.8-flash"]).unwrap();
894        assert_eq!(short.model.as_deref(), Some("gemini-3.8-flash"));
895
896        let long = Cli::try_parse_from(["cx", "--model", "claude-3-7-sonnet"]).unwrap();
897        assert_eq!(long.model.as_deref(), Some("claude-3-7-sonnet"));
898
899        let short_alias = Cli::try_parse_from(["cx", "-M", "o3-mini"]).unwrap();
900        assert_eq!(short_alias.model.as_deref(), Some("o3-mini"));
901    }
902
903    #[test]
904    fn test_cli_yolo_mode_flags() {
905        let short = Cli::try_parse_from(["cx", "-y"]).unwrap();
906        assert!(short.yolo);
907
908        let long = Cli::try_parse_from(["cx", "--yolo"]).unwrap();
909        assert!(long.yolo);
910    }
911
912    #[test]
913    fn test_cli_web_and_fetch_flags() {
914        let web_short = Cli::try_parse_from(["cx", "-w", "tokio select"]).unwrap();
915        assert_eq!(web_short.web.as_deref(), Some("tokio select"));
916
917        let web_long = Cli::try_parse_from(["cx", "--web", "rust 2024 edition"]).unwrap();
918        assert_eq!(web_long.web.as_deref(), Some("rust 2024 edition"));
919
920        let fetch = Cli::try_parse_from(["cx", "--fetch", "https://docs.rs"]).unwrap();
921        assert_eq!(fetch.fetch.as_deref(), Some("https://docs.rs"));
922    }
923
924    #[test]
925    fn test_cli_session_management_flags() {
926        let list_short = Cli::try_parse_from(["cx", "-l"]).unwrap();
927        assert!(list_short.list_sessions);
928
929        let list_long = Cli::try_parse_from(["cx", "--list-sessions"]).unwrap();
930        assert!(list_long.list_sessions);
931
932        let resume_short = Cli::try_parse_from(["cx", "-r", "sess_abc123"]).unwrap();
933        assert_eq!(resume_short.resume.as_deref(), Some("sess_abc123"));
934
935        let resume_long = Cli::try_parse_from(["cx", "--resume", "tag-refactor"]).unwrap();
936        assert_eq!(resume_long.resume.as_deref(), Some("tag-refactor"));
937    }
938
939    #[test]
940    fn test_cli_local_llm_flags() {
941        let local_flag = Cli::try_parse_from(["cx", "--local"]).unwrap();
942        assert_eq!(local_flag.local, Some(true));
943
944        let local_config = Cli::try_parse_from([
945            "cx",
946            "--local",
947            "--local-url", "http://127.0.0.1:11434/v1",
948            "--local-model", "qwen2.5-coder:32b"
949        ]).unwrap();
950        assert_eq!(local_config.local, Some(true));
951        assert_eq!(local_config.local_url.as_deref(), Some("http://127.0.0.1:11434/v1"));
952        assert_eq!(local_config.local_model.as_deref(), Some("qwen2.5-coder:32b"));
953    }
954
955    #[test]
956    fn test_cli_directory_override() {
957        let short = Cli::try_parse_from(["cx", "-C", "/tmp/test-project"]).unwrap();
958        assert_eq!(short.directory, Some(PathBuf::from("/tmp/test-project")));
959
960        let long = Cli::try_parse_from(["cx", "--directory", "/home/user/code"]).unwrap();
961        assert_eq!(long.directory, Some(PathBuf::from("/home/user/code")));
962    }
963
964    #[test]
965    fn test_cli_fleet_flags() {
966        let fleet = Cli::try_parse_from(["cx", "--fleet"]).unwrap();
967        assert!(fleet.fleet);
968
969        let sysadmin = Cli::try_parse_from(["cx", "--sysadmin"]).unwrap();
970        assert!(sysadmin.fleet);
971    }
972
973    #[test]
974    fn test_cli_positional_query() {
975        let query = Cli::try_parse_from(["cx", "inspect", "src/lib.rs", "--verbose-details"]).unwrap();
976        assert_eq!(query.query, vec!["inspect", "src/lib.rs", "--verbose-details"]);
977    }
978
979    #[test]
980    fn test_cli_completions_flag() {
981        let bash = Cli::try_parse_from(["cx", "--completions", "bash"]).unwrap();
982        assert_eq!(bash.completions, Some(clap_complete::Shell::Bash));
983
984        let zsh = Cli::try_parse_from(["cx", "--completions", "zsh"]).unwrap();
985        assert_eq!(zsh.completions, Some(clap_complete::Shell::Zsh));
986    }
987
988    #[test]
989    fn test_cli_upgrade_flags() {
990        let upgrade = Cli::try_parse_from(["cx", "--upgrade"]).unwrap();
991        assert!(upgrade.upgrade);
992
993        assert!(Cli::try_parse_from(["cx", "--no-update-check"]).unwrap().no_update_check);
994        assert!(!Cli::try_parse_from(["cx"]).unwrap().no_update_check);
995
996        let update_alias = Cli::try_parse_from(["cx", "--update", "-f"]).unwrap();
997        assert!(update_alias.upgrade);
998        assert!(update_alias.force);
999    }
1000}