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