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_snapshot, 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 (default here: the 1 h ceiling); 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::snapshot(&id),
73 "cancel" => crate::server::background_shell::cancel_snapshot(&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_snapshot(&id, is_cancel, state);
82 return Ok(ToolOutput {
83 shell_outcome: Some(outcome),
84 content_blocks: None,
85 mode: Some(crate::tools::server_metrics::BACKGROUND_POLL_MODE.to_string()),
88 ..ToolOutput::simple(text)
89 });
90 }
91 let command = get_str(args, "command")
92 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
93 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
94
95 let explicit_cwd = get_str(args, "cwd");
105 let had_explicit_cwd = explicit_cwd.is_some();
106 let resolved_cwd = match ctx.session.as_ref() {
112 Some(session_lock) => Some(tokio::task::block_in_place(|| {
113 let guard = crate::server::bounded_lock::read_for(
114 session_lock,
115 "ctx_shell_cwd",
116 SESSION_LOCK_BUDGET,
117 );
118 resolve_effective_cwd(guard, explicit_cwd.as_deref())
119 })?),
120 None => None,
121 };
122
123 let config = crate::core::config::Config::load();
128 let mut write_allow_paths = config.shell_write_allow_paths_effective();
129 write_allow_paths.extend(crate::tools::ctx_shell::capture_roots(
132 &ctx.project_root,
133 &ctx.extra_roots,
134 &config,
135 ));
136 if !config.shell_allow_writes_effective()
137 && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
138 &command,
139 &write_allow_paths,
140 None,
141 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
142 )
143 {
144 return Ok(ToolOutput {
147 shell_outcome: Some(ShellOutcome::Blocked),
148 content_blocks: None,
149 ..ToolOutput::simple(rejection)
150 });
151 }
152
153 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
154 return tokio::task::block_in_place(|| {
155 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
156 });
157 }
158
159 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist_granted(
160 &command,
161 &crate::server::shell_approval::current_grant(),
162 ) {
163 return Ok(ToolOutput {
164 shell_outcome: Some(ShellOutcome::Blocked),
165 content_blocks: None,
166 ..ToolOutput::simple(msg.to_string())
167 });
168 }
169
170 warn_shell_secret_paths(&command);
171
172 if let Some(read_path) = detect_bare_cat_file(&command)
176 && let Some(cache_lock) = ctx.cache.as_ref()
177 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
178 {
179 let result = crate::tools::ctx_read::handle_with_task_resolved(
180 &mut cache,
181 &read_path,
182 "full",
183 crate::tools::CrpMode::Off,
184 None,
185 );
186 let note = format!(
187 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
188 Use ctx_read(path=\"{read_path}\") directly next time.]"
189 );
190 let out = format!("{}{note}", result.content);
191 let sent = crate::core::tokens::count_tokens(&out);
192 return Ok(ToolOutput {
193 text: out,
194 original_tokens: sent,
195 saved_tokens: 0,
196 mode: Some("cat-redirect".to_string()),
197 path: Some(read_path),
198 changed: false,
199 shell_outcome: Some(ShellOutcome::Exit(0)),
200 content_blocks: None,
201 });
202 }
203
204 tokio::task::block_in_place(|| {
205 let session_lock = ctx
206 .session
207 .as_ref()
208 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
209 let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
210 return Err(ErrorData::internal_error("session not available", None));
211 };
212 let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
217 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
218 format!(
219 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
220 )
221 });
222
223 {
224 let Some(mut session) = crate::server::bounded_lock::write_for(
225 session_lock,
226 "ctx_shell_write",
227 SESSION_LOCK_BUDGET,
228 ) else {
229 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
230 let cmd_clone = command.clone();
231 let cwd_clone = effective_cwd.clone();
232 let extra_env = match collect_extra_env(args) {
233 Ok(env) => env,
234 Err(message) => {
235 return Ok(ToolOutput {
236 shell_outcome: Some(ShellOutcome::Blocked),
237 content_blocks: None,
238 ..ToolOutput::simple(message)
239 });
240 }
241 };
242 let execution = crate::server::execute::execute_command_with_env_captured(
243 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
244 );
245 let admission = crate::core::context_admission::admit_tool_output(
246 &execution.output,
247 execution.completeness,
248 );
249 let output = redact_shell_output_secrets(&admission.rendered());
250 let exit_suffix = crate::shell::exit_status::exit_footer(execution.exit_code);
253 let final_text = format!("{output}{exit_suffix}");
254 let final_admission = crate::core::context_admission::admit_tool_output(
255 &final_text,
256 execution.completeness,
257 );
258 return Ok(ToolOutput {
259 shell_outcome: Some(ShellOutcome::Exit(execution.exit_code)),
260 content_blocks: None,
261 ..ToolOutput::simple(crate::server::execute::with_notice(
264 execution.notice,
265 final_admission.rendered(),
266 ))
267 });
268 };
269 if had_explicit_cwd && cwd_jail_reason_was_none {
274 session.note_explicit_cwd(&effective_cwd);
275 }
276 session.update_shell_cwd(&command);
277 let root_missing = session
278 .project_root
279 .as_deref()
280 .is_none_or(|r| r.trim().is_empty());
281 if root_missing {
282 let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
283 if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
284 && home.as_deref() != Some(root.as_str())
285 {
286 session.project_root = Some(root.clone());
287 crate::core::index_orchestrator::ensure_all_background(&root);
288 }
289 }
290 }
291
292 let arg_raw = get_bool(args, "raw").unwrap_or(false);
293 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
294 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
295 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
296 let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
297
298 let crp_mode = ctx.crp_mode;
299 let cmd_clone = command.clone();
300 let cwd_clone = effective_cwd;
301 let proactive_block = if raw
302 || !crate::core::profiles::active_profile()
303 .output_hints
304 .proactive_context()
305 {
306 None
307 } else {
308 crate::core::relevance_tracker::proactive_context(&format!(
309 "ctx_shell command={cmd_clone} cwd={cwd_clone}"
310 ))
311 };
312
313 let extra_env = match collect_extra_env(args) {
314 Ok(env) => env,
315 Err(message) => {
316 return Ok(ToolOutput {
317 shell_outcome: Some(ShellOutcome::Blocked),
318 content_blocks: None,
319 ..ToolOutput::simple(message)
320 });
321 }
322 };
323
324 let inline = get_bool(args, "inline").unwrap_or(false);
325
326 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
327 let detached = get_bool(args, "run_in_background").unwrap_or(false);
328 if detached || auto_background {
329 let lifetime = if detached {
334 timeout_ms.or(Some(crate::shell::exec::MAX_CALL_TIMEOUT_MS))
335 } else {
336 timeout_ms
337 };
338 let job_id = crate::server::background_shell::start(
339 cmd_clone, cwd_clone, extra_env, lifetime,
340 );
341 let mode = if auto_background {
342 "auto-background"
343 } else {
344 "background"
345 };
346 return Ok(ToolOutput {
347 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
348 state: BackgroundJobState::Running,
349 exit_code: None,
350 job_id: job_id.clone(),
351 archive_id: None,
352 archive_truncated: None,
353 captured_chars: None,
354 archived_chars: None,
355 summary: format!("{mode} job started"),
356 is_error: false,
357 display: None,
358 })),
359 content_blocks: None,
360 ..ToolOutput::simple(format!(
361 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
362 ))
363 });
364 }
365
366 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
377 let progress_sender = ctx.progress_sender.clone();
378 let progress_label: String = cmd_clone.chars().take(60).collect();
379 let cap_secs = soft_cap.as_secs_f64();
380 let on_tick = |elapsed: std::time::Duration| {
381 #[allow(clippy::unwrap_or_default)]
382 if let Some(ref ps) = progress_sender
383 && let Some(sender) = ps
384 .lock()
385 .unwrap_or_else(std::sync::PoisonError::into_inner)
386 .as_ref()
387 {
388 sender.send(
389 elapsed.as_secs_f64(),
390 Some(cap_secs),
391 Some(format!(
392 "ctx_shell: {}s elapsed — {progress_label}",
393 elapsed.as_secs()
394 )),
395 );
396 }
397 };
398 let (process_output, exit_code, completeness, retained_withheld, containment_notice) =
399 match crate::server::background_shell::run_foreground_or_detach_captured(
400 cmd_clone.clone(),
401 cwd_clone.clone(),
402 extra_env.clone(),
403 timeout_ms,
404 soft_cap,
405 Some(&on_tick),
406 ctx.cancel.as_ref(),
407 ) {
408 crate::server::background_shell::CapturedForegroundResult::Finished {
409 output,
410 exit_code,
411 completeness,
412 retained_withheld,
413 notice,
414 } => (output, exit_code, completeness, retained_withheld, notice),
415 crate::server::background_shell::CapturedForegroundResult::Detached {
416 job_id,
417 } => {
418 return Ok(ToolOutput {
419 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
420 state: BackgroundJobState::Running,
421 exit_code: None,
422 job_id: job_id.clone(),
423 archive_id: None,
424 archive_truncated: None,
425 captured_chars: None,
426 archived_chars: None,
427 summary: "auto-detached job is still running".to_string(),
428 is_error: false,
429 display: None,
430 })),
431 content_blocks: None,
432 ..ToolOutput::simple(format!(
436 "[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]",
437 soft_cap.as_secs()
438 ))
439 });
440 }
441 };
442
443 let display_input = if retained_withheld {
444 "[lean-ctx gateway: retained output withheld by storage policy]".to_string()
445 } else {
446 process_output.clone()
447 };
448 let admission =
449 crate::core::context_admission::admit_tool_output(&display_input, completeness);
450 let output = redact_shell_output_secrets(&admission.rendered());
451 let output = if raw {
452 crate::server::walk_hint::strip_walk_hint(&output).to_string()
453 } else {
454 output
455 };
456
457 let store = crate::core::context_admission::stores::StoreAdmission::current();
460 let stored_command = store.admit_shell_command(&cmd_clone);
461 let stored_output = (!retained_withheld)
462 .then(|| store.admit_shell_output(&process_output, completeness))
463 .flatten();
464 let storage_allowed = !retained_withheld
465 && store.is_current()
466 && stored_command.is_some()
467 && stored_output.is_some();
468 let command_for_store = stored_command.as_deref().unwrap_or_default();
469 let output_for_store = stored_output.as_deref().unwrap_or_default();
470 if storage_allowed {
471 crate::core::diagnostics_store::record_from_shell(
472 command_for_store,
473 output_for_store,
474 exit_code,
475 );
476 }
477
478 let (result_out, original, saved, tee_hint) = if raw || inline {
479 let tokens = crate::core::tokens::count_tokens(&output);
480 (output, tokens, 0, String::new())
481 } else {
482 let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
483 let result =
484 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
485 let original = crate::core::tokens::count_tokens(&output);
486 let sent = crate::core::tokens::count_tokens(&result);
487 let saved = original.saturating_sub(sent);
488
489 let cfg = crate::core::config::Config::load();
490 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
493 let tee_hint = if storage_allowed
494 && crate::shell::tee_policy::should_tee(
495 &cfg.tee_mode,
496 exit_code,
497 output.trim().is_empty() || timeout_notice_only,
498 crate::shell::tee_policy::output_was_elided(&output, &result),
499 original,
500 sent,
501 ) {
502 crate::shell::save_tee(command_for_store, output_for_store)
503 .map(|p| {
504 if crate::cli::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
505 format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
506 } else if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
507 {
508 let pct = crate::shell::tee_policy::savings_pct(original, sent);
509 format!(
512 "\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]"
513 )
514 } else {
515 format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
516 }
517 })
518 .unwrap_or_default()
519 } else {
520 String::new()
521 };
522
523 (result, original, saved, tee_hint)
524 };
525
526 let mode = if bypass {
527 Some("bypass".to_string())
528 } else if raw {
529 Some("raw".to_string())
530 } else {
531 None
532 };
533
534 let shell_mismatch = if cfg!(windows) && !raw {
535 shell_mismatch_hint(&command, &result_out)
536 } else {
537 String::new()
538 };
539
540 let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
541 let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
545 let nudge = if raw { "" } else { search_tool_nudge(&command) };
546 let final_out = format!(
547 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
548 );
549 let final_out = if let Some(block) = proactive_block {
550 format!("{final_out}{block}")
551 } else {
552 final_out
553 };
554 let final_admission =
555 crate::core::context_admission::admit_tool_output(&final_out, completeness);
556 let final_out = final_admission.rendered();
557
558 Ok(ToolOutput {
559 text: crate::server::execute::with_notice(containment_notice, final_out),
562 original_tokens: original,
563 saved_tokens: saved,
564 mode,
565 path: None,
566 changed: false,
567 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
568 content_blocks: None,
569 })
570 })
571 }
572}
573
574pub(crate) fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
578 if let Some(role) = ctx.client_role.as_deref()
579 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
580 {
581 return Some(format!(
582 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
583 ));
584 }
585
586 if ctx.shell_access == Some(false) {
587 return Some(
588 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
589 .to_string(),
590 );
591 }
592
593 None
594}
595
596fn resolve_effective_cwd(
597 session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
598 explicit_cwd: Option<&str>,
599) -> Result<(String, Option<String>), ErrorData> {
600 match session {
601 Some(session) => session
604 .execution_cwd(explicit_cwd)
605 .map(|cwd| (cwd, None))
606 .map_err(|reason| {
607 ErrorData::invalid_params(
608 format!("working directory rejected, command not run: {reason}"),
609 None,
610 )
611 }),
612 None => Err(ErrorData::internal_error(
613 "session lock timeout — cannot validate working directory",
614 None,
615 )),
616 }
617}
618
619#[allow(clippy::fn_params_excessive_bools)]
620fn resolve_shell_raw_flags(
621 arg_raw: bool,
622 arg_bypass: bool,
623 _env_disabled: bool,
624 env_raw: bool,
625) -> (bool, bool) {
626 let bypass = arg_bypass || env_raw;
627 let raw = arg_raw || bypass;
628 (raw, bypass)
629}
630
631fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
638 exit_code == 124
639 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
640}
641
642fn search_tool_nudge(command: &str) -> &'static str {
643 let cmd = command.trim();
644 let first_word = cmd.split_whitespace().next().unwrap_or("");
645 if !cmd.contains('|') {
646 match first_word {
647 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
648 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
649 }
650 "find" => {
651 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
652 }
653 "ls" | "exa" | "eza" => {
654 return "\n[hint: use ctx_tree for structured directory listing]";
655 }
656 _ => {}
657 }
658 }
659 ""
660}
661
662fn shell_mismatch_hint(command: &str, output: &str) -> String {
663 let shell = crate::shell::shell_name();
664 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
665 let has_error = output.contains("is not recognized")
666 || output.contains("not found")
667 || output.contains("command not found");
668
669 if !has_error {
670 return String::new();
671 }
672
673 let powershell_cmds = [
674 "Get-Content",
675 "Select-Object",
676 "Get-ChildItem",
677 "Set-Location",
678 "Where-Object",
679 "ForEach-Object",
680 "Select-String",
681 "Invoke-Expression",
682 "Write-Output",
683 ];
684 let uses_powershell = powershell_cmds
685 .iter()
686 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
687
688 if is_posix && uses_powershell {
689 format!(
690 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
691 )
692 } else {
693 String::new()
694 }
695}
696
697fn collect_extra_env(
708 args: &Map<String, Value>,
709) -> Result<std::collections::HashMap<String, String>, String> {
710 let mut accepted = std::collections::HashMap::new();
711 let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
712 return Ok(accepted);
713 };
714 let mut rejected: Vec<&str> = Vec::new();
715 for (key, value) in obj {
716 let Some(text) = value.as_str() else { continue };
717 if is_dangerous_env_key(key) {
718 rejected.push(key.as_str());
719 continue;
720 }
721 accepted.insert(key.clone(), text.to_string());
722 }
723 if rejected.is_empty() {
724 return Ok(accepted);
725 }
726 rejected.sort_unstable();
727 let names = rejected
728 .iter()
729 .map(|k| format!("`{k}`"))
730 .collect::<Vec<_>>()
731 .join(", ");
732 let plural = if rejected.len() == 1 { "key" } else { "keys" };
733 Err(format!(
734 "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
735 redirect which binary executes, so lean-ctx never forwards them, and the command would \
736 otherwise have used the inherited value while appearing to honor yours. This is the \
737 same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
738 Invoke the binary by its full path instead, or drop the override."
739 ))
740}
741
742fn is_dangerous_env_key(key: &str) -> bool {
743 const BLOCKED: &[&str] = &[
744 "LD_PRELOAD",
746 "LD_LIBRARY_PATH",
747 "DYLD_INSERT_LIBRARIES",
748 "DYLD_LIBRARY_PATH",
749 "DYLD_FRAMEWORK_PATH",
750 "BASH_ENV",
752 "ENV",
753 "PROMPT_COMMAND",
754 "SHELL",
755 "IFS",
756 "CDPATH",
757 "PATH",
759 "GIT_EXEC_PATH",
760 "GIT_SSH",
761 "GIT_SSH_COMMAND",
762 "HOME",
764 "USER",
765 "LOGNAME",
766 "XDG_CONFIG_HOME",
767 "XDG_DATA_HOME",
768 "XDG_STATE_HOME",
769 "XDG_CACHE_HOME",
770 "PYTHONPATH",
772 "PYTHONSTARTUP",
773 "PYTHONHOME",
774 "NODE_PATH",
775 "NODE_OPTIONS",
776 "RUBYOPT",
777 "RUBYLIB",
778 "GEM_PATH",
779 "GEM_HOME",
780 "PERL5LIB",
781 "PERL5OPT",
782 "CLASSPATH",
783 "JAVA_HOME",
784 "CARGO_HOME",
785 "RUSTUP_HOME",
786 "GOPATH",
787 "GOROOT",
788 ];
789 let upper = key.to_uppercase();
790 if BLOCKED.contains(&upper.as_str()) {
791 return true;
792 }
793 if upper.starts_with("LD_") && upper.ends_with("_PATH") {
794 return true;
795 }
796 if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
798 return true;
799 }
800 false
801}
802
803fn warn_shell_secret_paths(command: &str) {
806 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
807 let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
808 for seg in &segments {
809 let trimmed = seg.trim();
810 let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
811 if tokens.is_empty() {
812 continue;
813 }
814 let base = tokens[0]
815 .rsplit('/')
816 .next()
817 .unwrap_or(&tokens[0])
818 .to_string();
819 if !READ_CMDS.contains(&base.as_str()) {
820 continue;
821 }
822 for tok in &tokens[1..] {
823 if tok.starts_with('-') {
824 continue;
825 }
826 let path = std::path::Path::new(tok.as_str());
827 if crate::core::io_boundary::is_secret_like(path).is_some() {
828 tracing::warn!(
829 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
830 );
831 }
832 }
833 }
834}
835
836fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
841 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
842 && command
843 .lines()
844 .any(|line| line.trim_start().starts_with("cargo test"))
845}
846
847fn foreground_soft_cap_ms() -> u64 {
852 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
853 .ok()
854 .and_then(|v| v.parse().ok())
855 .filter(|&ms| ms > 0)
856 .unwrap_or(110_000)
857}
858
859fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
861 match base {
862 "python" | "python2" | "python3" => Some("python"),
863 "node" => Some("javascript"),
864 "ruby" => Some("ruby"),
865 _ => None,
866 }
867}
868
869fn is_env_assignment_token(token: &str) -> bool {
870 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
871 unquoted.contains('=')
872 && !unquoted.starts_with('-')
873 && !unquoted.starts_with('/')
874 && !unquoted.starts_with('.')
875}
876
877fn prelude_has_compound_operator(prelude: &str) -> bool {
879 let bytes = prelude.as_bytes();
880 let len = bytes.len();
881 let mut i = 0;
882 let mut in_single = false;
883 let mut in_double = false;
884 while i < len {
885 let ch = bytes[i];
886 if in_single {
887 if ch == b'\'' {
888 in_single = false;
889 }
890 i += 1;
891 continue;
892 }
893 if in_double {
894 if ch == b'\\' && i + 1 < len {
895 i += 2;
896 } else {
897 if ch == b'"' {
898 in_double = false;
899 }
900 i += 1;
901 }
902 continue;
903 }
904 match ch {
905 b'\'' => {
906 in_single = true;
907 i += 1;
908 }
909 b'"' => {
910 in_double = true;
911 i += 1;
912 }
913 b';' | b'|' | b'&' | b'(' | b'{' => return true,
914 _ => i += 1,
915 }
916 }
917 false
918}
919
920fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
924 if !command.contains("<<") {
925 return None;
926 }
927
928 let lines: Vec<&str> = command.lines().collect();
929 if lines.is_empty() {
930 return None;
931 }
932
933 let first_line = lines[0];
934 let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
935 if delims.len() != 1 {
936 return None;
937 }
938 let delim = delims[0].clone();
939
940 let heredoc_pos = find_heredoc_operator(first_line)?;
941 let prelude = first_line[..heredoc_pos].trim();
942 if prelude_has_compound_operator(prelude) {
943 return None;
944 }
945
946 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
947
948 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
949 return None;
950 }
951
952 let mut body = String::new();
953 let mut remainder_start: Option<usize> = None;
954 for (idx, line) in lines.iter().enumerate().skip(1) {
955 if line.trim_start_matches('\t').trim() == delim {
956 remainder_start = Some(idx + 1);
957 break;
958 }
959 if !body.is_empty() {
960 body.push('\n');
961 }
962 body.push_str(line);
963 }
964 let remainder_start = remainder_start?;
965 let remainder = if remainder_start < lines.len() {
966 let rest = lines[remainder_start..].join("\n");
967 let rest = rest.trim();
968 if rest.is_empty() {
969 None
970 } else {
971 Some(rest.to_string())
972 }
973 } else {
974 None
975 };
976
977 Some((language, body, remainder))
978}
979
980fn find_heredoc_operator(line: &str) -> Option<usize> {
981 let bytes = line.as_bytes();
982 let len = bytes.len();
983 let mut i = 0;
984 let mut in_single = false;
985 let mut in_double = false;
986 while i < len {
987 let ch = bytes[i];
988 if in_single {
989 if ch == b'\'' {
990 in_single = false;
991 }
992 i += 1;
993 continue;
994 }
995 if in_double {
996 if ch == b'\\' && i + 1 < len {
997 i += 2;
998 } else {
999 if ch == b'"' {
1000 in_double = false;
1001 }
1002 i += 1;
1003 }
1004 continue;
1005 }
1006 match ch {
1007 b'\'' => {
1008 in_single = true;
1009 i += 1;
1010 }
1011 b'"' => {
1012 in_double = true;
1013 i += 1;
1014 }
1015 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
1016 if i + 2 < len && bytes[i + 2] == b'<' {
1017 i += 3;
1018 continue;
1019 }
1020 return Some(i);
1021 }
1022 _ => i += 1,
1023 }
1024 }
1025 None
1026}
1027
1028fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
1029 let bytes = line.as_bytes();
1030 let mut i = heredoc_pos + 2;
1031 if i < bytes.len() && bytes[i] == b'-' {
1032 i += 1;
1033 }
1034 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1035 i += 1;
1036 }
1037 let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
1038 return true;
1039 };
1040 !line[next..].trim().is_empty()
1041}
1042
1043fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
1044 let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
1045 let mut idx = 0;
1046 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
1047 idx += 1;
1048 }
1049 if idx >= tokens.len() {
1050 return None;
1051 }
1052 let base = tokens[idx]
1053 .rsplit('/')
1054 .next()
1055 .unwrap_or(tokens[idx].as_str());
1056 let language = interpreter_to_execute_language(base)?;
1057 idx += 1;
1058 match tokens.get(idx) {
1059 None => Some(language),
1060 Some(dash) if dash == "-" => {
1061 if tokens.len() == idx + 1 {
1062 Some(language)
1063 } else {
1064 None
1065 }
1066 }
1067 Some(_) => None,
1068 }
1069}
1070
1071fn resolve_reroute_cwd(
1082 ctx: &ToolContext,
1083 explicit_cwd: Option<&str>,
1084) -> Result<Option<String>, ErrorData> {
1085 let Some(session_lock) = ctx.session.as_ref() else {
1086 if explicit_cwd.is_some() {
1087 return Err(ErrorData::internal_error(
1088 "session not available — cannot validate the requested working directory",
1089 None,
1090 ));
1091 }
1092 return Ok(None);
1093 };
1094 let guard =
1095 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1096 let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1097 Ok(Some(cwd))
1098}
1099
1100fn handle_interpreter_heredoc_reroute(
1101 args: &Map<String, Value>,
1102 ctx: &ToolContext,
1103 language: &str,
1104 code: &str,
1105 remainder: Option<String>,
1106) -> Result<ToolOutput, ErrorData> {
1107 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1108 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1109
1110 let explicit_cwd = get_str(args, "cwd");
1116 let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1117
1118 let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1119 language,
1120 code,
1121 None,
1122 timeout_secs,
1123 exec_cwd.as_deref().map(std::path::Path::new),
1124 );
1125 let reroute_note = format!(
1126 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1127 );
1128 let exec_completeness = crate::core::context_admission::OutputCompleteness {
1129 reader_incomplete: true,
1130 ..crate::core::context_admission::OutputCompleteness::complete()
1131 };
1132 let exec_admission =
1133 crate::core::context_admission::admit_tool_output(&exec_text, exec_completeness);
1134 let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_admission.rendered());
1135
1136 let Some(rest_cmd) = remainder else {
1137 let final_text = format!("{exec_text}{reroute_note}");
1138 let final_admission =
1139 crate::core::context_admission::admit_tool_output(&final_text, exec_completeness);
1140 let text = final_admission.rendered();
1141 return Ok(ToolOutput {
1142 original_tokens: crate::core::tokens::count_tokens(&text),
1143 text,
1144 saved_tokens: 0,
1145 mode: Some("heredoc-reroute".to_string()),
1146 path: None,
1147 changed: false,
1148 shell_outcome: Some(exec_outcome),
1149 content_blocks: None,
1150 });
1151 };
1152
1153 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist_granted(
1154 &rest_cmd,
1155 &crate::server::shell_approval::current_grant(),
1156 ) {
1157 let blocked =
1158 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1159 return Ok(ToolOutput {
1160 shell_outcome: Some(ShellOutcome::Blocked),
1161 content_blocks: None,
1162 ..ToolOutput::simple(blocked)
1163 });
1164 }
1165
1166 let effective_cwd =
1169 exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1170
1171 let extra_env = match collect_extra_env(args) {
1172 Ok(env) => env,
1173 Err(message) => {
1174 return Ok(ToolOutput {
1175 shell_outcome: Some(ShellOutcome::Blocked),
1176 content_blocks: None,
1177 ..ToolOutput::simple(message)
1178 });
1179 }
1180 };
1181
1182 let shell_execution = crate::server::execute::execute_command_with_env_captured(
1183 &rest_cmd,
1184 &effective_cwd,
1185 &extra_env,
1186 timeout_ms,
1187 );
1188 let shell_exit = shell_execution.exit_code;
1189 let shell_admission = crate::core::context_admission::admit_tool_output(
1190 &shell_execution.output,
1191 shell_execution.completeness,
1192 );
1193 let shell_output = redact_shell_output_secrets(&shell_admission.rendered());
1194 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1195 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1196 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1197 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1198 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1199
1200 let shell_text = if raw {
1201 shell_output
1202 } else {
1203 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1204 };
1205 let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1206 let exit_suffix = crate::shell::exit_status::exit_footer(shell_exit);
1207
1208 let combined = format!(
1209 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1210 );
1211 let mut completeness = shell_execution.completeness;
1212 completeness.reader_incomplete = true;
1215 let final_admission =
1216 crate::core::context_admission::admit_tool_output(&combined, completeness);
1217 let text =
1219 crate::server::execute::with_notice(shell_execution.notice, final_admission.rendered());
1220 let token_count = crate::core::tokens::count_tokens(&text);
1221 Ok(ToolOutput {
1222 text,
1223 original_tokens: token_count,
1224 saved_tokens: 0,
1225 mode: Some("heredoc-reroute".to_string()),
1226 path: None,
1227 changed: false,
1228 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1229 content_blocks: None,
1230 })
1231}
1232
1233fn detect_bare_cat_file(command: &str) -> Option<String> {
1235 let trimmed = command.trim();
1236 let rest = trimmed.strip_prefix("cat ")?;
1237 let rest = rest.trim();
1238 if rest.is_empty()
1239 || rest.contains('|')
1240 || rest.contains('>')
1241 || rest.contains('<')
1242 || rest.contains(';')
1243 || rest.contains('&')
1244 || rest.contains('$')
1245 || rest.starts_with('-')
1246 {
1247 return None;
1248 }
1249 let parts: Vec<&str> = rest.split_whitespace().collect();
1250 if parts.len() != 1 {
1251 return None;
1252 }
1253 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1254 if file_path.is_empty() {
1255 return None;
1256 }
1257 Some(file_path.to_string())
1258}
1259
1260#[cfg(test)]
1261#[path = "ctx_shell_tests.rs"]
1262mod tests;