1use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7 BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
8 get_bool, get_int, get_str,
9};
10use lean_ctx::tool_defs::tool_def;
11
12use super::ctx_shell_background::{format_background_snapshot, redact_shell_output_secrets};
13
14pub struct CtxShellTool;
15
16const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
20
21impl McpTool for CtxShellTool {
22 fn name(&self) -> &'static str {
23 "ctx_shell"
24 }
25
26 fn tool_def(&self) -> Tool {
27 tool_def(
28 "ctx_shell",
29 "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
30 Big logs: narrow the command (grep, sed -n, head/tail).\n\
31 [exit:N] on errors (lossless).\n\
32 POLICY: allowlisted read-only path.\n\
33 A [BLOCKED] command is permanent; ctx_execute shares the same allowlist — fix with \
34 `lean-ctx allow <cmd>`.\n\
35 ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute \
36 (when exposed).",
37 json!({
38 "type": "object",
39 "properties": {
40 "command": { "type": "string", "description": "Shell command" },
41 "raw": { "type": "boolean", "description": "Exact bytes; only for diffs to apply, hashes, encoded output" },
42 "inline": { "type": "boolean", "description": "Verbatim up to archive.inline_max_bytes, else archived" },
43 "cwd": { "type": "string", "description": "Working dir for this call only (not remembered; never moves the base of relative ctx_read/ctx_patch paths)" },
44 "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~90s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
45 "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
46 "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." },
47 "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." },
48 "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
49 }
50 }),
51 )
52 }
53
54 fn handle(
55 &self,
56 args: &Map<String, Value>,
57 ctx: &ToolContext,
58 ) -> Result<ToolOutput, ErrorData> {
59 if let Some(message) = shell_access_denial(ctx) {
60 return Ok(ToolOutput {
61 shell_outcome: Some(ShellOutcome::Blocked),
62 content_blocks: None,
63 ..ToolOutput::simple(message)
64 });
65 }
66
67 if let Some(action) = get_str(args, "background_action") {
68 let id = get_str(args, "job_id").ok_or_else(|| {
69 ErrorData::invalid_params("job_id is required with background_action", None)
70 })?;
71 let is_cancel = action == "cancel";
72 let state = match action.as_str() {
73 "status" => crate::server::background_shell::snapshot(&id),
74 "cancel" => crate::server::background_shell::cancel_snapshot(&id),
75 _ => {
76 return Err(ErrorData::invalid_params(
77 "background_action must be status or cancel",
78 None,
79 ));
80 }
81 };
82 let (text, outcome) = format_background_snapshot(&id, is_cancel, state);
83 return Ok(ToolOutput {
84 shell_outcome: Some(outcome),
85 content_blocks: None,
86 mode: Some(crate::tools::server_metrics::BACKGROUND_POLL_MODE.to_string()),
89 ..ToolOutput::simple(text)
90 });
91 }
92 let command = get_str(args, "command")
93 .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
94 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
95
96 let explicit_cwd = get_str(args, "cwd");
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 note_tool_output(
125 &command,
126 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
127 &ctx.project_root,
128 );
129
130 let config = lean_ctx::core::config::Config::load();
135 let mut write_allow_paths = config.shell_write_allow_paths_effective();
136 write_allow_paths.extend(crate::tools::ctx_shell::capture_roots(
139 &ctx.project_root,
140 &ctx.extra_roots,
141 &config,
142 ));
143 if !lean_ctx::core::config::shell_policy::allow_writes()
144 && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
145 &command,
146 &write_allow_paths,
147 None,
148 resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
149 )
150 {
151 return Ok(ToolOutput {
154 shell_outcome: Some(ShellOutcome::Blocked),
155 content_blocks: None,
156 ..ToolOutput::simple(rejection)
157 });
158 }
159
160 let rights_cwd = resolved_cwd
163 .as_ref()
164 .map_or_else(|| ctx.project_root.clone(), |(cwd, _)| cwd.clone());
165 let env_keys: Vec<&str> = args
169 .get("env")
170 .and_then(Value::as_object)
171 .map(|obj| obj.keys().map(String::as_str).collect())
172 .unwrap_or_default();
173 if let Err(reason) = lean_ctx::core::session_rights::current().check_bash(
174 &command,
175 std::path::Path::new(&rights_cwd),
176 &env_keys,
177 ) {
178 return Ok(ToolOutput {
179 shell_outcome: Some(ShellOutcome::Blocked),
180 content_blocks: None,
181 ..ToolOutput::simple(reason)
182 });
183 }
184
185 if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
186 return tokio::task::block_in_place(|| {
187 handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
188 });
189 }
190
191 let grant = crate::server::shell_approval::current_grant();
192 let run_cwd = resolved_cwd
195 .as_ref()
196 .map(|(cwd, _)| std::path::PathBuf::from(cwd));
197 if let Err(msg) = lean_ctx_shell_policy::with_run_cwd(run_cwd, || {
198 lean_ctx_shell_policy::check_shell_allowlist_granted(&command, &grant)
199 }) {
200 if let Some(plan) = lean_ctx_shell_policy::partial_run(&command, &grant) {
203 let mut sub = args.clone();
204 sub.insert("command".into(), Value::String(plan.run));
205 let mut output = self.handle(&sub, ctx)?;
206 for note in &plan.skipped {
207 output.text.push('\n');
208 output.text.push_str(note);
209 }
210 if matches!(output.shell_outcome, None | Some(ShellOutcome::Exit(0))) {
215 output.shell_outcome = Some(ShellOutcome::Exit(126));
216 }
217 return Ok(output);
218 }
219 return Ok(ToolOutput {
220 shell_outcome: Some(ShellOutcome::Blocked),
221 content_blocks: None,
222 ..ToolOutput::simple(msg.to_string())
223 });
224 }
225
226 warn_shell_secret_paths(&command);
227
228 if let Some(read_path) = detect_bare_cat_file(&command)
232 && let Some(cache_lock) = ctx.cache.as_ref()
233 && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
234 {
235 let result = crate::tools::ctx_read::handle_with_task_resolved(
236 &mut cache,
237 &read_path,
238 "full",
239 crate::tools::CrpMode::Off,
240 None,
241 );
242 let note = format!(
243 "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
244 Use ctx_read(path=\"{read_path}\") directly next time.]"
245 );
246 let out = format!("{}{note}", result.content);
247 let sent = lean_ctx::core::tokens::count_tokens(&out);
248 return Ok(ToolOutput {
249 text: out,
250 original_tokens: sent,
251 saved_tokens: 0,
252 mode: Some("cat-redirect".to_string()),
253 path: Some(read_path),
254 changed: false,
255 shell_outcome: Some(ShellOutcome::Exit(0)),
256 content_blocks: None,
257 });
258 }
259
260 tokio::task::block_in_place(|| {
261 let session_lock = ctx
262 .session
263 .as_ref()
264 .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
265 let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
266 return Err(ErrorData::internal_error("session not available", None));
267 };
268 let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
273 format!(
274 "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
275 )
276 });
277 let checkout_hint = if cwd_jail_hint.is_empty() && explicit_cwd.is_some() {
281 other_checkout_note(&ctx.project_root, &effective_cwd).unwrap_or_default()
282 } else {
283 String::new()
284 };
285 let cwd_jail_hint = format!("{cwd_jail_hint}{checkout_hint}");
286
287 {
288 let Some(mut session) = crate::server::bounded_lock::write_for(
289 session_lock,
290 "ctx_shell_write",
291 SESSION_LOCK_BUDGET,
292 ) else {
293 tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
294 let cmd_clone = command.clone();
295 let cwd_clone = effective_cwd.clone();
296 let extra_env = match collect_extra_env(args) {
297 Ok(env) => env,
298 Err(message) => {
299 return Ok(ToolOutput {
300 shell_outcome: Some(ShellOutcome::Blocked),
301 content_blocks: None,
302 ..ToolOutput::simple(message)
303 });
304 }
305 };
306 let execution = crate::server::execute::execute_command_with_env_captured(
307 &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
308 );
309 let admission = lean_ctx::core::context_admission::admit_tool_output(
310 &execution.output,
311 execution.completeness,
312 );
313 let output = redact_shell_output_secrets(&admission.rendered());
314 let exit_suffix =
317 lean_ctx::shell::exit_status::exit_footer(execution.exit_code);
318 let final_text = format!("{output}{exit_suffix}");
319 let final_admission = lean_ctx::core::context_admission::admit_tool_output(
320 &final_text,
321 execution.completeness,
322 );
323 return Ok(ToolOutput {
324 shell_outcome: Some(ShellOutcome::Exit(execution.exit_code)),
325 content_blocks: None,
326 ..ToolOutput::simple(crate::server::execute::with_notice(
329 execution.notice,
330 final_admission.rendered(),
331 ))
332 });
333 };
334 let root_missing = session
346 .project_root
347 .as_deref()
348 .is_none_or(|r| r.trim().is_empty());
349 if root_missing {
350 let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
351 let start_dir = session.effective_cwd(None);
352 if let Some(root) = lean_ctx::core::protocol::detect_project_root(&start_dir)
353 && home.as_deref() != Some(root.as_str())
354 {
355 session.project_root = Some(root.clone());
356 lean_ctx::core::index_orchestrator::ensure_all_background(&root);
357 }
358 }
359 }
360
361 let arg_raw = get_bool(args, "raw").unwrap_or(false);
362 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
363 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
364 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
365 let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
366
367 let crp_mode = ctx.crp_mode;
368 let cmd_clone = command.clone();
369 let cwd_clone = effective_cwd;
370 let proactive_block = if raw
371 || !lean_ctx::core::profiles::active_profile()
372 .output_hints
373 .proactive_context()
374 {
375 None
376 } else {
377 lean_ctx::core::relevance_tracker::proactive_context(&format!(
378 "ctx_shell command={cmd_clone} cwd={cwd_clone}"
379 ))
380 };
381
382 let extra_env = match collect_extra_env(args) {
383 Ok(env) => env,
384 Err(message) => {
385 return Ok(ToolOutput {
386 shell_outcome: Some(ShellOutcome::Blocked),
387 content_blocks: None,
388 ..ToolOutput::simple(message)
389 });
390 }
391 };
392
393 let inline = get_bool(args, "inline").unwrap_or(false);
394
395 let auto_background = should_auto_background(&cmd_clone, timeout_ms);
396 let detached = get_bool(args, "run_in_background").unwrap_or(false);
397 if detached || auto_background {
398 let lifetime = if detached {
403 timeout_ms.or(Some(lean_ctx::shell::exec::MAX_CALL_TIMEOUT_MS))
404 } else {
405 timeout_ms
406 };
407 let job_id = crate::server::background_shell::start(
408 cmd_clone, cwd_clone, extra_env, lifetime,
409 );
410 let mode = if auto_background {
411 "auto-background"
412 } else {
413 "background"
414 };
415 return Ok(ToolOutput {
416 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
417 state: BackgroundJobState::Running,
418 exit_code: None,
419 job_id: job_id.clone(),
420 archive_id: None,
421 archive_truncated: None,
422 captured_chars: None,
423 archived_chars: None,
424 summary: format!("{mode} job started"),
425 is_error: false,
426 display: None,
427 })),
428 content_blocks: None,
429 ..ToolOutput::simple(format!(
430 "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
431 ))
432 });
433 }
434
435 let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
446 let progress_sender = ctx.progress_sender.clone();
447 let progress_label: String = cmd_clone.chars().take(60).collect();
448 let cap_secs = soft_cap.as_secs_f64();
449 let on_tick = |elapsed: std::time::Duration| {
450 #[allow(clippy::unwrap_or_default)]
451 if let Some(ref ps) = progress_sender
452 && let Some(sender) = ps
453 .lock()
454 .unwrap_or_else(std::sync::PoisonError::into_inner)
455 .as_ref()
456 {
457 sender.send(
458 elapsed.as_secs_f64(),
459 Some(cap_secs),
460 Some(format!(
461 "ctx_shell: {}s elapsed — {progress_label}",
462 elapsed.as_secs()
463 )),
464 );
465 }
466 };
467 let (process_output, exit_code, completeness, retained_withheld, containment_notice) =
468 match crate::server::background_shell::run_foreground_or_detach_captured(
469 cmd_clone.clone(),
470 cwd_clone.clone(),
471 extra_env.clone(),
472 timeout_ms,
473 soft_cap,
474 Some(&on_tick),
475 ctx.cancel.as_ref(),
476 ) {
477 crate::server::background_shell::CapturedForegroundResult::Finished {
478 output,
479 exit_code,
480 completeness,
481 retained_withheld,
482 notice,
483 } => (output, exit_code, completeness, retained_withheld, notice),
484 crate::server::background_shell::CapturedForegroundResult::Detached {
485 job_id,
486 } => {
487 return Ok(ToolOutput {
488 shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
489 state: BackgroundJobState::Running,
490 exit_code: None,
491 job_id: job_id.clone(),
492 archive_id: None,
493 archive_truncated: None,
494 captured_chars: None,
495 archived_chars: None,
496 summary: "auto-detached job is still running".to_string(),
497 is_error: false,
498 display: None,
499 })),
500 content_blocks: None,
501 ..ToolOutput::simple(format!(
505 "[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]",
506 soft_cap.as_secs()
507 ))
508 });
509 }
510 };
511
512 let display_input = if retained_withheld {
513 "[lean-ctx gateway: retained output withheld by storage policy]".to_string()
514 } else {
515 process_output.clone()
516 };
517 let admission =
518 lean_ctx::core::context_admission::admit_tool_output(&display_input, completeness);
519 let output = redact_shell_output_secrets(&admission.rendered());
520 let output = if raw {
521 crate::server::walk_hint::strip_walk_hint(&output).to_string()
522 } else {
523 output
524 };
525
526 let store = lean_ctx::core::context_admission::stores::StoreAdmission::current();
529 let stored_command = store.admit_shell_command(&cmd_clone);
530 let stored_output = (!retained_withheld)
531 .then(|| store.admit_shell_output(&process_output, completeness))
532 .flatten();
533 let storage_allowed = !retained_withheld
534 && store.is_current()
535 && stored_command.is_some()
536 && stored_output.is_some();
537 let command_for_store = stored_command.as_deref().unwrap_or_default();
538 let output_for_store = stored_output.as_deref().unwrap_or_default();
539 if storage_allowed {
540 lean_ctx::core::diagnostics_store::record_from_shell(
541 command_for_store,
542 output_for_store,
543 exit_code,
544 );
545 }
546
547 let (result_out, original, saved, tee_hint) = if raw || inline {
548 let tokens = lean_ctx::core::tokens::count_tokens(&output);
549 (output, tokens, 0, String::new())
550 } else {
551 let _mode_guard = lean_ctx::core::savings_footer::ModeGuard::new("shell");
552 let result =
553 crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
554 let original = lean_ctx::core::tokens::count_tokens(&output);
555 let sent = lean_ctx::core::tokens::count_tokens(&result);
556 let saved = original.saturating_sub(sent);
557
558 let cfg = lean_ctx::core::config::Config::load();
559 let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
562 let tee_hint = if storage_allowed
563 && lean_ctx::shell::tee_policy::should_tee(
564 &cfg.tee_mode,
565 exit_code,
566 output.trim().is_empty() || timeout_notice_only,
567 lean_ctx::shell::tee_policy::output_was_elided(&output, &result),
568 original,
569 sent,
570 ) {
571 lean_ctx::shell::save_tee(command_for_store, output_for_store)
572 .map(|p| {
573 if lean_ctx::core::protected_store::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
574 format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
575 } else if matches!(cfg.tee_mode, lean_ctx::core::config::TeeMode::HighCompression)
576 {
577 let pct = lean_ctx::shell::tee_policy::savings_pct(original, sent);
578 format!(
584 "\n[compressed {pct:.0}%: full output at {p} — `cat` it to re-read it exactly (no MCP), or ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\") for a slice]"
585 )
586 } else {
587 format!("\n[full output: {p} — `cat` it to re-read it exactly (no MCP), or ctx_expand(id=\"{p}\")]")
588 }
589 })
590 .unwrap_or_default()
591 } else {
592 String::new()
593 };
594
595 (result, original, saved, tee_hint)
596 };
597
598 let mode = if bypass {
599 Some("bypass".to_string())
600 } else if raw {
601 Some("raw".to_string())
602 } else {
603 None
604 };
605
606 let shell_mismatch = if cfg!(windows) && !raw {
607 shell_mismatch_hint(&command, &result_out)
608 } else {
609 String::new()
610 };
611
612 let result_out = lean_ctx::core::redaction::redact_text_if_enabled(&result_out);
613 let exit_suffix = lean_ctx::shell::exit_status::exit_footer(exit_code);
617 let nudge = if raw { "" } else { search_tool_nudge(&command) };
618 let final_out = format!(
619 "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
620 );
621 let final_out = if let Some(block) = proactive_block {
622 format!("{final_out}{block}")
623 } else {
624 final_out
625 };
626 let final_admission =
627 lean_ctx::core::context_admission::admit_tool_output(&final_out, completeness);
628 let final_out = final_admission.rendered();
629
630 Ok(ToolOutput {
631 text: crate::server::execute::with_notice(containment_notice, final_out),
634 original_tokens: original,
635 saved_tokens: saved,
636 mode,
637 path: None,
638 changed: false,
639 shell_outcome: Some(ShellOutcome::Exit(exit_code)),
640 content_blocks: None,
641 })
642 })
643 }
644}
645
646pub(crate) fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
650 if let Some(role) = ctx.client_role.as_deref()
651 && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
652 {
653 return Some(format!(
654 "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
655 ));
656 }
657
658 if ctx.shell_access == Some(false) {
659 return Some(
660 "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
661 .to_string(),
662 );
663 }
664
665 None
666}
667
668fn resolve_effective_cwd(
669 session: Option<tokio::sync::OwnedRwLockReadGuard<lean_ctx::core::session::SessionState>>,
670 explicit_cwd: Option<&str>,
671) -> Result<(String, Option<String>), ErrorData> {
672 match session {
673 Some(session) => session
676 .execution_cwd(explicit_cwd)
677 .map(|cwd| (cwd, None))
678 .map_err(|reason| {
679 ErrorData::invalid_params(
680 format!("working directory rejected, command not run: {reason}"),
681 None,
682 )
683 }),
684 None => Err(ErrorData::internal_error(
685 "session lock timeout — cannot validate working directory",
686 None,
687 )),
688 }
689}
690
691#[allow(clippy::fn_params_excessive_bools)]
692fn resolve_shell_raw_flags(
693 arg_raw: bool,
694 arg_bypass: bool,
695 _env_disabled: bool,
696 env_raw: bool,
697) -> (bool, bool) {
698 let bypass = arg_bypass || env_raw;
699 let raw = arg_raw || bypass;
700 (raw, bypass)
701}
702
703fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
710 exit_code == 124
711 && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
712}
713
714fn search_tool_nudge(command: &str) -> &'static str {
715 let cmd = command.trim();
716 let first_word = cmd.split_whitespace().next().unwrap_or("");
717 if !cmd.contains('|') {
718 match first_word {
719 "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
720 return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
721 }
722 "find" => {
723 return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
724 }
725 "ls" | "exa" | "eza" => {
726 return "\n[hint: use ctx_tree for structured directory listing]";
727 }
728 _ => {}
729 }
730 }
731 ""
732}
733
734fn shell_mismatch_hint(command: &str, output: &str) -> String {
735 let shell = lean_ctx::shell::shell_name();
736 let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
737 let has_error = output.contains("is not recognized")
738 || output.contains("not found")
739 || output.contains("command not found");
740
741 if !has_error {
742 return String::new();
743 }
744
745 let powershell_cmds = [
746 "Get-Content",
747 "Select-Object",
748 "Get-ChildItem",
749 "Set-Location",
750 "Where-Object",
751 "ForEach-Object",
752 "Select-String",
753 "Invoke-Expression",
754 "Write-Output",
755 ];
756 let uses_powershell = powershell_cmds
757 .iter()
758 .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
759
760 if is_posix && uses_powershell {
761 format!(
762 "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
763 )
764 } else {
765 String::new()
766 }
767}
768
769fn collect_extra_env(
781 args: &Map<String, Value>,
782) -> Result<std::collections::HashMap<String, String>, String> {
783 let mut accepted = std::collections::HashMap::new();
784 let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
785 return Ok(accepted);
786 };
787 let mut rejected: Vec<&str> = Vec::new();
788 for (key, value) in obj {
789 let Some(text) = value.as_str() else { continue };
790 if lean_ctx_shell_policy::env_override_refused(key, text) {
791 rejected.push(key.as_str());
792 continue;
793 }
794 accepted.insert(key.clone(), text.to_string());
795 }
796 if rejected.is_empty() {
797 return Ok(accepted);
798 }
799 rejected.sort_unstable();
800 let names = rejected
801 .iter()
802 .map(|k| format!("`{k}`"))
803 .collect::<Vec<_>>()
804 .join(", ");
805 let plural = if rejected.len() == 1 { "key" } else { "keys" };
806 Err(format!(
807 "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
808 redirect which binary executes, so lean-ctx never forwards them, and the command would \
809 otherwise have used the inherited value while appearing to honor yours. This is the \
810 same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
811 Invoke the binary by its full path instead, or drop the override."
812 ))
813}
814
815fn warn_shell_secret_paths(command: &str) {
818 const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
819 let segments = lean_ctx_shell_policy::extract_all_commands_pub(command);
820 for seg in &segments {
821 let trimmed = seg.trim();
822 let tokens = lean_ctx_shell_policy::shell_tokenize(trimmed);
823 if tokens.is_empty() {
824 continue;
825 }
826 let base = tokens[0]
827 .rsplit('/')
828 .next()
829 .unwrap_or(&tokens[0])
830 .to_string();
831 if !READ_CMDS.contains(&base.as_str()) {
832 continue;
833 }
834 for tok in &tokens[1..] {
835 if tok.starts_with('-') {
836 continue;
837 }
838 let path = std::path::Path::new(tok.as_str());
839 if lean_ctx::core::io_boundary::is_secret_like(path).is_some() {
840 tracing::warn!(
841 "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
842 );
843 }
844 }
845 }
846}
847
848fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
853 timeout_ms.is_some_and(|timeout| timeout >= 300_000)
854 && command
855 .lines()
856 .any(|line| line.trim_start().starts_with("cargo test"))
857}
858
859pub(crate) const DEFAULT_FOREGROUND_SOFT_CAP_MS: u64 = 90_000;
870
871fn foreground_soft_cap_ms() -> u64 {
872 std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
873 .ok()
874 .and_then(|v| v.parse().ok())
875 .filter(|&ms| ms > 0)
876 .unwrap_or(DEFAULT_FOREGROUND_SOFT_CAP_MS)
877}
878
879fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
881 match base {
882 "python" | "python2" | "python3" => Some("python"),
883 "node" => Some("javascript"),
884 "ruby" => Some("ruby"),
885 _ => None,
886 }
887}
888
889fn is_env_assignment_token(token: &str) -> bool {
890 let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
891 unquoted.contains('=')
892 && !unquoted.starts_with('-')
893 && !unquoted.starts_with('/')
894 && !unquoted.starts_with('.')
895}
896
897fn prelude_has_compound_operator(prelude: &str) -> bool {
899 let bytes = prelude.as_bytes();
900 let len = bytes.len();
901 let mut i = 0;
902 let mut in_single = false;
903 let mut in_double = false;
904 while i < len {
905 let ch = bytes[i];
906 if in_single {
907 if ch == b'\'' {
908 in_single = false;
909 }
910 i += 1;
911 continue;
912 }
913 if in_double {
914 if ch == b'\\' && i + 1 < len {
915 i += 2;
916 } else {
917 if ch == b'"' {
918 in_double = false;
919 }
920 i += 1;
921 }
922 continue;
923 }
924 match ch {
925 b'\'' => {
926 in_single = true;
927 i += 1;
928 }
929 b'"' => {
930 in_double = true;
931 i += 1;
932 }
933 b';' | b'|' | b'&' | b'(' | b'{' => return true,
934 _ => i += 1,
935 }
936 }
937 false
938}
939
940fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
944 if !command.contains("<<") {
945 return None;
946 }
947
948 let lines: Vec<&str> = command.lines().collect();
949 if lines.is_empty() {
950 return None;
951 }
952
953 let first_line = lines[0];
954 let delims = lean_ctx_shell_policy::heredoc_delims(first_line, false);
955 if delims.len() != 1 {
956 return None;
957 }
958 let delim = delims[0].clone();
959
960 let heredoc_pos = find_heredoc_operator(first_line)?;
961 let prelude = first_line[..heredoc_pos].trim();
962 if prelude_has_compound_operator(prelude) {
963 return None;
964 }
965
966 let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
967
968 if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
969 return None;
970 }
971
972 let mut body = String::new();
973 let mut remainder_start: Option<usize> = None;
974 for (idx, line) in lines.iter().enumerate().skip(1) {
975 if line.trim_start_matches('\t').trim() == delim {
976 remainder_start = Some(idx + 1);
977 break;
978 }
979 if !body.is_empty() {
980 body.push('\n');
981 }
982 body.push_str(line);
983 }
984 let remainder_start = remainder_start?;
985 let remainder = if remainder_start < lines.len() {
986 let rest = lines[remainder_start..].join("\n");
987 let rest = rest.trim();
988 if rest.is_empty() {
989 None
990 } else {
991 Some(rest.to_string())
992 }
993 } else {
994 None
995 };
996
997 Some((language, body, remainder))
998}
999
1000fn find_heredoc_operator(line: &str) -> Option<usize> {
1001 let bytes = line.as_bytes();
1002 let len = bytes.len();
1003 let mut i = 0;
1004 let mut in_single = false;
1005 let mut in_double = false;
1006 while i < len {
1007 let ch = bytes[i];
1008 if in_single {
1009 if ch == b'\'' {
1010 in_single = false;
1011 }
1012 i += 1;
1013 continue;
1014 }
1015 if in_double {
1016 if ch == b'\\' && i + 1 < len {
1017 i += 2;
1018 } else {
1019 if ch == b'"' {
1020 in_double = false;
1021 }
1022 i += 1;
1023 }
1024 continue;
1025 }
1026 match ch {
1027 b'\'' => {
1028 in_single = true;
1029 i += 1;
1030 }
1031 b'"' => {
1032 in_double = true;
1033 i += 1;
1034 }
1035 b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
1036 if i + 2 < len && bytes[i + 2] == b'<' {
1037 i += 3;
1038 continue;
1039 }
1040 return Some(i);
1041 }
1042 _ => i += 1,
1043 }
1044 }
1045 None
1046}
1047
1048fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
1049 let bytes = line.as_bytes();
1050 let mut i = heredoc_pos + 2;
1051 if i < bytes.len() && bytes[i] == b'-' {
1052 i += 1;
1053 }
1054 while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
1055 i += 1;
1056 }
1057 let Some((_, _, next)) = lean_ctx_shell_policy::read_heredoc_delim(bytes, i) else {
1058 return true;
1059 };
1060 !line[next..].trim().is_empty()
1061}
1062
1063fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
1064 let tokens = lean_ctx_shell_policy::shell_tokenize(prelude.trim());
1065 let mut idx = 0;
1066 while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
1067 idx += 1;
1068 }
1069 if idx >= tokens.len() {
1070 return None;
1071 }
1072 let base = tokens[idx]
1073 .rsplit('/')
1074 .next()
1075 .unwrap_or(tokens[idx].as_str());
1076 let language = interpreter_to_execute_language(base)?;
1077 idx += 1;
1078 match tokens.get(idx) {
1079 None => Some(language),
1080 Some(dash) if dash == "-" => {
1081 if tokens.len() == idx + 1 {
1082 Some(language)
1083 } else {
1084 None
1085 }
1086 }
1087 Some(_) => None,
1088 }
1089}
1090
1091fn resolve_reroute_cwd(
1102 ctx: &ToolContext,
1103 explicit_cwd: Option<&str>,
1104) -> Result<Option<String>, ErrorData> {
1105 let Some(session_lock) = ctx.session.as_ref() else {
1106 if explicit_cwd.is_some() {
1107 return Err(ErrorData::internal_error(
1108 "session not available — cannot validate the requested working directory",
1109 None,
1110 ));
1111 }
1112 return Ok(None);
1113 };
1114 let guard =
1115 crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1116 let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1117 Ok(Some(cwd))
1118}
1119
1120fn handle_interpreter_heredoc_reroute(
1121 args: &Map<String, Value>,
1122 ctx: &ToolContext,
1123 language: &str,
1124 code: &str,
1125 remainder: Option<String>,
1126) -> Result<ToolOutput, ErrorData> {
1127 let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1128 let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1129
1130 let explicit_cwd = get_str(args, "cwd");
1136 let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1137
1138 let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1139 language,
1140 code,
1141 None,
1142 timeout_secs,
1143 exec_cwd.as_deref().map(std::path::Path::new),
1144 );
1145 let reroute_note = format!(
1146 "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1147 );
1148 let exec_completeness = lean_ctx::core::context_admission::OutputCompleteness {
1149 reader_incomplete: true,
1150 ..lean_ctx::core::context_admission::OutputCompleteness::complete()
1151 };
1152 let exec_admission =
1153 lean_ctx::core::context_admission::admit_tool_output(&exec_text, exec_completeness);
1154 let exec_text = lean_ctx::core::redaction::redact_text_if_enabled(&exec_admission.rendered());
1155
1156 let Some(rest_cmd) = remainder else {
1157 let final_text = format!("{exec_text}{reroute_note}");
1158 let final_admission =
1159 lean_ctx::core::context_admission::admit_tool_output(&final_text, exec_completeness);
1160 let text = final_admission.rendered();
1161 return Ok(ToolOutput {
1162 original_tokens: lean_ctx::core::tokens::count_tokens(&text),
1163 text,
1164 saved_tokens: 0,
1165 mode: Some("heredoc-reroute".to_string()),
1166 path: None,
1167 changed: false,
1168 shell_outcome: Some(exec_outcome),
1169 content_blocks: None,
1170 });
1171 };
1172
1173 if let Err(msg) = lean_ctx_shell_policy::check_shell_allowlist_granted(
1174 &rest_cmd,
1175 &crate::server::shell_approval::current_grant(),
1176 ) {
1177 let blocked =
1178 format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1179 return Ok(ToolOutput {
1180 shell_outcome: Some(ShellOutcome::Blocked),
1181 content_blocks: None,
1182 ..ToolOutput::simple(blocked)
1183 });
1184 }
1185
1186 let effective_cwd =
1189 exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1190
1191 let extra_env = match collect_extra_env(args) {
1192 Ok(env) => env,
1193 Err(message) => {
1194 return Ok(ToolOutput {
1195 shell_outcome: Some(ShellOutcome::Blocked),
1196 content_blocks: None,
1197 ..ToolOutput::simple(message)
1198 });
1199 }
1200 };
1201
1202 let shell_execution = crate::server::execute::execute_command_with_env_captured(
1203 &rest_cmd,
1204 &effective_cwd,
1205 &extra_env,
1206 timeout_ms,
1207 );
1208 let shell_exit = shell_execution.exit_code;
1209 let shell_admission = lean_ctx::core::context_admission::admit_tool_output(
1210 &shell_execution.output,
1211 shell_execution.completeness,
1212 );
1213 let shell_output = redact_shell_output_secrets(&shell_admission.rendered());
1214 let arg_raw = get_bool(args, "raw").unwrap_or(false);
1215 let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1216 let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1217 let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1218 let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1219
1220 let shell_text = if raw {
1221 shell_output
1222 } else {
1223 crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1224 };
1225 let shell_text = lean_ctx::core::redaction::redact_text_if_enabled(&shell_text);
1226 let exit_suffix = lean_ctx::shell::exit_status::exit_footer(shell_exit);
1227
1228 let combined = format!(
1229 "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1230 );
1231 let mut completeness = shell_execution.completeness;
1232 completeness.reader_incomplete = true;
1235 let final_admission =
1236 lean_ctx::core::context_admission::admit_tool_output(&combined, completeness);
1237 let text =
1239 crate::server::execute::with_notice(shell_execution.notice, final_admission.rendered());
1240 let token_count = lean_ctx::core::tokens::count_tokens(&text);
1241 Ok(ToolOutput {
1242 text,
1243 original_tokens: token_count,
1244 saved_tokens: 0,
1245 mode: Some("heredoc-reroute".to_string()),
1246 path: None,
1247 changed: false,
1248 shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1249 content_blocks: None,
1250 })
1251}
1252
1253fn detect_bare_cat_file(command: &str) -> Option<String> {
1255 let trimmed = command.trim();
1256 let rest = trimmed.strip_prefix("cat ")?;
1257 let rest = rest.trim();
1258 if rest.is_empty()
1259 || rest.contains('|')
1260 || rest.contains('>')
1261 || rest.contains('<')
1262 || rest.contains(';')
1263 || rest.contains('&')
1264 || rest.contains('$')
1265 || rest.starts_with('-')
1266 {
1267 return None;
1268 }
1269 let parts: Vec<&str> = rest.split_whitespace().collect();
1270 if parts.len() != 1 {
1271 return None;
1272 }
1273 let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1274 if file_path.is_empty() {
1275 return None;
1276 }
1277 Some(file_path.to_string())
1278}
1279
1280fn nearest_git_boundary(start: &std::path::Path) -> Option<std::path::PathBuf> {
1284 let start = lean_ctx::core::pathutil::safe_canonicalize_or_self(start);
1285 let found = std::path::PathBuf::from(lean_ctx::core::command_root::promote_to_git_root(
1286 &start.to_string_lossy(),
1287 ));
1288 found.join(".git").exists().then_some(found)
1289}
1290
1291fn other_checkout_note(project_root: &str, cwd: &str) -> Option<String> {
1295 if project_root.trim().is_empty() || project_root == "." {
1296 return None;
1297 }
1298 let root_boundary = nearest_git_boundary(std::path::Path::new(project_root))?;
1299 let cwd_boundary = nearest_git_boundary(std::path::Path::new(cwd))?;
1300 (root_boundary != cwd_boundary).then(|| {
1301 format!(
1302 "\n[note: relative paths in ctx_read/ctx_patch resolve to {project_root}; use absolute paths for {}]",
1303 cwd_boundary.display()
1304 )
1305 })
1306}
1307
1308fn note_tool_output(command: &str, cwd: Option<&str>, project_root: &str) {
1313 use lean_ctx::core::context_admission::{capture, origin};
1314 let Some(found) = lean_ctx::core::context_admission::tool_output::classify(command) else {
1315 if let Some(capture) = capture::current() {
1318 capture.set_output_class(lean_ctx::core::patterns::output_class(command));
1319 }
1320 return;
1321 };
1322 let class = found.class();
1323 if let Some(capture) = capture::current() {
1324 capture.set_output_class(class.clone());
1325 }
1326 capture::note_origin(&class);
1327 let root = std::path::Path::new(project_root);
1328 let base = cwd.map_or(root, std::path::Path::new);
1329 for download in &found.downloads {
1330 let class = origin::download_origin(root, base, std::path::Path::new(download)).map_or(
1331 origin::SourceClass::Unclassified { tool: "download" },
1332 origin::SourceClass::External,
1333 );
1334 capture::note_origin(&class);
1335 }
1336}
1337
1338#[cfg(test)]
1339#[path = "ctx_shell_tests.rs"]
1340mod tests;