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`).
53/// The elision marker of the output truncation convention (one vocabulary
54/// across the family: kernel tools, script tools, code cells).
55pub(crate) const TRUNCATION_MARKER: &str = "...[output truncated]";
56
57/// Path-law violation at definition/install time. Fail-closed: reject what is illegal, no compromises.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum ScriptLawError {
60    /// Tool name is invalid (character set / reserved word / too long).
61    BadName { name: String },
62    /// `run` is empty.
63    EmptyRun,
64    /// `run[0]` is not an absolute path and not in the interpreter whitelist — rejected to prevent shadowing.
65    RelativeProgram { program: String },
66    /// The interpreter lacks a script file argument (`-File`/`-f`/`/c` not found), so the script path cannot be pinned.
67    InterpreterMissingScriptArg { interpreter: String },
68    /// The interpreter's script file argument is not an absolute path.
69    RelativeScriptArg { interpreter: String, arg: String },
70    /// A path inside a plugin escapes the plugin root after resolution (`../` escape / absolute path outside).
71    EscapedPluginRoot { path: String },
72    /// The script file does not exist at install/mount time (or is not a regular file).
73    ScriptFileMissing { path: String },
74    /// The script body (the non-interpreter form's `run[0]`) has no executable bit.
75    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/// Parameter-table entry (the author-facing side of plugin manifest / tools.json): scalars only.
116#[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/// A single parameter: `{ "type": "string", "description": "…" }`.
125#[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/// Tool-table budget tier (`ToolExposure` has no serde; the author-facing side uses this string form).
134#[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/// A script tool entry (one row of tools.json / one row of the plugin manifest `script` form).
154///
155/// JSON form (the design's "global script tool entry"):
156/// ```json
157/// {
158///   "name": "deploy",
159///   "description": "部署当前项目到 staging",
160///   "parameters": { "env": { "type": "string", "description": "目标环境" } },
161///   "run": ["/Users/me/proj/deploy.sh", "--env", "${env}"],
162///   "timeout_secs": 120
163/// }
164/// ```
165///
166/// serde parsing enforces the path law and the name law (fail-closed: failing to parse a legal entry = parse failure).
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(try_from = "ScriptEntryRaw", into = "ScriptEntryRaw")]
169pub struct ScriptToolEntry {
170    /// Name (`script.{name}` / the plugin's tool segment). `[a-z0-9_-]{1,32}`, not a reserved word.
171    pub name: String,
172    /// Model-visible description.
173    pub description: String,
174    /// Parameter table (scalars only).
175    pub parameters: BTreeMap<String, ParamSpec>,
176    /// argv template: `${param}` substitution per element, no shell. The path law has already been enforced.
177    pub run: Vec<String>,
178    /// Hard timeout (milliseconds). `None` = [`DEFAULT_TIMEOUT_MS`].
179    pub timeout_ms: Option<u64>,
180    /// Environment variable overrides (layered on top of the inherited process env).
181    pub env: BTreeMap<String, String>,
182    /// Working directory (the current project root; pinned at product-layer registration, the framework does not sniff paths).
183    /// Not stored in tools.json (machine-specific path, injected at product-layer load time).
184    pub cwd: Option<PathBuf>,
185    /// Tool-table budget tier, defaults to direct.
186    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    /// Construct + enforce the laws (name law + path law). Manual construction also goes through here; never assemble the struct bare.
243    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    /// Name law + path law (called at definition/install time; at execution time only check whether the script file is still there).
263    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    /// Hard timeout (milliseconds): the entry's value, defaulting to [`DEFAULT_TIMEOUT_MS`].
271    pub fn timeout_ms(&self) -> u64 {
272        self.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS)
273    }
274
275    /// LLM parameter envelope (MCP `inputSchema` form: object + properties + required=all).
276    pub fn parameters_envelope(&self) -> Value {
277        parameters_envelope(&self.parameters)
278    }
279
280    /// Identity key (global-script form `script.{name}`). The plugin form is assembled by the plugin provider itself.
281    pub fn identity(&self) -> ToolIdentity {
282        // check_laws already guarantees validity; construction failure = programming error.
283        ToolIdentity::script(&self.name).expect("entry name validated at construction")
284    }
285}
286
287/// Parameter table → JSON Schema envelope: `type: object` + properties + required=all +
288/// `additionalProperties: false` (in v1 all parameters are de facto required, see contract §appendix 3).
289pub 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
314/// Interpreter whitelist check: takes the file stem of `run[0]` (lowercased).
315fn 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
327/// Index of the interpreter's "script file argument": powershell/pwsh → after `-File`/`-f`;
328/// cmd → after `/c`. Not found (or no argument after the flag) = cannot pin → error.
329/// Not an interpreter → `Ok(None)` (the script is `run[0]` itself).
330fn 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            // absolute index of the flag itself within run
345            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
358/// Index of the "script file" element: interpreter → its script argument position; otherwise 0.
359pub 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
366/// Path law (anti-shadowing): `run[0]` is an absolute path, or the interpreter whitelist + an absolute script file argument.
367pub 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
395/// Whether the script body is `run[0]` itself (non-interpreter form). Interpreter form → `false`
396/// (the script is read in, no executable bit needed). Invalid/empty errors out on the same criteria as [`check_run_law`].
397pub fn script_file_is_program(run: &[String]) -> Result<bool, ScriptLawError> {
398    Ok(interpreter_script_arg_index(run)?.is_none())
399}
400
401/// Script file check at install/mount time (fail-closed, the same law as a missing wasm file):
402/// it must be a regular file; when the script body is executed directly it must also have the
403/// executable bit on unix.
404///
405/// `path` is supplied by the caller: plugin install checks the **staging area** contents (bytes
406/// unchanged after the rename), global mount checks the final path. Not checked at load time —
407/// archived entries are left to self-check at execution time (see [`ScriptToolEntry::check_laws`]);
408/// once the file comes back the tool is alive again.
409pub 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
434/// Lexical normalization (does not touch the file system): consumes `.`, `..` steps back;
435/// stepping back past the start = escape → `None`.
436fn 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
452/// Resolve an in-plugin path (relative to the plugin root) to an absolute path and pin it.
453///
454/// - Relative path → resolved under `plugin_root`; absolute path → verified to be inside the plugin root;
455/// - After lexical normalization it must still be under the plugin root (`../` escape → [`ScriptLawError::EscapedPluginRoot`]).
456pub 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
474/// Plugin script pinning at install time: resolve the script file element to an absolute path
475/// under the plugin root, then enforce the path law.
476///
477/// The same law as global scripts' "`run[0]` anti-shadowing" rule; plugins are not exempt.
478pub 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
489/// `${param}` substitution per element (argv, no shell).
490///
491/// - Only the `${name}` form is recognized; bare text such as `$FOO` or anything outside the
492///   `${…}` form is left untouched (`${ENV:…}` has already been resolved to a literal at
493///   product-layer registration, so none should remain by this point);
494/// - Parameter values are inserted verbatim, **no re-expansion**;
495/// - Missing, non-scalar (null/array/object), or unclosed `${` → [`AgentError::ToolArgsInvalid`]
496///   (fail-closed, tool error for that call).
497pub 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)), // null/array/object are non-scalar
539        };
540        out.push_str(&scalar); // inserted verbatim, no re-expansion
541        rest = &after[end + 1..];
542    }
543    out.push_str(rest);
544    Ok(out)
545}
546
547/// Output truncation convention (copied from phi-kernel-tools `local_shell::truncate_output`):
548/// first 1/3 + `...[output truncated]` + last 2/3. Plus one clamp the kernel
549/// copy lacks: a budget too small to carry the marker returns a head slice,
550/// because the contract is `result <= max_chars` — an over-budget result makes
551/// the engine reject the whole call (`Tool '…' output exceeds the …-char
552/// limit`) and the model loses the result entirely.
553pub(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
579/// Kill the whole process tree (on timeout/cancellation).
580///
581/// - POSIX: the script starts as a process group leader (`process_group(0)`), `killpg` SIGKILL;
582/// - Windows: `taskkill /T /F /PID` (Job Object comes later; this semantically equivalent fallback
583///   covers us for now).
584async fn kill_tree(pid: Option<u32>) {
585    let Some(pid) = pid else { return };
586    #[cfg(unix)]
587    {
588        // process group = leader pid (process_group(0) at spawn).
589        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) // CREATE_NO_WINDOW
598            .stdout(Stdio::null())
599            .stderr(Stdio::null())
600            .status()
601            .await;
602    }
603}
604
605/// Execute one script entry (shared by `ScriptProvider` / `ScriptTool` / the future plugin `script` form).
606///
607/// `tool_key` is the identity key (carried in errors); `args` MUST already have been validated by
608/// the host against the envelope.
609pub 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    // Script gone → "script is gone" error, no silent file swap.
618    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) // inherit process env + entry overrides
636        .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); // own process group, leader = this script → killpg the whole tree
645    #[cfg(windows)]
646    cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
647
648    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    // Concurrent pipe reads (wait and the read ends don't exclude each other; leaked background
658    // children holding the pipes get a fallback deadline).
659    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    // Timeout / cancellation / normal exit. Bind before matching so the wait future is dropped
677    // before `child` is finalized (a match scrutinee temporary lives until the match ends).
678    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            // Timeout: kill the whole tree (the tool dies, not the host).
694            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        // exit ≠ 0 → tool error (with a stderr summary).
728        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/// Global script tool supply: namespace `script.{name}`, a name → entry table.
754///
755/// Contract invariant: `call` rejects every foreign key (builtin / `mcp.` / `plugin.` all get
756/// [`AgentError::ToolNotFound`]).
757#[derive(Debug, Default)]
758pub struct ScriptProvider {
759    entries: BTreeMap<String, ScriptToolEntry>,
760}
761
762impl ScriptProvider {
763    /// Build the table in bulk; **duplicate names keep the first one** (design: skip the later one
764    /// at load time and warn — the warning lives at the product layer).
765    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    /// Add/replace one entry.
774    pub fn insert(&mut self, entry: ScriptToolEntry) -> Option<ScriptToolEntry> {
775        self.entries.insert(entry.name.clone(), entry)
776    }
777
778    /// Remove one entry (used by `/tools remove`; ledger cleanup is the product layer's job, see approval_ledger).
779    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        // Cheap probe: is the script file still there.
833        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
849/// A single script tool (plugs into the [`Tool`] table; `Box::leak` naming follows the existing
850/// `McpToolAdapter` precedent).
851///
852/// Global scripts use [`ScriptTool::new`] (key = `script.{name}`); the plugin `script` form uses
853/// [`ScriptTool::with_key`] in P2 to mount `plugin.{plugin}.{tool}`.
854pub struct ScriptTool {
855    name: &'static str,
856    description: &'static str,
857    schema: Value,
858    entry: ScriptToolEntry,
859}
860
861impl ScriptTool {
862    /// Global script tool: key = `script.{name}`.
863    pub fn new(entry: ScriptToolEntry) -> Self {
864        let key = format!("script.{}", entry.name);
865        Self::with_key(&key, entry)
866    }
867
868    /// Explicit identity key (plugin `script` form: `plugin.{plugin}.{tool}`).
869    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    /// Platform absolute path (the test criterion follows the same law as `Path::is_absolute`, runs
933    /// the same on unix/windows).
934    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    // ── Path law (anti-shadowing) ────────────────────────────────────────────
952
953    #[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        // Global tools.json + relative path = another project shadowing a same-named script → reject.
962        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        // Whitelisted interpreter: the script file argument must be an absolute path.
974        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            // No script argument found → cannot pin → reject.
993            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        // `npx` is not on the whitelist → run[0] must still be an absolute path.
1010        let err = check_run_law(&[s("npx"), s("-y"), s("pkg")]).unwrap_err();
1011        assert!(matches!(err, ScriptLawError::RelativeProgram { .. }));
1012    }
1013
1014    // ── In-plugin path pinning (the same law, plugins are not exempt) ─────────────────────
1015
1016    #[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        // After pinning it must pass the same path law
1029        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        // An escaping interpreter script argument is rejected just the same
1073        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    // ── ${param} substitution (argv, fail-closed, no re-expansion) ──────────────────────
1079
1080    #[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        // ${x} inside a parameter value is not re-expanded; bare $FOO / non-${ forms are untouched.
1124        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    // ── serde (tools.json entry form, parsing enforces the laws) ───────────────────────────
1148
1149    #[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    // ── Execution semantics (actually run on unix; Windows semantics see the §win tests + docs) ────
1208
1209    #[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            // argv goes through no shell; env override verification relies on /bin/sh -c (an absolute run[0] is legal).
1227            // Since edition 2024 env::set_var is unsafe (races with multithreaded env access).
1228            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            // Grandchild process sleeps 30 and records its pid; after the timeout the whole tree must die.
1259            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; // the grandchild died with the tree
1276                }
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            // Wait for the pidfile to appear (the tree has grown) before cancelling
1294            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            // Both head and tail are present (seq runs from 1 to 1000)
1321            assert!(text.starts_with('1'), "{text}");
1322            assert!(text.contains("1000"), "{text}");
1323        }
1324
1325        #[test]
1326        fn truncation_never_exceeds_the_budget() {
1327            // Regression: a budget below the marker floor used to return the
1328            // marker itself — still over budget — and the engine then rejected
1329            // the whole call (`Tool '…' output exceeds the …-char limit`),
1330            // losing the result entirely.
1331            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    // ── Provider / Tool wiring ───────────────────────────────────────────────
1353
1354    #[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}