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