Skip to main content

lean_ctx/tools/registered/
ctx_shell.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6    BackgroundJobState, BackgroundShellOutcome, McpTool, ShellOutcome, ToolContext, ToolOutput,
7    get_bool, get_int, get_str,
8};
9use crate::tool_defs::tool_def;
10
11use super::ctx_shell_background::{format_background_state, redact_shell_output_secrets};
12
13pub struct CtxShellTool;
14
15/// Shell execution must never wait through the general-purpose session-lock
16/// recovery window. The command can run without bookkeeping; cwd validation
17/// cannot, so it fails promptly and lets the client retry.
18const SESSION_LOCK_BUDGET: std::time::Duration = std::time::Duration::from_millis(250);
19
20impl McpTool for CtxShellTool {
21    fn name(&self) -> &'static str {
22        "ctx_shell"
23    }
24
25    fn tool_def(&self) -> Tool {
26        tool_def(
27            "ctx_shell",
28            "WORKFLOW: preferred — auto-compresses output (build/test/log).\n\
29              raw=true for verbatim output; inline=true for moderately-sized verbatim output.\n\
30             [exit:N] on errors (lossless).\n\
31             POLICY: allowlisted read-only path.\n\
32             A [BLOCKED] command is permanent; ctx_execute shares the same allowlist — fix with \
33             `lean-ctx allow <cmd>`.\n\
34             ANTIPATTERN: multi-line scripts, sh/bash script.sh, $var-as-command → ctx_execute \
35             (when exposed).",
36            json!({
37                "type": "object",
38                "properties": {
39                    "command": { "type": "string", "description": "Shell command" },
40                    "raw": { "type": "boolean", "description": "Skip compression (verbatim)" },
41                    "inline": { "type": "boolean", "description": "Return verbatim output inline up to archive.inline_max_bytes; larger output uses the archive/firewall" },
42                    "cwd": { "type": "string", "description": "Working dir (persists across calls)" },
43                    "timeout_ms": { "type": "integer", "description": "Job lifetime in ms (max 3600000) — NOT the inline wait. A command still running at the ~110s foreground cap detaches to a pollable shell_* job and keeps running up to timeout_ms. Overridden by LEAN_CTX_SHELL_TIMEOUT_MS." },
44                    "env": { "type": "object", "description": "Extra env vars", "additionalProperties": { "type": "string" } },
45                    "run_in_background": { "type": "boolean", "description": "Detach immediately and return a job id. The command keeps timeout_ms; poll or cancel with background_action and job_id." },
46                    "background_action": { "type": "string", "enum": ["status", "cancel"], "description": "Inspect or cancel a background ctx_shell job; terminal status may include archiveId. Evicted/expired jobs return a structured lookup error." },
47                    "job_id": { "type": "string", "description": "Job id returned by run_in_background." }
48                }
49            }),
50        )
51    }
52
53    fn handle(
54        &self,
55        args: &Map<String, Value>,
56        ctx: &ToolContext,
57    ) -> Result<ToolOutput, ErrorData> {
58        if let Some(message) = shell_access_denial(ctx) {
59            return Ok(ToolOutput {
60                shell_outcome: Some(ShellOutcome::Blocked),
61                content_blocks: None,
62                ..ToolOutput::simple(message)
63            });
64        }
65
66        if let Some(action) = get_str(args, "background_action") {
67            let id = get_str(args, "job_id").ok_or_else(|| {
68                ErrorData::invalid_params("job_id is required with background_action", None)
69            })?;
70            let is_cancel = action == "cancel";
71            let state = match action.as_str() {
72                "status" => crate::server::background_shell::status(&id),
73                "cancel" => crate::server::background_shell::cancel(&id),
74                _ => {
75                    return Err(ErrorData::invalid_params(
76                        "background_action must be status or cancel",
77                        None,
78                    ));
79                }
80            };
81            let (text, outcome) = format_background_state(&id, is_cancel, state);
82            return Ok(ToolOutput {
83                shell_outcome: Some(outcome),
84                content_blocks: None,
85                // Looking after a running job is no new command: the session
86                // stats leave it out (`server_metrics::counts_in_session`).
87                mode: Some(crate::tools::server_metrics::BACKGROUND_POLL_MODE.to_string()),
88                ..ToolOutput::simple(text)
89            });
90        }
91        let command = get_str(args, "command")
92            .ok_or_else(|| ErrorData::invalid_params("command is required", None))?;
93        let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
94
95        // #1811: the write-doctrine guard classifies the *destination*, so a
96        // relative redirect target only means something once it is placed
97        // against the directory the command runs in. That directory is not the
98        // `cwd` argument: `effective_cwd_checked` replaces a jail-rejected one
99        // with the project root, and falls back to the session cwd when none
100        // was passed. So it is resolved once, here, and the same value feeds
101        // both the guard and the run below — resolving it twice would let the
102        // two answers drift, and a guard that judged a directory the command
103        // never ran in is exactly the bug #1811 reports.
104        let explicit_cwd = get_str(args, "cwd");
105        let had_explicit_cwd = explicit_cwd.is_some();
106        // Without a session (one-shot CLI contexts) the run directory cannot be
107        // resolved here. That is not an error yet — the cat-redirect below never
108        // needs one — so the guard is simply told nothing and keeps its stricter
109        // pre-#1811 refusal, and the session requirement is raised further down,
110        // where running the command actually depends on it.
111        let resolved_cwd = match ctx.session.as_ref() {
112            Some(session_lock) => Some(tokio::task::block_in_place(|| {
113                let guard = crate::server::bounded_lock::read_for(
114                    session_lock,
115                    "ctx_shell_cwd",
116                    SESSION_LOCK_BUDGET,
117                );
118                resolve_effective_cwd(guard, explicit_cwd.as_deref())
119            })?),
120            None => None,
121        };
122
123        // The write-doctrine check (no `>`, `tee`, heredoc-to-file, curl -o, …)
124        // is an MCP-payload-safety convention, not a security boundary, so it is
125        // opt-out via `shell_allow_writes` (#523). The real command gating
126        // (`check_shell_allowlist`, below) is NOT affected by this flag.
127        let config = crate::core::config::Config::load();
128        let mut write_allow_paths = config.shell_write_allow_paths_effective();
129        // The session's project and the jail's allow entries are capture
130        // targets too, so no project root is passed as a refusal below.
131        write_allow_paths.extend(crate::tools::ctx_shell::capture_roots(
132            &ctx.project_root,
133            &ctx.extra_roots,
134            &config,
135        ));
136        if !config.shell_allow_writes_effective()
137            && let Some(rejection) = crate::tools::ctx_shell::validate_command_in_cwd(
138                &command,
139                &write_allow_paths,
140                None,
141                resolved_cwd.as_ref().map(|(cwd, _)| cwd.as_str()),
142            )
143        {
144            // The command never ran — report as a tool error so MCP clients
145            // (guards, retry logic) can detect it programmatically (#389).
146            return Ok(ToolOutput {
147                shell_outcome: Some(ShellOutcome::Blocked),
148                content_blocks: None,
149                ..ToolOutput::simple(rejection)
150            });
151        }
152
153        if let Some((lang, code, remainder)) = detect_heredoc_reroute(&command) {
154            return tokio::task::block_in_place(|| {
155                handle_interpreter_heredoc_reroute(args, ctx, &lang, &code, remainder)
156            });
157        }
158
159        if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&command) {
160            return Ok(ToolOutput {
161                shell_outcome: Some(ShellOutcome::Blocked),
162                content_blocks: None,
163                ..ToolOutput::simple(msg.to_string())
164            });
165        }
166
167        warn_shell_secret_paths(&command);
168
169        // #842: a bare `cat <file>` is better served by ctx_read — it delivers
170        // content inline instead of firewalling/archiving the output, avoiding
171        // a mandatory ctx_expand round-trip for agents with cat-muscle-memory.
172        if let Some(read_path) = detect_bare_cat_file(&command)
173            && let Some(cache_lock) = ctx.cache.as_ref()
174            && let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "cat_redirect")
175        {
176            let result = crate::tools::ctx_read::handle_with_task_resolved(
177                &mut cache,
178                &read_path,
179                "full",
180                crate::tools::CrpMode::Off,
181                None,
182            );
183            let note = format!(
184                "\n[ctx_shell: bare `cat` redirected to ctx_read for inline delivery. \
185                         Use ctx_read(path=\"{read_path}\") directly next time.]"
186            );
187            let out = format!("{}{note}", result.content);
188            let sent = crate::core::tokens::count_tokens(&out);
189            return Ok(ToolOutput {
190                text: out,
191                original_tokens: sent,
192                saved_tokens: 0,
193                mode: Some("cat-redirect".to_string()),
194                path: Some(read_path),
195                changed: false,
196                shell_outcome: Some(ShellOutcome::Exit(0)),
197                content_blocks: None,
198            });
199        }
200
201        tokio::task::block_in_place(|| {
202            let session_lock = ctx
203                .session
204                .as_ref()
205                .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
206            let Some((effective_cwd, cwd_jail_reason)) = resolved_cwd else {
207                return Err(ErrorData::internal_error("session not available", None));
208            };
209            // A `cwd` rejected by the project-root jail is silently replaced with
210            // the root (deliberate sandboxing). Surface that swap as a one-line
211            // hint so the caller does not mistake the run dir for the requested
212            // one (#629); appended at the end of the output like the other hints.
213            let cwd_jail_reason_was_none = cwd_jail_reason.is_none();
214            let cwd_jail_hint = cwd_jail_reason.map_or_else(String::new, |reason| {
215                format!(
216                    "\n[cwd: requested path rejected by project-root jail ({reason}) \u{2014} ran in {effective_cwd} instead]"
217                )
218            });
219
220            {
221                let Some(mut session) = crate::server::bounded_lock::write_for(
222                    session_lock,
223                    "ctx_shell_write",
224                    SESSION_LOCK_BUDGET,
225                ) else {
226                    tracing::debug!("[ctx_shell: session lock timeout, proceeding without update]");
227                    let cmd_clone = command.clone();
228                    let cwd_clone = effective_cwd.clone();
229                    let extra_env = match collect_extra_env(args) {
230                        Ok(env) => env,
231                        Err(message) => {
232                            return Ok(ToolOutput {
233                                shell_outcome: Some(ShellOutcome::Blocked),
234                                content_blocks: None,
235                                ..ToolOutput::simple(message)
236                            });
237                        }
238                    };
239                    let (raw_output, exit_code) = crate::server::execute::execute_command_with_env(
240                        &cmd_clone, &cwd_clone, &extra_env, timeout_ms,
241                    );
242                    let output = redact_shell_output_secrets(&raw_output);
243                    // Keep failure reporting consistent on this degraded path:
244                    // same [exit:N] footer and the same structured outcome (#389).
245                    let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
246                    return Ok(ToolOutput {
247                        shell_outcome: Some(ShellOutcome::Exit(exit_code)),
248                        content_blocks: None,
249                        ..ToolOutput::simple(format!("{output}{exit_suffix}"))
250                    });
251                };
252                // #707: a jail-accepted explicit `cwd` param is the client
253                // telling us where it now works (worktree switches arrive
254                // this way, not as `cd` commands) — persist it so path
255                // resolution's divergence check tracks the live checkout.
256                if had_explicit_cwd && cwd_jail_reason_was_none {
257                    session.note_explicit_cwd(&effective_cwd);
258                }
259                session.update_shell_cwd(&command);
260                let root_missing = session
261                    .project_root
262                    .as_deref()
263                    .is_none_or(|r| r.trim().is_empty());
264                if root_missing {
265                    let home = dirs::home_dir().map(|h| h.to_string_lossy().to_string());
266                    if let Some(root) = crate::core::protocol::detect_project_root(&effective_cwd)
267                        && home.as_deref() != Some(root.as_str())
268                    {
269                        session.project_root = Some(root.clone());
270                        crate::core::index_orchestrator::ensure_all_background(&root);
271                    }
272                }
273            }
274
275            let arg_raw = get_bool(args, "raw").unwrap_or(false);
276            let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
277            let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
278            let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
279            let (raw, bypass) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
280
281            let crp_mode = ctx.crp_mode;
282            let cmd_clone = command.clone();
283            let cwd_clone = effective_cwd;
284            let proactive_block = if raw
285                || !crate::core::profiles::active_profile()
286                    .output_hints
287                    .proactive_context()
288            {
289                None
290            } else {
291                crate::core::relevance_tracker::proactive_context(&format!(
292                    "ctx_shell command={cmd_clone} cwd={cwd_clone}"
293                ))
294            };
295
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
307            let inline = get_bool(args, "inline").unwrap_or(false);
308
309            let auto_background = should_auto_background(&cmd_clone, timeout_ms);
310            if get_bool(args, "run_in_background").unwrap_or(false) || auto_background {
311                let job_id = crate::server::background_shell::start(
312                    cmd_clone, cwd_clone, extra_env, timeout_ms,
313                );
314                let mode = if auto_background {
315                    "auto-background"
316                } else {
317                    "background"
318                };
319                return Ok(ToolOutput {
320                    shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
321                        state: BackgroundJobState::Running,
322                        exit_code: None,
323                        job_id: job_id.clone(),
324                        archive_id: None,
325                        archive_truncated: None,
326                        captured_chars: None,
327                        archived_chars: None,
328                        summary: format!("{mode} job started"),
329                        is_error: false,
330                        display: None,
331                    })),
332                    content_blocks: None,
333                    ..ToolOutput::simple(format!(
334                        "[{mode}:{job_id} started — use ctx_shell(background_action=\"status\", job_id=\"{job_id}\") to poll or background_action=\"cancel\" to stop it]"
335                    ))
336                });
337            }
338
339            // Foreground runs still detach onto a pollable job if they outlast
340            // the soft cap, so the MCP host's ~120s abort never strands the
341            // result behind an unresolvable task id (#1106).
342            //
343            // #1173: `timeout_ms` is the *job's* lifetime, never the foreground
344            // wait, so it must not raise this cap. Raising it bought no extra
345            // inline wait — the host aborts at ~120s regardless — it only
346            // suppressed our own detach, producing exactly the unresolvable
347            // task id the cap exists to prevent. Separate knobs, one direction:
348            // `LEAN_CTX_SHELL_FG_CAP_MS` moves the cap, `timeout_ms` does not.
349            let soft_cap = std::time::Duration::from_millis(foreground_soft_cap_ms());
350            let progress_sender = ctx.progress_sender.clone();
351            let progress_label: String = cmd_clone.chars().take(60).collect();
352            let cap_secs = soft_cap.as_secs_f64();
353            let on_tick = |elapsed: std::time::Duration| {
354                #[allow(clippy::unwrap_or_default)]
355                if let Some(ref ps) = progress_sender
356                    && let Some(sender) = ps
357                        .lock()
358                        .unwrap_or_else(std::sync::PoisonError::into_inner)
359                        .as_ref()
360                {
361                    sender.send(
362                        elapsed.as_secs_f64(),
363                        Some(cap_secs),
364                        Some(format!(
365                            "ctx_shell: {}s elapsed — {progress_label}",
366                            elapsed.as_secs()
367                        )),
368                    );
369                }
370            };
371            let (raw_output, exit_code) =
372                match crate::server::background_shell::run_foreground_or_detach(
373                    cmd_clone.clone(),
374                    cwd_clone.clone(),
375                    extra_env.clone(),
376                    timeout_ms,
377                    soft_cap,
378                    Some(&on_tick),
379                    ctx.cancel.as_ref(),
380                ) {
381                    crate::server::background_shell::ForegroundResult::Finished {
382                        output,
383                        exit_code,
384                    } => (output, exit_code),
385                    crate::server::background_shell::ForegroundResult::Detached { job_id } => {
386                        return Ok(ToolOutput {
387                            shell_outcome: Some(ShellOutcome::Background(BackgroundShellOutcome {
388                                state: BackgroundJobState::Running,
389                                exit_code: None,
390                                job_id: job_id.clone(),
391                                archive_id: None,
392                                archive_truncated: None,
393                                captured_chars: None,
394                                archived_chars: None,
395                                summary: "auto-detached job is still running".to_string(),
396                                is_error: false,
397                                display: None,
398                            })),
399                            content_blocks: None,
400                            // #1173: a detach is not a failure — the command is
401                            // alive and its output is recoverable, so say so
402                            // rather than leaving the caller to infer a hang.
403                            ..ToolOutput::simple(format!(
404                                "[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]",
405                                soft_cap.as_secs()
406                            ))
407                        });
408                    }
409                };
410
411            // Structured diagnostics (#499) — same hook as the CLI path.
412            crate::core::diagnostics_store::record_from_shell(&cmd_clone, &raw_output, exit_code);
413
414            let output = redact_shell_output_secrets(&raw_output);
415            let output = if raw {
416                crate::server::walk_hint::strip_walk_hint(&output).to_string()
417            } else {
418                output
419            };
420
421            let (result_out, original, saved, tee_hint) = if raw || inline {
422                let tokens = crate::core::tokens::count_tokens(&output);
423                (output, tokens, 0, String::new())
424            } else {
425                let _mode_guard = crate::core::savings_footer::ModeGuard::new("shell");
426                let result =
427                    crate::tools::ctx_shell::handle(&cmd_clone, &output, exit_code, crp_mode);
428                let original = crate::core::tokens::count_tokens(&output);
429                let sent = crate::core::tokens::count_tokens(&result);
430                let saved = original.saturating_sub(sent);
431
432                let cfg = crate::core::config::Config::load();
433                // Shared tee policy (#811): identical decision to the CLI path —
434                // `Failures` keys off the real exit code, not a substring match.
435                let timeout_notice_only = is_timeout_notice_only(&output, exit_code);
436                let tee_hint = if crate::shell::tee_policy::should_tee(
437                    &cfg.tee_mode,
438                    exit_code,
439                    output.trim().is_empty() || timeout_notice_only,
440                    crate::shell::tee_policy::output_was_elided(&output, &result),
441                    original,
442                    sent,
443                ) {
444                    crate::shell::save_tee(&cmd_clone, &output)
445                        .map(|p| {
446                            if crate::cli::enforce_protected_store_path(std::path::Path::new(&p)).is_err() {
447                                format!("\n[full output: ctx_expand(id=\"{p}\", search=\"…\"|head=N|json_path=\"…\")]")
448                            } else if matches!(cfg.tee_mode, crate::core::config::TeeMode::HighCompression)
449                            {
450                                let pct = crate::shell::tee_policy::savings_pct(original, sent);
451                                // Recovery grammar is path-first: agents without ctx_expand
452                                // can still read the saved artifact directly (#936).
453                                format!(
454                                    "\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]"
455                                )
456                            } else {
457                                format!("\n[full output: {p} — read it directly (no MCP), or ctx_expand(id=\"{p}\")]")
458                            }
459                        })
460                        .unwrap_or_default()
461                } else {
462                    String::new()
463                };
464
465                (result, original, saved, tee_hint)
466            };
467
468            let mode = if bypass {
469                Some("bypass".to_string())
470            } else if raw {
471                Some("raw".to_string())
472            } else {
473                None
474            };
475
476            let shell_mismatch = if cfg!(windows) && !raw {
477                shell_mismatch_hint(&command, &result_out)
478            } else {
479                String::new()
480            };
481
482            let result_out = crate::core::redaction::redact_text_if_enabled(&result_out);
483            // #815: exit 124 = timeout signal (from timeout(1) / lean-ctx
484            // shell timeout). Make it explicit so agents don't confuse a
485            // timed-out command with a successful empty result.
486            let exit_suffix = crate::shell::exit_status::exit_footer(exit_code);
487            let nudge = if raw { "" } else { search_tool_nudge(&command) };
488            let final_out = format!(
489                "{result_out}{tee_hint}{shell_mismatch}{cwd_jail_hint}{nudge}{exit_suffix}"
490            );
491            let final_out = if let Some(block) = proactive_block {
492                format!("{final_out}{block}")
493            } else {
494                final_out
495            };
496
497            Ok(ToolOutput {
498                text: final_out,
499                original_tokens: original,
500                saved_tokens: saved,
501                mode,
502                path: None,
503                changed: false,
504                shell_outcome: Some(ShellOutcome::Exit(exit_code)),
505                content_blocks: None,
506            })
507        })
508    }
509}
510
511/// Deny shell execution for explicitly restricted MCP clients. Missing client
512/// context remains allowed so existing integrations retain their current access.
513fn shell_access_denial(ctx: &ToolContext) -> Option<String> {
514    if let Some(role) = ctx.client_role.as_deref()
515        && (role.eq_ignore_ascii_case("untrusted") || role.eq_ignore_ascii_case("readonly"))
516    {
517        return Some(format!(
518            "[SHELL ACCESS DENIED] ctx_shell is unavailable to MCP clients with role '{role}'."
519        ));
520    }
521
522    if ctx.shell_access == Some(false) {
523        return Some(
524            "[SHELL ACCESS DENIED] ctx_shell requires shell_access=true in the MCP session/request context."
525                .to_string(),
526        );
527    }
528
529    None
530}
531
532fn resolve_effective_cwd(
533    session: Option<tokio::sync::OwnedRwLockReadGuard<crate::core::session::SessionState>>,
534    explicit_cwd: Option<&str>,
535) -> Result<(String, Option<String>), ErrorData> {
536    match session {
537        Some(session) => Ok(session.effective_cwd_checked(explicit_cwd)),
538        None => Err(ErrorData::internal_error(
539            "session lock timeout — cannot validate working directory",
540            None,
541        )),
542    }
543}
544
545#[allow(clippy::fn_params_excessive_bools)]
546fn resolve_shell_raw_flags(
547    arg_raw: bool,
548    arg_bypass: bool,
549    _env_disabled: bool,
550    env_raw: bool,
551) -> (bool, bool) {
552    let bypass = arg_bypass || env_raw;
553    let raw = arg_raw || bypass;
554    (raw, bypass)
555}
556
557/// A timeout notice is framework metadata, not recoverable command output. Do
558/// not archive it as a tee artifact: expanding it cannot recover any bytes (#995).
559///
560/// Keyed on what precedes the marker rather than on the notice's exact shape,
561/// so enriching it (the idle-timeout wording, the still-running segment list)
562/// cannot silently turn every timeout back into an archived artifact (#1173).
563fn is_timeout_notice_only(output: &str, exit_code: i32) -> bool {
564    exit_code == 124
565        && crate::server::execute::output_before_timeout_marker(output).is_some_and(str::is_empty)
566}
567
568fn search_tool_nudge(command: &str) -> &'static str {
569    let cmd = command.trim();
570    let first_word = cmd.split_whitespace().next().unwrap_or("");
571    if !cmd.contains('|') {
572        match first_word {
573            "grep" | "rg" | "egrep" | "fgrep" | "ag" => {
574                return "\n[hint: use ctx_search for structured, cached results with symbol/semantic modes]";
575            }
576            "find" => {
577                return "\n[hint: use ctx_glob or ctx_tree for structured file discovery]";
578            }
579            "ls" | "exa" | "eza" => {
580                return "\n[hint: use ctx_tree for structured directory listing]";
581            }
582            _ => {}
583        }
584    }
585    ""
586}
587
588fn shell_mismatch_hint(command: &str, output: &str) -> String {
589    let shell = crate::shell::shell_name();
590    let is_posix = matches!(shell.as_str(), "bash" | "sh" | "zsh" | "fish");
591    let has_error = output.contains("is not recognized")
592        || output.contains("not found")
593        || output.contains("command not found");
594
595    if !has_error {
596        return String::new();
597    }
598
599    let powershell_cmds = [
600        "Get-Content",
601        "Select-Object",
602        "Get-ChildItem",
603        "Set-Location",
604        "Where-Object",
605        "ForEach-Object",
606        "Select-String",
607        "Invoke-Expression",
608        "Write-Output",
609    ];
610    let uses_powershell = powershell_cmds
611        .iter()
612        .any(|c| command.contains(c) || command.contains(&c.to_lowercase()));
613
614    if is_posix && uses_powershell {
615        format!(
616            "\n[shell: {shell} — use POSIX commands (cat, head, grep, find, ls) not PowerShell cmdlets]"
617        )
618    } else {
619        String::new()
620    }
621}
622
623/// Collect the caller's `env` overrides, refusing protected keys by name instead
624/// of dropping them silently (#1771).
625///
626/// The inline-override refusal in `core/shell_allowlist/enforcement.rs` points the
627/// caller at this parameter and uses `PATH` as its worked example — yet five of the
628/// nine variables it blocks inline (`PATH`, `GIT_SSH`, `GIT_SSH_COMMAND`,
629/// `LD_PRELOAD`, `DYLD_INSERT_LIBRARIES`) are also in [`is_dangerous_env_key`].
630/// Filtering them away meant the recommended recovery ran the command with the
631/// ambient value and reported success, which is worse than the refusal it replaced:
632/// a wrong result that looks right. Naming the key is the only honest outcome.
633fn collect_extra_env(
634    args: &Map<String, Value>,
635) -> Result<std::collections::HashMap<String, String>, String> {
636    let mut accepted = std::collections::HashMap::new();
637    let Some(obj) = args.get("env").and_then(|v| v.as_object()) else {
638        return Ok(accepted);
639    };
640    let mut rejected: Vec<&str> = Vec::new();
641    for (key, value) in obj {
642        let Some(text) = value.as_str() else { continue };
643        if is_dangerous_env_key(key) {
644            rejected.push(key.as_str());
645            continue;
646        }
647        accepted.insert(key.clone(), text.to_string());
648    }
649    if rejected.is_empty() {
650        return Ok(accepted);
651    }
652    rejected.sort_unstable();
653    let names = rejected
654        .iter()
655        .map(|k| format!("`{k}`"))
656        .collect::<Vec<_>>()
657        .join(", ");
658    let plural = if rejected.len() == 1 { "key" } else { "keys" };
659    Err(format!(
660        "ERROR: ctx_shell refuses the `env` {plural} {names} — nothing was run. These keys can \
661         redirect which binary executes, so lean-ctx never forwards them, and the command would \
662         otherwise have used the inherited value while appearing to honor yours. This is the \
663         same rule that blocks the inline `KEY=value cmd` form; `env` is not a way around it. \
664         Invoke the binary by its full path instead, or drop the override."
665    ))
666}
667
668fn is_dangerous_env_key(key: &str) -> bool {
669    const BLOCKED: &[&str] = &[
670        // Dynamic linker injection
671        "LD_PRELOAD",
672        "LD_LIBRARY_PATH",
673        "DYLD_INSERT_LIBRARIES",
674        "DYLD_LIBRARY_PATH",
675        "DYLD_FRAMEWORK_PATH",
676        // Shell re-entry / startup injection
677        "BASH_ENV",
678        "ENV",
679        "PROMPT_COMMAND",
680        "SHELL",
681        "IFS",
682        "CDPATH",
683        // Binary resolution hijacking
684        "PATH",
685        "GIT_EXEC_PATH",
686        "GIT_SSH",
687        "GIT_SSH_COMMAND",
688        // Identity / home directory manipulation
689        "HOME",
690        "USER",
691        "LOGNAME",
692        "XDG_CONFIG_HOME",
693        "XDG_DATA_HOME",
694        "XDG_STATE_HOME",
695        "XDG_CACHE_HOME",
696        // Language runtime search path hijacking
697        "PYTHONPATH",
698        "PYTHONSTARTUP",
699        "PYTHONHOME",
700        "NODE_PATH",
701        "NODE_OPTIONS",
702        "RUBYOPT",
703        "RUBYLIB",
704        "GEM_PATH",
705        "GEM_HOME",
706        "PERL5LIB",
707        "PERL5OPT",
708        "CLASSPATH",
709        "JAVA_HOME",
710        "CARGO_HOME",
711        "RUSTUP_HOME",
712        "GOPATH",
713        "GOROOT",
714    ];
715    let upper = key.to_uppercase();
716    if BLOCKED.contains(&upper.as_str()) {
717        return true;
718    }
719    if upper.starts_with("LD_") && upper.ends_with("_PATH") {
720        return true;
721    }
722    // Block all lean-ctx config overrides from env
723    if upper.starts_with("LEAN_CTX_") || upper.starts_with("LCTX_") {
724        return true;
725    }
726    false
727}
728
729/// Warn when shell reads secret-like paths via cat/head/tail/less/more.
730/// WARN-ONLY: command still executes, this is purely observational.
731fn warn_shell_secret_paths(command: &str) {
732    const READ_CMDS: &[&str] = &["cat", "head", "tail", "less", "more", "bat"];
733    let segments = crate::core::shell_allowlist::extract_all_commands_pub(command);
734    for seg in &segments {
735        let trimmed = seg.trim();
736        let tokens = crate::core::shell_allowlist::shell_tokenize(trimmed);
737        if tokens.is_empty() {
738            continue;
739        }
740        let base = tokens[0]
741            .rsplit('/')
742            .next()
743            .unwrap_or(&tokens[0])
744            .to_string();
745        if !READ_CMDS.contains(&base.as_str()) {
746            continue;
747        }
748        for tok in &tokens[1..] {
749            if tok.starts_with('-') {
750                continue;
751            }
752            let path = std::path::Path::new(tok.as_str());
753            if crate::core::io_boundary::is_secret_like(path).is_some() {
754                tracing::warn!(
755                    "[SECURITY] Shell reading secret-like path: {tok} (command: {base})"
756                );
757            }
758        }
759    }
760}
761
762/// The Codex MCP client abandons a tool call after five minutes. A Cargo test
763/// with an explicit five-minute-or-longer shell timeout cannot reliably finish
764/// inside that transport deadline (and can wait on Cargo's target lock), so
765/// detach it and return a pollable job instead.
766fn should_auto_background(command: &str, timeout_ms: Option<u64>) -> bool {
767    timeout_ms.is_some_and(|timeout| timeout >= 300_000)
768        && command
769            .lines()
770            .any(|line| line.trim_start().starts_with("cargo test"))
771}
772
773/// Foreground wait budget before a still-running command is detached into a
774/// pollable background job. Kept below the MCP host's ~120s tool-call abort so
775/// the caller always receives a real `shell_*` job id instead of an
776/// unresolvable task id (#1106). Override with `LEAN_CTX_SHELL_FG_CAP_MS`.
777fn foreground_soft_cap_ms() -> u64 {
778    std::env::var("LEAN_CTX_SHELL_FG_CAP_MS")
779        .ok()
780        .and_then(|v| v.parse().ok())
781        .filter(|&ms| ms > 0)
782        .unwrap_or(110_000)
783}
784
785/// Map an interpreter binary to a `ctx_execute` language name.
786fn interpreter_to_execute_language(base: &str) -> Option<&'static str> {
787    match base {
788        "python" | "python2" | "python3" => Some("python"),
789        "node" => Some("javascript"),
790        "ruby" => Some("ruby"),
791        _ => None,
792    }
793}
794
795fn is_env_assignment_token(token: &str) -> bool {
796    let unquoted: String = token.chars().filter(|c| *c != '"' && *c != '\'').collect();
797    unquoted.contains('=')
798        && !unquoted.starts_with('-')
799        && !unquoted.starts_with('/')
800        && !unquoted.starts_with('.')
801}
802
803/// Quote-aware scan for compound operators that would invalidate a reroute.
804fn prelude_has_compound_operator(prelude: &str) -> bool {
805    let bytes = prelude.as_bytes();
806    let len = bytes.len();
807    let mut i = 0;
808    let mut in_single = false;
809    let mut in_double = false;
810    while i < len {
811        let ch = bytes[i];
812        if in_single {
813            if ch == b'\'' {
814                in_single = false;
815            }
816            i += 1;
817            continue;
818        }
819        if in_double {
820            if ch == b'\\' && i + 1 < len {
821                i += 2;
822            } else {
823                if ch == b'"' {
824                    in_double = false;
825                }
826                i += 1;
827            }
828            continue;
829        }
830        match ch {
831            b'\'' => {
832                in_single = true;
833                i += 1;
834            }
835            b'"' => {
836                in_double = true;
837                i += 1;
838            }
839            b';' | b'|' | b'&' | b'(' | b'{' => return true,
840            _ => i += 1,
841        }
842    }
843    false
844}
845
846/// Detect interpreter heredoc patterns and extract the language + code body.
847/// Returns `Some((language, code, remainder))` where remainder is any command
848/// after the heredoc terminator that still needs shell execution.
849fn detect_heredoc_reroute(command: &str) -> Option<(String, String, Option<String>)> {
850    if !command.contains("<<") {
851        return None;
852    }
853
854    let lines: Vec<&str> = command.lines().collect();
855    if lines.is_empty() {
856        return None;
857    }
858
859    let first_line = lines[0];
860    let delims = crate::core::shell_allowlist::heredoc_delims(first_line, false);
861    if delims.len() != 1 {
862        return None;
863    }
864    let delim = delims[0].clone();
865
866    let heredoc_pos = find_heredoc_operator(first_line)?;
867    let prelude = first_line[..heredoc_pos].trim();
868    if prelude_has_compound_operator(prelude) {
869        return None;
870    }
871
872    let language = parse_interpreter_heredoc_prelude(prelude)?.to_string();
873
874    if has_trailing_tokens_after_heredoc_delim(first_line, heredoc_pos) {
875        return None;
876    }
877
878    let mut body = String::new();
879    let mut remainder_start: Option<usize> = None;
880    for (idx, line) in lines.iter().enumerate().skip(1) {
881        if line.trim_start_matches('\t').trim() == delim {
882            remainder_start = Some(idx + 1);
883            break;
884        }
885        if !body.is_empty() {
886            body.push('\n');
887        }
888        body.push_str(line);
889    }
890    let remainder_start = remainder_start?;
891    let remainder = if remainder_start < lines.len() {
892        let rest = lines[remainder_start..].join("\n");
893        let rest = rest.trim();
894        if rest.is_empty() {
895            None
896        } else {
897            Some(rest.to_string())
898        }
899    } else {
900        None
901    };
902
903    Some((language, body, remainder))
904}
905
906fn find_heredoc_operator(line: &str) -> Option<usize> {
907    let bytes = line.as_bytes();
908    let len = bytes.len();
909    let mut i = 0;
910    let mut in_single = false;
911    let mut in_double = false;
912    while i < len {
913        let ch = bytes[i];
914        if in_single {
915            if ch == b'\'' {
916                in_single = false;
917            }
918            i += 1;
919            continue;
920        }
921        if in_double {
922            if ch == b'\\' && i + 1 < len {
923                i += 2;
924            } else {
925                if ch == b'"' {
926                    in_double = false;
927                }
928                i += 1;
929            }
930            continue;
931        }
932        match ch {
933            b'\'' => {
934                in_single = true;
935                i += 1;
936            }
937            b'"' => {
938                in_double = true;
939                i += 1;
940            }
941            b'<' if i + 1 < len && bytes[i + 1] == b'<' => {
942                if i + 2 < len && bytes[i + 2] == b'<' {
943                    i += 3;
944                    continue;
945                }
946                return Some(i);
947            }
948            _ => i += 1,
949        }
950    }
951    None
952}
953
954fn has_trailing_tokens_after_heredoc_delim(line: &str, heredoc_pos: usize) -> bool {
955    let bytes = line.as_bytes();
956    let mut i = heredoc_pos + 2;
957    if i < bytes.len() && bytes[i] == b'-' {
958        i += 1;
959    }
960    while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') {
961        i += 1;
962    }
963    let Some((_, _, next)) = crate::core::shell_allowlist::read_heredoc_delim(bytes, i) else {
964        return true;
965    };
966    !line[next..].trim().is_empty()
967}
968
969fn parse_interpreter_heredoc_prelude(prelude: &str) -> Option<&'static str> {
970    let tokens = crate::core::shell_allowlist::shell_tokenize(prelude.trim());
971    let mut idx = 0;
972    while idx < tokens.len() && is_env_assignment_token(&tokens[idx]) {
973        idx += 1;
974    }
975    if idx >= tokens.len() {
976        return None;
977    }
978    let base = tokens[idx]
979        .rsplit('/')
980        .next()
981        .unwrap_or(tokens[idx].as_str());
982    let language = interpreter_to_execute_language(base)?;
983    idx += 1;
984    match tokens.get(idx) {
985        None => Some(language),
986        Some(dash) if dash == "-" => {
987            if tokens.len() == idx + 1 {
988                Some(language)
989            } else {
990                None
991            }
992        }
993        Some(_) => None,
994    }
995}
996
997/// The one working directory both halves of a rerouted heredoc call run in.
998///
999/// Resolution goes through the session so an explicit `cwd` is validated
1000/// against the configured roots, exactly as the non-rerouted path does. A `cwd`
1001/// the caller named that cannot be validated is an error, never a silent
1002/// substitution (#1666).
1003///
1004/// `Ok(None)` means only that no directory could be established without a
1005/// session. The heredoc-only path never needed one and must keep working; the
1006/// shell remainder always required a session and keeps requiring it.
1007fn resolve_reroute_cwd(
1008    ctx: &ToolContext,
1009    explicit_cwd: Option<&str>,
1010) -> Result<Option<String>, ErrorData> {
1011    let Some(session_lock) = ctx.session.as_ref() else {
1012        if explicit_cwd.is_some() {
1013            return Err(ErrorData::internal_error(
1014                "session not available — cannot validate the requested working directory",
1015                None,
1016            ));
1017        }
1018        return Ok(None);
1019    };
1020    let guard =
1021        crate::server::bounded_lock::read_for(session_lock, "ctx_shell_cwd", SESSION_LOCK_BUDGET);
1022    let (cwd, _) = resolve_effective_cwd(guard, explicit_cwd)?;
1023    Ok(Some(cwd))
1024}
1025
1026fn handle_interpreter_heredoc_reroute(
1027    args: &Map<String, Value>,
1028    ctx: &ToolContext,
1029    language: &str,
1030    code: &str,
1031    remainder: Option<String>,
1032) -> Result<ToolOutput, ErrorData> {
1033    let timeout_ms = get_int(args, "timeout_ms").and_then(|n| u64::try_from(n).ok());
1034    let timeout_secs = timeout_ms.map(|ms| ms.div_ceil(1000).max(1));
1035
1036    // #1666: resolve the working directory *before* the interpreter runs. The
1037    // shell remainder below always ran in the call's `cwd`; the rerouted
1038    // interpreter ran wherever the server process happened to sit. One tool
1039    // call, two directories — and a script using relative paths silently read
1040    // and wrote the wrong tree while reporting success.
1041    let explicit_cwd = get_str(args, "cwd");
1042    let exec_cwd = resolve_reroute_cwd(ctx, explicit_cwd.as_deref())?;
1043
1044    let (exec_text, exec_outcome) = crate::tools::ctx_execute::handle_in(
1045        language,
1046        code,
1047        None,
1048        timeout_secs,
1049        exec_cwd.as_deref().map(std::path::Path::new),
1050    );
1051    let reroute_note = format!(
1052        "\n[ctx_shell: interpreter heredoc auto-rerouted to ctx_execute(language=\"{language}\")]"
1053    );
1054    let exec_text = crate::core::redaction::redact_text_if_enabled(&exec_text);
1055
1056    let Some(rest_cmd) = remainder else {
1057        return Ok(ToolOutput {
1058            text: format!("{exec_text}{reroute_note}"),
1059            original_tokens: crate::core::tokens::count_tokens(&exec_text),
1060            saved_tokens: 0,
1061            mode: Some("heredoc-reroute".to_string()),
1062            path: None,
1063            changed: false,
1064            shell_outcome: Some(exec_outcome),
1065            content_blocks: None,
1066        });
1067    };
1068
1069    if let Err(msg) = crate::core::shell_allowlist::check_shell_allowlist(&rest_cmd) {
1070        let blocked =
1071            format!("{exec_text}{reroute_note}\n\n[remainder blocked by shell allowlist]\n{msg}");
1072        return Ok(ToolOutput {
1073            shell_outcome: Some(ShellOutcome::Blocked),
1074            content_blocks: None,
1075            ..ToolOutput::simple(blocked)
1076        });
1077    }
1078
1079    // Unchanged from before #1666: running the shell remainder requires a
1080    // validated working directory.
1081    let effective_cwd =
1082        exec_cwd.ok_or_else(|| ErrorData::internal_error("session not available", None))?;
1083
1084    let extra_env = match collect_extra_env(args) {
1085        Ok(env) => env,
1086        Err(message) => {
1087            return Ok(ToolOutput {
1088                shell_outcome: Some(ShellOutcome::Blocked),
1089                content_blocks: None,
1090                ..ToolOutput::simple(message)
1091            });
1092        }
1093    };
1094
1095    let (shell_raw, shell_exit) = crate::server::execute::execute_command_with_env(
1096        &rest_cmd,
1097        &effective_cwd,
1098        &extra_env,
1099        timeout_ms,
1100    );
1101    let shell_output = redact_shell_output_secrets(&shell_raw);
1102    let arg_raw = get_bool(args, "raw").unwrap_or(false);
1103    let arg_bypass = get_bool(args, "bypass").unwrap_or(false);
1104    let env_disabled = std::env::var("LEAN_CTX_DISABLED").is_ok();
1105    let env_raw = std::env::var("LEAN_CTX_RAW").is_ok();
1106    let (raw, _) = resolve_shell_raw_flags(arg_raw, arg_bypass, env_disabled, env_raw);
1107
1108    let shell_text = if raw {
1109        shell_output
1110    } else {
1111        crate::tools::ctx_shell::handle(&rest_cmd, &shell_output, shell_exit, ctx.crp_mode)
1112    };
1113    let shell_text = crate::core::redaction::redact_text_if_enabled(&shell_text);
1114    let exit_suffix = crate::shell::exit_status::exit_footer(shell_exit);
1115
1116    let combined = format!(
1117        "{exec_text}{reroute_note}\n\n[heredoc remainder via ctx_shell]\n{shell_text}{exit_suffix}"
1118    );
1119    let token_count = crate::core::tokens::count_tokens(&combined);
1120    Ok(ToolOutput {
1121        text: combined,
1122        original_tokens: token_count,
1123        saved_tokens: 0,
1124        mode: Some("heredoc-reroute".to_string()),
1125        path: None,
1126        changed: false,
1127        shell_outcome: Some(ShellOutcome::Exit(shell_exit)),
1128        content_blocks: None,
1129    })
1130}
1131
1132/// #842: detect a bare `cat <single_file>` command (no pipes, redirects, flags).
1133fn detect_bare_cat_file(command: &str) -> Option<String> {
1134    let trimmed = command.trim();
1135    let rest = trimmed.strip_prefix("cat ")?;
1136    let rest = rest.trim();
1137    if rest.is_empty()
1138        || rest.contains('|')
1139        || rest.contains('>')
1140        || rest.contains('<')
1141        || rest.contains(';')
1142        || rest.contains('&')
1143        || rest.contains('$')
1144        || rest.starts_with('-')
1145    {
1146        return None;
1147    }
1148    let parts: Vec<&str> = rest.split_whitespace().collect();
1149    if parts.len() != 1 {
1150        return None;
1151    }
1152    let file_path = parts[0].trim_matches(|c: char| c == '\'' || c == '"');
1153    if file_path.is_empty() {
1154        return None;
1155    }
1156    Some(file_path.to_string())
1157}
1158
1159#[cfg(test)]
1160#[path = "ctx_shell_tests.rs"]
1161mod tests;