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
129macro_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
139macro_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 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 #[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 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 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 &sandbox_request.working_dir_path,
407 sandbox_plan.sandbox_policy,
408 )?;
409
410 let rows = match backend {
411 ExecRunBackendKind::Pty => {
412 Some(parse_pty_dimension("rows", payload.get("rows"), self.pty_config().default_rows)?)
413 }
414 ExecRunBackendKind::Pipe => None,
415 };
416 let cols = match backend {
417 ExecRunBackendKind::Pty => {
418 Some(parse_pty_dimension("cols", payload.get("cols"), self.pty_config().default_cols)?)
419 }
420 ExecRunBackendKind::Pipe => None,
421 };
422
423 Ok(PreparedExecRunRequest {
424 prepared_command,
425 working_dir_path: sandbox_request.working_dir_path,
426 output_config,
427 yield_duration: Duration::from_millis(
428 clamp_exec_yield_ms(
429 payload.get("yield_time_ms").and_then(Value::as_u64),
430 if background { 250 } else { 10_000 },
431 )
432 .min(if background { 1_000 } else { 30_000 }),
433 ),
434 session_id: resolve_exec_run_session_id(payload)?,
435 shell_program,
436 env_overrides: parse_exec_env_overrides(payload)?,
437 is_git_diff,
438 confirm,
439 rows,
440 cols,
441 sandbox_active,
442 background,
443 stdin,
444 monitor,
445 })
446 }
447
448 pub(super) async fn execute_command_session(&self, args: Value) -> Result<Value> {
449 self.execute_command_session_internal(args, ExecSettlementMode::Manual).await
450 }
451
452 pub(super) async fn execute_harness_command_session_terminal_run_raw(&self, args: Value) -> Result<Value> {
453 let args = normalize_command_session_run_alias_args(&args, true)?;
454 self.execute_command_session_run_pty(args, true).await
455 }
456
457 fn dispatch_command_session_alias(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
458 Box::pin(async move { self.execute_command_session(args).await.map(super::normalize_tool_output) })
459 }
460
461 fn dispatch_command_session_run_alias(&self, args: Value, tty: bool) -> BoxFuture<'_, Result<Value>> {
462 Box::pin(async move {
463 let args = normalize_command_session_run_alias_args(&args, tty)?;
464 self.execute_command_session(args).await.map(super::normalize_tool_output)
465 })
466 }
467
468 fn dispatch_command_session_action_alias(&self, args: Value, action: &'static str) -> BoxFuture<'_, Result<Value>> {
469 self.dispatch_command_session_alias(with_command_session_action_default(args, action))
470 }
471
472 pub(super) async fn execute_command_session_internal(
473 &self,
474 args: Value,
475 exec_settlement_mode: ExecSettlementMode,
476 ) -> Result<Value> {
477 let launch = self.begin_completion_verifier(&args);
478 let result = self.execute_command_session_observed(args.clone(), exec_settlement_mode).await;
479 self.observe_completion_verifier(launch, &args, &result);
480 result
481 }
482
483 async fn execute_command_session_observed(
484 &self,
485 args: Value,
486 exec_settlement_mode: ExecSettlementMode,
487 ) -> Result<Value> {
488 let args = crate::tools::command_args::normalize_shell_args(&args).map_err(|error| anyhow!(error))?;
489
490 let action_str =
491 tool_intent::command_session_action(&args).ok_or_else(|| missing_command_session_action_error(&args))?;
492 let action: CommandSessionAction = parse_action(action_str)?;
493
494 match action {
495 CommandSessionAction::Run => self.execute_command_session_run_internal(args, exec_settlement_mode).await,
496 CommandSessionAction::Write => self.execute_command_session_write(args).await,
497 CommandSessionAction::Poll => self.execute_command_session_poll_internal(args, exec_settlement_mode).await,
498 CommandSessionAction::Wait => self.execute_command_session_wait(args).await,
499 CommandSessionAction::Continue => {
500 self.execute_command_session_continue_internal(args, exec_settlement_mode).await
501 }
502 CommandSessionAction::Inspect => self.execute_command_session_inspect(args).await,
503 CommandSessionAction::List => self.execute_command_session_list().await,
504 CommandSessionAction::Close => self.execute_command_session_close(args).await,
505 CommandSessionAction::Code => self.execute_code(args).await,
506 }
507 }
508
509 async fn execute_command_session_run_internal(
510 &self,
511 args: Value,
512 exec_settlement_mode: ExecSettlementMode,
513 ) -> Result<Value> {
514 let tty = args.get("tty").and_then(Value::as_bool).unwrap_or(false);
515 if tty {
516 self.execute_command_session_run_pty(args, false).await
517 } else {
518 self.execute_run_pipe_cmd(args, exec_settlement_mode).await
519 }
520 }
521
522 async fn execute_code_search(&self, args: Value) -> Result<Value> {
523 let request = serde_json::from_value(args).context("invalid code_search request")?;
524 let response = crate::tools::code_search::execute(self.workspace_root(), request).await?;
525 serde_json::to_value(response).context("failed to serialise code_search response")
526 }
527
528 async fn execute_code(&self, args: Value) -> Result<Value> {
529 acquire_executor_rate_limit("unified_exec:code", 2.0)?;
530
531 let code = args
532 .get("command")
533 .or_else(|| args.get("code"))
534 .and_then(|v| v.as_str())
535 .ok_or_else(|| anyhow!("Missing code/command in execute_code"))?;
536
537 let cwd = self.workspace_root();
538 self.edited_file_monitor_ref().source_inspection().check_shell(&args, cwd)?;
541 let language = code_language_from_args(&args);
542
543 let interpreter = language.interpreter().to_string();
547 if !self.inventory.command_policy_allows(std::slice::from_ref(&interpreter)) {
548 return Err(anyhow!("code execution via '{interpreter}' is not permitted by the execution policy"));
549 }
550
551 let track_files = args.get("track_files").and_then(|v| v.as_bool()).unwrap_or(false);
552
553 let mcp_client = self.mcp_client().ok_or_else(|| anyhow!("MCP client not available"))?;
554
555 let workspace_root = self.workspace_root_owned();
556 let builtin_executor = self.builtin_executor_for_code();
560 let executor =
561 crate::exec::code_executor::CodeExecutor::new(language, mcp_client.clone(), workspace_root.clone())
562 .with_builtin_executor(builtin_executor);
563 let execution_start = SystemTime::now();
564
565 let result = executor.execute(code).await?;
566
567 let mut response = json!(result);
568
569 if track_files {
570 let tracker = FileTracker::new(workspace_root);
571 match tracker.detect_new_files(execution_start).await {
572 Ok(changes) => {
573 response["generated_files"] = json!({
574 "count": changes.len(),
575 "files": changes,
576 "summary": tracker.generate_file_summary(&changes),
577 });
578 }
579 Err(e) => {
580 tracing::warn!(
581 error = %e,
582 "FileTracker failed to detect new files after code execution"
583 );
584 }
585 }
586 }
587
588 Ok(response)
589 }
590
591 async fn execute_apply_patch(&self, args: Value) -> Result<Value> {
592 let (patch_args, patch_input_bytes, patch_base64) = self.prepare_apply_patch_args(args)?;
593 let context = self.harness_context_snapshot();
594 tracing::debug!(
595 tool = tools::APPLY_PATCH,
596 payload_bytes = serialized_payload_size_bytes(&patch_args),
597 patch_input_bytes,
598 patch_base64,
599 patch_decoded_bytes = patch_args
600 .get("input")
601 .and_then(|v| v.as_str())
602 .map(|s| s.len())
603 .unwrap_or(0),
604 session_id = %context.session_id,
605 task_id = %context.task_id.as_deref().unwrap_or(""),
606 "Prepared apply_patch payload"
607 );
608
609 self.execute_apply_patch_internal(patch_args).await
610 }
611
612 fn prepare_apply_patch_args(&self, args: Value) -> Result<(Value, usize, bool)> {
613 let patch_input = crate::tools::apply_patch::decode_apply_patch_input(&args)?
614 .ok_or_else(|| anyhow!("Missing patch input {}", crate::tools::error_helpers::PATCH_PARAMETER_HINT))?;
615 let patch_input_bytes = patch_input.source_bytes;
616 let patch_base64 = patch_input.was_base64;
617
618 let mut patch_args = if args.is_object() { args } else { json!({}) };
623 patch_args["input"] = json!(patch_input.text);
624 Ok((patch_args, patch_input_bytes, patch_base64))
625 }
626
627 async fn resolve_exec_sandbox_request(
628 &self,
629 payload: &serde_json::Map<String, Value>,
630 ) -> Result<ResolvedExecSandboxRequest> {
631 let working_dir_path = self.pty_manager().resolve_working_dir(shell_working_dir_value(payload)).await?;
632 let sandbox_config = self.sandbox_config();
633 let (sandbox_permissions, additional_permissions) =
634 parse_requested_sandbox_permissions(payload, self.workspace_root(), &working_dir_path, &sandbox_config)
635 .await?;
636
637 Ok(ResolvedExecSandboxRequest {
638 working_dir_path,
639 sandbox_permissions,
640 additional_permissions,
641 })
642 }
643
644 delegate_to_tool!(read_file_executor, file_ops_tool, read_file);
650 delegate_to_tool!(write_file_executor, file_ops_tool, write_file);
651
652 delegate_to_self!(list_files_executor, list_files);
654 delegate_to_self!(edit_file_executor, edit_file);
655 delegate_to_self!(get_errors_executor, execute_get_errors);
656 delegate_to_self!(search_tools_executor, execute_search_tools);
657 delegate_to_self!(mcp_search_tools_executor, execute_mcp_search_tools);
658 delegate_to_self!(mcp_get_tool_details_executor, execute_mcp_get_tool_details);
659 delegate_to_self!(mcp_list_servers_executor, execute_mcp_list_servers);
660 delegate_to_self!(mcp_connect_server_executor, execute_mcp_connect_server);
661 delegate_to_self!(mcp_disconnect_server_executor, execute_mcp_disconnect_server);
662 delegate_to_self!(apply_patch_executor, execute_apply_patch);
663
664 #[cfg_attr(
674 not(test),
675 allow(
676 dead_code,
677 reason = "Legacy executor aliases remain available for compatibility tests."
678 )
679 )]
680 pub(super) fn mcp_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
681 Box::pin(async move {
682 let action = args
683 .get("action")
684 .and_then(Value::as_str)
685 .map(str::to_ascii_lowercase)
686 .unwrap_or_else(|| {
687 if args.get("query").is_some() {
688 "search_tools".to_string()
689 } else if args.get("name").is_some() {
690 "get_tool_details".to_string()
691 } else {
692 "list_servers".to_string()
693 }
694 });
695 match action.as_str() {
696 "search_tools" => self.mcp_search_tools_executor(args).await,
697 "get_tool_details" => self.mcp_get_tool_details_executor(args).await,
698 "list_servers" => self.mcp_list_servers_executor(args).await,
699 "connect" => self.mcp_connect_server_executor(args).await,
700 "disconnect" => self.mcp_disconnect_server_executor(args).await,
701 other => Err(anyhow!(
702 "mcp: unknown action '{other}'. Use action='search_tools' (query), 'get_tool_details' (name), 'list_servers', 'connect' (name), or 'disconnect' (name)."
703 )),
704 }
705 })
706 }
707
708 pub(super) fn run_pty_cmd_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
713 self.dispatch_command_session_run_alias(args, true)
714 }
715
716 pub(super) fn exec_command_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
717 self.dispatch_command_session_run_alias(args, false)
718 }
719
720 pub(super) fn write_stdin_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
721 Box::pin(self.execute_write_stdin(args, ExecSettlementMode::Manual))
722 }
723
724 pub(super) async fn execute_write_stdin(&self, args: Value, settlement_mode: ExecSettlementMode) -> Result<Value> {
725 let (args, dispatch) = normalize_write_stdin_args(&args)?;
726
727 let observed_args = args.clone();
728 let result = async {
729 let response = match dispatch {
730 crate::tools::command_args::WriteStdinDispatch::Write => {
731 self.execute_command_session_write_for_tool(args, tools::WRITE_STDIN).await
732 }
733 crate::tools::command_args::WriteStdinDispatch::Poll => {
734 self.execute_command_session_poll_for_tool(args, settlement_mode, tools::WRITE_STDIN)
735 .await
736 }
737 crate::tools::command_args::WriteStdinDispatch::Wait => self.execute_command_session_wait(args).await,
738 crate::tools::command_args::WriteStdinDispatch::Inspect => {
739 self.execute_command_session_inspect(args).await
740 }
741 crate::tools::command_args::WriteStdinDispatch::Terminate => {
742 self.execute_command_session_terminate(args).await
743 }
744 crate::tools::command_args::WriteStdinDispatch::Close => self.execute_command_session_close(args).await,
745 }?;
746 Ok(response)
747 }
748 .await;
749 self.observe_completion_verifier(None, &observed_args, &result);
750 result
751 }
752
753 pub(super) fn send_pty_input_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
754 self.dispatch_command_session_action_alias(args, "write")
755 }
756
757 pub(super) fn read_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
758 self.dispatch_command_session_action_alias(args, "poll")
759 }
760
761 pub(super) fn create_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
762 self.dispatch_command_session_run_alias(args, true)
763 }
764
765 pub(super) fn list_pty_sessions_executor(&self, _args: Value) -> BoxFuture<'_, Result<Value>> {
766 self.dispatch_command_session_alias(json!({"action": "list"}))
767 }
768
769 pub(super) fn close_pty_session_executor(&self, args: Value) -> BoxFuture<'_, Result<Value>> {
770 self.dispatch_command_session_action_alias(args, "close")
771 }
772
773 }
777
778#[cfg(test)]
779mod sandbox_runtime_tests;
780#[cfg(test)]
781mod session_messaging_tests;
782
783#[cfg(test)]
784mod execute_code_tests;
785#[cfg(test)]
786mod git_diff_tests;
787#[cfg(test)]
788mod mcp_action_dispatch_tests;
789#[cfg(test)]
790mod pty_context_tests;
791#[cfg(test)]
792mod pty_output_filter_tests;
793#[cfg(test)]
794mod shell_preference_tests;
795#[cfg(test)]
796mod subagent_tool_output_tests;
797#[cfg(test)]
798mod token_efficiency_tests;
799#[cfg(test)]
800mod unified_action_error_tests;