agent_works/script_tool/
exec.rs1use std::path::Path;
2use std::process::Stdio;
3use std::time::Duration;
4
5use agent_base::{AgentError, AgentResult, Content, ToolContext};
6use serde_json::Value;
7use tokio::io::AsyncReadExt;
8use tokio::process::Command;
9
10use super::TRUNCATION_MARKER;
11use super::law::script_file_index;
12use super::subst::substitute_params;
13use super::types::ScriptToolEntry;
14
15pub(crate) fn truncate_output(s: &str, max_chars: Option<usize>) -> String {
22 let Some(max_chars) = max_chars else {
23 return s.to_string();
24 };
25 let total = s.chars().count();
26 if total <= max_chars {
27 return s.to_string();
28 }
29 if max_chars <= TRUNCATION_MARKER.chars().count() + 2 {
30 return s.chars().take(max_chars).collect();
31 }
32 let available = max_chars.saturating_sub(TRUNCATION_MARKER.chars().count() + 2);
33 let head_chars = available / 3;
34 let tail_chars = available - head_chars;
35 let head: String = s.chars().take(head_chars).collect();
36 let tail: String = s
37 .chars()
38 .rev()
39 .take(tail_chars)
40 .collect::<Vec<_>>()
41 .into_iter()
42 .rev()
43 .collect();
44 format!("{head}\n{TRUNCATION_MARKER}\n{tail}")
45}
46
47async fn kill_tree(pid: Option<u32>) {
53 let Some(pid) = pid else { return };
54 #[cfg(unix)]
55 {
56 unsafe {
58 libc::kill(-(pid as i32), libc::SIGKILL);
59 }
60 }
61 #[cfg(windows)]
62 {
63 let _ = Command::new("taskkill")
64 .args(["/T", "/F", "/PID", &pid.to_string()])
65 .creation_flags(0x0800_0000) .stdout(Stdio::null())
67 .stderr(Stdio::null())
68 .status()
69 .await;
70 }
71}
72
73pub async fn execute_entry(
78 tool_key: &str,
79 entry: &ScriptToolEntry,
80 args: &Value,
81 ctx: &ToolContext,
82) -> AgentResult<Vec<Content>> {
83 let argv = substitute_params(tool_key, &entry.run, args)?;
84
85 let script_index = script_file_index(&entry.run).map_err(|e| AgentError::ToolExecution {
87 name: tool_key.to_string(),
88 source: Box::new(AgentError::Internal(e.to_string())),
89 })?;
90 let script_path = Path::new(&argv[script_index]);
91 if !script_path.is_file() {
92 return Err(AgentError::ToolExecution {
93 name: tool_key.to_string(),
94 source: Box::new(AgentError::Internal(format!(
95 "script is gone: {}",
96 script_path.display()
97 ))),
98 });
99 }
100
101 let mut cmd = Command::new(&argv[0]);
102 cmd.args(&argv[1..])
103 .envs(&entry.env) .stdin(Stdio::null())
105 .stdout(Stdio::piped())
106 .stderr(Stdio::piped())
107 .kill_on_drop(true);
108 if let Some(dir) = &entry.cwd {
109 cmd.current_dir(dir);
110 }
111 #[cfg(unix)]
112 cmd.process_group(0); #[cfg(windows)]
114 cmd.creation_flags(0x0800_0000); let mut child = cmd.spawn().map_err(|e| AgentError::ToolExecution {
117 name: tool_key.to_string(),
118 source: Box::new(AgentError::Internal(format!(
119 "failed to spawn {}: {e}",
120 argv[0]
121 ))),
122 })?;
123 let pid = child.id();
124
125 let mut stdout_pipe = child.stdout.take();
128 let mut stderr_pipe = child.stderr.take();
129 let stdout_task = tokio::spawn(async move {
130 let mut buf = Vec::new();
131 if let Some(pipe) = stdout_pipe.as_mut() {
132 let _ = pipe.read_to_end(&mut buf).await;
133 }
134 buf
135 });
136 let stderr_task = tokio::spawn(async move {
137 let mut buf = Vec::new();
138 if let Some(pipe) = stderr_pipe.as_mut() {
139 let _ = pipe.read_to_end(&mut buf).await;
140 }
141 buf
142 });
143
144 enum WaitEnd {
147 Exited(std::io::Result<std::process::ExitStatus>),
148 Cancelled,
149 }
150 let timeout = Duration::from_millis(entry.timeout_ms());
151 let wait_future = async {
152 tokio::select! {
153 _ = ctx.cancel_token.cancelled() => WaitEnd::Cancelled,
154 status = child.wait() => WaitEnd::Exited(status),
155 }
156 };
157 let ended = tokio::time::timeout(timeout, wait_future).await;
158
159 let status = match ended {
160 Err(_elapsed) => {
161 kill_tree(pid).await;
163 let _ = child.wait().await;
164 return Err(AgentError::ToolTimeout);
165 }
166 Ok(WaitEnd::Cancelled) => {
167 kill_tree(pid).await;
168 let _ = child.wait().await;
169 return Err(AgentError::Cancelled);
170 }
171 Ok(WaitEnd::Exited(Err(e))) => {
172 return Err(AgentError::ToolExecution {
173 name: tool_key.to_string(),
174 source: Box::new(AgentError::Internal(format!("wait failed: {e}"))),
175 });
176 }
177 Ok(WaitEnd::Exited(Ok(status))) => status,
178 };
179
180 let read_deadline = Duration::from_secs(5);
181 let stdout = tokio::time::timeout(read_deadline, stdout_task)
182 .await
183 .ok()
184 .and_then(|t| t.ok())
185 .unwrap_or_default();
186 let stderr = tokio::time::timeout(read_deadline, stderr_task)
187 .await
188 .ok()
189 .and_then(|t| t.ok())
190 .unwrap_or_default();
191 let stdout = String::from_utf8_lossy(&stdout).into_owned();
192 let stderr = String::from_utf8_lossy(&stderr).into_owned();
193
194 if !status.success() {
195 let summary = if stderr.trim().is_empty() {
197 stdout.clone()
198 } else {
199 stderr.clone()
200 };
201 let summary = truncate_output(summary.trim(), ctx.max_output_chars);
202 return Err(AgentError::ToolExecution {
203 name: tool_key.to_string(),
204 source: Box::new(AgentError::Internal(format!(
205 "script exited with {status}: {summary}"
206 ))),
207 });
208 }
209
210 let body = if stdout.trim().is_empty() {
211 stderr
212 } else {
213 stdout
214 };
215 Ok(vec![Content::text(truncate_output(
216 body.trim_end_matches('\n'),
217 ctx.max_output_chars,
218 ))])
219}