1use std::collections::BTreeMap;
32use std::path::{Component, Path, PathBuf};
33use std::process::Stdio;
34use std::time::Duration;
35
36use agent_base::tool::Tool;
37use agent_base::{AgentError, AgentResult, Content, ToolContext, ToolExposure};
38use async_trait::async_trait;
39use serde::{Deserialize, Serialize};
40use serde_json::{Value, json};
41use tokio::io::AsyncReadExt;
42use tokio::process::Command;
43
44use crate::tool_provider::{ToolDescriptor, ToolIdentity, ToolProvider};
45
46pub const DEFAULT_TIMEOUT_MS: u64 = 60_000;
48
49pub const INTERPRETER_WHITELIST: [&str; 3] = ["powershell", "pwsh", "cmd"];
51
52pub(crate) const TRUNCATION_MARKER: &str = "...[output truncated]";
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum ScriptLawError {
60 BadName { name: String },
62 EmptyRun,
64 RelativeProgram { program: String },
66 InterpreterMissingScriptArg { interpreter: String },
68 RelativeScriptArg { interpreter: String, arg: String },
70 EscapedPluginRoot { path: String },
72 ScriptFileMissing { path: String },
74 ScriptFileNotExecutable { path: String },
76}
77
78impl std::fmt::Display for ScriptLawError {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 match self {
81 Self::BadName { name } => write!(f, "script tool name `{name}` is invalid"),
82 Self::EmptyRun => write!(f, "`run` must not be empty"),
83 Self::RelativeProgram { program } => write!(
84 f,
85 "`run[0]` must be an absolute path (got `{program}`); \
86 the only exception is the interpreter whitelist {INTERPRETER_WHITELIST:?} \
87 with an absolute script file argument"
88 ),
89 Self::InterpreterMissingScriptArg { interpreter } => write!(
90 f,
91 "interpreter `{interpreter}` needs a script file argument \
92 (`-File`/`-f` for powershell/pwsh, `/c` for cmd) so its absolute path can be pinned"
93 ),
94 Self::RelativeScriptArg { interpreter, arg } => write!(
95 f,
96 "script file argument `{arg}` of interpreter `{interpreter}` must be an absolute path"
97 ),
98 Self::EscapedPluginRoot { path } => {
99 write!(f, "script path `{path}` escapes the plugin root")
100 }
101 Self::ScriptFileMissing { path } => write!(
102 f,
103 "script file `{path}` does not exist (must be a regular file)"
104 ),
105 Self::ScriptFileNotExecutable { path } => write!(
106 f,
107 "script file `{path}` is not executable (chmod +x) — it runs directly as `run[0]`"
108 ),
109 }
110 }
111}
112
113impl std::error::Error for ScriptLawError {}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum ParamType {
119 String,
120 Number,
121 Boolean,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct ParamSpec {
127 #[serde(rename = "type")]
128 pub ty: ParamType,
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub description: Option<String>,
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum ExposureSpec {
137 #[default]
138 Direct,
139 Deferred,
140 Hidden,
141}
142
143impl From<ExposureSpec> for ToolExposure {
144 fn from(value: ExposureSpec) -> Self {
145 match value {
146 ExposureSpec::Direct => ToolExposure::Direct,
147 ExposureSpec::Deferred => ToolExposure::Deferred,
148 ExposureSpec::Hidden => ToolExposure::Hidden,
149 }
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(try_from = "ScriptEntryRaw", into = "ScriptEntryRaw")]
169pub struct ScriptToolEntry {
170 pub name: String,
172 pub description: String,
174 pub parameters: BTreeMap<String, ParamSpec>,
176 pub run: Vec<String>,
178 pub timeout_ms: Option<u64>,
180 pub env: BTreeMap<String, String>,
182 pub cwd: Option<PathBuf>,
185 pub exposure: ExposureSpec,
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
190struct ScriptEntryRaw {
191 name: String,
192 description: String,
193 #[serde(default)]
194 parameters: BTreeMap<String, ParamSpec>,
195 run: Vec<String>,
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 timeout_secs: Option<u64>,
198 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
199 env: BTreeMap<String, String>,
200 #[serde(default, skip_serializing_if = "is_default_exposure")]
201 exposure: ExposureSpec,
202}
203
204fn is_default_exposure(e: &ExposureSpec) -> bool {
205 *e == ExposureSpec::default()
206}
207
208impl TryFrom<ScriptEntryRaw> for ScriptToolEntry {
209 type Error = ScriptLawError;
210
211 fn try_from(raw: ScriptEntryRaw) -> Result<Self, Self::Error> {
212 let entry = Self {
213 name: raw.name,
214 description: raw.description,
215 parameters: raw.parameters,
216 run: raw.run,
217 timeout_ms: raw.timeout_secs.map(|s| s.saturating_mul(1_000)),
218 env: raw.env,
219 cwd: None,
220 exposure: raw.exposure,
221 };
222 entry.check_laws()?;
223 Ok(entry)
224 }
225}
226
227impl From<ScriptToolEntry> for ScriptEntryRaw {
228 fn from(entry: ScriptToolEntry) -> Self {
229 Self {
230 name: entry.name,
231 description: entry.description,
232 parameters: entry.parameters,
233 run: entry.run,
234 timeout_secs: entry.timeout_ms.map(|ms| ms.div_ceil(1_000)),
235 env: entry.env,
236 exposure: entry.exposure,
237 }
238 }
239}
240
241impl ScriptToolEntry {
242 pub fn new(
244 name: impl Into<String>,
245 description: impl Into<String>,
246 run: Vec<String>,
247 ) -> Result<Self, ScriptLawError> {
248 let entry = Self {
249 name: name.into(),
250 description: description.into(),
251 parameters: BTreeMap::new(),
252 run,
253 timeout_ms: None,
254 env: BTreeMap::new(),
255 cwd: None,
256 exposure: ExposureSpec::default(),
257 };
258 entry.check_laws()?;
259 Ok(entry)
260 }
261
262 pub fn check_laws(&self) -> Result<(), ScriptLawError> {
264 ToolIdentity::script(&self.name).map_err(|_| ScriptLawError::BadName {
265 name: self.name.clone(),
266 })?;
267 check_run_law(&self.run)
268 }
269
270 pub fn timeout_ms(&self) -> u64 {
272 self.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS)
273 }
274
275 pub fn parameters_envelope(&self) -> Value {
277 parameters_envelope(&self.parameters)
278 }
279
280 pub fn identity(&self) -> ToolIdentity {
282 ToolIdentity::script(&self.name).expect("entry name validated at construction")
284 }
285}
286
287pub fn parameters_envelope(params: &BTreeMap<String, ParamSpec>) -> Value {
290 let mut properties = serde_json::Map::new();
291 let mut required = Vec::new();
292 for (name, spec) in params {
293 let mut schema = serde_json::Map::new();
294 let ty = match spec.ty {
295 ParamType::String => "string",
296 ParamType::Number => "number",
297 ParamType::Boolean => "boolean",
298 };
299 schema.insert("type".into(), json!(ty));
300 if let Some(desc) = &spec.description {
301 schema.insert("description".into(), json!(desc));
302 }
303 properties.insert(name.clone(), Value::Object(schema));
304 required.push(json!(name));
305 }
306 json!({
307 "type": "object",
308 "properties": properties,
309 "required": required,
310 "additionalProperties": false,
311 })
312}
313
314fn interpreter_of(program: &str) -> Option<&'static str> {
316 let stem = Path::new(program)
317 .file_stem()
318 .and_then(|s| s.to_str())
319 .unwrap_or("")
320 .to_lowercase();
321 INTERPRETER_WHITELIST
322 .iter()
323 .find(|name| **name == stem)
324 .copied()
325}
326
327fn interpreter_script_arg_index(run: &[String]) -> Result<Option<usize>, ScriptLawError> {
331 let Some((program, args)) = run.split_first() else {
332 return Err(ScriptLawError::EmptyRun);
333 };
334 let Some(interpreter) = interpreter_of(program) else {
335 return Ok(None);
336 };
337 let flags: &[&str] = if interpreter == "cmd" {
338 &["/c"]
339 } else {
340 &["-file", "-f"]
341 };
342 for (offset, arg) in args.iter().enumerate() {
343 if flags.iter().any(|f| arg.eq_ignore_ascii_case(f)) {
344 let flag_index = offset + 1;
346 return run.get(flag_index + 1).map(|_| Some(flag_index + 1)).ok_or(
347 ScriptLawError::InterpreterMissingScriptArg {
348 interpreter: interpreter.to_string(),
349 },
350 );
351 }
352 }
353 Err(ScriptLawError::InterpreterMissingScriptArg {
354 interpreter: interpreter.to_string(),
355 })
356}
357
358pub fn script_file_index(run: &[String]) -> Result<usize, ScriptLawError> {
360 if run.is_empty() {
361 return Err(ScriptLawError::EmptyRun);
362 }
363 Ok(interpreter_script_arg_index(run)?.unwrap_or(0))
364}
365
366pub fn check_run_law(run: &[String]) -> Result<(), ScriptLawError> {
368 let Some((program, _)) = run.split_first() else {
369 return Err(ScriptLawError::EmptyRun);
370 };
371 match interpreter_script_arg_index(run)? {
372 Some(index) => {
373 let arg = &run[index];
374 if Path::new(arg).is_absolute() {
375 Ok(())
376 } else {
377 Err(ScriptLawError::RelativeScriptArg {
378 interpreter: program.clone(),
379 arg: arg.clone(),
380 })
381 }
382 }
383 None => {
384 if Path::new(program).is_absolute() {
385 Ok(())
386 } else {
387 Err(ScriptLawError::RelativeProgram {
388 program: program.clone(),
389 })
390 }
391 }
392 }
393}
394
395pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
398 Ok(interpreter_script_arg_index(run)?.is_none())
399}
400
401pub fn check_script_file_on_disk(
410 path: &Path,
411 require_executable: bool,
412) -> Result<(), ScriptLawError> {
413 let missing = ScriptLawError::ScriptFileMissing {
414 path: path.display().to_string(),
415 };
416 let meta = std::fs::metadata(path).map_err(|_| missing.clone())?;
417 if !meta.is_file() {
418 return Err(missing);
419 }
420 #[cfg(unix)]
421 if require_executable {
422 use std::os::unix::fs::PermissionsExt;
423 if meta.permissions().mode() & 0o111 == 0 {
424 return Err(ScriptLawError::ScriptFileNotExecutable {
425 path: path.display().to_string(),
426 });
427 }
428 }
429 #[cfg(not(unix))]
430 let _ = require_executable;
431 Ok(())
432}
433
434fn normalize_lexical(path: &Path) -> Option<PathBuf> {
437 let mut out = PathBuf::new();
438 for component in path.components() {
439 match component {
440 Component::CurDir => {}
441 Component::ParentDir => {
442 if !out.pop() {
443 return None;
444 }
445 }
446 other => out.push(other.as_os_str()),
447 }
448 }
449 Some(out)
450}
451
452pub fn resolve_under_root(plugin_root: &Path, path: &str) -> Result<String, ScriptLawError> {
457 let escape = |p: &str| ScriptLawError::EscapedPluginRoot {
458 path: p.to_string(),
459 };
460 let root_norm = normalize_lexical(plugin_root).ok_or_else(|| escape(path))?;
461 let joined = if Path::new(path).is_absolute() {
462 PathBuf::from(path)
463 } else {
464 root_norm.join(path)
465 };
466 let normalized = normalize_lexical(&joined).ok_or_else(|| escape(path))?;
467 if normalized.starts_with(&root_norm) {
468 Ok(normalized.to_string_lossy().into_owned())
469 } else {
470 Err(escape(path))
471 }
472}
473
474pub fn pin_from_plugin_root(
479 run: &[String],
480 plugin_root: &Path,
481) -> Result<Vec<String>, ScriptLawError> {
482 let index = script_file_index(run)?;
483 let mut pinned = run.to_vec();
484 pinned[index] = resolve_under_root(plugin_root, &run[index])?;
485 check_run_law(&pinned)?;
486 Ok(pinned)
487}
488
489pub fn substitute_params(tool_key: &str, run: &[String], args: &Value) -> AgentResult<Vec<String>> {
498 let Some(obj) = args.as_object() else {
499 return Err(AgentError::ToolArgsInvalid {
500 name: tool_key.to_string(),
501 raw: args.to_string(),
502 });
503 };
504 run.iter()
505 .map(|element| substitute_element(tool_key, element, obj, args))
506 .collect()
507}
508
509fn invalid_args(tool_key: &str, raw_args: &Value) -> AgentError {
510 AgentError::ToolArgsInvalid {
511 name: tool_key.to_string(),
512 raw: raw_args.to_string(),
513 }
514}
515
516fn substitute_element(
517 tool_key: &str,
518 element: &str,
519 obj: &serde_json::Map<String, Value>,
520 raw_args: &Value,
521) -> AgentResult<String> {
522 let mut out = String::with_capacity(element.len());
523 let mut rest = element;
524 while let Some(start) = rest.find("${") {
525 out.push_str(&rest[..start]);
526 let after = &rest[start + 2..];
527 let end = after
528 .find('}')
529 .ok_or_else(|| invalid_args(tool_key, raw_args))?;
530 let name = &after[..end];
531 let value = obj
532 .get(name)
533 .ok_or_else(|| invalid_args(tool_key, raw_args))?;
534 let scalar = match value {
535 Value::String(s) => s.clone(),
536 Value::Number(n) => n.to_string(),
537 Value::Bool(b) => b.to_string(),
538 _ => return Err(invalid_args(tool_key, raw_args)), };
540 out.push_str(&scalar); rest = &after[end + 1..];
542 }
543 out.push_str(rest);
544 Ok(out)
545}
546
547pub(crate) fn truncate_output(s: &str, max_chars: Option<usize>) -> String {
554 let Some(max_chars) = max_chars else {
555 return s.to_string();
556 };
557 let total = s.chars().count();
558 if total <= max_chars {
559 return s.to_string();
560 }
561 if max_chars <= TRUNCATION_MARKER.chars().count() + 2 {
562 return s.chars().take(max_chars).collect();
563 }
564 let available = max_chars.saturating_sub(TRUNCATION_MARKER.chars().count() + 2);
565 let head_chars = available / 3;
566 let tail_chars = available - head_chars;
567 let head: String = s.chars().take(head_chars).collect();
568 let tail: String = s
569 .chars()
570 .rev()
571 .take(tail_chars)
572 .collect::<Vec<_>>()
573 .into_iter()
574 .rev()
575 .collect();
576 format!("{head}\n{TRUNCATION_MARKER}\n{tail}")
577}
578
579async fn kill_tree(pid: Option<u32>) {
585 let Some(pid) = pid else { return };
586 #[cfg(unix)]
587 {
588 unsafe {
590 libc::kill(-(pid as i32), libc::SIGKILL);
591 }
592 }
593 #[cfg(windows)]
594 {
595 let _ = Command::new("taskkill")
596 .args(["/T", "/F", "/PID", &pid.to_string()])
597 .creation_flags(0x0800_0000) .stdout(Stdio::null())
599 .stderr(Stdio::null())
600 .status()
601 .await;
602 }
603}
604
605pub async fn execute_entry(
610 tool_key: &str,
611 entry: &ScriptToolEntry,
612 args: &Value,
613 ctx: &ToolContext,
614) -> AgentResult<Vec<Content>> {
615 let argv = substitute_params(tool_key, &entry.run, args)?;
616
617 let script_index = script_file_index(&entry.run).map_err(|e| AgentError::ToolExecution {
619 name: tool_key.to_string(),
620 source: Box::new(AgentError::Internal(e.to_string())),
621 })?;
622 let script_path = Path::new(&argv[script_index]);
623 if !script_path.is_file() {
624 return Err(AgentError::ToolExecution {
625 name: tool_key.to_string(),
626 source: Box::new(AgentError::Internal(format!(
627 "script is gone: {}",
628 script_path.display()
629 ))),
630 });
631 }
632
633 let mut cmd = Command::new(&argv[0]);
634 cmd.args(&argv[1..])
635 .envs(&entry.env) .stdin(Stdio::null())
637 .stdout(Stdio::piped())
638 .stderr(Stdio::piped())
639 .kill_on_drop(true);
640 if let Some(dir) = &entry.cwd {
641 cmd.current_dir(dir);
642 }
643 #[cfg(unix)]
644 cmd.process_group(0); #[cfg(windows)]
646 cmd.creation_flags(0x0800_0000); let mut child = cmd.spawn().map_err(|e| AgentError::ToolExecution {
649 name: tool_key.to_string(),
650 source: Box::new(AgentError::Internal(format!(
651 "failed to spawn {}: {e}",
652 argv[0]
653 ))),
654 })?;
655 let pid = child.id();
656
657 let mut stdout_pipe = child.stdout.take();
660 let mut stderr_pipe = child.stderr.take();
661 let stdout_task = tokio::spawn(async move {
662 let mut buf = Vec::new();
663 if let Some(pipe) = stdout_pipe.as_mut() {
664 let _ = pipe.read_to_end(&mut buf).await;
665 }
666 buf
667 });
668 let stderr_task = tokio::spawn(async move {
669 let mut buf = Vec::new();
670 if let Some(pipe) = stderr_pipe.as_mut() {
671 let _ = pipe.read_to_end(&mut buf).await;
672 }
673 buf
674 });
675
676 enum WaitEnd {
679 Exited(std::io::Result<std::process::ExitStatus>),
680 Cancelled,
681 }
682 let timeout = Duration::from_millis(entry.timeout_ms());
683 let wait_future = async {
684 tokio::select! {
685 _ = ctx.cancel_token.cancelled() => WaitEnd::Cancelled,
686 status = child.wait() => WaitEnd::Exited(status),
687 }
688 };
689 let ended = tokio::time::timeout(timeout, wait_future).await;
690
691 let status = match ended {
692 Err(_elapsed) => {
693 kill_tree(pid).await;
695 let _ = child.wait().await;
696 return Err(AgentError::ToolTimeout);
697 }
698 Ok(WaitEnd::Cancelled) => {
699 kill_tree(pid).await;
700 let _ = child.wait().await;
701 return Err(AgentError::Cancelled);
702 }
703 Ok(WaitEnd::Exited(Err(e))) => {
704 return Err(AgentError::ToolExecution {
705 name: tool_key.to_string(),
706 source: Box::new(AgentError::Internal(format!("wait failed: {e}"))),
707 });
708 }
709 Ok(WaitEnd::Exited(Ok(status))) => status,
710 };
711
712 let read_deadline = Duration::from_secs(5);
713 let stdout = tokio::time::timeout(read_deadline, stdout_task)
714 .await
715 .ok()
716 .and_then(|t| t.ok())
717 .unwrap_or_default();
718 let stderr = tokio::time::timeout(read_deadline, stderr_task)
719 .await
720 .ok()
721 .and_then(|t| t.ok())
722 .unwrap_or_default();
723 let stdout = String::from_utf8_lossy(&stdout).into_owned();
724 let stderr = String::from_utf8_lossy(&stderr).into_owned();
725
726 if !status.success() {
727 let summary = if stderr.trim().is_empty() {
729 stdout.clone()
730 } else {
731 stderr.clone()
732 };
733 let summary = truncate_output(summary.trim(), ctx.max_output_chars);
734 return Err(AgentError::ToolExecution {
735 name: tool_key.to_string(),
736 source: Box::new(AgentError::Internal(format!(
737 "script exited with {status}: {summary}"
738 ))),
739 });
740 }
741
742 let body = if stdout.trim().is_empty() {
743 stderr
744 } else {
745 stdout
746 };
747 Ok(vec![Content::text(truncate_output(
748 body.trim_end_matches('\n'),
749 ctx.max_output_chars,
750 ))])
751}
752
753#[derive(Debug, Default)]
758pub struct ScriptProvider {
759 entries: BTreeMap<String, ScriptToolEntry>,
760}
761
762impl ScriptProvider {
763 pub fn new(entries: impl IntoIterator<Item = ScriptToolEntry>) -> Self {
766 let mut provider = Self::default();
767 for entry in entries {
768 provider.entries.entry(entry.name.clone()).or_insert(entry);
769 }
770 provider
771 }
772
773 pub fn insert(&mut self, entry: ScriptToolEntry) -> Option<ScriptToolEntry> {
775 self.entries.insert(entry.name.clone(), entry)
776 }
777
778 pub fn remove(&mut self, name: &str) -> Option<ScriptToolEntry> {
780 self.entries.remove(name)
781 }
782
783 pub fn get(&self, name: &str) -> Option<&ScriptToolEntry> {
784 self.entries.get(name)
785 }
786
787 pub fn len(&self) -> usize {
788 self.entries.len()
789 }
790
791 pub fn is_empty(&self) -> bool {
792 self.entries.is_empty()
793 }
794}
795
796#[async_trait]
797impl ToolProvider for ScriptProvider {
798 async fn list(&self) -> AgentResult<Vec<ToolDescriptor>> {
799 Ok(self
800 .entries
801 .values()
802 .map(|entry| ToolDescriptor {
803 identity: entry.identity(),
804 description: entry.description.clone(),
805 parameters: entry.parameters_envelope(),
806 timeout_ms: Some(entry.timeout_ms()),
807 exposure: entry.exposure.into(),
808 })
809 .collect())
810 }
811
812 async fn call(
813 &self,
814 identity: &ToolIdentity,
815 args: &Value,
816 ctx: &ToolContext,
817 ) -> AgentResult<Vec<Content>> {
818 let ToolIdentity::Script { name } = identity else {
819 return Err(AgentError::ToolNotFound {
820 name: identity.to_key(),
821 });
822 };
823 let Some(entry) = self.entries.get(name) else {
824 return Err(AgentError::ToolNotFound {
825 name: identity.to_key(),
826 });
827 };
828 execute_entry(&identity.to_key(), entry, args, ctx).await
829 }
830
831 async fn health(&self) -> AgentResult<()> {
832 for entry in self.entries.values() {
834 let index = script_file_index(&entry.run)
835 .map_err(|e| AgentError::Internal(format!("script.{}: {e}", entry.name)))?;
836 let path = Path::new(&entry.run[index]);
837 if !path.is_file() {
838 return Err(AgentError::Internal(format!(
839 "script.{} is gone: {}",
840 entry.name,
841 path.display()
842 )));
843 }
844 }
845 Ok(())
846 }
847}
848
849pub struct ScriptTool {
855 name: &'static str,
856 description: &'static str,
857 schema: Value,
858 entry: ScriptToolEntry,
859}
860
861impl ScriptTool {
862 pub fn new(entry: ScriptToolEntry) -> Self {
864 let key = format!("script.{}", entry.name);
865 Self::with_key(&key, entry)
866 }
867
868 pub fn with_key(identity_key: &str, entry: ScriptToolEntry) -> Self {
870 let name: &'static str = Box::leak(identity_key.to_string().into_boxed_str());
871 let description: &'static str = Box::leak(entry.description.clone().into_boxed_str());
872 let schema = entry.parameters_envelope();
873 Self {
874 name,
875 description,
876 schema,
877 entry,
878 }
879 }
880
881 pub fn entry(&self) -> &ScriptToolEntry {
882 &self.entry
883 }
884}
885
886#[async_trait]
887impl Tool for ScriptTool {
888 fn name(&self) -> &'static str {
889 self.name
890 }
891
892 fn description(&self) -> &'static str {
893 self.description
894 }
895
896 fn schema(&self) -> Value {
897 self.schema.clone()
898 }
899
900 async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
901 execute_entry(self.name, &self.entry, args, ctx).await
902 }
903
904 fn timeout_ms(&self) -> Option<u64> {
905 Some(self.entry.timeout_ms())
906 }
907
908 fn metadata(&self) -> agent_base::ToolMetadata {
909 agent_base::ToolMetadata {
910 name: self.name.to_string(),
911 description: self.description.to_string(),
912 origin: "script".to_string(),
913 version: "unknown".to_string(),
914 requirements: vec![],
915 }
916 }
917
918 fn exposure(&self) -> ToolExposure {
919 self.entry.exposure.into()
920 }
921}
922
923#[cfg(test)]
924mod tests {
925 use super::*;
926 use serde_json::json;
927
928 fn s(v: &str) -> String {
929 v.to_string()
930 }
931
932 fn abs(rel: &str) -> String {
935 std::env::current_dir()
936 .unwrap()
937 .join(rel)
938 .to_string_lossy()
939 .into_owned()
940 }
941
942 fn entry(run: &[&str]) -> ScriptToolEntry {
943 ScriptToolEntry::new(
944 "deploy",
945 "deploy the project",
946 run.iter().map(|s| s.to_string()).collect(),
947 )
948 .expect("entry must pass the path law")
949 }
950
951 #[test]
954 fn run_law_accepts_absolute_program() {
955 let program = abs("deploy.sh");
956 assert!(check_run_law(&[s(&program), s("--env"), s("prod")]).is_ok());
957 }
958
959 #[test]
960 fn run_law_rejects_relative_program_global_anti_shadowing() {
961 for program in ["./deploy.sh", "deploy.sh", "../deploy.sh", "~/deploy.sh"] {
963 let err = check_run_law(&[s(program)]).unwrap_err();
964 assert!(
965 matches!(err, ScriptLawError::RelativeProgram { .. }),
966 "{program}: {err}"
967 );
968 }
969 }
970
971 #[test]
972 fn run_law_interpreter_whitelist_requires_absolute_script_arg() {
973 for (interpreter, flag, script_rel) in [
975 ("powershell", "-File", "deploy.ps1"),
976 ("pwsh", "-f", "deploy.ps1"),
977 ("powershell.exe", "-File", "deploy.ps1"),
978 ("cmd", "/c", "deploy.cmd"),
979 ("cmd.exe", "/C", "deploy.cmd"),
980 ] {
981 let script = abs(script_rel);
982 let ok = vec![s(interpreter), s(flag), s(&script), s("prod")];
983 assert!(check_run_law(&ok).is_ok(), "{interpreter} absolute script");
984
985 let bad = vec![s(interpreter), s(flag), s("./deploy.ps1")];
986 let err = check_run_law(&bad).unwrap_err();
987 assert!(
988 matches!(err, ScriptLawError::RelativeScriptArg { .. }),
989 "{interpreter} relative script: {err}"
990 );
991
992 let missing = vec![s(interpreter), s("-Command"), s("echo hi")];
994 let err = check_run_law(&missing).unwrap_err();
995 assert!(
996 matches!(err, ScriptLawError::InterpreterMissingScriptArg { .. }),
997 "{interpreter} missing script arg: {err}"
998 );
999 }
1000 }
1001
1002 #[test]
1003 fn run_law_empty_run_rejected() {
1004 assert_eq!(check_run_law(&[]).unwrap_err(), ScriptLawError::EmptyRun);
1005 }
1006
1007 #[test]
1008 fn non_interpreter_bare_name_is_not_exempt() {
1009 let err = check_run_law(&[s("npx"), s("-y"), s("pkg")]).unwrap_err();
1011 assert!(matches!(err, ScriptLawError::RelativeProgram { .. }));
1012 }
1013
1014 #[test]
1017 fn pin_from_plugin_root_pins_relative_script_absolute() {
1018 let root = PathBuf::from(abs("plugins/my-tools"));
1019 let pinned =
1020 pin_from_plugin_root(&[s("scripts/deploy.sh"), s("--env"), s("${env}")], &root)
1021 .unwrap();
1022 assert_eq!(
1023 Path::new(&pinned[0]),
1024 root.join("scripts/deploy.sh").as_path(),
1025 "package-relative path pinned to an absolute path under the plugin root"
1026 );
1027 assert!(Path::new(&pinned[0]).is_absolute());
1028 assert!(check_run_law(&pinned).is_ok());
1030 }
1031
1032 #[test]
1033 fn pin_from_plugin_root_rejects_escape_relative_and_absolute() {
1034 let root = PathBuf::from(abs("plugins/my-tools"));
1035 let outside = abs("plugins/other/x.sh");
1036 for bad in [
1037 vec![s("../outside.sh")],
1038 vec![s("scripts/../../outside.sh")],
1039 vec![s(&outside)],
1040 ] {
1041 let err = pin_from_plugin_root(&bad, &root).unwrap_err();
1042 assert!(
1043 matches!(err, ScriptLawError::EscapedPluginRoot { .. }),
1044 "{bad:?}: {err}"
1045 );
1046 }
1047 }
1048
1049 #[test]
1050 fn pin_from_plugin_root_pins_interpreter_script_arg() {
1051 let root = PathBuf::from(abs("plugins/my-tools"));
1052 let pinned = pin_from_plugin_root(
1053 &[
1054 s("powershell"),
1055 s("-File"),
1056 s("scripts/deploy.ps1"),
1057 s("-env"),
1058 s("prod"),
1059 ],
1060 &root,
1061 )
1062 .unwrap();
1063 assert_eq!(
1064 pinned[0], "powershell",
1065 "the interpreter itself is not pinned (whitelist)"
1066 );
1067 assert_eq!(
1068 Path::new(&pinned[2]),
1069 root.join("scripts/deploy.ps1").as_path(),
1070 "the interpreter's script argument is pinned"
1071 );
1072 let err =
1074 pin_from_plugin_root(&[s("powershell"), s("-File"), s("../x.ps1")], &root).unwrap_err();
1075 assert!(matches!(err, ScriptLawError::EscapedPluginRoot { .. }));
1076 }
1077
1078 #[test]
1081 fn substitute_replaces_whole_and_inline_placeholders() {
1082 let run = [
1083 s("/abs/deploy.sh"),
1084 s("--env"),
1085 s("${env}"),
1086 s("--tag=${tag}"),
1087 ];
1088 let args = json!({"env": "prod", "tag": "v1"});
1089 let got = substitute_params("script.deploy", &run, &args).unwrap();
1090 assert_eq!(got, vec!["/abs/deploy.sh", "--env", "prod", "--tag=v1"]);
1091 }
1092
1093 #[test]
1094 fn substitute_missing_param_is_tool_error() {
1095 let run = [s("/abs/deploy.sh"), s("${env}")];
1096 let err = substitute_params("script.deploy", &run, &json!({})).unwrap_err();
1097 assert!(matches!(err, AgentError::ToolArgsInvalid { name, .. } if name == "script.deploy"));
1098 }
1099
1100 #[test]
1101 fn substitute_non_scalar_param_is_tool_error() {
1102 let run = [s("/abs/deploy.sh"), s("${env}")];
1103 for bad in [
1104 json!({"env": null}),
1105 json!({"env": ["a"]}),
1106 json!({"env": {"a": 1}}),
1107 ] {
1108 let err = substitute_params("script.deploy", &run, &bad).unwrap_err();
1109 assert!(matches!(err, AgentError::ToolArgsInvalid { .. }), "{bad}");
1110 }
1111 }
1112
1113 #[test]
1114 fn substitute_scalar_params_stringify() {
1115 let run = [s("${n}"), s("${b}"), s("${s}")];
1116 let args = json!({"n": 42, "b": true, "s": "txt"});
1117 let got = substitute_params("script.deploy", &run, &args).unwrap();
1118 assert_eq!(got, vec!["42", "true", "txt"]);
1119 }
1120
1121 #[test]
1122 fn substitute_does_not_reexpand_values() {
1123 let run = [s("${a}"), s("$FOO"), s("plain")];
1125 let args = json!({"a": "${b}", "b": "NOPE"});
1126 let got = substitute_params("script.deploy", &run, &args).unwrap();
1127 assert_eq!(got, vec!["${b}", "$FOO", "plain"]);
1128 }
1129
1130 #[test]
1131 fn substitute_unclosed_placeholder_fails_closed() {
1132 let err = substitute_params(
1133 "script.deploy",
1134 &[s("/abs/x.sh ${env")],
1135 &json!({"env": "p"}),
1136 )
1137 .unwrap_err();
1138 assert!(matches!(err, AgentError::ToolArgsInvalid { .. }));
1139 }
1140
1141 #[test]
1142 fn substitute_non_object_args_fails_closed() {
1143 let err = substitute_params("script.deploy", &[s("x")], &json!(["a"])).unwrap_err();
1144 assert!(matches!(err, AgentError::ToolArgsInvalid { .. }));
1145 }
1146
1147 #[test]
1150 fn entry_serde_round_trips_design_shape() {
1151 let script = abs("proj/deploy.sh");
1152 let raw = json!({
1153 "name": "deploy",
1154 "description": "部署当前项目到 staging",
1155 "parameters": { "env": { "type": "string", "description": "目标环境" } },
1156 "run": [script, "--env", "${env}"],
1157 "timeout_secs": 120
1158 });
1159 let entry: ScriptToolEntry = serde_json::from_value(raw).unwrap();
1160 assert_eq!(entry.name, "deploy");
1161 assert_eq!(entry.timeout_ms(), 120_000);
1162 assert_eq!(entry.parameters["env"].ty, ParamType::String);
1163 let back = serde_json::to_value(&entry).unwrap();
1164 assert_eq!(back["timeout_secs"], 120);
1165 assert_eq!(back["run"][0], script);
1166 }
1167
1168 #[test]
1169 fn entry_serde_rejects_shadowable_run() {
1170 let raw = json!({
1171 "name": "deploy",
1172 "description": "d",
1173 "run": ["deploy.sh"]
1174 });
1175 let err = serde_json::from_value::<ScriptToolEntry>(raw).unwrap_err();
1176 assert!(err.to_string().contains("deploy.sh"), "{err}");
1177 }
1178
1179 #[test]
1180 fn entry_serde_rejects_bad_name() {
1181 let raw = json!({
1182 "name": "Deploy",
1183 "description": "d",
1184 "run": [abs("deploy.sh")]
1185 });
1186 assert!(serde_json::from_value::<ScriptToolEntry>(raw).is_err());
1187 }
1188
1189 #[test]
1190 fn parameters_envelope_requires_all_scalars() {
1191 let script = abs("deploy.sh");
1192 let mut entry = entry(&[script.as_str()]);
1193 entry.parameters.insert(
1194 "env".into(),
1195 ParamSpec {
1196 ty: ParamType::String,
1197 description: Some("目标环境".into()),
1198 },
1199 );
1200 let envelope = entry.parameters_envelope();
1201 assert_eq!(envelope["type"], "object");
1202 assert_eq!(envelope["properties"]["env"]["type"], "string");
1203 assert_eq!(envelope["required"], json!(["env"]));
1204 assert_eq!(envelope["additionalProperties"], false);
1205 }
1206
1207 #[cfg(unix)]
1210 mod unix_exec {
1211 use super::*;
1212
1213 #[tokio::test]
1214 async fn runs_argv_without_shell_and_substitutes_params() {
1215 let entry = entry(&["/bin/echo", "${msg}"]);
1216 let ctx = ToolContext::for_test();
1217 let out = execute_entry("script.echo", &entry, &json!({"msg": "hello"}), &ctx)
1218 .await
1219 .unwrap();
1220 assert_eq!(out.len(), 1);
1221 assert_eq!(agent_base::tool::content_text(&out), "hello");
1222 }
1223
1224 #[tokio::test]
1225 async fn env_inherits_and_overrides() {
1226 unsafe { std::env::set_var("SCRIPT_TOOL_TEST_INHERITED", "inh") };
1229 let mut entry = entry(&[
1230 "/bin/sh",
1231 "-c",
1232 r#"echo "$SCRIPT_TOOL_TEST_INHERITED/$SCRIPT_TOOL_TEST_SET""#,
1233 ]);
1234 entry
1235 .env
1236 .insert("SCRIPT_TOOL_TEST_SET".into(), "set".into());
1237 let ctx = ToolContext::for_test();
1238 let out = execute_entry("script.env", &entry, &json!({}), &ctx)
1239 .await
1240 .unwrap();
1241 assert_eq!(agent_base::tool::content_text(&out), "inh/set");
1242 }
1243
1244 #[tokio::test]
1245 async fn non_zero_exit_reports_stderr_summary() {
1246 let entry = entry(&["/bin/sh", "-c", "echo boom >&2; exit 3"]);
1247 let ctx = ToolContext::for_test();
1248 let err = execute_entry("script.fail", &entry, &json!({}), &ctx)
1249 .await
1250 .unwrap_err();
1251 let msg = err.to_string();
1252 assert!(msg.contains("boom"), "{msg}");
1253 assert!(msg.contains("3"), "{msg}");
1254 }
1255
1256 #[tokio::test]
1257 async fn timeout_kills_whole_process_tree() {
1258 let dir = tempfile::tempdir().unwrap();
1260 let pidfile = dir.path().join("grandchild.pid");
1261 let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
1262 let mut entry = entry(&["/bin/sh", "-c", &script]);
1263 entry.timeout_ms = Some(1_000);
1264 let ctx = ToolContext::for_test();
1265 let err = execute_entry("script.tree", &entry, &json!({}), &ctx)
1266 .await
1267 .unwrap_err();
1268 assert!(matches!(err, AgentError::ToolTimeout), "{err}");
1269
1270 let pid_raw = std::fs::read_to_string(&pidfile).expect("grandchild pidfile");
1271 let pid: i32 = pid_raw.trim().parse().unwrap();
1272 for _ in 0..50 {
1273 let alive = unsafe { libc::kill(pid, 0) == 0 };
1274 if !alive {
1275 return; }
1277 tokio::time::sleep(Duration::from_millis(100)).await;
1278 }
1279 panic!("grandchild {pid} survived the tree kill");
1280 }
1281
1282 #[tokio::test]
1283 async fn cancel_token_stops_script_and_reports_cancelled() {
1284 let dir = tempfile::tempdir().unwrap();
1285 let pidfile = dir.path().join("grandchild.pid");
1286 let script = format!("sleep 30 & echo $! > {}; wait", pidfile.display());
1287 let entry = entry(&["/bin/sh", "-c", &script]);
1288 let ctx = ToolContext::for_test();
1289 let token = ctx.cancel_token.clone();
1290 let run = tokio::spawn(async move {
1291 execute_entry("script.cancel", &entry, &json!({}), &ctx).await
1292 });
1293 for _ in 0..100 {
1295 if pidfile.exists() {
1296 break;
1297 }
1298 tokio::time::sleep(Duration::from_millis(50)).await;
1299 }
1300 token.cancel();
1301 let err = run.await.unwrap().unwrap_err();
1302 assert!(matches!(err, AgentError::Cancelled), "{err}");
1303 }
1304
1305 #[tokio::test]
1306 async fn output_truncation_follows_kernel_convention() {
1307 let entry = entry(&["/bin/sh", "-c", "seq 1 1000"]);
1308 let mut ctx = ToolContext::for_test();
1309 ctx.max_output_chars = Some(60);
1310 let out = execute_entry("script.big", &entry, &json!({}), &ctx)
1311 .await
1312 .unwrap();
1313 let text = agent_base::tool::content_text(&out);
1314 assert!(text.contains(TRUNCATION_MARKER), "{text}");
1315 assert!(
1316 text.chars().count() < 200,
1317 "still huge: {}",
1318 text.chars().count()
1319 );
1320 assert!(text.starts_with('1'), "{text}");
1322 assert!(text.contains("1000"), "{text}");
1323 }
1324
1325 #[test]
1326 fn truncation_never_exceeds_the_budget() {
1327 for max in 0..40usize {
1332 let out = truncate_output(&"x".repeat(500), Some(max));
1333 assert!(
1334 out.chars().count() <= max,
1335 "max={max} produced {} chars",
1336 out.chars().count()
1337 );
1338 }
1339 }
1340
1341 #[tokio::test]
1342 async fn missing_script_file_reports_script_is_gone() {
1343 let entry = entry(&["/definitely/not/here/deploy.sh"]);
1344 let ctx = ToolContext::for_test();
1345 let err = execute_entry("script.gone", &entry, &json!({}), &ctx)
1346 .await
1347 .unwrap_err();
1348 assert!(err.to_string().contains("script is gone"), "{err}");
1349 }
1350 }
1351
1352 #[tokio::test]
1355 async fn provider_lists_scripts_and_rejects_foreign_keys() {
1356 #[cfg(unix)]
1357 let entry = entry(&["/bin/echo", "hi"]);
1358 #[cfg(windows)]
1359 let entry = entry(&[r"C:\Windows\System32\cmd.exe", "/c", r"C:\proj\deploy.cmd"]);
1360
1361 let provider = ScriptProvider::new([entry.clone()]);
1362 let listed = provider.list().await.unwrap();
1363 assert_eq!(listed.len(), 1);
1364 assert_eq!(listed[0].identity.to_key(), "script.deploy");
1365 assert_eq!(listed[0].timeout_ms, Some(DEFAULT_TIMEOUT_MS));
1366
1367 let ctx = ToolContext::for_test();
1368 for foreign in [
1369 ToolIdentity::builtin("read_file").unwrap(),
1370 ToolIdentity::mcp("figma", "get_file").unwrap(),
1371 ToolIdentity::plugin("my-tools", "deploy").unwrap(),
1372 ToolIdentity::script("other").unwrap(),
1373 ] {
1374 let err = provider.call(&foreign, &json!({}), &ctx).await.unwrap_err();
1375 assert!(
1376 matches!(err, AgentError::ToolNotFound { .. }),
1377 "{foreign:?}"
1378 );
1379 }
1380
1381 let own = entry.identity();
1382 provider.call(&own, &json!({}), &ctx).await.unwrap();
1383 }
1384
1385 #[tokio::test]
1386 async fn provider_health_detects_gone_script() {
1387 let dir = tempfile::tempdir().unwrap();
1388 let script = dir.path().join("deploy.sh");
1389 std::fs::write(&script, "#!/bin/sh\necho ok\n").unwrap();
1390 let entry = entry(&[script.to_str().unwrap()]);
1391 let provider = ScriptProvider::new([entry.clone()]);
1392 provider.health().await.unwrap();
1393
1394 std::fs::remove_file(&script).unwrap();
1395 let err = provider.health().await.unwrap_err();
1396 assert!(err.to_string().contains("is gone"), "{err}");
1397 }
1398
1399 #[tokio::test]
1400 async fn script_tool_plugs_into_tool_table() {
1401 let entry = entry(&["/bin/echo", "hi"]);
1402 let tool = ScriptTool::new(entry.clone());
1403 assert_eq!(tool.name(), "script.deploy");
1404 assert_eq!(tool.timeout_ms(), Some(DEFAULT_TIMEOUT_MS));
1405 assert_eq!(tool.metadata().origin, "script");
1406 assert_eq!(tool.schema()["type"], "object");
1407
1408 let plugin_tool = ScriptTool::with_key("plugin.my-tools.deploy", entry);
1409 assert_eq!(plugin_tool.name(), "plugin.my-tools.deploy");
1410 }
1411}