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