Skip to main content

vtcode_core/tools/registry/executors/
mod.rs

1use std::path::PathBuf;
2use std::time::{Duration, SystemTime};
3
4use anyhow::{Context, Result, anyhow, bail};
5#[cfg(test)]
6use cargo_failure_diagnostics::{
7    CargoTestCommandKind, attach_exec_recovery_guidance, attach_failure_diagnostics_metadata,
8    cargo_selector_error_diagnostics, cargo_test_failure_diagnostics, cargo_test_rerun_hint,
9};
10use chrono;
11use exec_support::*;
12use futures::future::BoxFuture;
13use hashbrown::HashMap;
14use sandbox_runtime::*;
15use serde::de::DeserializeOwned;
16use serde_json::{Value, json};
17
18use super::{ExecSettlementMode, ToolRegistry};
19use crate::config::constants::tools;
20use crate::tools::exec_session::MonitorSpec;
21use crate::tools::file_tracker::FileTracker;
22use crate::tools::registry::unified_actions::CommandSessionAction;
23use crate::tools::{native_memory, tool_intent};
24
25mod cargo_failure_diagnostics;
26mod exec_command;
27mod exec_output;
28mod exec_sessions;
29mod exec_support;
30mod matrix;
31mod patch_pipeline;
32mod sandbox_runtime;
33mod search_introspection;
34mod session_messaging;
35mod subagents;
36
37pub use sandbox_runtime::sandbox_policy_from_runtime_config;
38
39#[derive(Clone, Copy)]
40enum ExecRunBackendKind {
41    Pty,
42    Pipe,
43}
44
45struct PreparedExecRunRequest {
46    prepared_command: PreparedExecCommand,
47    working_dir_path: PathBuf,
48    output_config: ExecRunOutputConfig,
49    yield_duration: Duration,
50    session_id: String,
51    shell_program: String,
52    env_overrides: HashMap<String, String>,
53    is_git_diff: bool,
54    confirm: bool,
55    rows: Option<u16>,
56    cols: Option<u16>,
57    sandbox_active: bool,
58    background: bool,
59    stdin: bool,
60    monitor: Option<MonitorSpec>,
61}
62
63struct ResolvedExecSandboxRequest {
64    working_dir_path: PathBuf,
65    sandbox_permissions: crate::sandboxing::SandboxPermissions,
66    additional_permissions: Option<crate::sandboxing::AdditionalPermissions>,
67}
68
69fn set_payload_default(payload: &mut serde_json::Map<String, Value>, key: &str, value: Value) {
70    payload.entry(key.to_string()).or_insert(value);
71}
72
73pub(super) fn normalize_command_session_run_alias_args(args: &Value, tty: bool) -> Result<Value> {
74    let mut args = crate::tools::command_args::normalize_shell_args(args).map_err(|error| anyhow!(error))?;
75    if let Some(payload) = args.as_object_mut() {
76        set_payload_default(payload, "action", json!("run"));
77        if tty {
78            set_payload_default(payload, "tty", json!(true));
79        }
80    }
81    Ok(args)
82}
83
84fn with_command_session_action_default(mut args: Value, action: &'static str) -> Value {
85    if let Some(payload) = args.as_object_mut() {
86        set_payload_default(payload, "action", json!(action));
87    }
88    args
89}
90
91pub(super) fn normalize_write_stdin_args(
92    args: &Value,
93) -> Result<(Value, crate::tools::command_args::WriteStdinDispatch)> {
94    let dispatch = crate::tools::command_args::write_stdin_dispatch(args).map_err(|error| anyhow!(error))?;
95    let mut args = crate::tools::command_args::normalize_shell_args(args).map_err(|error| anyhow!(error))?;
96    let payload = args
97        .as_object_mut()
98        .ok_or_else(|| anyhow!("write_stdin requires a JSON object"))?;
99    payload.insert("action".to_string(), json!(dispatch.command_session_action()));
100    if dispatch == crate::tools::command_args::WriteStdinDispatch::Poll {
101        payload.remove("input");
102    }
103    Ok((args, dispatch))
104}
105
106fn annotate_exec_run_response(response: &mut Value, is_git_diff: bool) {
107    if is_git_diff {
108        response["no_spool"] = json!(true);
109        response["content_type"] = json!("git_diff");
110    }
111}
112
113fn acquire_executor_rate_limit(bucket: &str, multiplier: f64) -> Result<()> {
114    let mut guard = crate::tools::rate_limiter::PER_TOOL_RATE_LIMITER
115        .lock()
116        .map_err(|err| anyhow!("per-tool rate limiter poisoned: {err}"))?;
117    guard
118        .try_acquire_for_scaled(bucket, multiplier)
119        .map_err(|e| anyhow!("tool rate limit exceeded for {bucket}: {e}"))
120}
121
122fn parse_action<T>(action_str: &str) -> Result<T>
123where
124    T: DeserializeOwned,
125{
126    serde_json::from_value(json!(action_str)).with_context(|| format!("Invalid action: {action_str}"))
127}
128
129/// Generate an executor that delegates to a cloned tool instance from the inventory.
130macro_rules! delegate_to_tool {
131    ($name:ident, $tool_accessor:ident, $method:ident) => {
132        pub(super) fn $name(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
133            let tool = self.inventory.$tool_accessor().clone();
134            Box::pin(async move { tool.$method(args).await })
135        }
136    };
137}
138
139/// Generate an executor that delegates to an async method on `self`.
140macro_rules! delegate_to_self {
141    ($name:ident, $method:ident) => {
142        pub(super) fn $name(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
143            Box::pin(async move { self.$method(args).await })
144        }
145    };
146}
147
148impl ToolRegistry {
149    pub(super) fn record_decision_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
150        Box::pin(async move {
151            let decision = crate::core::agent::events::validate_decision_input(args)?;
152            let task = self
153                .harness_context_snapshot()
154                .task_id
155                .context("decision recording requires current task identity")?;
156            let validator = self
157                .harness_context
158                .decision_validator
159                .read()
160                .clone()
161                .context("canonical decision recording is unavailable")?;
162            validator(task, decision.evidence_ids).await?;
163            Ok(json!({"recorded":true,"rationale_source":"agent-reported"}))
164        })
165    }
166    /// Unified `cron` executor: dispatches on `action` (create | list | delete).
167    /// For legacy alias calls that omit `action`, the action is inferred from
168    /// the argument shape: `prompt` implies create, `id` implies delete,
169    /// otherwise list.
170    #[cfg_attr(
171        not(test),
172        allow(
173            dead_code,
174            reason = "Legacy executor aliases remain available for compatibility tests."
175        )
176    )]
177    pub(super) fn cron_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
178        Box::pin(async move {
179            let action = args
180                .get("action")
181                .and_then(Value::as_str)
182                .map(str::to_ascii_lowercase)
183                .unwrap_or_else(|| {
184                    if args.get("prompt").is_some() {
185                        "create".to_string()
186                    } else if args.get("id").is_some() {
187                        "delete".to_string()
188                    } else {
189                        "list".to_string()
190                    }
191                });
192            match action.as_str() {
193                "create" => self.cron_create_executor(args).await,
194                "list" => self.cron_list_executor(args).await,
195                "delete" => self.cron_delete_executor(args).await,
196                other => bail!(
197                    "cron: unknown action '{other}'. Use action='create' (schedule a prompt), 'list', or 'delete' (requires id)."
198                ),
199            }
200        })
201    }
202
203    fn cron_create_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
204        Box::pin(async move {
205            let prompt = args
206                .get("prompt")
207                .and_then(Value::as_str)
208                .map(str::trim)
209                .filter(|value| !value.is_empty())
210                .ok_or_else(|| anyhow!("cron_create requires a non-empty prompt"))?
211                .to_string();
212            let name = args.get("name").and_then(Value::as_str).map(ToOwned::to_owned);
213            let cron = args.get("cron").and_then(Value::as_str);
214            let delay_minutes = args.get("delay_minutes").and_then(Value::as_u64);
215            let run_at = args.get("run_at").and_then(Value::as_str);
216
217            let schedule = match (cron, delay_minutes, run_at) {
218                (Some(expression), None, None) => crate::scheduler::ScheduleSpec::cron5(expression)?,
219                (None, Some(minutes), None) => crate::scheduler::ScheduleSpec::fixed_interval(Duration::from_secs(
220                    minutes.checked_mul(60).ok_or_else(|| anyhow!("delay_minutes is too large"))?,
221                ))?,
222                (None, None, Some(raw)) => crate::scheduler::ScheduleSpec::one_shot(
223                    crate::scheduler::parse_local_datetime(raw, chrono::Local::now())?,
224                ),
225                _ => bail!("Choose exactly one of cron, delay_minutes, or run_at"),
226            };
227
228            let summary = self
229                .create_session_prompt_task(name, prompt, schedule, chrono::Utc::now())
230                .await?;
231            serde_json::to_value(summary).context("Failed to serialize cron_create response")
232        })
233    }
234
235    fn cron_list_executor(&self, _args: Value) -> BoxFuture<'_, Result<Value>> {
236        Box::pin(async move {
237            Ok(json!({
238                "tasks": self.list_session_tasks().await,
239            }))
240        })
241    }
242
243    fn cron_delete_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
244        Box::pin(async move {
245            let id = args
246                .get("id")
247                .and_then(Value::as_str)
248                .map(str::trim)
249                .filter(|value| !value.is_empty())
250                .ok_or_else(|| anyhow!("cron_delete requires id"))?;
251            let deleted = self.delete_session_task(id).await;
252            Ok(json!({
253                "deleted": deleted.is_some(),
254                "task": deleted,
255            }))
256        })
257    }
258
259    pub(super) fn memory_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
260        Box::pin(async move {
261            let workspace_root = self.workspace_root_owned();
262            native_memory::execute_with_persistent_memory_config(
263                &workspace_root,
264                self.persistent_memory_config.as_ref(),
265                self.persistent_memory_enabled,
266                args,
267            )
268            .await
269        })
270    }
271
272    pub async fn shell_run_approval_reason(
273        &self,
274        tool_name: &str,
275        tool_args: Option<&Value>,
276    ) -> Result<Option<String>> {
277        let resolved_tool_name = self
278            .resolve_public_tool_name_sync(tool_name)
279            .unwrap_or_else(|_| tool_name.to_string());
280        let Some(payload) = shell_run_payload(&resolved_tool_name, tool_args) else {
281            return Ok(None);
282        };
283
284        let (requested_command, raw_command) = parse_command_parts(
285            payload,
286            "shell run request requires a command",
287            "shell run request command cannot be empty",
288        )?;
289        let shell_script = shell_script_text(payload, raw_command.as_deref(), &requested_command);
290        let sandbox_request = self.resolve_exec_sandbox_request(payload).await?;
291        let sandbox_config = self.sandbox_config();
292        let plan = build_shell_execution_plan(
293            &sandbox_config,
294            self.workspace_root(),
295            &sandbox_request.working_dir_path,
296            &requested_command,
297            Some(&shell_script),
298            sandbox_request.sandbox_permissions,
299            sandbox_request.additional_permissions.as_ref(),
300        )?;
301
302        Ok(plan.approval_reason)
303    }
304
305    pub(super) fn code_search_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
306        Box::pin(async move { self.execute_code_search(args).await })
307    }
308
309    async fn prepare_exec_run_request(
310        &self,
311        args: &Value,
312        backend: ExecRunBackendKind,
313        missing_error: &str,
314        empty_error: &str,
315    ) -> Result<PreparedExecRunRequest> {
316        acquire_executor_rate_limit("exec_command:run", 2.0)?;
317
318        // Direct registry callers do not necessarily run model preflight.
319        // Normalize here as well so every pipe/PTY launch reports the same
320        // truthful verifier status the gate classifies. This is idempotent.
321        let executed_args = tool_intent::shell_args_as_executed(tools::EXEC_COMMAND, args);
322        let payload = executed_args
323            .as_object()
324            .ok_or_else(|| anyhow!("command execution requires a JSON object"))?;
325        let background = payload.get("background").and_then(Value::as_bool).unwrap_or(false);
326        let stdin = match payload.get("stdin") {
327            None => false,
328            Some(value) => value.as_bool().ok_or_else(|| anyhow!("stdin must be a boolean"))?,
329        };
330        let monitor = match payload.get("monitor_filter") {
331            None => None,
332            Some(value) => Some(
333                MonitorSpec::new(value.as_str().ok_or_else(|| anyhow!("monitor_filter must be a string"))?, None, None)
334                    .with_context(|| "invalid monitor_filter")?,
335            ),
336        };
337        if monitor.is_some() && matches!(backend, ExecRunBackendKind::Pty) {
338            bail!("monitor_filter is pipe-only in v1; pty runs cannot attach a line monitor");
339        }
340
341        let (command, auto_raw_command) = parse_command_parts(payload, missing_error, empty_error)?;
342        let shell_program = match backend {
343            ExecRunBackendKind::Pty => resolve_shell_preference_with_zsh_fork(
344                payload.get("shell").and_then(|value| value.as_str()),
345                self.pty_config(),
346            )?,
347            ExecRunBackendKind::Pipe => {
348                resolve_shell_preference(payload.get("shell").and_then(|value| value.as_str()), self.pty_config())
349            }
350        };
351        let login_shell = payload.get("login").and_then(|value| value.as_bool()).unwrap_or(false);
352        let confirm = payload.get("confirm").and_then(|value| value.as_bool()).unwrap_or(false);
353
354        let mut prepared_command =
355            prepare_exec_command(payload, &shell_program, login_shell, command, auto_raw_command);
356        let is_git_diff = is_git_diff_command(&prepared_command.requested_command);
357
358        // Evaluate the concrete invocation so raw shell fragments retain their
359        // original quoting. An explicitly supplied shell argv is already a
360        // policy boundary; keep that request intact when the runtime's
361        // preferred shell differs and would otherwise add a nested wrapper.
362        let policy_command = if crate::tools::command_policy::is_shell_argv(&prepared_command.requested_command) {
363            &prepared_command.requested_command
364        } else {
365            &prepared_command.command
366        };
367        if !self.inventory.command_policy_allows(policy_command) {
368            return Err(anyhow!(
369                "Execution policy violation: command '{}' is not permitted by the execution policy",
370                prepared_command.requested_command_display
371            ));
372        }
373
374        let inspection_cwd = self
375            .pty_manager()
376            .working_dir_candidate(crate::tools::command_args::working_dir_text(args))?;
377        self.edited_file_monitor_ref()
378            .source_inspection()
379            .check_shell(args, &inspection_cwd)?;
380        let sandbox_request = self.resolve_exec_sandbox_request(payload).await?;
381        let output_config = exec_run_output_config(payload, &prepared_command.display_command);
382
383        enforce_pty_command_policy(&prepared_command.display_command, confirm)?;
384        let sandbox_config = self.sandbox_config();
385        let sandbox_plan = build_shell_execution_plan(
386            &sandbox_config,
387            self.workspace_root(),
388            &sandbox_request.working_dir_path,
389            &prepared_command.requested_command,
390            Some(&prepared_command.shell_script),
391            sandbox_request.sandbox_permissions,
392            sandbox_request.additional_permissions.as_ref(),
393        )?;
394        let sandbox_active = sandbox_plan.sandbox_policy.is_some();
395        prepared_command.command = apply_runtime_sandbox_to_command(
396            prepared_command.command,
397            &prepared_command.requested_command,
398            &sandbox_request.working_dir_path,
399            sandbox_plan.sandbox_policy,
400        )?;
401
402        let rows = match backend {
403            ExecRunBackendKind::Pty => {
404                Some(parse_pty_dimension("rows", payload.get("rows"), self.pty_config().default_rows)?)
405            }
406            ExecRunBackendKind::Pipe => None,
407        };
408        let cols = match backend {
409            ExecRunBackendKind::Pty => {
410                Some(parse_pty_dimension("cols", payload.get("cols"), self.pty_config().default_cols)?)
411            }
412            ExecRunBackendKind::Pipe => None,
413        };
414
415        Ok(PreparedExecRunRequest {
416            prepared_command,
417            working_dir_path: sandbox_request.working_dir_path,
418            output_config,
419            yield_duration: Duration::from_millis(
420                clamp_exec_yield_ms(
421                    payload.get("yield_time_ms").and_then(Value::as_u64),
422                    if background { 250 } else { 10_000 },
423                )
424                .min(if background { 1_000 } else { 30_000 }),
425            ),
426            session_id: resolve_exec_run_session_id(payload)?,
427            shell_program,
428            env_overrides: parse_exec_env_overrides(payload)?,
429            is_git_diff,
430            confirm,
431            rows,
432            cols,
433            sandbox_active,
434            background,
435            stdin,
436            monitor,
437        })
438    }
439
440    pub(super) async fn execute_command_session(&self, args: Value) -> Result<Value> {
441        self.execute_command_session_internal(args, ExecSettlementMode::Manual).await
442    }
443
444    pub(super) async fn execute_harness_command_session_terminal_run_raw(&self, args: Value) -> Result<Value> {
445        let args = normalize_command_session_run_alias_args(&args, true)?;
446        self.execute_command_session_run_pty(args, true).await
447    }
448
449    fn dispatch_command_session_alias(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
450        Box::pin(async move { self.execute_command_session(args).await.map(super::normalize_tool_output) })
451    }
452
453    fn dispatch_command_session_run_alias(&self, args: Value, tty: bool) -> BoxFuture<'_, Result<Value>> {
454        Box::pin(async move {
455            let args = normalize_command_session_run_alias_args(&args, tty)?;
456            self.execute_command_session(args).await.map(super::normalize_tool_output)
457        })
458    }
459
460    fn dispatch_command_session_action_alias(&self, args: Value, action: &'static str) -> BoxFuture<'_, Result<Value>> {
461        self.dispatch_command_session_alias(with_command_session_action_default(args, action))
462    }
463
464    pub(super) async fn execute_command_session_internal(
465        &self,
466        args: Value,
467        exec_settlement_mode: ExecSettlementMode,
468    ) -> Result<Value> {
469        let launch = self.begin_completion_verifier(&args);
470        let result = self.execute_command_session_observed(args.clone(), exec_settlement_mode).await;
471        self.observe_completion_verifier(launch, &args, &result);
472        result
473    }
474
475    async fn execute_command_session_observed(
476        &self,
477        args: Value,
478        exec_settlement_mode: ExecSettlementMode,
479    ) -> Result<Value> {
480        let args = crate::tools::command_args::normalize_shell_args(&args).map_err(|error| anyhow!(error))?;
481
482        let action_str =
483            tool_intent::command_session_action(&args).ok_or_else(|| missing_command_session_action_error(&args))?;
484        let action: CommandSessionAction = parse_action(action_str)?;
485
486        match action {
487            CommandSessionAction::Run => self.execute_command_session_run_internal(args, exec_settlement_mode).await,
488            CommandSessionAction::Write => self.execute_command_session_write(args).await,
489            CommandSessionAction::Poll => self.execute_command_session_poll_internal(args, exec_settlement_mode).await,
490            CommandSessionAction::Wait => self.execute_command_session_wait(args).await,
491            CommandSessionAction::Continue => {
492                self.execute_command_session_continue_internal(args, exec_settlement_mode).await
493            }
494            CommandSessionAction::Inspect => self.execute_command_session_inspect(args).await,
495            CommandSessionAction::List => self.execute_command_session_list().await,
496            CommandSessionAction::Close => self.execute_command_session_close(args).await,
497            CommandSessionAction::Code => self.execute_code(args).await,
498        }
499    }
500
501    async fn execute_command_session_run_internal(
502        &self,
503        args: Value,
504        exec_settlement_mode: ExecSettlementMode,
505    ) -> Result<Value> {
506        let tty = args.get("tty").and_then(Value::as_bool).unwrap_or(false);
507        if tty {
508            self.execute_command_session_run_pty(args, false).await
509        } else {
510            self.execute_run_pipe_cmd(args, exec_settlement_mode).await
511        }
512    }
513
514    async fn execute_code_search(&self, args: Value) -> Result<Value> {
515        let request = serde_json::from_value(args).context("invalid code_search request")?;
516        let response = crate::tools::code_search::execute(self.workspace_root(), request).await?;
517        serde_json::to_value(response).context("failed to serialise code_search response")
518    }
519
520    async fn execute_code(&self, args: Value) -> Result<Value> {
521        acquire_executor_rate_limit("unified_exec:code", 2.0)?;
522
523        let code = args
524            .get("command")
525            .or_else(|| args.get("code"))
526            .and_then(|v| v.as_str())
527            .ok_or_else(|| anyhow!("Missing code/command in execute_code"))?;
528
529        let cwd = self.workspace_root();
530        // Arbitrary interpreter code has the same file-writing authority as a
531        // shell script. It cannot be a route around guarded file mutations.
532        self.edited_file_monitor_ref().source_inspection().check_shell(&args, cwd)?;
533        let language = code_language_from_args(&args);
534
535        // The `code` action spawns the interpreter directly, so it must clear
536        // the same command policy as `run`: a policy that excludes
537        // `python3`/`node` must not be bypassed through code mode.
538        let interpreter = language.interpreter().to_string();
539        if !self.inventory.command_policy_allows(std::slice::from_ref(&interpreter)) {
540            return Err(anyhow!("code execution via '{interpreter}' is not permitted by the execution policy"));
541        }
542
543        let track_files = args.get("track_files").and_then(|v| v.as_bool()).unwrap_or(false);
544
545        let mcp_client = self.mcp_client().ok_or_else(|| anyhow!("MCP client not available"))?;
546
547        let workspace_root = self.workspace_root_owned();
548        // Expose built-in tools to the snippet as callable library functions
549        // (curated, non-recursive subset) when a weak self-reference was
550        // installed at session bootstrap.
551        let builtin_executor = self.builtin_executor_for_code();
552        let executor =
553            crate::exec::code_executor::CodeExecutor::new(language, mcp_client.clone(), workspace_root.clone())
554                .with_builtin_executor(builtin_executor);
555        let execution_start = SystemTime::now();
556
557        let result = executor.execute(code).await?;
558
559        let mut response = json!(result);
560
561        if track_files {
562            let tracker = FileTracker::new(workspace_root);
563            match tracker.detect_new_files(execution_start).await {
564                Ok(changes) => {
565                    response["generated_files"] = json!({
566                        "count": changes.len(),
567                        "files": changes,
568                        "summary": tracker.generate_file_summary(&changes),
569                    });
570                }
571                Err(e) => {
572                    tracing::warn!(
573                        error = %e,
574                        "FileTracker failed to detect new files after code execution"
575                    );
576                }
577            }
578        }
579
580        Ok(response)
581    }
582
583    async fn execute_apply_patch(&self, args: Value) -> Result<Value> {
584        let (patch_args, patch_input_bytes, patch_base64) = self.prepare_apply_patch_args(args)?;
585        let context = self.harness_context_snapshot();
586        tracing::debug!(
587            tool = tools::APPLY_PATCH,
588            payload_bytes = serialized_payload_size_bytes(&patch_args),
589            patch_input_bytes,
590            patch_base64,
591            patch_decoded_bytes = patch_args
592                .get("input")
593                .and_then(|v| v.as_str())
594                .map(|s| s.len())
595                .unwrap_or(0),
596            session_id = %context.session_id,
597            task_id = %context.task_id.as_deref().unwrap_or(""),
598            "Prepared apply_patch payload"
599        );
600
601        self.execute_apply_patch_internal(patch_args).await
602    }
603
604    fn prepare_apply_patch_args(&self, args: Value) -> Result<(Value, usize, bool)> {
605        let patch_input = crate::tools::apply_patch::decode_apply_patch_input(&args)?
606            .ok_or_else(|| anyhow!("Missing patch input {}", crate::tools::error_helpers::PATCH_PARAMETER_HINT))?;
607        let patch_input_bytes = patch_input.source_bytes;
608        let patch_base64 = patch_input.was_base64;
609
610        // Guard against a bare-string `args` (some callers pass the patch text
611        // directly as a JSON string rather than an object). Indexing a
612        // `Value::String` with `["input"]` panics in serde_json, so normalize
613        // to an object first.
614        let mut patch_args = if args.is_object() { args } else { json!({}) };
615        patch_args["input"] = json!(patch_input.text);
616        Ok((patch_args, patch_input_bytes, patch_base64))
617    }
618
619    async fn resolve_exec_sandbox_request(
620        &self,
621        payload: &serde_json::Map<String, Value>,
622    ) -> Result<ResolvedExecSandboxRequest> {
623        let working_dir_path = self.pty_manager().resolve_working_dir(shell_working_dir_value(payload)).await?;
624        let sandbox_config = self.sandbox_config();
625        let (sandbox_permissions, additional_permissions) =
626            parse_requested_sandbox_permissions(payload, self.workspace_root(), &working_dir_path, &sandbox_config)
627                .await?;
628
629        Ok(ResolvedExecSandboxRequest {
630            working_dir_path,
631            sandbox_permissions,
632            additional_permissions,
633        })
634    }
635
636    // ============================================================
637    // SPECIALIZED EXECUTORS (Hidden from LLM, used by unified tools)
638    // ============================================================
639
640    // File operation executors -- delegate to the file_ops_tool from inventory
641    delegate_to_tool!(read_file_executor, file_ops_tool, read_file);
642    delegate_to_tool!(write_file_executor, file_ops_tool, write_file);
643
644    // Self-delegating executors -- forward to async methods on ToolRegistry
645    delegate_to_self!(list_files_executor, list_files);
646    delegate_to_self!(edit_file_executor, edit_file);
647    delegate_to_self!(get_errors_executor, execute_get_errors);
648    delegate_to_self!(search_tools_executor, execute_search_tools);
649    delegate_to_self!(mcp_search_tools_executor, execute_mcp_search_tools);
650    delegate_to_self!(mcp_get_tool_details_executor, execute_mcp_get_tool_details);
651    delegate_to_self!(mcp_list_servers_executor, execute_mcp_list_servers);
652    delegate_to_self!(mcp_connect_server_executor, execute_mcp_connect_server);
653    delegate_to_self!(mcp_disconnect_server_executor, execute_mcp_disconnect_server);
654    delegate_to_self!(apply_patch_executor, execute_apply_patch);
655
656    /// Unified `mcp` executor: dispatches on `action`
657    /// (search_tools | get_tool_details | list_servers | connect | disconnect).
658    /// For legacy alias calls that omit `action`, the action is inferred from
659    /// the argument shape: `query` implies search_tools, `name` implies
660    /// get_tool_details, otherwise list_servers. `connect`/`disconnect` require
661    /// an explicit `action` since the schema marks it required, and are
662    /// evaluated under the action-qualified policy keys `mcp:connect` /
663    /// `mcp:disconnect` so they keep their Prompt confirmation even though
664    /// `mcp` itself is `ToolPolicy::Allow`.
665    #[cfg_attr(
666        not(test),
667        allow(
668            dead_code,
669            reason = "Legacy executor aliases remain available for compatibility tests."
670        )
671    )]
672    pub(super) fn mcp_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
673        Box::pin(async move {
674            let action = args
675                .get("action")
676                .and_then(Value::as_str)
677                .map(str::to_ascii_lowercase)
678                .unwrap_or_else(|| {
679                    if args.get("query").is_some() {
680                        "search_tools".to_string()
681                    } else if args.get("name").is_some() {
682                        "get_tool_details".to_string()
683                    } else {
684                        "list_servers".to_string()
685                    }
686                });
687            match action.as_str() {
688                "search_tools" => self.mcp_search_tools_executor(args).await,
689                "get_tool_details" => self.mcp_get_tool_details_executor(args).await,
690                "list_servers" => self.mcp_list_servers_executor(args).await,
691                "connect" => self.mcp_connect_server_executor(args).await,
692                "disconnect" => self.mcp_disconnect_server_executor(args).await,
693                other => Err(anyhow!(
694                    "mcp: unknown action '{other}'. Use action='search_tools' (query), 'get_tool_details' (name), 'list_servers', 'connect' (name), or 'disconnect' (name)."
695                )),
696            }
697        })
698    }
699
700    // PTY executors -- distinct signatures, kept explicit.
701    // `run_pty_cmd` and `create_pty_session` are intentional aliases: both
702    // create a PTY session and run a command. The separate names exist for
703    // backward compatibility with existing tool registrations.
704    pub(super) fn run_pty_cmd_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
705        self.dispatch_command_session_run_alias(args, true)
706    }
707
708    pub(super) fn exec_command_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
709        self.dispatch_command_session_run_alias(args, false)
710    }
711
712    pub(super) fn write_stdin_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
713        Box::pin(self.execute_write_stdin(args, ExecSettlementMode::Manual))
714    }
715
716    pub(super) async fn execute_write_stdin(&self, args: Value, settlement_mode: ExecSettlementMode) -> Result<Value> {
717        let (args, dispatch) = normalize_write_stdin_args(&args)?;
718
719        let observed_args = args.clone();
720        let result = async {
721            let response = match dispatch {
722                crate::tools::command_args::WriteStdinDispatch::Write => {
723                    self.execute_command_session_write_for_tool(args, tools::WRITE_STDIN).await
724                }
725                crate::tools::command_args::WriteStdinDispatch::Poll => {
726                    self.execute_command_session_poll_for_tool(args, settlement_mode, tools::WRITE_STDIN)
727                        .await
728                }
729                crate::tools::command_args::WriteStdinDispatch::Wait => self.execute_command_session_wait(args).await,
730                crate::tools::command_args::WriteStdinDispatch::Inspect => {
731                    self.execute_command_session_inspect(args).await
732                }
733                crate::tools::command_args::WriteStdinDispatch::Terminate => {
734                    self.execute_command_session_terminate(args).await
735                }
736                crate::tools::command_args::WriteStdinDispatch::Close => self.execute_command_session_close(args).await,
737            }?;
738            Ok(response)
739        }
740        .await;
741        self.observe_completion_verifier(None, &observed_args, &result);
742        result
743    }
744
745    pub(super) fn send_pty_input_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
746        self.dispatch_command_session_action_alias(args, "write")
747    }
748
749    pub(super) fn read_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
750        self.dispatch_command_session_action_alias(args, "poll")
751    }
752
753    pub(super) fn create_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
754        self.dispatch_command_session_run_alias(args, true)
755    }
756
757    pub(super) fn list_pty_sessions_executor(&self, _args: Value) -> BoxFuture<'_, Result<Value>> {
758        self.dispatch_command_session_alias(json!({"action": "list"}))
759    }
760
761    pub(super) fn close_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
762        self.dispatch_command_session_action_alias(args, "close")
763    }
764
765    // ============================================================
766    // INTERNAL IMPLEMENTATIONS
767    // ============================================================
768}
769
770#[cfg(test)]
771mod sandbox_runtime_tests;
772#[cfg(test)]
773mod session_messaging_tests;
774
775#[cfg(test)]
776mod execute_code_tests;
777#[cfg(test)]
778mod git_diff_tests;
779#[cfg(test)]
780mod mcp_action_dispatch_tests;
781#[cfg(test)]
782mod pty_context_tests;
783#[cfg(test)]
784mod pty_output_filter_tests;
785#[cfg(test)]
786mod shell_preference_tests;
787#[cfg(test)]
788mod subagent_tool_output_tests;
789#[cfg(test)]
790mod token_efficiency_tests;
791#[cfg(test)]
792mod unified_action_error_tests;