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