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 mut write_allow_paths = config.shell_write_allow_paths_effective();
126 write_allow_paths.extend(crate::tools::ctx_shell::capture_roots(
129 &ctx.project_root,
130 &ctx.extra_roots,
131 &config,
132 ));
133 if !config.shell_allow_writes_effective()
134 && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
135 &command,
136 &write_allow_paths,
137 None,
138 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
139 )
140 {
141 return Ok(ToolOutput {
144 shell_outcome: Some(ShellOutcome::Blocked),
145 content_blocks: None,
146 ..ToolOutput::simple(rejection)
147 });
148 }
149
150 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
151 return tokio::task::block_in_place(|| {
152 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
153 });
154 }
155
156 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
157 return Ok(ToolOutput {
158 shell_outcome: Some(ShellOutcome::Blocked),
159 content_blocks: None,
160 ..ToolOutput::simple(msg.to_string())
161 });
162 }
163
164 warn_shell_secret_paths(&command);
165
166 if let Some(read_path) = detect_bare_cat_file(&command)
170 && let Some(cache_lock) = ctx.cache.as_ref()
171 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
172 {
173 let result = crate::tools::ctx_read::handle_with_task_resolved(
174 &mut cache,
175 &read_path,
176 "full",
177 crate::tools::CrpMode::Off,
178 None,
179 );
180 let note = format!(
181 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
182 Use ctx_read(path=\"{read_path}\") directly next time.]"
183 );
184 let out = format!("{}{note}", result.content);
185 let sent = crate::core::tokens::count_tokens(&out);
186 return Ok(ToolOutput {
187 text: out,
188 original_tokens: sent,
189 saved_tokens: 0,
190 mode: Some("cat-redirect".to_string()),
191 path: Some(read_path),
192 changed: false,
193 shell_outcome: Some(ShellOutcome::Exit(0)),
194 content_blocks: None,
195 });
196 }
197
198 tokio::task::block_in_place(|| {
199 let session_lock = ctx
200 .session
201 .as_ref()
202 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
203 let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
204 return Err(ErrorData::internal_error("session not available", None));
205 };
206 let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
211 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
212 format!(
213 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
214 )
215 });
216
217 {
218 let Some(mut session) = crate::server::bounded_lock::write_for(
219 session_lock,
220 "ctx_shell_write",
221 SESSION_LOCK_BUDGET,
222 ) else {
223 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
224 let cmd_clone = command.clone();
225 let cwd_clone = effective_cwd.clone();
226 let extra_env = match collect_extra_env(args) {
227 Ok(env) => env,
228 Err(message) => {
229 return Ok(ToolOutput {
230 shell_outcome: Some(ShellOutcome::Blocked),
231 content_blocks: None,
232 ..ToolOutput::simple(message)
233 });
234 }
235 };
236 let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
237 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
238 );
239 let output = redact_shell_output_secrets(&raw_output);
240 let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
243 return Ok(ToolOutput {
244 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
245 content_blocks: None,
246 ..ToolOutput::simple(format!("{output}{exit_suffix}"))
247 });
248 };
249 if had_explicit_cwd && cwd_jail_reason_was_none {
254 session.note_explicit_cwd(&effective_cwd);
255 }
256 session.update_shell_cwd(&command);
257 let root_missing = session
258 .project_root
259 .as_deref()
260 .is_none_or(|r| r.trim().is_empty());
261 if root_missing {
262 let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
263 if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
264 && home.as_deref() != Some(root.as_str())
265 {
266 session.project_root = Some(root.clone());
267 crate::core::index_orchestrator::ensure_all_background(&root);
268 }
269 }
270 }
271
272 let arg_raw = get_bool(args, "raw").unwrap_or(false);
273 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
274 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
275 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
276 let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
277
278 let crp_mode = ctx.crp_mode;
279 let cmd_clone = command.clone();
280 let cwd_clone = effective_cwd;
281 let proactive_block = if raw
282 || !crate::core::profiles::active_profile()
283 .output_hints
284 .proactive_context()
285 {
286 None
287 } else {
288 crate::core::relevance_tracker::proactive_context(&format!(
289 "ctx_shell command={cmd_clone} cwd={cwd_clone}"
290 ))
291 };
292
293 let extra_env = match collect_extra_env(args) {
294 Ok(env) => env,
295 Err(message) => {
296 return Ok(ToolOutput {
297 shell_outcome: Some(ShellOutcome::Blocked),
298 content_blocks: None,
299 ..ToolOutput::simple(message)
300 });
301 }
302 };
303
304 let inline = get_bool(args, "inline").unwrap_or(false);
305
306 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
307 if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
308 let job_id = crate::server::background_shell::start(
309 cmd_clone, cwd_clone, extra_env, timeout_ms,
310 );
311 let mode = if auto_background {
312 "auto-background"
313 } else {
314 "background"
315 };
316 return Ok(ToolOutput {
317 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
318 state: BackgroundJobState::Running,
319 exit_code: None,
320 job_id: job_id.clone(),
321 archive_id: None,
322 archive_truncated: None,
323 captured_chars: None,
324 archived_chars: None,
325 summary: format!("{mode} job started"),
326 is_error: false,
327 display: None,
328 })),
329 content_blocks: None,
330 ..ToolOutput::simple(format!(
331 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
332 ))
333 });
334 }
335
336 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
347 let progress_sender = ctx.progress_sender.clone();
348 let progress_label: String = cmd_clone.chars().take(60).collect();
349 let cap_secs = soft_cap.as_secs_f64();
350 let on_tick = |elapsed: std::time::Duration| {
351 #[allow(clippy::unwrap_or_default)]
352 if let Some(ref ps) = progress_sender
353 && let Some(sender) = ps
354 .lock()
355 .unwrap_or_else(std::sync::PoisonError::into_inner)
356 .as_ref()
357 {
358 sender.send(
359 elapsed.as_secs_f64(),
360 Some(cap_secs),
361 Some(format!(
362 "ctx_shell: {}s elapsed — {progress_label}",
363 elapsed.as_secs()
364 )),
365 );
366 }
367 };
368 let (raw_output, exit_code) =
369 match crate::server::background_shell::run_foreground_or_detach(
370 cmd_clone.clone(),
371 cwd_clone.clone(),
372 extra_env.clone(),
373 timeout_ms,
374 soft_cap,
375 Some(&on_tick),
376 ctx.cancel.as_ref(),
377 ) {
378 crate::server::background_shell::ForegroundResult::Finished {
379 output,
380 exit_code,
381 } => (output, exit_code),
382 crate::server::background_shell::ForegroundResult::Detached { job_id } => {
383 return Ok(ToolOutput {
384 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
385 state: BackgroundJobState::Running,
386 exit_code: None,
387 job_id: job_id.clone(),
388 archive_id: None,
389 archive_truncated: None,
390 captured_chars: None,
391 archived_chars: None,
392 summary: "auto-detached job is still running".to_string(),
393 is_error: false,
394 display: None,
395 })),
396 content_blocks: None,
397 ..ToolOutput::simple(format!(
401 "[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]",
402 soft_cap.as_secs()
403 ))
404 });
405 }
406 };
407
408 crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
410
411 let output = redact_shell_output_secrets(&raw_output);
412 let output = if raw {
413 crate::server::walk_hint::strip_walk_hint(&output).to_string()
414 } else {
415 output
416 };
417
418 let (result_out, original, saved, tee_hint) = if raw || inline {
419 let tokens = crate::core::tokens::count_tokens(&output);
420 (output, tokens, 0, String::new())
421 } else {
422 let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
423 let result =
424 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
425 let original = crate::core::tokens::count_tokens(&output);
426 let sent = crate::core::tokens::count_tokens(&result);
427 let saved = original.saturating_sub(sent);
428
429 let cfg = crate::core::config::Config::load();
430 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
433 let tee_hint = if crate::shell::tee_policy::should_tee(
434 &cfg.tee_mode,
435 exit_code,
436 output.trim().is_empty() || timeout_notice_only,
437 crate::shell::tee_policy::output_was_elided(&output, &result),
438 original,
439 sent,
440 ) {
441 crate::shell::save_tee(&cmd_clone, &output)
442 .map(|p| {
443 if crate::cli::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
444 format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
445 } else if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
446 {
447 let pct = crate::shell::tee_policy::savings_pct(original, sent);
448 format!(
451 "\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]"
452 )
453 } else {
454 format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
455 }
456 })
457 .unwrap_or_default()
458 } else {
459 String::new()
460 };
461
462 (result, original, saved, tee_hint)
463 };
464
465 let mode = if bypass {
466 Some("bypass".to_string())
467 } else if raw {
468 Some("raw".to_string())
469 } else {
470 None
471 };
472
473 let shell_mismatch = if cfg!(windows) && !raw {
474 shell_mismatch_hint(&command, &result_out)
475 } else {
476 String::new()
477 };
478
479 let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
480 let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
484 let nudge = if raw { "" } else { search_tool_nudge(&command) };
485 let final_out = format!(
486 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
487 );
488 let final_out = if let Some(block) = proactive_block {
489 format!("{final_out}{block}")
490 } else {
491 final_out
492 };
493
494 Ok(ToolOutput {
495 text: final_out,
496 original_tokens: original,
497 saved_tokens: saved,
498 mode,
499 path: None,
500 changed: false,
501 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
502 content_blocks: None,
503 })
504 })
505 }
506}
507
508fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
511 if let Some(role) = ctx.client_role.as_deref()
512 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
513 {
514 return Some(format!(
515 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
516 ));
517 }
518
519 if ctx.shell_access == Some(false) {
520 return Some(
521 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
522 .to_string(),
523 );
524 }
525
526 None
527}
528
529fn resolve_effective_cwd(
530 session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
531 explicit_cwd: Option<&str>,
532) -> Result<(String, Option<String>), ErrorData> {
533 match session {
534 Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
535 None => Err(ErrorData::internal_error(
536 "session lock timeout — cannot validate working directory",
537 None,
538 )),
539 }
540}
541
542#[allow(clippy::fn_params_excessive_bools)]
543fn resolve_shell_raw_flags(
544 arg_raw: bool,
545 arg_bypass: bool,
546 _env_disabled: bool,
547 env_raw: bool,
548) -> (bool, bool) {
549 let bypass = arg_bypass || env_raw;
550 let raw = arg_raw || bypass;
551 (raw, bypass)
552}
553
554fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
561 exit_code == 124
562 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
563}
564
565fn search_tool_nudge(command: &str) -> &'static str {
566 let cmd = command.trim();
567 let first_word = cmd.split_whitespace().next().unwrap_or("");
568 if !cmd.contains('|') {
569 match first_word {
570 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
571 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
572 }
573 "find" => {
574 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
575 }
576 "ls" | "exa" | "eza" => {
577 return "\n[hint: use ctx_tree for structured directory listing]";
578 }
579 _ => {}
580 }
581 }
582 ""
583}
584
585fn shell_mismatch_hint(command: &str, output: &str) -> String {
586 let shell = crate::shell::shell_name();
587 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
588 let has_error = output.contains("is not recognized")
589 || output.contains("not found")
590 || output.contains("command not found");
591
592 if !has_error {
593 return String::new();
594 }
595
596 let powershell_cmds = [
597 "Get-Content",
598 "Select-Object",
599 "Get-ChildItem",
600 "Set-Location",
601 "Where-Object",
602 "ForEach-Object",
603 "Select-String",
604 "Invoke-Expression",
605 "Write-Output",
606 ];
607 let uses_powershell = powershell_cmds
608 .iter()
609 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
610
611 if is_posix && uses_powershell {
612 format!(
613 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
614 )
615 } else {
616 String::new()
617 }
618}
619
620fn collect_extra_env(
631 args: &Map<String, Value>,
632) -> Result<std::collections::HashMap<String, String>, String> {
633 let mut accepted = std::collections::HashMap::new();
634 let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
635 return Ok(accepted);
636 };
637 let mut rejected: Vec<&str> = Vec::new();
638 for (key, value) in obj {
639 let Some(text) = value.as_str() else { continue };
640 if is_dangerous_env_key(key) {
641 rejected.push(key.as_str());
642 continue;
643 }
644 accepted.insert(key.clone(), text.to_string());
645 }
646 if rejected.is_empty() {
647 return Ok(accepted);
648 }
649 rejected.sort_unstable();
650 let names = rejected
651 .iter()
652 .map(|k| format!("`{k}`"))
653 .collect::<Vec<_>>()
654 .join(", ");
655 let plural = if rejected.len() == 1 { "key" } else { "keys" };
656 Err(format!(
657 "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
658 redirect which binary executes, so lean-ctx never forwards them, and the command would \
659 otherwise have used the inherited value while appearing to honor yours. This is the \
660 same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
661 Invoke the binary by its full path instead, or drop the override."
662 ))
663}
664
665fn is_dangerous_env_key(key: &str) -> bool {
666 const BLOCKED: &[&str] = &[
667 "LD_PRELOAD",
669 "LD_LIBRARY_PATH",
670 "DYLD_INSERT_LIBRARIES",
671 "DYLD_LIBRARY_PATH",
672 "DYLD_FRAMEWORK_PATH",
673 "BASH_ENV",
675 "ENV",
676 "PROMPT_COMMAND",
677 "SHELL",
678 "IFS",
679 "CDPATH",
680 "PATH",
682 "GIT_EXEC_PATH",
683 "GIT_SSH",
684 "GIT_SSH_COMMAND",
685 "HOME",
687 "USER",
688 "LOGNAME",
689 "XDG_CONFIG_HOME",
690 "XDG_DATA_HOME",
691 "XDG_STATE_HOME",
692 "XDG_CACHE_HOME",
693 "PYTHONPATH",
695 "PYTHONSTARTUP",
696 "PYTHONHOME",
697 "NODE_PATH",
698 "NODE_OPTIONS",
699 "RUBYOPT",
700 "RUBYLIB",
701 "GEM_PATH",
702 "GEM_HOME",
703 "PERL5LIB",
704 "PERL5OPT",
705 "CLASSPATH",
706 "JAVA_HOME",
707 "CARGO_HOME",
708 "RUSTUP_HOME",
709 "GOPATH",
710 "GOROOT",
711 ];
712 let upper = key.to_uppercase();
713 if BLOCKED.contains(&upper.as_str()) {
714 return true;
715 }
716 if upper.starts_with("LD_") && upper.ends_with("_PATH") {
717 return true;
718 }
719 if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
721 return true;
722 }
723 false
724}
725
726fn warn_shell_secret_paths(command: &str) {
729 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
730 let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
731 for seg in &segments {
732 let trimmed = seg.trim();
733 let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
734 if tokens.is_empty() {
735 continue;
736 }
737 let base = tokens[0]
738 .rsplit('/')
739 .next()
740 .unwrap_or(&tokens[0])
741 .to_string();
742 if !READ_CMDS.contains(&base.as_str()) {
743 continue;
744 }
745 for tok in &tokens[1..] {
746 if tok.starts_with('-') {
747 continue;
748 }
749 let path = std::path::Path::new(tok.as_str());
750 if crate::core::io_boundary::is_secret_like(path).is_some() {
751 tracing::warn!(
752 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
753 );
754 }
755 }
756 }
757}
758
759fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
764 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
765 && command
766 .lines()
767 .any(|line| line.trim_start().starts_with("cargo test"))
768}
769
770fn foreground_soft_cap_ms() -> u64 {
775 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
776 .ok()
777 .and_then(|v| v.parse().ok())
778 .filter(|&ms| ms > 0)
779 .unwrap_or(110_000)
780}
781
782fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
784 match base {
785 "python" | "python2" | "python3" => Some("python"),
786 "node" => Some("javascript"),
787 "ruby" => Some("ruby"),
788 _ => None,
789 }
790}
791
792fn is_env_assignment_token(token: &str) -> bool {
793 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
794 unquoted.contains('=')
795 && !unquoted.starts_with('-')
796 && !unquoted.starts_with('/')
797 && !unquoted.starts_with('.')
798}
799
800fn prelude_has_compound_operator(prelude: &str) -> bool {
802 let bytes = prelude.as_bytes();
803 let len = bytes.len();
804 let mut i = 0;
805 let mut in_single = false;
806 let mut in_double = false;
807 while i < len {
808 let ch = bytes[i];
809 if in_single {
810 if ch == b'\'' {
811 in_single = false;
812 }
813 i += 1;
814 continue;
815 }
816 if in_double {
817 if ch == b'\\' && i + 1 < len {
818 i += 2;
819 } else {
820 if ch == b'"' {
821 in_double = false;
822 }
823 i += 1;
824 }
825 continue;
826 }
827 match ch {
828 b'\'' => {
829 in_single = true;
830 i += 1;
831 }
832 b'"' => {
833 in_double = true;
834 i += 1;
835 }
836 b';' | b'|' | b'&' | b'(' | b'{' => return true,
837 _ => i += 1,
838 }
839 }
840 false
841}
842
843fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
847 if !command.contains("<<") {
848 return None;
849 }
850
851 let lines: Vec<&str> = command.lines().collect();
852 if lines.is_empty() {
853 return None;
854 }
855
856 let first_line = lines[0];
857 let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
858 if delims.len() != 1 {
859 return None;
860 }
861 let delim = delims[0].clone();
862
863 let heredoc_pos = find_heredoc_operator(first_line)?;
864 let prelude = first_line[..heredoc_pos].trim();
865 if prelude_has_compound_operator(prelude) {
866 return None;
867 }
868
869 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
870
871 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
872 return None;
873 }
874
875 let mut body = String::new();
876 let mut remainder_start: Option<usize> = None;
877 for (idx, line) in lines.iter().enumerate().skip(1) {
878 if line.trim_start_matches('\t').trim() == delim {
879 remainder_start = Some(idx + 1);
880 break;
881 }
882 if !body.is_empty() {
883 body.push('\n');
884 }
885 body.push_str(line);
886 }
887 let remainder_start = remainder_start?;
888 let remainder = if remainder_start < lines.len() {
889 let rest = lines[remainder_start..].join("\n");
890 let rest = rest.trim();
891 if rest.is_empty() {
892 None
893 } else {
894 Some(rest.to_string())
895 }
896 } else {
897 None
898 };
899
900 Some((language, body, remainder))
901}
902
903fn find_heredoc_operator(line: &str) -> Option<usize> {
904 let bytes = line.as_bytes();
905 let len = bytes.len();
906 let mut i = 0;
907 let mut in_single = false;
908 let mut in_double = false;
909 while i < len {
910 let ch = bytes[i];
911 if in_single {
912 if ch == b'\'' {
913 in_single = false;
914 }
915 i += 1;
916 continue;
917 }
918 if in_double {
919 if ch == b'\\' && i + 1 < len {
920 i += 2;
921 } else {
922 if ch == b'"' {
923 in_double = false;
924 }
925 i += 1;
926 }
927 continue;
928 }
929 match ch {
930 b'\'' => {
931 in_single = true;
932 i += 1;
933 }
934 b'"' => {
935 in_double = true;
936 i += 1;
937 }
938 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
939 if i + 2 < len && bytes[i + 2] == b'<' {
940 i += 3;
941 continue;
942 }
943 return Some(i);
944 }
945 _ => i += 1,
946 }
947 }
948 None
949}
950
951fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
952 let bytes = line.as_bytes();
953 let mut i = heredoc_pos + 2;
954 if i < bytes.len() && bytes[i] == b'-' {
955 i += 1;
956 }
957 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
958 i += 1;
959 }
960 let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
961 return true;
962 };
963 !line[next..].trim().is_empty()
964}
965
966fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
967 let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
968 let mut idx = 0;
969 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
970 idx += 1;
971 }
972 if idx >= tokens.len() {
973 return None;
974 }
975 let base = tokens[idx]
976 .rsplit('/')
977 .next()
978 .unwrap_or(tokens[idx].as_str());
979 let language = interpreter_to_execute_language(base)?;
980 idx += 1;
981 match tokens.get(idx) {
982 None => Some(language),
983 Some(dash) if dash == "-" => {
984 if tokens.len() == idx + 1 {
985 Some(language)
986 } else {
987 None
988 }
989 }
990 Some(_) => None,
991 }
992}
993
994fn resolve_reroute_cwd(
1005 ctx: &ToolContext,
1006 explicit_cwd: Option<&str>,
1007) -> Result<Option<String>, ErrorData> {
1008 let Some(session_lock) = ctx.session.as_ref() else {
1009 if explicit_cwd.is_some() {
1010 return Err(ErrorData::internal_error(
1011 "session not available — cannot validate the requested working directory",
1012 None,
1013 ));
1014 }
1015 return Ok(None);
1016 };
1017 let guard =
1018 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1019 let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1020 Ok(Some(cwd))
1021}
1022
1023fn handle_interpreter_heredoc_reroute(
1024 args: &Map<String, Value>,
1025 ctx: &ToolContext,
1026 language: &str,
1027 code: &str,
1028 remainder: Option<String>,
1029) -> Result<ToolOutput, ErrorData> {
1030 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1031 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1032
1033 let explicit_cwd = get_str(args, "cwd");
1039 let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1040
1041 let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1042 language,
1043 code,
1044 None,
1045 timeout_secs,
1046 exec_cwd.as_deref().map(std::path::Path::new),
1047 );
1048 let reroute_note = format!(
1049 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1050 );
1051 let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1052
1053 let Some(rest_cmd) = remainder else {
1054 return Ok(ToolOutput {
1055 text: format!("{exec_text}{reroute_note}"),
1056 original_tokens: crate::core::tokens::count_tokens(&exec_text),
1057 saved_tokens: 0,
1058 mode: Some("heredoc-reroute".to_string()),
1059 path: None,
1060 changed: false,
1061 shell_outcome: Some(exec_outcome),
1062 content_blocks: None,
1063 });
1064 };
1065
1066 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1067 let blocked =
1068 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1069 return Ok(ToolOutput {
1070 shell_outcome: Some(ShellOutcome::Blocked),
1071 content_blocks: None,
1072 ..ToolOutput::simple(blocked)
1073 });
1074 }
1075
1076 let effective_cwd =
1079 exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1080
1081 let extra_env = match collect_extra_env(args) {
1082 Ok(env) => env,
1083 Err(message) => {
1084 return Ok(ToolOutput {
1085 shell_outcome: Some(ShellOutcome::Blocked),
1086 content_blocks: None,
1087 ..ToolOutput::simple(message)
1088 });
1089 }
1090 };
1091
1092 let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1093 &rest_cmd,
1094 &effective_cwd,
1095 &extra_env,
1096 timeout_ms,
1097 );
1098 let shell_output = redact_shell_output_secrets(&shell_raw);
1099 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1100 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1101 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1102 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1103 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1104
1105 let shell_text = if raw {
1106 shell_output
1107 } else {
1108 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1109 };
1110 let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1111 let exit_suffix = crate::shell::exit_status::exit_footer(shell_exit);
1112
1113 let combined = format!(
1114 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1115 );
1116 let token_count = crate::core::tokens::count_tokens(&combined);
1117 Ok(ToolOutput {
1118 text: combined,
1119 original_tokens: token_count,
1120 saved_tokens: 0,
1121 mode: Some("heredoc-reroute".to_string()),
1122 path: None,
1123 changed: false,
1124 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1125 content_blocks: None,
1126 })
1127}
1128
1129fn detect_bare_cat_file(command: &str) -> Option<String> {
1131 let trimmed = command.trim();
1132 let rest = trimmed.strip_prefix("cat ")?;
1133 let rest = rest.trim();
1134 if rest.is_empty()
1135 || rest.contains('|')
1136 || rest.contains('>')
1137 || rest.contains('<')
1138 || rest.contains(';')
1139 || rest.contains('&')
1140 || rest.contains('$')
1141 || rest.starts_with('-')
1142 {
1143 return None;
1144 }
1145 let parts: Vec<&str> = rest.split_whitespace().collect();
1146 if parts.len() != 1 {
1147 return None;
1148 }
1149 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1150 if file_path.is_empty() {
1151 return None;
1152 }
1153 Some(file_path.to_string())
1154}
1155
1156#[cfg(test)]
1157#[path = "ctx_shell_tests.rs"]
1158mod tests;