1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6 BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
7 get_bool, get_int, get_str,
8};
9use crate::tool_defs::tool_def;
10
11use super::ctx_shell_background::{format_background_state, redact_shell_output_secrets};
12
13pub struct CtxShellTool;
14
15const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
19
20impl McpTool for CtxShellTool {
21 fn name(&self) -> &'static str {
22 "ctx_shell"
23 }
24
25 fn tool_def(&self) -> Tool {
26 tool_def(
27 "ctx_shell",
28 "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
29 raw=true for verbatim output; inline=true for moderately-sized verbatim output.\n\
30 [exit:N] on errors (lossless).\n\
31 POLICY: allowlisted read-only path.\n\
32 A [BLOCKED] command is permanent; ctx_execute shares the same allowlist — fix with \
33 `lean-ctx allow <cmd>`.\n\
34 ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute \
35 (when exposed).",
36 json!({
37 "type": "object",
38 "properties": {
39 "command": { "type": "string", "description": "Shell command" },
40 "raw": { "type": "boolean", "description": "Skip compression (verbatim)" },
41 "inline": { "type": "boolean", "description": "Return verbatim output inline up to archive.inline_max_bytes; larger output uses the archive/firewall" },
42 "cwd": { "type": "string", "description": "Working dir (persists across calls)" },
43 "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~110s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
44 "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
45 "run_in_background": { "type": "boolean", "description": "Detach immediately and return a job id. The command keeps timeout_ms; poll or cancel with background_action and job_id." },
46 "background_action": { "type": "string", "enum": ["status", "cancel"], "description": "Inspect or cancel a background ctx_shell job; terminal status may include archiveId. Evicted/expired jobs return a structured lookup error." },
47 "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
48 }
49 }),
50 )
51 }
52
53 fn handle(
54 &self,
55 args: &Map<String, Value>,
56 ctx: &ToolContext,
57 ) -> Result<ToolOutput, ErrorData> {
58 if let Some(message) = shell_access_denial(ctx) {
59 return Ok(ToolOutput {
60 shell_outcome: Some(ShellOutcome::Blocked),
61 content_blocks: None,
62 ..ToolOutput::simple(message)
63 });
64 }
65
66 if let Some(action) = get_str(args, "background_action") {
67 let id = get_str(args, "job_id").ok_or_else(|| {
68 ErrorData::invalid_params("job_id is required with background_action", None)
69 })?;
70 let is_cancel = action == "cancel";
71 let state = match action.as_str() {
72 "status" => crate::server::background_shell::status(&id),
73 "cancel" => crate::server::background_shell::cancel(&id),
74 _ => {
75 return Err(ErrorData::invalid_params(
76 "background_action must be status or cancel",
77 None,
78 ));
79 }
80 };
81 let (text, outcome) = format_background_state(&id, is_cancel, state);
82 return Ok(ToolOutput {
83 shell_outcome: Some(outcome),
84 content_blocks: None,
85 ..ToolOutput::simple(text)
86 });
87 }
88 let command = get_str(args, "command")
89 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
90 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
91
92 let explicit_cwd = get_str(args, "cwd");
102 let had_explicit_cwd = explicit_cwd.is_some();
103 let resolved_cwd = match ctx.session.as_ref() {
109 Some(session_lock) => Some(tokio::task::block_in_place(|| {
110 let guard = crate::server::bounded_lock::read_for(
111 session_lock,
112 "ctx_shell_cwd",
113 SESSION_LOCK_BUDGET,
114 );
115 resolve_effective_cwd(guard, explicit_cwd.as_deref())
116 })?),
117 None => None,
118 };
119
120 let config = crate::core::config::Config::load();
125 let write_allow_paths = config.shell_write_allow_paths_effective();
126 let project_root = crate::core::config::Config::find_project_root();
127 if !config.shell_allow_writes_effective()
128 && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
129 &command,
130 &write_allow_paths,
131 project_root.as_deref(),
132 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
133 )
134 {
135 return Ok(ToolOutput {
138 shell_outcome: Some(ShellOutcome::Blocked),
139 content_blocks: None,
140 ..ToolOutput::simple(rejection)
141 });
142 }
143
144 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
145 return tokio::task::block_in_place(|| {
146 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
147 });
148 }
149
150 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
151 return Ok(ToolOutput {
152 shell_outcome: Some(ShellOutcome::Blocked),
153 content_blocks: None,
154 ..ToolOutput::simple(msg.to_string())
155 });
156 }
157
158 warn_shell_secret_paths(&command);
159
160 if let Some(read_path) = detect_bare_cat_file(&command)
164 && let Some(cache_lock) = ctx.cache.as_ref()
165 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
166 {
167 let result = crate::tools::ctx_read::handle_with_task_resolved(
168 &mut cache,
169 &read_path,
170 "full",
171 crate::tools::CrpMode::Off,
172 None,
173 );
174 let note = format!(
175 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
176 Use ctx_read(path=\"{read_path}\") directly next time.]"
177 );
178 let out = format!("{}{note}", result.content);
179 let sent = crate::core::tokens::count_tokens(&out);
180 return Ok(ToolOutput {
181 text: out,
182 original_tokens: sent,
183 saved_tokens: 0,
184 mode: Some("cat-redirect".to_string()),
185 path: Some(read_path),
186 changed: false,
187 shell_outcome: Some(ShellOutcome::Exit(0)),
188 content_blocks: None,
189 });
190 }
191
192 tokio::task::block_in_place(|| {
193 let session_lock = ctx
194 .session
195 .as_ref()
196 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
197 let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
198 return Err(ErrorData::internal_error("session not available", None));
199 };
200 let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
205 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
206 format!(
207 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
208 )
209 });
210
211 {
212 let Some(mut session) = crate::server::bounded_lock::write_for(
213 session_lock,
214 "ctx_shell_write",
215 SESSION_LOCK_BUDGET,
216 ) else {
217 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
218 let cmd_clone = command.clone();
219 let cwd_clone = effective_cwd.clone();
220 let extra_env = match collect_extra_env(args) {
221 Ok(env) => env,
222 Err(message) => {
223 return Ok(ToolOutput {
224 shell_outcome: Some(ShellOutcome::Blocked),
225 content_blocks: None,
226 ..ToolOutput::simple(message)
227 });
228 }
229 };
230 let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
231 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
232 );
233 let output = redact_shell_output_secrets(&raw_output);
234 let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
237 return Ok(ToolOutput {
238 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
239 content_blocks: None,
240 ..ToolOutput::simple(format!("{output}{exit_suffix}"))
241 });
242 };
243 if had_explicit_cwd && cwd_jail_reason_was_none {
248 session.note_explicit_cwd(&effective_cwd);
249 }
250 session.update_shell_cwd(&command);
251 let root_missing = session
252 .project_root
253 .as_deref()
254 .is_none_or(|r| r.trim().is_empty());
255 if root_missing {
256 let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
257 if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
258 && home.as_deref() != Some(root.as_str())
259 {
260 session.project_root = Some(root.clone());
261 crate::core::index_orchestrator::ensure_all_background(&root);
262 }
263 }
264 }
265
266 let arg_raw = get_bool(args, "raw").unwrap_or(false);
267 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
268 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
269 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
270 let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
271
272 let crp_mode = ctx.crp_mode;
273 let cmd_clone = command.clone();
274 let cwd_clone = effective_cwd;
275 let proactive_block = if raw
276 || !crate::core::profiles::active_profile()
277 .output_hints
278 .proactive_context()
279 {
280 None
281 } else {
282 crate::core::relevance_tracker::proactive_context(&format!(
283 "ctx_shell command={cmd_clone} cwd={cwd_clone}"
284 ))
285 };
286
287 let extra_env = match collect_extra_env(args) {
288 Ok(env) => env,
289 Err(message) => {
290 return Ok(ToolOutput {
291 shell_outcome: Some(ShellOutcome::Blocked),
292 content_blocks: None,
293 ..ToolOutput::simple(message)
294 });
295 }
296 };
297
298 let inline = get_bool(args, "inline").unwrap_or(false);
299
300 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
301 if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
302 let job_id = crate::server::background_shell::start(
303 cmd_clone, cwd_clone, extra_env, timeout_ms,
304 );
305 let mode = if auto_background {
306 "auto-background"
307 } else {
308 "background"
309 };
310 return Ok(ToolOutput {
311 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
312 state: BackgroundJobState::Running,
313 exit_code: None,
314 job_id: job_id.clone(),
315 archive_id: None,
316 archive_truncated: None,
317 captured_chars: None,
318 archived_chars: None,
319 summary: format!("{mode} job started"),
320 is_error: false,
321 display: None,
322 })),
323 content_blocks: None,
324 ..ToolOutput::simple(format!(
325 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
326 ))
327 });
328 }
329
330 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
341 let progress_sender = ctx.progress_sender.clone();
342 let progress_label: String = cmd_clone.chars().take(60).collect();
343 let cap_secs = soft_cap.as_secs_f64();
344 let on_tick = |elapsed: std::time::Duration| {
345 #[allow(clippy::unwrap_or_default)]
346 if let Some(ref ps) = progress_sender
347 && let Some(sender) = ps
348 .lock()
349 .unwrap_or_else(std::sync::PoisonError::into_inner)
350 .as_ref()
351 {
352 sender.send(
353 elapsed.as_secs_f64(),
354 Some(cap_secs),
355 Some(format!(
356 "ctx_shell: {}s elapsed — {progress_label}",
357 elapsed.as_secs()
358 )),
359 );
360 }
361 };
362 let (raw_output, exit_code) =
363 match crate::server::background_shell::run_foreground_or_detach(
364 cmd_clone.clone(),
365 cwd_clone.clone(),
366 extra_env.clone(),
367 timeout_ms,
368 soft_cap,
369 Some(&on_tick),
370 ctx.cancel.as_ref(),
371 ) {
372 crate::server::background_shell::ForegroundResult::Finished {
373 output,
374 exit_code,
375 } => (output, exit_code),
376 crate::server::background_shell::ForegroundResult::Detached { job_id } => {
377 return Ok(ToolOutput {
378 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
379 state: BackgroundJobState::Running,
380 exit_code: None,
381 job_id: job_id.clone(),
382 archive_id: None,
383 archive_truncated: None,
384 captured_chars: None,
385 archived_chars: None,
386 summary: "auto-detached job is still running".to_string(),
387 is_error: false,
388 display: None,
389 })),
390 content_blocks: None,
391 ..ToolOutput::simple(format!(
395 "[auto-background:{job_id} still running — passed the {}s foreground cap, not an error; output is kept and delivered by ctx_shell(background_action=\"status\", job_id=\"{job_id}\"), or background_action=\"cancel\" to stop it]",
396 soft_cap.as_secs()
397 ))
398 });
399 }
400 };
401
402 crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
404
405 let output = redact_shell_output_secrets(&raw_output);
406
407 let (result_out, original, saved, tee_hint) = if raw || inline {
408 let tokens = crate::core::tokens::count_tokens(&output);
409 (output, tokens, 0, String::new())
410 } else {
411 let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
412 let result =
413 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
414 let original = crate::core::tokens::count_tokens(&output);
415 let sent = crate::core::tokens::count_tokens(&result);
416 let saved = original.saturating_sub(sent);
417
418 let cfg = crate::core::config::Config::load();
419 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
422 let tee_hint = if crate::shell::tee_policy::should_tee(
423 &cfg.tee_mode,
424 exit_code,
425 output.trim().is_empty() || timeout_notice_only,
426 crate::shell::tee_policy::output_was_elided(&output, &result),
427 original,
428 sent,
429 ) {
430 crate::shell::save_tee(&cmd_clone, &output)
431 .map(|p| {
432 if crate::cli::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
433 format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
434 } else if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
435 {
436 let pct = crate::shell::tee_policy::savings_pct(original, sent);
437 format!(
440 "\n[compressed {pct:.0}%: full output at {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\") for a slice]"
441 )
442 } else {
443 format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
444 }
445 })
446 .unwrap_or_default()
447 } else {
448 String::new()
449 };
450
451 (result, original, saved, tee_hint)
452 };
453
454 let mode = if bypass {
455 Some("bypass".to_string())
456 } else if raw {
457 Some("raw".to_string())
458 } else {
459 None
460 };
461
462 let shell_mismatch = if cfg!(windows) && !raw {
463 shell_mismatch_hint(&command, &result_out)
464 } else {
465 String::new()
466 };
467
468 let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
469 let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
473 let nudge = if raw { "" } else { search_tool_nudge(&command) };
474 let final_out = format!(
475 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
476 );
477 let final_out = if let Some(block) = proactive_block {
478 format!("{final_out}{block}")
479 } else {
480 final_out
481 };
482
483 Ok(ToolOutput {
484 text: final_out,
485 original_tokens: original,
486 saved_tokens: saved,
487 mode,
488 path: None,
489 changed: false,
490 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
491 content_blocks: None,
492 })
493 })
494 }
495}
496
497fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
500 if let Some(role) = ctx.client_role.as_deref()
501 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
502 {
503 return Some(format!(
504 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
505 ));
506 }
507
508 if ctx.shell_access == Some(false) {
509 return Some(
510 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
511 .to_string(),
512 );
513 }
514
515 None
516}
517
518fn resolve_effective_cwd(
519 session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
520 explicit_cwd: Option<&str>,
521) -> Result<(String, Option<String>), ErrorData> {
522 match session {
523 Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
524 None => Err(ErrorData::internal_error(
525 "session lock timeout — cannot validate working directory",
526 None,
527 )),
528 }
529}
530
531#[allow(clippy::fn_params_excessive_bools)]
532fn resolve_shell_raw_flags(
533 arg_raw: bool,
534 arg_bypass: bool,
535 _env_disabled: bool,
536 env_raw: bool,
537) -> (bool, bool) {
538 let bypass = arg_bypass || env_raw;
539 let raw = arg_raw || bypass;
540 (raw, bypass)
541}
542
543fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
550 exit_code == 124
551 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
552}
553
554fn search_tool_nudge(command: &str) -> &'static str {
555 let cmd = command.trim();
556 let first_word = cmd.split_whitespace().next().unwrap_or("");
557 if !cmd.contains('|') {
558 match first_word {
559 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
560 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
561 }
562 "find" => {
563 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
564 }
565 "ls" | "exa" | "eza" => {
566 return "\n[hint: use ctx_tree for structured directory listing]";
567 }
568 _ => {}
569 }
570 }
571 ""
572}
573
574fn shell_mismatch_hint(command: &str, output: &str) -> String {
575 let shell = crate::shell::shell_name();
576 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
577 let has_error = output.contains("is not recognized")
578 || output.contains("not found")
579 || output.contains("command not found");
580
581 if !has_error {
582 return String::new();
583 }
584
585 let powershell_cmds = [
586 "Get-Content",
587 "Select-Object",
588 "Get-ChildItem",
589 "Set-Location",
590 "Where-Object",
591 "ForEach-Object",
592 "Select-String",
593 "Invoke-Expression",
594 "Write-Output",
595 ];
596 let uses_powershell = powershell_cmds
597 .iter()
598 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
599
600 if is_posix && uses_powershell {
601 format!(
602 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
603 )
604 } else {
605 String::new()
606 }
607}
608
609fn collect_extra_env(
620 args: &Map<String, Value>,
621) -> Result<std::collections::HashMap<String, String>, String> {
622 let mut accepted = std::collections::HashMap::new();
623 let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
624 return Ok(accepted);
625 };
626 let mut rejected: Vec<&str> = Vec::new();
627 for (key, value) in obj {
628 let Some(text) = value.as_str() else { continue };
629 if is_dangerous_env_key(key) {
630 rejected.push(key.as_str());
631 continue;
632 }
633 accepted.insert(key.clone(), text.to_string());
634 }
635 if rejected.is_empty() {
636 return Ok(accepted);
637 }
638 rejected.sort_unstable();
639 let names = rejected
640 .iter()
641 .map(|k| format!("`{k}`"))
642 .collect::<Vec<_>>()
643 .join(", ");
644 let plural = if rejected.len() == 1 { "key" } else { "keys" };
645 Err(format!(
646 "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
647 redirect which binary executes, so lean-ctx never forwards them, and the command would \
648 otherwise have used the inherited value while appearing to honor yours. This is the \
649 same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
650 Invoke the binary by its full path instead, or drop the override."
651 ))
652}
653
654fn is_dangerous_env_key(key: &str) -> bool {
655 const BLOCKED: &[&str] = &[
656 "LD_PRELOAD",
658 "LD_LIBRARY_PATH",
659 "DYLD_INSERT_LIBRARIES",
660 "DYLD_LIBRARY_PATH",
661 "DYLD_FRAMEWORK_PATH",
662 "BASH_ENV",
664 "ENV",
665 "PROMPT_COMMAND",
666 "SHELL",
667 "IFS",
668 "CDPATH",
669 "PATH",
671 "GIT_EXEC_PATH",
672 "GIT_SSH",
673 "GIT_SSH_COMMAND",
674 "HOME",
676 "USER",
677 "LOGNAME",
678 "XDG_CONFIG_HOME",
679 "XDG_DATA_HOME",
680 "XDG_STATE_HOME",
681 "XDG_CACHE_HOME",
682 "PYTHONPATH",
684 "PYTHONSTARTUP",
685 "PYTHONHOME",
686 "NODE_PATH",
687 "NODE_OPTIONS",
688 "RUBYOPT",
689 "RUBYLIB",
690 "GEM_PATH",
691 "GEM_HOME",
692 "PERL5LIB",
693 "PERL5OPT",
694 "CLASSPATH",
695 "JAVA_HOME",
696 "CARGO_HOME",
697 "RUSTUP_HOME",
698 "GOPATH",
699 "GOROOT",
700 ];
701 let upper = key.to_uppercase();
702 if BLOCKED.contains(&upper.as_str()) {
703 return true;
704 }
705 if upper.starts_with("LD_") && upper.ends_with("_PATH") {
706 return true;
707 }
708 if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
710 return true;
711 }
712 false
713}
714
715fn warn_shell_secret_paths(command: &str) {
718 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
719 let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
720 for seg in &segments {
721 let trimmed = seg.trim();
722 let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
723 if tokens.is_empty() {
724 continue;
725 }
726 let base = tokens[0]
727 .rsplit('/')
728 .next()
729 .unwrap_or(&tokens[0])
730 .to_string();
731 if !READ_CMDS.contains(&base.as_str()) {
732 continue;
733 }
734 for tok in &tokens[1..] {
735 if tok.starts_with('-') {
736 continue;
737 }
738 let path = std::path::Path::new(tok.as_str());
739 if crate::core::io_boundary::is_secret_like(path).is_some() {
740 tracing::warn!(
741 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
742 );
743 }
744 }
745 }
746}
747
748fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
753 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
754 && command
755 .lines()
756 .any(|line| line.trim_start().starts_with("cargo test"))
757}
758
759fn foreground_soft_cap_ms() -> u64 {
764 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
765 .ok()
766 .and_then(|v| v.parse().ok())
767 .filter(|&ms| ms > 0)
768 .unwrap_or(110_000)
769}
770
771fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
773 match base {
774 "python" | "python2" | "python3" => Some("python"),
775 "node" => Some("javascript"),
776 "ruby" => Some("ruby"),
777 _ => None,
778 }
779}
780
781fn is_env_assignment_token(token: &str) -> bool {
782 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
783 unquoted.contains('=')
784 && !unquoted.starts_with('-')
785 && !unquoted.starts_with('/')
786 && !unquoted.starts_with('.')
787}
788
789fn prelude_has_compound_operator(prelude: &str) -> bool {
791 let bytes = prelude.as_bytes();
792 let len = bytes.len();
793 let mut i = 0;
794 let mut in_single = false;
795 let mut in_double = false;
796 while i < len {
797 let ch = bytes[i];
798 if in_single {
799 if ch == b'\'' {
800 in_single = false;
801 }
802 i += 1;
803 continue;
804 }
805 if in_double {
806 if ch == b'\\' && i + 1 < len {
807 i += 2;
808 } else {
809 if ch == b'"' {
810 in_double = false;
811 }
812 i += 1;
813 }
814 continue;
815 }
816 match ch {
817 b'\'' => {
818 in_single = true;
819 i += 1;
820 }
821 b'"' => {
822 in_double = true;
823 i += 1;
824 }
825 b';' | b'|' | b'&' | b'(' | b'{' => return true,
826 _ => i += 1,
827 }
828 }
829 false
830}
831
832fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
836 if !command.contains("<<") {
837 return None;
838 }
839
840 let lines: Vec<&str> = command.lines().collect();
841 if lines.is_empty() {
842 return None;
843 }
844
845 let first_line = lines[0];
846 let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
847 if delims.len() != 1 {
848 return None;
849 }
850 let delim = delims[0].clone();
851
852 let heredoc_pos = find_heredoc_operator(first_line)?;
853 let prelude = first_line[..heredoc_pos].trim();
854 if prelude_has_compound_operator(prelude) {
855 return None;
856 }
857
858 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
859
860 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
861 return None;
862 }
863
864 let mut body = String::new();
865 let mut remainder_start: Option<usize> = None;
866 for (idx, line) in lines.iter().enumerate().skip(1) {
867 if line.trim_start_matches('\t').trim() == delim {
868 remainder_start = Some(idx + 1);
869 break;
870 }
871 if !body.is_empty() {
872 body.push('\n');
873 }
874 body.push_str(line);
875 }
876 let remainder_start = remainder_start?;
877 let remainder = if remainder_start < lines.len() {
878 let rest = lines[remainder_start..].join("\n");
879 let rest = rest.trim();
880 if rest.is_empty() {
881 None
882 } else {
883 Some(rest.to_string())
884 }
885 } else {
886 None
887 };
888
889 Some((language, body, remainder))
890}
891
892fn find_heredoc_operator(line: &str) -> Option<usize> {
893 let bytes = line.as_bytes();
894 let len = bytes.len();
895 let mut i = 0;
896 let mut in_single = false;
897 let mut in_double = false;
898 while i < len {
899 let ch = bytes[i];
900 if in_single {
901 if ch == b'\'' {
902 in_single = false;
903 }
904 i += 1;
905 continue;
906 }
907 if in_double {
908 if ch == b'\\' && i + 1 < len {
909 i += 2;
910 } else {
911 if ch == b'"' {
912 in_double = false;
913 }
914 i += 1;
915 }
916 continue;
917 }
918 match ch {
919 b'\'' => {
920 in_single = true;
921 i += 1;
922 }
923 b'"' => {
924 in_double = true;
925 i += 1;
926 }
927 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
928 if i + 2 < len && bytes[i + 2] == b'<' {
929 i += 3;
930 continue;
931 }
932 return Some(i);
933 }
934 _ => i += 1,
935 }
936 }
937 None
938}
939
940fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
941 let bytes = line.as_bytes();
942 let mut i = heredoc_pos + 2;
943 if i < bytes.len() && bytes[i] == b'-' {
944 i += 1;
945 }
946 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
947 i += 1;
948 }
949 let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
950 return true;
951 };
952 !line[next..].trim().is_empty()
953}
954
955fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
956 let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
957 let mut idx = 0;
958 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
959 idx += 1;
960 }
961 if idx >= tokens.len() {
962 return None;
963 }
964 let base = tokens[idx]
965 .rsplit('/')
966 .next()
967 .unwrap_or(tokens[idx].as_str());
968 let language = interpreter_to_execute_language(base)?;
969 idx += 1;
970 match tokens.get(idx) {
971 None => Some(language),
972 Some(dash) if dash == "-" => {
973 if tokens.len() == idx + 1 {
974 Some(language)
975 } else {
976 None
977 }
978 }
979 Some(_) => None,
980 }
981}
982
983fn resolve_reroute_cwd(
994 ctx: &ToolContext,
995 explicit_cwd: Option<&str>,
996) -> Result<Option<String>, ErrorData> {
997 let Some(session_lock) = ctx.session.as_ref() else {
998 if explicit_cwd.is_some() {
999 return Err(ErrorData::internal_error(
1000 "session not available — cannot validate the requested working directory",
1001 None,
1002 ));
1003 }
1004 return Ok(None);
1005 };
1006 let guard =
1007 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1008 let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1009 Ok(Some(cwd))
1010}
1011
1012fn handle_interpreter_heredoc_reroute(
1013 args: &Map<String, Value>,
1014 ctx: &ToolContext,
1015 language: &str,
1016 code: &str,
1017 remainder: Option<String>,
1018) -> Result<ToolOutput, ErrorData> {
1019 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1020 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1021
1022 let explicit_cwd = get_str(args, "cwd");
1028 let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1029
1030 let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1031 language,
1032 code,
1033 None,
1034 timeout_secs,
1035 exec_cwd.as_deref().map(std::path::Path::new),
1036 );
1037 let reroute_note = format!(
1038 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1039 );
1040 let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1041
1042 let Some(rest_cmd) = remainder else {
1043 return Ok(ToolOutput {
1044 text: format!("{exec_text}{reroute_note}"),
1045 original_tokens: crate::core::tokens::count_tokens(&exec_text),
1046 saved_tokens: 0,
1047 mode: Some("heredoc-reroute".to_string()),
1048 path: None,
1049 changed: false,
1050 shell_outcome: Some(exec_outcome),
1051 content_blocks: None,
1052 });
1053 };
1054
1055 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1056 let blocked =
1057 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1058 return Ok(ToolOutput {
1059 shell_outcome: Some(ShellOutcome::Blocked),
1060 content_blocks: None,
1061 ..ToolOutput::simple(blocked)
1062 });
1063 }
1064
1065 let effective_cwd =
1068 exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1069
1070 let extra_env = match collect_extra_env(args) {
1071 Ok(env) => env,
1072 Err(message) => {
1073 return Ok(ToolOutput {
1074 shell_outcome: Some(ShellOutcome::Blocked),
1075 content_blocks: None,
1076 ..ToolOutput::simple(message)
1077 });
1078 }
1079 };
1080
1081 let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1082 &rest_cmd,
1083 &effective_cwd,
1084 &extra_env,
1085 timeout_ms,
1086 );
1087 let shell_output = redact_shell_output_secrets(&shell_raw);
1088 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1089 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1090 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1091 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1092 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1093
1094 let shell_text = if raw {
1095 shell_output
1096 } else {
1097 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1098 };
1099 let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1100 let exit_suffix = crate::shell::exit_status::exit_footer(shell_exit);
1101
1102 let combined = format!(
1103 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1104 );
1105 let token_count = crate::core::tokens::count_tokens(&combined);
1106 Ok(ToolOutput {
1107 text: combined,
1108 original_tokens: token_count,
1109 saved_tokens: 0,
1110 mode: Some("heredoc-reroute".to_string()),
1111 path: None,
1112 changed: false,
1113 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1114 content_blocks: None,
1115 })
1116}
1117
1118fn detect_bare_cat_file(command: &str) -> Option<String> {
1120 let trimmed = command.trim();
1121 let rest = trimmed.strip_prefix("cat ")?;
1122 let rest = rest.trim();
1123 if rest.is_empty()
1124 || rest.contains('|')
1125 || rest.contains('>')
1126 || rest.contains('<')
1127 || rest.contains(';')
1128 || rest.contains('&')
1129 || rest.contains('$')
1130 || rest.starts_with('-')
1131 {
1132 return None;
1133 }
1134 let parts: Vec<&str> = rest.split_whitespace().collect();
1135 if parts.len() != 1 {
1136 return None;
1137 }
1138 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1139 if file_path.is_empty() {
1140 return None;
1141 }
1142 Some(file_path.to_string())
1143}
1144
1145#[cfg(test)]
1146#[path = "ctx_shell_tests.rs"]
1147mod tests;