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