Skip to main content

agent_works/
script_tool.rs

1//! Script-tier adapter (P1) — the runtime law for global script tools
2//! (`script.{name}`) and the plugin `script` form.
3//!
4//! Spec text: `phimint/notes/tool-socket-design.md`, sections
5//! "global script tool entry / script runtime semantics":
6//!
7//! - **Absolute path pinning (anti-shadowing)**: `run[0]` must be an absolute
8//!   path. The only exception is the interpreter whitelist
9//!   (`powershell` / `pwsh` / `cmd`), in which case the **script file argument**
10//!   must be an absolute path (powershell: after `-File`/`-f`; cmd: after `/c`).
11//!   A relative path = running that other project's same-named script in that
12//!   project; rejected at definition/install time.
13//! - **Scripts inside plugins obey the same law**: package-relative paths are
14//!   resolved to absolute paths at install time by [`pin_from_plugin_root`]
15//!   and pinned (lexical normalization + escape from the plugin root → reject).
16//! - **argv spawn, no shell**: `run` substitutes `${param}` per element; a
17//!   missing or non-scalar parameter → tool error for that call (fail-closed);
18//!   parameter values are not re-expanded.
19//! - cwd = current project root (pinned at product-layer registration in
20//!   [`ScriptToolEntry::cwd`]; the framework does not sniff paths);
21//!   env = inherited + entry overrides.
22//! - timeout defaults to 60s; on timeout the **whole process tree** is killed
23//!   (POSIX process group + `killpg`; Windows `taskkill /T /F` +
24//!   `CREATE_NO_WINDOW`).
25//! - Output exceeding `max_output_chars` reuses the kernel-tools truncation
26//!   convention (first 1/3 + last 2/3 + `...[output truncated]`; the convention
27//!   is copied verbatim, no cross-crate code import).
28//! - exit ≠ 0 → tool error (with a stderr summary). If the script file is gone
29//!   at execution time → a "script is gone" error, **no silent file swap**.
30
31use 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
46/// Default timeout (milliseconds).
47pub const DEFAULT_TIMEOUT_MS: u64 = 60_000;
48
49/// Interpreter whitelist: the **only** exception where `run[0]` need not be an absolute path.
50pub const INTERPRETER_WHITELIST: [&str; 3] = ["powershell", "pwsh", "cmd"];
51
52/// Output truncation marker (same convention as phi-kernel-tools `local_shell::truncate_output`).
53const TRUNCATION_MARKER: &str = "...[output truncated]";
54
55/// Path-law violation at definition/install time. Fail-closed: reject what is illegal, no compromises.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum ScriptLawError {
58    /// Tool name is invalid (character set / reserved word / too long).
59    BadName { name: String },
60    /// `run` is empty.
61    EmptyRun,
62    /// `run[0]` is not an absolute path and not in the interpreter whitelist — rejected to prevent shadowing.
63    RelativeProgram { program: String },
64    /// The interpreter lacks a script file argument (`-File`/`-f`/`/c` not found), so the script path cannot be pinned.
65    InterpreterMissingScriptArg { interpreter: String },
66    /// The interpreter's script file argument is not an absolute path.
67    RelativeScriptArg { interpreter: String, arg: String },
68    /// A path inside a plugin escapes the plugin root after resolution (`../` escape / absolute path outside).
69    EscapedPluginRoot { path: String },
70    /// The script file does not exist at install/mount time (or is not a regular file).
71    ScriptFileMissing { path: String },
72    /// The script body (the non-interpreter form's `run[0]`) has no executable bit.
73    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/// Parameter-table entry (the author-facing side of plugin manifest / tools.json): scalars only.
114#[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/// A single parameter: `{ "type": "string", "description": "…" }`.
123#[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/// Tool-table budget tier (`ToolExposure` has no serde; the author-facing side uses this string form).
132#[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/// A script tool entry (one row of tools.json / one row of the plugin manifest `script` form).
152///
153/// JSON form (the design's "global script tool entry"):
154/// ```json
155/// {
156///   "name": "deploy",
157///   "description": "部署当前项目到 staging",
158///   "parameters": { "env": { "type": "string", "description": "目标环境" } },
159///   "run": ["/Users/me/proj/deploy.sh", "--env", "${env}"],
160///   "timeout_secs": 120
161/// }
162/// ```
163///
164/// serde parsing enforces the path law and the name law (fail-closed: failing to parse a legal entry = parse failure).
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(try_from = "ScriptEntryRaw", into = "ScriptEntryRaw")]
167pub struct ScriptToolEntry {
168    /// Name (`script.{name}` / the plugin's tool segment). `[a-z0-9_-]{1,32}`, not a reserved word.
169    pub name: String,
170    /// Model-visible description.
171    pub description: String,
172    /// Parameter table (scalars only).
173    pub parameters: BTreeMap<String, ParamSpec>,
174    /// argv template: `${param}` substitution per element, no shell. The path law has already been enforced.
175    pub run: Vec<String>,
176    /// Hard timeout (milliseconds). `None` = [`DEFAULT_TIMEOUT_MS`].
177    pub timeout_ms: Option<u64>,
178    /// Environment variable overrides (layered on top of the inherited process env).
179    pub env: BTreeMap<String, String>,
180    /// Working directory (the current project root; pinned at product-layer registration, the framework does not sniff paths).
181    /// Not stored in tools.json (machine-specific path, injected at product-layer load time).
182    pub cwd: Option<PathBuf>,
183    /// Tool-table budget tier, defaults to direct.
184    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    /// Construct + enforce the laws (name law + path law). Manual construction also goes through here; never assemble the struct bare.
241    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    /// Name law + path law (called at definition/install time; at execution time only check whether the script file is still there).
261    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    /// Hard timeout (milliseconds): the entry's value, defaulting to [`DEFAULT_TIMEOUT_MS`].
269    pub fn timeout_ms(&self) -> u64 {
270        self.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS)
271    }
272
273    /// LLM parameter envelope (MCP `inputSchema` form: object + properties + required=all).
274    pub fn parameters_envelope(&self) -> Value {
275        parameters_envelope(&self.parameters)
276    }
277
278    /// Identity key (global-script form `script.{name}`). The plugin form is assembled by the plugin provider itself.
279    pub fn identity(&self) -> ToolIdentity {
280        // check_laws already guarantees validity; construction failure = programming error.
281        ToolIdentity::script(&self.name).expect("entry name validated at construction")
282    }
283}
284
285/// Parameter table → JSON Schema envelope: `type: object` + properties + required=all +
286/// `additionalProperties: false` (in v1 all parameters are de facto required, see contract §appendix 3).
287pub 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
312/// Interpreter whitelist check: takes the file stem of `run[0]` (lowercased).
313fn 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
325/// Index of the interpreter's "script file argument": powershell/pwsh → after `-File`/`-f`;
326/// cmd → after `/c`. Not found (or no argument after the flag) = cannot pin → error.
327/// Not an interpreter → `Ok(None)` (the script is `run[0]` itself).
328fn 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            // absolute index of the flag itself within run
343            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
356/// Index of the "script file" element: interpreter → its script argument position; otherwise 0.
357pub 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
364/// Path law (anti-shadowing): `run[0]` is an absolute path, or the interpreter whitelist + an absolute script file argument.
365pub 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
393/// Whether the script body is `run[0]` itself (non-interpreter form). Interpreter form → `false`
394/// (the script is read in, no executable bit needed). Invalid/empty errors out on the same criteria as [`check_run_law`].
395pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
396    Ok(interpreter_script_arg_index(run)?.is_none())
397}
398
399/// Script file check at install/mount time (fail-closed, the same law as a missing wasm file):
400/// it must be a regular file; when the script body is executed directly it must also have the
401/// executable bit on unix.
402///
403/// `path` is supplied by the caller: plugin install checks the **staging area** contents (bytes
404/// unchanged after the rename), global mount checks the final path. Not checked at load time —
405/// archived entries are left to self-check at execution time (see [`ScriptToolEntry::check_laws`]);
406/// once the file comes back the tool is alive again.
407pub 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
432/// Lexical normalization (does not touch the file system): consumes `.`, `..` steps back;
433/// stepping back past the start = escape → `None`.
434fn 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
450/// Resolve an in-plugin path (relative to the plugin root) to an absolute path and pin it.
451///
452/// - Relative path → resolved under `plugin_root`; absolute path → verified to be inside the plugin root;
453/// - After lexical normalization it must still be under the plugin root (`../` escape → [`ScriptLawError::EscapedPluginRoot`]).
454pub 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
472/// Plugin script pinning at install time: resolve the script file element to an absolute path
473/// under the plugin root, then enforce the path law.
474///
475/// The same law as global scripts' "`run[0]` anti-shadowing" rule; plugins are not exempt.
476pub 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
487/// `${param}` substitution per element (argv, no shell).
488///
489/// - Only the `${name}` form is recognized; bare text such as `$FOO` or anything outside the
490///   `${…}` form is left untouched (`${ENV:…}` has already been resolved to a literal at
491///   product-layer registration, so none should remain by this point);
492/// - Parameter values are inserted verbatim, **no re-expansion**;
493/// - Missing, non-scalar (null/array/object), or unclosed `${` → [`AgentError::ToolArgsInvalid`]
494///   (fail-closed, tool error for that call).
495pub 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)), // null/array/object are non-scalar
537        };
538        out.push_str(&scalar); // inserted verbatim, no re-expansion
539        rest = &after[end + 1..];
540    }
541    out.push_str(rest);
542    Ok(out)
543}
544
545/// Output truncation convention (copied verbatim from phi-kernel-tools `local_shell::truncate_output`):
546/// first 1/3 + `...[output truncated]` + last 2/3.
547fn 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
570/// Kill the whole process tree (on timeout/cancellation).
571///
572/// - POSIX: the script starts as a process group leader (`process_group(0)`), `killpg` SIGKILL;
573/// - Windows: `taskkill /T /F /PID` (Job Object comes later; this semantically equivalent fallback
574///   covers us for now).
575async fn kill_tree(pid: Option<u32>) {
576    let Some(pid) = pid else { return };
577    #[cfg(unix)]
578    {
579        // process group = leader pid (process_group(0) at spawn).
580        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) // CREATE_NO_WINDOW
589            .stdout(Stdio::null())
590            .stderr(Stdio::null())
591            .status()
592            .await;
593    }
594}
595
596/// Execute one script entry (shared by `ScriptProvider` / `ScriptTool` / the future plugin `script` form).
597///
598/// `tool_key` is the identity key (carried in errors); `args` MUST already have been validated by
599/// the host against the envelope.
600pub 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    // Script gone → "script is gone" error, no silent file swap.
609    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) // inherit process env + entry overrides
627        .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); // own process group, leader = this script → killpg the whole tree
636    #[cfg(windows)]
637    cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
638
639    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    // Concurrent pipe reads (wait and the read ends don't exclude each other; leaked background
649    // children holding the pipes get a fallback deadline).
650    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    // Timeout / cancellation / normal exit. Bind before matching so the wait future is dropped
668    // before `child` is finalized (a match scrutinee temporary lives until the match ends).
669    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            // Timeout: kill the whole tree (the tool dies, not the host).
685            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        // exit ≠ 0 → tool error (with a stderr summary).
719        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/// Global script tool supply: namespace `script.{name}`, a name → entry table.
745///
746/// Contract invariant: `call` rejects every foreign key (builtin / `mcp.` / `plugin.` all get
747/// [`AgentError::ToolNotFound`]).
748#[derive(Debug, Default)]
749pub struct ScriptProvider {
750    entries: BTreeMap<String, ScriptToolEntry>,
751}
752
753impl ScriptProvider {
754    /// Build the table in bulk; **duplicate names keep the first one** (design: skip the later one
755    /// at load time and warn — the warning lives at the product layer).
756    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    /// Add/replace one entry.
765    pub fn insert(&mut self, entry: ScriptToolEntry) -> Option<ScriptToolEntry> {
766        self.entries.insert(entry.name.clone(), entry)
767    }
768
769    /// Remove one entry (used by `/tools remove`; ledger cleanup is the product layer's job, see approval_ledger).
770    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        // Cheap probe: is the script file still there.
824        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
840/// A single script tool (plugs into the [`Tool`] table; `Box::leak` naming follows the existing
841/// `McpToolAdapter` precedent).
842///
843/// Global scripts use [`ScriptTool::new`] (key = `script.{name}`); the plugin `script` form uses
844/// [`ScriptTool::with_key`] in P2 to mount `plugin.{plugin}.{tool}`.
845pub struct ScriptTool {
846    name: &'static str,
847    description: &'static str,
848    schema: Value,
849    entry: ScriptToolEntry,
850}
851
852impl ScriptTool {
853    /// Global script tool: key = `script.{name}`.
854    pub fn new(entry: ScriptToolEntry) -> Self {
855        let key = format!("script.{}", entry.name);
856        Self::with_key(&key, entry)
857    }
858
859    /// Explicit identity key (plugin `script` form: `plugin.{plugin}.{tool}`).
860    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    /// Platform absolute path (the test criterion follows the same law as `Path::is_absolute`, runs
924    /// the same on unix/windows).
925    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    // ── Path law (anti-shadowing) ────────────────────────────────────────────
943
944    #[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        // Global tools.json + relative path = another project shadowing a same-named script → reject.
953        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        // Whitelisted interpreter: the script file argument must be an absolute path.
965        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            // No script argument found → cannot pin → reject.
984            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        // `npx` is not on the whitelist → run[0] must still be an absolute path.
1001        let err = check_run_law(&[s("npx"), s("-y"), s("pkg")]).unwrap_err();
1002        assert!(matches!(err, ScriptLawError::RelativeProgram { .. }));
1003    }
1004
1005    // ── In-plugin path pinning (the same law, plugins are not exempt) ─────────────────────
1006
1007    #[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        // After pinning it must pass the same path law
1020        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        // An escaping interpreter script argument is rejected just the same
1064        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    // ── ${param} substitution (argv, fail-closed, no re-expansion) ──────────────────────
1070
1071    #[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        // ${x} inside a parameter value is not re-expanded; bare $FOO / non-${ forms are untouched.
1115        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    // ── serde (tools.json entry form, parsing enforces the laws) ───────────────────────────
1139
1140    #[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    // ── Execution semantics (actually run on unix; Windows semantics see the §win tests + docs) ────
1199
1200    #[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            // argv goes through no shell; env override verification relies on /bin/sh -c (an absolute run[0] is legal).
1218            // Since edition 2024 env::set_var is unsafe (races with multithreaded env access).
1219            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            // Grandchild process sleeps 30 and records its pid; after the timeout the whole tree must die.
1250            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; // the grandchild died with the tree
1267                }
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            // Wait for the pidfile to appear (the tree has grown) before cancelling
1285            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            // Both head and tail are present (seq runs from 1 to 1000)
1312            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    // ── Provider / Tool wiring ───────────────────────────────────────────────
1328
1329    #[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}