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
15#[derive(Parser, Debug)]
16#[command(
17 name = "cx",
18 version = env!("CARGO_PKG_VERSION"),
19 author = "sluisr <contact@sluisr.com>",
20 about = "Corex — High-Performance Autonomous Coding Agent"
21)]
22struct Cli {
23 #[arg(short = 'p', long = "prompt", alias = "message")]
25 message: Option<String>,
26
27 #[arg(trailing_var_arg = true)]
29 query: Vec<String>,
30
31 #[arg(short = 'w', long = "web")]
33 web: Option<String>,
34
35 #[arg(short = 'm', short_alias = 'M', long = "model")]
37 model: Option<String>,
38
39 #[arg(long)]
41 base_url: Option<String>,
42
43 #[arg(long)]
45 api_key: Option<String>,
46
47 #[arg(short = 'r', long)]
49 resume: Option<String>,
50
51 #[arg(short = 'l', long = "list-sessions")]
53 list_sessions: bool,
54
55 #[arg(short = 'y', long)]
57 yolo: bool,
58
59 #[arg(short = 'C', long)]
61 directory: Option<PathBuf>,
62
63 #[arg(long, default_missing_value = "true", num_args = 0..=1)]
65 local: Option<bool>,
66
67 #[arg(long)]
69 local_url: Option<String>,
70
71 #[arg(long)]
73 local_model: Option<String>,
74
75 #[arg(long = "upgrade", alias = "update")]
77 upgrade: bool,
78
79 #[arg(long = "force", short = 'f')]
81 force: bool,
82
83 #[arg(long = "completions", value_enum)]
85 completions: Option<clap_complete::Shell>,
86}
87
88pub async fn run() -> Result<()> {
89 let cli = Cli::parse();
90
91 let workspace_dir = cli
92 .directory
93 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
94
95 if cli.list_sessions {
97 let ws_str = workspace_dir.display().to_string();
98 let sessions = Session::list_all(Some(&ws_str));
99 if sessions.is_empty() {
100 println!("No previous sessions found for this project.");
101 } else {
102 println!("\nAvailable sessions for this project ({}):", sessions.len());
103 for (i, s) in sessions.iter().enumerate() {
104 let rel_time = Session::format_relative_time(s.updated_at);
105 let tag_str = s.tag.as_ref().map(|t| format!(" [tag: {}]", t)).unwrap_or_default();
106 let model_display = if s.model == "deepseek-flash" || s.model == "deepseek-v4.1-flash" || s.model == "deepseek-v4-flash" || s.model == "deepseek-chat" {
107 "DeepSeek-V4.1-Flash"
108 } else if s.model == "deepseek-v4-pro" || s.model == "deepseek-reasoner" {
109 "DeepSeek-V4-Pro"
110 } else if s.model == "deepseek-v4-flash-vision-exp" {
111 "DeepSeek-V4.1-Flash (Vision)"
112 } else {
113 &s.model
114 };
115 println!(" {}. {} ({}){} · {} [{}]", i + 1, s.title, rel_time, tag_str, model_display, s.id);
116 }
117 println!("\nResume any session with: cx --resume <index | tag | id>\n");
118 }
119 return Ok(());
120 }
121
122 let completions_shell = cli.completions.or_else(|| {
124 if cli.message.is_none() && !cli.query.is_empty() && cli.query[0] == "completions" {
125 cli.query.get(1).and_then(|s| s.parse::<clap_complete::Shell>().ok())
126 } else {
127 None
128 }
129 });
130
131 if let Some(shell) = completions_shell {
132 let mut cmd = Cli::command();
133 clap_complete::generate(shell, &mut cmd, "cx", &mut std::io::stdout());
134 return Ok(());
135 }
136
137 if cli.message.is_none() && !cli.query.is_empty() && cli.query[0] == "completions" && cli.query.len() == 1 {
138 println!("Usage: cx --completions <bash|zsh|fish|powershell|elvish>");
139 return Ok(());
140 }
141
142 let is_update_cmd = cli.upgrade
144 || (cli.message.is_none()
145 && !cli.query.is_empty()
146 && (cli.query[0] == "update" || cli.query[0] == "upgrade" || cli.query[0] == "--update" || cli.query[0] == "--upgrade"));
147
148 if is_update_cmd {
149 let current = env!("CARGO_PKG_VERSION");
150 let force = cli.force || cli.query.iter().any(|q| q == "--force" || q == "-f");
151 println!("🚀 Corex In-Place Self-Updater (v{})", current);
152 match corex_core::update::perform_self_update(current, force, |msg| {
153 println!(" • {}", msg);
154 }).await {
155 Ok(summary) => {
156 println!(
157 "\n✨ Successfully updated Corex from v{} to v{}!\n📍 Binary: {}\n🎯 Target: {}\n",
158 summary.previous_version,
159 summary.updated_version,
160 summary.binary_path.display(),
161 summary.target_triple
162 );
163 }
164 Err(e) => {
165 eprintln!("\n⚠️ Update notice: {}", e);
166 if !force && e.contains("already on the latest version") {
167 println!("To force re-download the latest release, run:\n cx update --force\n");
168 }
169 }
170 }
171 return Ok(());
172 }
173
174 let log_path = corex_core::ForensicLogger::init(Some(&workspace_dir));
176 tracing::debug!("Forensic audit logger initialized at {:?}", log_path);
177
178 let mut config = Config::load_with_workspace(Some(&workspace_dir));
179 let mut headless_prompt = cli.message.clone();
180
181 if let Some(m) = cli.model {
182 if (m.contains(' ') || m.ends_with('?') || m.starts_with("arregla") || m.starts_with("que ") || m.starts_with("fix"))
184 && headless_prompt.is_none()
185 {
186 headless_prompt = Some(m);
187 } else {
188 config.model = m;
189 }
190 }
191 if let Some(u) = cli.base_url {
192 config.base_url = u;
193 }
194 if let Some(k) = cli.api_key {
195 config.api_key = k;
196 }
197 if let Some(loc_en) = cli.local {
198 config.local_llm_enabled = loc_en;
199 }
200 if let Some(loc_url) = cli.local_url {
201 config.local_llm_url = loc_url;
202 }
203 if let Some(loc_m) = cli.local_model {
204 config.local_llm_model = loc_m;
205 }
206 if cli.yolo {
207 config.yolo_mode = true;
208 }
209
210 let llm_client = LlmClient::new(config.clone());
211
212 let web_search_query = cli.web.or_else(|| {
214 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") {
215 let q = cli.query[1..].join(" ");
216 if !q.is_empty() {
217 Some(q)
218 } else {
219 None
220 }
221 } else {
222 None
223 }
224 });
225
226 if let Some(query) = web_search_query {
227 let prompt = format!(
228 "Por favor busca en internet usando la herramienta web_search y responde de manera clara, directa y sintetizada con fuentes a: {}",
229 query
230 );
231 let display = format!("/web {}", query);
232 run_headless(llm_client, workspace_dir, prompt, Some(display), config.yolo_mode).await?;
233 return Ok(());
234 }
235
236 if headless_prompt.is_none() && !cli.query.is_empty() {
238 headless_prompt = Some(cli.query.join(" "));
239 }
240
241 if let Some(prompt_text) = headless_prompt {
242 run_headless(llm_client, workspace_dir, prompt_text, None, config.yolo_mode).await?;
243 return Ok(());
244 }
245
246 let mut app = App::new(llm_client, workspace_dir.clone(), cli.yolo);
248 let _ = app.reload_mcp_servers().await;
249 if let Some(session_id) = cli.resume {
250 match Session::load_by_id_or_tag(&session_id) {
251 Ok(loaded) => {
252 let mut cfg = app.llm_client.get_config();
253 cfg.model = loaded.model.clone();
254 if let Some(t) = loaded.temperature {
255 cfg.temperature = t;
256 }
257 if let Some(ref r) = loaded.reasoning_effort {
258 cfg.reasoning_effort = r.clone();
259 }
260 app.llm_client.update_config(cfg);
261 app.session = loaded;
262 }
263 Err(e) => {
264 eprintln!("Warning: Could not resume session {}: {}. Starting new session.", session_id, e);
265 }
266 }
267 }
268
269 run_tui(app).await?;
270 Ok(())
271}
272
273async fn run_headless(
274 client: LlmClient,
275 workspace_dir: PathBuf,
276 user_prompt: String,
277 display_prompt: Option<String>,
278 yolo: bool,
279) -> Result<()> {
280 let mut tool_registry = ToolRegistry::new();
281 let (mcp_tools, _) = corex_tools::load_mcp_servers(&client.get_config().mcp_servers).await;
282 for t in mcp_tools {
283 tool_registry.register(t);
284 }
285 let prompt_builder = PromptBuilder::new(&workspace_dir)
286 .with_sudo_password(get_sudo_password().is_some());
287
288 let mut messages = vec![
289 Message::system(prompt_builder.build()),
290 Message::user(user_prompt.clone()),
291 ];
292
293 println!("You: {}", display_prompt.as_deref().unwrap_or(&user_prompt));
294
295 let tools = tool_registry.list_definitions();
296 let context = ToolContext {
297 workspace_dir: workspace_dir.clone(),
298 yolo_mode: yolo,
299 sudo_password: get_sudo_password(),
300 allowed_commands: client.get_config().allowed_commands.clone(),
301 };
302
303 use std::io::IsTerminal;
304 let is_tty = std::io::stdout().is_terminal();
305 let term_width = crossterm::terminal::size().map(|(w, _)| w as usize).unwrap_or(80);
306
307 struct StatusSpinner {
308 stop_tx: Option<tokio::sync::oneshot::Sender<()>>,
309 handle: Option<tokio::task::JoinHandle<()>>,
310 }
311
312 impl StatusSpinner {
313 fn start(is_tty: bool, prefix_color: &'static str, message: String) -> Self {
314 if !is_tty {
315 return Self { stop_tx: None, handle: None };
316 }
317 let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
318 let handle = tokio::spawn(async move {
319 let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
320 let mut i = 0;
321 loop {
322 print!("\r\x1b[2K{}{}\x1b[0m {}", prefix_color, frames[i], message);
323 use std::io::Write;
324 let _ = std::io::stdout().flush();
325 i = (i + 1) % frames.len();
326 tokio::select! {
327 _ = &mut rx => break,
328 _ = tokio::time::sleep(tokio::time::Duration::from_millis(70)) => {}
329 }
330 }
331 print!("\r\x1b[2K");
332 use std::io::Write;
333 let _ = std::io::stdout().flush();
334 });
335 Self {
336 stop_tx: Some(tx),
337 handle: Some(handle),
338 }
339 }
340
341 async fn stop(&mut self) {
342 if let Some(tx) = self.stop_tx.take() {
343 let _ = tx.send(());
344 }
345 if let Some(handle) = self.handle.take() {
346 let _ = handle.await;
347 }
348 print!("\r\x1b[2K");
349 use std::io::Write;
350 let _ = std::io::stdout().flush();
351 }
352 }
353
354 const MAX_HEADLESS_TURNS: usize = 35;
355 let mut turn_count = 0;
356
357 loop {
358 turn_count += 1;
359 if turn_count > MAX_HEADLESS_TURNS {
360 eprintln!("\n[WARNING] Maximum headless tool iteration limit ({}) reached. Terminating loop to protect budget.", MAX_HEADLESS_TURNS);
361 break;
362 }
363
364 let cancel_token = CancellationToken::new();
365 let mut rx = client
366 .stream_chat(messages.clone(), Some(tools.clone()), cancel_token.clone())
367 .await?;
368
369 let mut current_tool_calls: Vec<ToolCall> = Vec::new();
370 let mut assistant_text = String::new();
371 let mut reasoning_text = String::new();
372 let mut current_extra_content: Option<serde_json::Value> = None;
373 let mut active_spinner: Option<StatusSpinner> = None;
374 let mut current_stage: u8 = 0; while let Some(event) = rx.recv().await {
377 match event {
378 StreamEvent::ReasoningDelta(delta) => {
379 reasoning_text.push_str(&delta);
380 if current_stage != 1 {
381 if let Some(mut s) = active_spinner.take() {
382 s.stop().await;
383 }
384 active_spinner = Some(StatusSpinner::start(
385 is_tty,
386 "\x1b[90m",
387 "Thinking...".to_string(),
388 ));
389 current_stage = 1;
390 }
391 }
392 StreamEvent::ContentDelta(delta) => {
393 assistant_text.push_str(&delta);
394 if current_stage != 2 {
395 if let Some(mut s) = active_spinner.take() {
396 s.stop().await;
397 }
398 active_spinner = Some(StatusSpinner::start(
399 is_tty,
400 "\x1b[36m",
401 "Generating response...".to_string(),
402 ));
403 current_stage = 2;
404 }
405 }
406 StreamEvent::ToolCallDelta { index, id, name, arguments, extra_content } => {
407 while current_tool_calls.len() <= index {
408 current_tool_calls.push(ToolCall {
409 id: String::new(),
410 call_type: "function".to_string(),
411 function: corex_core::types::FunctionCall {
412 name: String::new(),
413 arguments: String::new(),
414 },
415 extra_content: None,
416 });
417 }
418 if let Some(i) = id {
419 current_tool_calls[index].id.push_str(&i);
420 }
421 if let Some(n) = name {
422 current_tool_calls[index].function.name.push_str(&n);
423 }
424 if let Some(a) = arguments {
425 current_tool_calls[index].function.arguments.push_str(&a);
426 }
427 if let Some(ec) = extra_content {
428 current_tool_calls[index].extra_content = Some(ec);
429 }
430 }
431 StreamEvent::ExtraContentDelta(ec) => {
432 current_extra_content = Some(ec);
433 }
434 StreamEvent::Notice(msg) => {
435 if let Some(mut s) = active_spinner.take() {
436 s.stop().await;
437 }
438 println!("\n[INFO] {}\n", msg);
439 }
440 StreamEvent::ContextCompacted { notice, .. } => {
441 if let Some(mut s) = active_spinner.take() {
442 s.stop().await;
443 }
444 println!("\n[INFO] {}\n", notice);
445 }
446 StreamEvent::Completed { .. } => {}
447 StreamEvent::Error(err) => {
448 if let Some(mut s) = active_spinner.take() {
449 s.stop().await;
450 }
451 eprintln!("\nError: {}", err);
452 return Ok(());
453 }
454 _ => {}
455 }
456 }
457
458 if let Some(mut s) = active_spinner.take() {
459 s.stop().await;
460 }
461
462 if !assistant_text.trim().is_empty() {
463 if is_tty {
464 let theme = corex_tui::Theme::default();
465 let rendered = corex_tui::render_markdown_to_ansi(&assistant_text, &theme, term_width);
466 println!("{}\n", rendered);
467 } else {
468 println!("{}\n", assistant_text);
469 }
470 }
471
472 if !current_tool_calls.is_empty() {
473 let text_opt = if assistant_text.is_empty() { None } else { Some(assistant_text) };
474 let cot_opt = if reasoning_text.is_empty() { None } else { Some(reasoning_text) };
475
476 for call in &mut current_tool_calls {
477 if call.extra_content.is_none() {
478 call.extra_content = current_extra_content.clone();
479 }
480 }
481
482 messages.push(Message::assistant_with_tools(
483 text_opt,
484 cot_opt,
485 current_tool_calls.clone(),
486 ));
487
488 for call in ¤t_tool_calls {
489 let args_json = corex_core::parse_lenient_json(&call.function.arguments)
490 .unwrap_or(serde_json::Value::Null);
491
492 let (action_label, target_detail) = if call.function.name == "run_shell_command" || call.function.name == "shell" || call.function.name == "run_command" {
493 let cmd = args_json.get("command").and_then(|c| c.as_str()).unwrap_or("").trim();
494 ("Running command", cmd)
495 } else if call.function.name == "read_file" {
496 let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
497 ("Reading file", p)
498 } else if call.function.name == "write_file" {
499 let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
500 ("Writing file", p)
501 } else if call.function.name == "edit" || call.function.name == "apply_patch" {
502 let p = args_json.get("path").or_else(|| args_json.get("file_path")).and_then(|c| c.as_str()).unwrap_or("");
503 ("Editing file", p)
504 } else if call.function.name == "glob" || call.function.name == "ls" || call.function.name == "list_directory" {
505 let p = args_json.get("path").or_else(|| args_json.get("dir")).and_then(|c| c.as_str()).unwrap_or(".");
506 ("Exploring directory", p)
507 } else if call.function.name == "web_search" || call.function.name == "google_web_search" {
508 let q = args_json.get("query").and_then(|c| c.as_str()).unwrap_or("");
509 ("Searching web", q)
510 } else if call.function.name == "web_fetch" {
511 let u = args_json.get("url").and_then(|c| c.as_str()).unwrap_or("");
512 ("Fetching web page", u)
513 } else {
514 ("Running tool", call.function.name.as_str())
515 };
516
517 let display_detail = corex_core::truncate_ellipsis(&corex_core::sanitize_for_terminal(target_detail), 70);
518
519 if !context.yolo_mode {
521 if let Some(tool) = tool_registry.get(&call.function.name) {
522 if tool.needs_confirmation(&args_json, &context) {
523 if is_tty {
524 print!("\r\x1b[2K");
525 use std::io::Write;
526 let _ = std::io::stdout().flush();
527 }
528 println!("\n[WARNING] Action requires confirmation: [{}]", call.function.name);
529 if let Some(diff) = tool.format_diff(&args_json, &context.workspace_dir) {
530 println!("{}", diff);
531 } else if let Some(cmd) = args_json.get("command").and_then(|c| c.as_str()) {
532 println!(" Command: {}", corex_core::sanitize_for_terminal(cmd));
533 } else {
534 println!(" Arguments: {}", corex_core::sanitize_for_terminal(&serde_json::to_string_pretty(&args_json).unwrap_or_default()));
535 }
536
537 print!("Allow execution? [y/N]: ");
538 use std::io::Write;
539 let _ = std::io::stdout().flush();
540
541 let mut input = String::new();
542 let _ = std::io::stdin().read_line(&mut input);
543 let trimmed = input.trim().to_lowercase();
544 if trimmed != "y" && trimmed != "yes" {
545 println!("Execution cancelled by user.");
546 messages.push(Message::tool_response(call.id.clone(), "Execution denied by user."));
547 continue;
548 }
549 }
550 }
551 }
552
553 let mut tool_spinner = StatusSpinner::start(
555 is_tty,
556 "\x1b[33m",
557 format!("\x1b[1m{}:\x1b[0m \x1b[36m{}\x1b[0m", action_label, display_detail),
558 );
559
560 let output = match tool_registry
561 .execute(&call.function.name, args_json, &context)
562 .await
563 {
564 Ok(o) => {
565 tool_spinner.stop().await;
566 if is_tty {
567 println!("\x1b[32m✓\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m", action_label, display_detail);
568 }
569 o.output
570 }
571 Err(e) => {
572 tool_spinner.stop().await;
573 if is_tty {
574 println!("\x1b[31m✗\x1b[0m \x1b[1m{}\x1b[0m: \x1b[90m{}\x1b[0m ({})", action_label, display_detail, e);
575 }
576 let msg = format!("Error executing {}: {}", call.function.name, e);
577 eprintln!("{}", msg);
578 msg
579 }
580 };
581 messages.push(Message::tool_response(call.id.clone(), output));
582 }
583
584 continue;
586 }
587
588 break;
590 }
591
592 Ok(())
593}