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