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