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 explicit_cwd = get_str(args, "cwd");
104 let had_explicit_cwd = explicit_cwd.is_some();
105 let resolved_cwd = match ctx.session.as_ref() {
111 Some(session_lock) => Some(tokio::task::block_in_place(|| {
112 let guard = crate::server::bounded_lock::read_for(
113 session_lock,
114 "ctx_shell_cwd",
115 SESSION_LOCK_BUDGET,
116 );
117 resolve_effective_cwd(guard, explicit_cwd.as_deref())
118 })?),
119 None => None,
120 };
121
122 let config = crate::core::config::Config::load();
127 let write_allow_paths = config.shell_write_allow_paths_effective();
128 let project_root = crate::core::config::Config::find_project_root();
129 if !config.shell_allow_writes_effective()
130 && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
131 &command,
132 &write_allow_paths,
133 project_root.as_deref(),
134 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
135 )
136 {
137 return Ok(ToolOutput {
140 shell_outcome: Some(ShellOutcome::Blocked),
141 content_blocks: None,
142 ..ToolOutput::simple(rejection)
143 });
144 }
145
146 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
147 return tokio::task::block_in_place(|| {
148 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
149 });
150 }
151
152 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
153 return Ok(ToolOutput {
154 shell_outcome: Some(ShellOutcome::Blocked),
155 content_blocks: None,
156 ..ToolOutput::simple(msg.to_string())
157 });
158 }
159
160 warn_shell_secret_paths(&command);
161
162 if let Some(read_path) = detect_bare_cat_file(&command)
166 && let Some(cache_lock) = ctx.cache.as_ref()
167 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
168 {
169 let result = crate::tools::ctx_read::handle_with_task_resolved(
170 &mut cache,
171 &read_path,
172 "full",
173 crate::tools::CrpMode::Off,
174 None,
175 );
176 let note = format!(
177 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
178 Use ctx_read(path=\"{read_path}\") directly next time.]"
179 );
180 let out = format!("{}{note}", result.content);
181 let sent = crate::core::tokens::count_tokens(&out);
182 return Ok(ToolOutput {
183 text: out,
184 original_tokens: sent,
185 saved_tokens: 0,
186 mode: Some("cat-redirect".to_string()),
187 path: Some(read_path),
188 changed: false,
189 shell_outcome: Some(ShellOutcome::Exit(0)),
190 content_blocks: None,
191 });
192 }
193
194 tokio::task::block_in_place(|| {
195 let session_lock = ctx
196 .session
197 .as_ref()
198 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
199 let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
200 return Err(ErrorData::internal_error("session not available", None));
201 };
202 let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
207 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
208 format!(
209 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
210 )
211 });
212
213 {
214 let Some(mut session) = crate::server::bounded_lock::write_for(
215 session_lock,
216 "ctx_shell_write",
217 SESSION_LOCK_BUDGET,
218 ) else {
219 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
220 let cmd_clone = command.clone();
221 let cwd_clone = effective_cwd.clone();
222 let extra_env = match collect_extra_env(args) {
223 Ok(env) => env,
224 Err(message) => {
225 return Ok(ToolOutput {
226 shell_outcome: Some(ShellOutcome::Blocked),
227 content_blocks: None,
228 ..ToolOutput::simple(message)
229 });
230 }
231 };
232 let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
233 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
234 );
235 let output = redact_shell_output_secrets(&raw_output);
236 let exit_suffix = match exit_code {
239 0 => String::new(),
240 124 => "\n[exit:124 — command timed out]".to_string(),
241 _ => format!("\n[exit:{exit_code}]"),
242 };
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 let shell_cache_key = shell_cache_key(&cmd_clone, &cwd_clone, &extra_env);
306 if !raw
307 && !inline
308 && crate::core::config::Config::load()
309 .cache
310 .shell_cache_enabled
311 && let Some(key) = shell_cache_key.as_ref()
312 && let Some(cached) = crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
313 .get(&key.cache_key())
314 .map(|r| r.clone())
315 && let Ok(value) = serde_json::from_str::<Value>(&cached)
316 && let (Some(text), Some(exit_code)) = (
317 value.get("text").and_then(Value::as_str),
318 value.get("exit_code").and_then(Value::as_i64),
319 )
320 {
321 return Ok(ToolOutput {
322 text: text.to_string(),
323 original_tokens: crate::core::tokens::count_tokens(text),
324 saved_tokens: 0,
325 mode: Some("cross-agent-cache".to_string()),
326 path: None,
327 changed: false,
328 shell_outcome: Some(ShellOutcome::Exit(exit_code as i32)),
329 content_blocks: None,
330 });
331 }
332
333 if let Some(ref key) = shell_cache_key {
335 let ck = key.cache_key();
336 let validator = key.validator();
337 if let Some(entry) =
338 crate::core::ocla::cache_delivery::check(&ck, &validator, "ctx_shell")
339 {
340 let stub = crate::core::ocla::cache_delivery::stub(&entry, "shell command");
341 return Ok(ToolOutput {
342 text: stub,
343 original_tokens: entry.token_count as usize,
344 saved_tokens: entry.token_count as usize,
345 mode: Some("cross-agent-cache".to_string()),
346 path: None,
347 changed: false,
348 shell_outcome: None,
349 content_blocks: None,
350 });
351 }
352 }
353
354 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
355 if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
356 let job_id = crate::server::background_shell::start(
357 cmd_clone, cwd_clone, extra_env, timeout_ms,
358 );
359 let mode = if auto_background {
360 "auto-background"
361 } else {
362 "background"
363 };
364 return Ok(ToolOutput {
365 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
366 state: BackgroundJobState::Running,
367 exit_code: None,
368 job_id: job_id.clone(),
369 archive_id: None,
370 archive_truncated: None,
371 captured_chars: None,
372 archived_chars: None,
373 summary: format!("{mode} job started"),
374 is_error: false,
375 display: None,
376 })),
377 content_blocks: None,
378 ..ToolOutput::simple(format!(
379 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
380 ))
381 });
382 }
383
384 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
395 let progress_sender = ctx.progress_sender.clone();
396 let progress_label: String = cmd_clone.chars().take(60).collect();
397 let cap_secs = soft_cap.as_secs_f64();
398 let on_tick = |elapsed: std::time::Duration| {
399 #[allow(clippy::unwrap_or_default)]
400 if let Some(ref ps) = progress_sender
401 && let Some(sender) = ps
402 .lock()
403 .unwrap_or_else(std::sync::PoisonError::into_inner)
404 .as_ref()
405 {
406 sender.send(
407 elapsed.as_secs_f64(),
408 Some(cap_secs),
409 Some(format!(
410 "ctx_shell: {}s elapsed — {progress_label}",
411 elapsed.as_secs()
412 )),
413 );
414 }
415 };
416 let (raw_output, exit_code) =
417 match crate::server::background_shell::run_foreground_or_detach(
418 cmd_clone.clone(),
419 cwd_clone.clone(),
420 extra_env.clone(),
421 timeout_ms,
422 soft_cap,
423 Some(&on_tick),
424 ctx.cancel.as_ref(),
425 ) {
426 crate::server::background_shell::ForegroundResult::Finished {
427 output,
428 exit_code,
429 } => (output, exit_code),
430 crate::server::background_shell::ForegroundResult::Detached { job_id } => {
431 return Ok(ToolOutput {
432 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
433 state: BackgroundJobState::Running,
434 exit_code: None,
435 job_id: job_id.clone(),
436 archive_id: None,
437 archive_truncated: None,
438 captured_chars: None,
439 archived_chars: None,
440 summary: "auto-detached job is still running".to_string(),
441 is_error: false,
442 display: None,
443 })),
444 content_blocks: None,
445 ..ToolOutput::simple(format!(
449 "[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]",
450 soft_cap.as_secs()
451 ))
452 });
453 }
454 };
455
456 crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
458
459 let output = redact_shell_output_secrets(&raw_output);
460
461 let (result_out, original, saved, tee_hint) = if raw || inline {
462 let tokens = crate::core::tokens::count_tokens(&output);
463 (output, tokens, 0, String::new())
464 } else {
465 let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
466 let result =
467 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
468 let original = crate::core::tokens::count_tokens(&output);
469 let sent = crate::core::tokens::count_tokens(&result);
470 let saved = original.saturating_sub(sent);
471
472 let cfg = crate::core::config::Config::load();
473 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
476 let tee_hint = if crate::shell::tee_policy::should_tee(
477 &cfg.tee_mode,
478 exit_code,
479 output.trim().is_empty() || timeout_notice_only,
480 crate::shell::tee_policy::output_was_elided(&output, &result),
481 original,
482 sent,
483 ) {
484 crate::shell::save_tee(&cmd_clone, &output)
485 .map(|p| {
486 if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
487 {
488 let pct = crate::shell::tee_policy::savings_pct(original, sent);
489 format!(
492 "\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]"
493 )
494 } else {
495 format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
496 }
497 })
498 .unwrap_or_default()
499 } else {
500 String::new()
501 };
502
503 (result, original, saved, tee_hint)
504 };
505
506 let mode = if bypass {
507 Some("bypass".to_string())
508 } else if raw {
509 Some("raw".to_string())
510 } else {
511 None
512 };
513
514 let shell_mismatch = if cfg!(windows) && !raw {
515 shell_mismatch_hint(&command, &result_out)
516 } else {
517 String::new()
518 };
519
520 let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
521 let exit_suffix = match exit_code {
525 0 => String::new(),
526 124 => "\n[exit:124 — command timed out]".to_string(),
527 _ => format!("\n[exit:{exit_code}]"),
528 };
529 let nudge = if raw { "" } else { search_tool_nudge(&command) };
530 let final_out = format!(
531 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
532 );
533 let final_out = if let Some(block) = proactive_block {
534 format!("{final_out}{block}")
535 } else {
536 final_out
537 };
538
539 if !raw
540 && !inline
541 && crate::core::config::Config::load()
542 .cache
543 .shell_cache_enabled
544 && let Some(key) = shell_cache_key
545 {
546 let cached = json!({ "text": final_out, "exit_code": exit_code }).to_string();
547 crate::core::ocla::shell_cache_allowlist::SHELL_RESULT_CACHE
548 .insert(key.cache_key(), cached);
549 crate::core::ocla::cache_delivery::record(
551 key.cache_key(),
552 crate::core::ocla::cache_types::DeliveryKind::ShellCommand,
553 key.validator(),
554 None,
555 &final_out,
556 "ctx_shell",
557 );
558 }
559
560 Ok(ToolOutput {
561 text: 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
574fn shell_cache_key(
575 command: &str,
576 cwd: &str,
577 env: &std::collections::HashMap<String, String>,
578) -> Option<ShellCommandKey> {
579 if !crate::core::ocla::shell_cache_allowlist::is_cacheable_command(command) {
580 return None;
581 }
582 let mut env_pairs = env.iter().collect::<Vec<_>>();
583 env_pairs.sort_unstable_by(|left, right| left.0.cmp(right.0));
584 let mut canonical_env = String::new();
585 for (name, value) in env_pairs {
586 canonical_env.push_str(name);
587 canonical_env.push('=');
588 canonical_env.push_str(value);
589 canonical_env.push('\n');
590 }
591 Some(ShellCommandKey {
592 command_normalized: crate::core::ocla::shell_cache_allowlist::normalize_command(command),
593 cwd: if std::path::Path::new(cwd).is_absolute() {
594 "$PROJECT_ROOT".to_string()
595 } else {
596 cwd.to_string()
597 },
598 env_hash: blake3::hash(canonical_env.as_bytes()).to_hex().to_string(),
599 })
600}
601
602fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
605 if let Some(role) = ctx.client_role.as_deref()
606 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
607 {
608 return Some(format!(
609 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
610 ));
611 }
612
613 if ctx.shell_access == Some(false) {
614 return Some(
615 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
616 .to_string(),
617 );
618 }
619
620 None
621}
622
623fn resolve_effective_cwd(
624 session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
625 explicit_cwd: Option<&str>,
626) -> Result<(String, Option<String>), ErrorData> {
627 match session {
628 Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
629 None => Err(ErrorData::internal_error(
630 "session lock timeout — cannot validate working directory",
631 None,
632 )),
633 }
634}
635
636#[allow(clippy::fn_params_excessive_bools)]
637fn resolve_shell_raw_flags(
638 arg_raw: bool,
639 arg_bypass: bool,
640 _env_disabled: bool,
641 env_raw: bool,
642) -> (bool, bool) {
643 let bypass = arg_bypass || env_raw;
644 let raw = arg_raw || bypass;
645 (raw, bypass)
646}
647
648fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
655 exit_code == 124
656 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
657}
658
659fn search_tool_nudge(command: &str) -> &'static str {
660 let cmd = command.trim();
661 let first_word = cmd.split_whitespace().next().unwrap_or("");
662 if !cmd.contains('|') {
663 match first_word {
664 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
665 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
666 }
667 "find" => {
668 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
669 }
670 "ls" | "exa" | "eza" => {
671 return "\n[hint: use ctx_tree for structured directory listing]";
672 }
673 _ => {}
674 }
675 }
676 ""
677}
678
679fn shell_mismatch_hint(command: &str, output: &str) -> String {
680 let shell = crate::shell::shell_name();
681 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
682 let has_error = output.contains("is not recognized")
683 || output.contains("not found")
684 || output.contains("command not found");
685
686 if !has_error {
687 return String::new();
688 }
689
690 let powershell_cmds = [
691 "Get-Content",
692 "Select-Object",
693 "Get-ChildItem",
694 "Set-Location",
695 "Where-Object",
696 "ForEach-Object",
697 "Select-String",
698 "Invoke-Expression",
699 "Write-Output",
700 ];
701 let uses_powershell = powershell_cmds
702 .iter()
703 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
704
705 if is_posix && uses_powershell {
706 format!(
707 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
708 )
709 } else {
710 String::new()
711 }
712}
713
714fn collect_extra_env(
725 args: &Map<String, Value>,
726) -> Result<std::collections::HashMap<String, String>, String> {
727 let mut accepted = std::collections::HashMap::new();
728 let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
729 return Ok(accepted);
730 };
731 let mut rejected: Vec<&str> = Vec::new();
732 for (key, value) in obj {
733 let Some(text) = value.as_str() else { continue };
734 if is_dangerous_env_key(key) {
735 rejected.push(key.as_str());
736 continue;
737 }
738 accepted.insert(key.clone(), text.to_string());
739 }
740 if rejected.is_empty() {
741 return Ok(accepted);
742 }
743 rejected.sort_unstable();
744 let names = rejected
745 .iter()
746 .map(|k| format!("`{k}`"))
747 .collect::<Vec<_>>()
748 .join(", ");
749 let plural = if rejected.len() == 1 { "key" } else { "keys" };
750 Err(format!(
751 "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
752 redirect which binary executes, so lean-ctx never forwards them, and the command would \
753 otherwise have used the inherited value while appearing to honor yours. This is the \
754 same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
755 Invoke the binary by its full path instead, or drop the override."
756 ))
757}
758
759fn is_dangerous_env_key(key: &str) -> bool {
760 const BLOCKED: &[&str] = &[
761 "LD_PRELOAD",
763 "LD_LIBRARY_PATH",
764 "DYLD_INSERT_LIBRARIES",
765 "DYLD_LIBRARY_PATH",
766 "DYLD_FRAMEWORK_PATH",
767 "BASH_ENV",
769 "ENV",
770 "PROMPT_COMMAND",
771 "SHELL",
772 "IFS",
773 "CDPATH",
774 "PATH",
776 "GIT_EXEC_PATH",
777 "GIT_SSH",
778 "GIT_SSH_COMMAND",
779 "HOME",
781 "USER",
782 "LOGNAME",
783 "XDG_CONFIG_HOME",
784 "XDG_DATA_HOME",
785 "XDG_STATE_HOME",
786 "XDG_CACHE_HOME",
787 "PYTHONPATH",
789 "PYTHONSTARTUP",
790 "PYTHONHOME",
791 "NODE_PATH",
792 "NODE_OPTIONS",
793 "RUBYOPT",
794 "RUBYLIB",
795 "GEM_PATH",
796 "GEM_HOME",
797 "PERL5LIB",
798 "PERL5OPT",
799 "CLASSPATH",
800 "JAVA_HOME",
801 "CARGO_HOME",
802 "RUSTUP_HOME",
803 "GOPATH",
804 "GOROOT",
805 ];
806 let upper = key.to_uppercase();
807 if BLOCKED.contains(&upper.as_str()) {
808 return true;
809 }
810 if upper.starts_with("LD_") && upper.ends_with("_PATH") {
811 return true;
812 }
813 if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
815 return true;
816 }
817 false
818}
819
820fn warn_shell_secret_paths(command: &str) {
823 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
824 let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
825 for seg in &segments {
826 let trimmed = seg.trim();
827 let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
828 if tokens.is_empty() {
829 continue;
830 }
831 let base = tokens[0]
832 .rsplit('/')
833 .next()
834 .unwrap_or(&tokens[0])
835 .to_string();
836 if !READ_CMDS.contains(&base.as_str()) {
837 continue;
838 }
839 for tok in &tokens[1..] {
840 if tok.starts_with('-') {
841 continue;
842 }
843 let path = std::path::Path::new(tok.as_str());
844 if crate::core::io_boundary::is_secret_like(path).is_some() {
845 tracing::warn!(
846 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
847 );
848 }
849 }
850 }
851}
852
853fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
858 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
859 && command
860 .lines()
861 .any(|line| line.trim_start().starts_with("cargo test"))
862}
863
864fn foreground_soft_cap_ms() -> u64 {
869 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
870 .ok()
871 .and_then(|v| v.parse().ok())
872 .filter(|&ms| ms > 0)
873 .unwrap_or(110_000)
874}
875
876fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
878 match base {
879 "python" | "python2" | "python3" => Some("python"),
880 "node" => Some("javascript"),
881 "ruby" => Some("ruby"),
882 _ => None,
883 }
884}
885
886fn is_env_assignment_token(token: &str) -> bool {
887 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
888 unquoted.contains('=')
889 && !unquoted.starts_with('-')
890 && !unquoted.starts_with('/')
891 && !unquoted.starts_with('.')
892}
893
894fn prelude_has_compound_operator(prelude: &str) -> bool {
896 let bytes = prelude.as_bytes();
897 let len = bytes.len();
898 let mut i = 0;
899 let mut in_single = false;
900 let mut in_double = false;
901 while i < len {
902 let ch = bytes[i];
903 if in_single {
904 if ch == b'\'' {
905 in_single = false;
906 }
907 i += 1;
908 continue;
909 }
910 if in_double {
911 if ch == b'\\' && i + 1 < len {
912 i += 2;
913 } else {
914 if ch == b'"' {
915 in_double = false;
916 }
917 i += 1;
918 }
919 continue;
920 }
921 match ch {
922 b'\'' => {
923 in_single = true;
924 i += 1;
925 }
926 b'"' => {
927 in_double = true;
928 i += 1;
929 }
930 b';' | b'|' | b'&' | b'(' | b'{' => return true,
931 _ => i += 1,
932 }
933 }
934 false
935}
936
937fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
941 if !command.contains("<<") {
942 return None;
943 }
944
945 let lines: Vec<&str> = command.lines().collect();
946 if lines.is_empty() {
947 return None;
948 }
949
950 let first_line = lines[0];
951 let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
952 if delims.len() != 1 {
953 return None;
954 }
955 let delim = delims[0].clone();
956
957 let heredoc_pos = find_heredoc_operator(first_line)?;
958 let prelude = first_line[..heredoc_pos].trim();
959 if prelude_has_compound_operator(prelude) {
960 return None;
961 }
962
963 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
964
965 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
966 return None;
967 }
968
969 let mut body = String::new();
970 let mut remainder_start: Option<usize> = None;
971 for (idx, line) in lines.iter().enumerate().skip(1) {
972 if line.trim_start_matches('\t').trim() == delim {
973 remainder_start = Some(idx + 1);
974 break;
975 }
976 if !body.is_empty() {
977 body.push('\n');
978 }
979 body.push_str(line);
980 }
981 let remainder_start = remainder_start?;
982 let remainder = if remainder_start < lines.len() {
983 let rest = lines[remainder_start..].join("\n");
984 let rest = rest.trim();
985 if rest.is_empty() {
986 None
987 } else {
988 Some(rest.to_string())
989 }
990 } else {
991 None
992 };
993
994 Some((language, body, remainder))
995}
996
997fn find_heredoc_operator(line: &str) -> Option<usize> {
998 let bytes = line.as_bytes();
999 let len = bytes.len();
1000 let mut i = 0;
1001 let mut in_single = false;
1002 let mut in_double = false;
1003 while i < len {
1004 let ch = bytes[i];
1005 if in_single {
1006 if ch == b'\'' {
1007 in_single = false;
1008 }
1009 i += 1;
1010 continue;
1011 }
1012 if in_double {
1013 if ch == b'\\' && i + 1 < len {
1014 i += 2;
1015 } else {
1016 if ch == b'"' {
1017 in_double = false;
1018 }
1019 i += 1;
1020 }
1021 continue;
1022 }
1023 match ch {
1024 b'\'' => {
1025 in_single = true;
1026 i += 1;
1027 }
1028 b'"' => {
1029 in_double = true;
1030 i += 1;
1031 }
1032 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
1033 if i + 2 < len && bytes[i + 2] == b'<' {
1034 i += 3;
1035 continue;
1036 }
1037 return Some(i);
1038 }
1039 _ => i += 1,
1040 }
1041 }
1042 None
1043}
1044
1045fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
1046 let bytes = line.as_bytes();
1047 let mut i = heredoc_pos + 2;
1048 if i < bytes.len() && bytes[i] == b'-' {
1049 i += 1;
1050 }
1051 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1052 i += 1;
1053 }
1054 let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
1055 return true;
1056 };
1057 !line[next..].trim().is_empty()
1058}
1059
1060fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
1061 let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
1062 let mut idx = 0;
1063 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
1064 idx += 1;
1065 }
1066 if idx >= tokens.len() {
1067 return None;
1068 }
1069 let base = tokens[idx]
1070 .rsplit('/')
1071 .next()
1072 .unwrap_or(tokens[idx].as_str());
1073 let language = interpreter_to_execute_language(base)?;
1074 idx += 1;
1075 match tokens.get(idx) {
1076 None => Some(language),
1077 Some(dash) if dash == "-" => {
1078 if tokens.len() == idx + 1 {
1079 Some(language)
1080 } else {
1081 None
1082 }
1083 }
1084 Some(_) => None,
1085 }
1086}
1087
1088fn resolve_reroute_cwd(
1099 ctx: &ToolContext,
1100 explicit_cwd: Option<&str>,
1101) -> Result<Option<String>, ErrorData> {
1102 let Some(session_lock) = ctx.session.as_ref() else {
1103 if explicit_cwd.is_some() {
1104 return Err(ErrorData::internal_error(
1105 "session not available — cannot validate the requested working directory",
1106 None,
1107 ));
1108 }
1109 return Ok(None);
1110 };
1111 let guard =
1112 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1113 let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1114 Ok(Some(cwd))
1115}
1116
1117fn handle_interpreter_heredoc_reroute(
1118 args: &Map<String, Value>,
1119 ctx: &ToolContext,
1120 language: &str,
1121 code: &str,
1122 remainder: Option<String>,
1123) -> Result<ToolOutput, ErrorData> {
1124 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1125 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1126
1127 let explicit_cwd = get_str(args, "cwd");
1133 let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1134
1135 let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1136 language,
1137 code,
1138 None,
1139 timeout_secs,
1140 exec_cwd.as_deref().map(std::path::Path::new),
1141 );
1142 let reroute_note = format!(
1143 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1144 );
1145 let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1146
1147 let Some(rest_cmd) = remainder else {
1148 return Ok(ToolOutput {
1149 text: format!("{exec_text}{reroute_note}"),
1150 original_tokens: crate::core::tokens::count_tokens(&exec_text),
1151 saved_tokens: 0,
1152 mode: Some("heredoc-reroute".to_string()),
1153 path: None,
1154 changed: false,
1155 shell_outcome: Some(exec_outcome),
1156 content_blocks: None,
1157 });
1158 };
1159
1160 if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1161 let blocked =
1162 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1163 return Ok(ToolOutput {
1164 shell_outcome: Some(ShellOutcome::Blocked),
1165 content_blocks: None,
1166 ..ToolOutput::simple(blocked)
1167 });
1168 }
1169
1170 let effective_cwd =
1173 exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1174
1175 let extra_env = match collect_extra_env(args) {
1176 Ok(env) => env,
1177 Err(message) => {
1178 return Ok(ToolOutput {
1179 shell_outcome: Some(ShellOutcome::Blocked),
1180 content_blocks: None,
1181 ..ToolOutput::simple(message)
1182 });
1183 }
1184 };
1185
1186 let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1187 &rest_cmd,
1188 &effective_cwd,
1189 &extra_env,
1190 timeout_ms,
1191 );
1192 let shell_output = redact_shell_output_secrets(&shell_raw);
1193 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1194 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1195 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1196 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1197 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1198
1199 let shell_text = if raw {
1200 shell_output
1201 } else {
1202 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1203 };
1204 let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1205 let exit_suffix = match shell_exit {
1206 0 => String::new(),
1207 124 => "\n[exit:124 — command timed out]".to_string(),
1208 _ => format!("\n[exit:{shell_exit}]"),
1209 };
1210
1211 let combined = format!(
1212 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1213 );
1214 let token_count = crate::core::tokens::count_tokens(&combined);
1215 Ok(ToolOutput {
1216 text: combined,
1217 original_tokens: token_count,
1218 saved_tokens: 0,
1219 mode: Some("heredoc-reroute".to_string()),
1220 path: None,
1221 changed: false,
1222 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1223 content_blocks: None,
1224 })
1225}
1226
1227fn detect_bare_cat_file(command: &str) -> Option<String> {
1229 let trimmed = command.trim();
1230 let rest = trimmed.strip_prefix("cat ")?;
1231 let rest = rest.trim();
1232 if rest.is_empty()
1233 || rest.contains('|')
1234 || rest.contains('>')
1235 || rest.contains('<')
1236 || rest.contains(';')
1237 || rest.contains('&')
1238 || rest.contains('$')
1239 || rest.starts_with('-')
1240 {
1241 return None;
1242 }
1243 let parts: Vec<&str> = rest.split_whitespace().collect();
1244 if parts.len() != 1 {
1245 return None;
1246 }
1247 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1248 if file_path.is_empty() {
1249 return None;
1250 }
1251 Some(file_path.to_string())
1252}
1253
1254#[cfg(test)]
1255#[path = "ctx_shell_tests.rs"]
1256mod tests;