use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use agent_base::{AgentError, AgentResult, Content, ToolContext};
use serde_json::Value;
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use super::TRUNCATION_MARKER;
use super::law::script_file_index;
use super::subst::substitute_params;
use super::types::ScriptToolEntry;
pub(crate) fn truncate_output(s: &str, max_chars: Option<usize>) -> String {
let Some(max_chars) = max_chars else {
return s.to_string();
};
let total = s.chars().count();
if total <= max_chars {
return s.to_string();
}
if max_chars <= TRUNCATION_MARKER.chars().count() + 2 {
return s.chars().take(max_chars).collect();
}
let available = max_chars.saturating_sub(TRUNCATION_MARKER.chars().count() + 2);
let head_chars = available / 3;
let tail_chars = available - head_chars;
let head: String = s.chars().take(head_chars).collect();
let tail: String = s
.chars()
.rev()
.take(tail_chars)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
format!("{head}\n{TRUNCATION_MARKER}\n{tail}")
}
async fn kill_tree(pid: Option<u32>) {
let Some(pid) = pid else { return };
#[cfg(unix)]
{
unsafe {
libc::kill(-(pid as i32), libc::SIGKILL);
}
}
#[cfg(windows)]
{
let _ = Command::new("taskkill")
.args(["/T", "/F", "/PID", &pid.to_string()])
.creation_flags(0x0800_0000) .stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.await;
}
}
pub async fn execute_entry(
tool_key: &str,
entry: &ScriptToolEntry,
args: &Value,
ctx: &ToolContext,
) -> AgentResult<Vec<Content>> {
let argv = substitute_params(tool_key, &entry.run, args)?;
let script_index = script_file_index(&entry.run).map_err(|e| AgentError::ToolExecution {
name: tool_key.to_string(),
source: Box::new(AgentError::Internal(e.to_string())),
})?;
let script_path = Path::new(&argv[script_index]);
if !script_path.is_file() {
return Err(AgentError::ToolExecution {
name: tool_key.to_string(),
source: Box::new(AgentError::Internal(format!(
"script is gone: {}",
script_path.display()
))),
});
}
let mut cmd = Command::new(&argv[0]);
cmd.args(&argv[1..])
.envs(&entry.env) .stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(dir) = &entry.cwd {
cmd.current_dir(dir);
}
#[cfg(unix)]
cmd.process_group(0); #[cfg(windows)]
cmd.creation_flags(0x0800_0000);
let mut child = cmd.spawn().map_err(|e| AgentError::ToolExecution {
name: tool_key.to_string(),
source: Box::new(AgentError::Internal(format!(
"failed to spawn {}: {e}",
argv[0]
))),
})?;
let pid = child.id();
let mut stdout_pipe = child.stdout.take();
let mut stderr_pipe = child.stderr.take();
let stdout_task = tokio::spawn(async move {
let mut buf = Vec::new();
if let Some(pipe) = stdout_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf).await;
}
buf
});
let stderr_task = tokio::spawn(async move {
let mut buf = Vec::new();
if let Some(pipe) = stderr_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf).await;
}
buf
});
enum WaitEnd {
Exited(std::io::Result<std::process::ExitStatus>),
Cancelled,
}
let timeout = Duration::from_millis(entry.timeout_ms());
let wait_future = async {
tokio::select! {
_ = ctx.cancel_token.cancelled() => WaitEnd::Cancelled,
status = child.wait() => WaitEnd::Exited(status),
}
};
let ended = tokio::time::timeout(timeout, wait_future).await;
let status = match ended {
Err(_elapsed) => {
kill_tree(pid).await;
let _ = child.wait().await;
return Err(AgentError::ToolTimeout);
}
Ok(WaitEnd::Cancelled) => {
kill_tree(pid).await;
let _ = child.wait().await;
return Err(AgentError::Cancelled);
}
Ok(WaitEnd::Exited(Err(e))) => {
return Err(AgentError::ToolExecution {
name: tool_key.to_string(),
source: Box::new(AgentError::Internal(format!("wait failed: {e}"))),
});
}
Ok(WaitEnd::Exited(Ok(status))) => status,
};
let read_deadline = Duration::from_secs(5);
let stdout = tokio::time::timeout(read_deadline, stdout_task)
.await
.ok()
.and_then(|t| t.ok())
.unwrap_or_default();
let stderr = tokio::time::timeout(read_deadline, stderr_task)
.await
.ok()
.and_then(|t| t.ok())
.unwrap_or_default();
let stdout = String::from_utf8_lossy(&stdout).into_owned();
let stderr = String::from_utf8_lossy(&stderr).into_owned();
if !status.success() {
let summary = if stderr.trim().is_empty() {
stdout.clone()
} else {
stderr.clone()
};
let summary = truncate_output(summary.trim(), ctx.max_output_chars);
return Err(AgentError::ToolExecution {
name: tool_key.to_string(),
source: Box::new(AgentError::Internal(format!(
"script exited with {status}: {summary}"
))),
});
}
let body = if stdout.trim().is_empty() {
stderr
} else {
stdout
};
Ok(vec![Content::text(truncate_output(
body.trim_end_matches('\n'),
ctx.max_output_chars,
))])
}