Skip to main content

eclipse_core/
tools_script.rs

1//! The `script` tool: workflows the agent writes once and then calls by name.
2//!
3//! A script is an executable file in the scripts directory (`<config dir>/scripts/`, or the
4//! profile's own under a profile). The agent works something out, writes it there, and the next
5//! run — or the next minute — it is a command: `script` runs it, and `shell` finds it on `PATH`.
6//! This module is the one place that decides what a script *is*: [`list_scripts`] says what is
7//! in the directory, [`resolve`] turns a name into a file that is safe to run or a sentence
8//! saying why not, and [`command`] builds the process. The tool and `eclipse scripts run` both
9//! go through those three, so the CLI cannot run something the tool would refuse.
10//!
11//! What a name may be is deliberately narrow. Scripts are flat — no `/`, no `\`, no `..` — and
12//! the file is canonicalised before it runs: a symlink that leads out of the directory is
13//! refused rather than followed, because the directory is writable by the agent and a link in it
14//! would otherwise be a way to run anything. The directory itself is the user's own config
15//! directory, which is why `write_file` may write there at all.
16//!
17//! The process limits are `shell`'s, by sharing its code: `[tools] shell_timeout_secs`, a
18//! process-group kill so a background child cannot outlive the run, and output capped at
19//! `[tools] max_output_bytes`.
20//!
21//! Nothing reads more of a file than it needs. A listing takes the first few kilobytes of each
22//! script for its description and no more, so a directory holding a large file costs what a
23//! small one does.
24
25use crate::tools::{str_arg, Tool, ToolError, SHELL_KILL_GRACE};
26use async_trait::async_trait;
27use serde_json::{json, Value};
28use std::ffi::OsString;
29use std::io::Read;
30use std::path::{Path, PathBuf};
31use std::time::Duration;
32
33/// The environment variable that carries the scripts directory to everything Eclipse starts:
34/// scripts, `shell` commands and plugin tool processes.
35pub const ENV_SCRIPTS_DIR: &str = "ECLIPSE_SCRIPTS_DIR";
36
37/// How much of a script is read to find its description. A description is the first comment
38/// line; if it is not in the first few kilobytes there is no description worth showing.
39const HEAD_BYTES: u64 = 4096;
40/// The longest description shown, in characters.
41const MAX_DESCRIPTION_CHARS: usize = 200;
42/// The most scripts a listing describes. Past this the listing says how many it left out.
43const MAX_LISTED: usize = 200;
44/// The most names the tool's own description carries; `{"list": true}` is the full answer.
45const MAX_NAMED_IN_DESCRIPTION: usize = 20;
46
47/// One file in the scripts directory.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ScriptInfo {
50    pub name: String,
51    /// The first comment line, after any shebang. `None` when the script has no comment.
52    pub description: Option<String>,
53    pub path: PathBuf,
54    /// Whether the file's mode lets it run. A file that is not is still listed, so a script
55    /// written without `chmod +x` is visible rather than mysteriously absent.
56    pub executable: bool,
57    /// Set when the file is a symlink that leads out of the directory: listed so it is
58    /// visible, never read and never run.
59    pub escapes: bool,
60}
61
62/// What [`list_scripts`] found.
63#[derive(Debug, Clone, Default, PartialEq, Eq)]
64pub struct Listing {
65    pub scripts: Vec<ScriptInfo>,
66    /// Scripts beyond [`MAX_LISTED`] that were not described.
67    pub omitted: usize,
68    /// False when the directory does not exist (yet). That is not an error: nothing has been
69    /// written.
70    pub exists: bool,
71}
72
73/// The description a script gives itself: its first comment line.
74///
75/// A `#!` shebang on the first line is skipped; then the first line that starts with `#`, with
76/// the `#` characters and surrounding spaces removed. A comment line with nothing on it
77/// (`#` alone, or a ruled `#####`) is a separator rather than a description and is skipped.
78pub fn first_comment(head: &str) -> Option<String> {
79    let mut lines = head.lines();
80    let first = lines.next()?;
81    let rest = if first.starts_with("#!") {
82        lines
83    } else {
84        head.lines()
85    };
86    for line in rest {
87        if !line.starts_with('#') {
88            continue;
89        }
90        let text = line.trim_start_matches('#').trim();
91        if text.is_empty() {
92            continue;
93        }
94        let mut chars = text.chars();
95        let kept: String = chars.by_ref().take(MAX_DESCRIPTION_CHARS).collect();
96        return Some(if chars.next().is_some() {
97            format!("{kept}...")
98        } else {
99            kept
100        });
101    }
102    None
103}
104
105/// Read at most [`HEAD_BYTES`] of `path`. The file is the agent's to write, so its size is not
106/// known to be small, and nothing here reads the rest.
107fn read_head(path: &Path) -> Option<String> {
108    let mut buf = Vec::new();
109    std::fs::File::open(path)
110        .ok()?
111        .take(HEAD_BYTES)
112        .read_to_end(&mut buf)
113        .ok()?;
114    Some(String::from_utf8_lossy(&buf).into_owned())
115}
116
117#[cfg(unix)]
118fn is_executable(meta: &std::fs::Metadata) -> bool {
119    use std::os::unix::fs::PermissionsExt;
120    meta.permissions().mode() & 0o111 != 0
121}
122
123#[cfg(not(unix))]
124fn is_executable(_: &std::fs::Metadata) -> bool {
125    true
126}
127
128/// The scripts in `dir`, sorted by name.
129///
130/// Regular files only, dotfiles skipped (editor swap files, `.DS_Store`). A missing directory
131/// gives an empty listing; any other failure to read it is an error.
132pub fn list_scripts(dir: &Path) -> Result<Listing, String> {
133    let entries = match std::fs::read_dir(dir) {
134        Ok(entries) => entries,
135        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Listing::default()),
136        Err(e) => return Err(format!("cannot read {}: {e}", dir.display())),
137    };
138    let canonical_dir = std::fs::canonicalize(dir).ok();
139    let mut names: Vec<String> = entries
140        .flatten()
141        .filter_map(|e| e.file_name().into_string().ok())
142        .filter(|n| !n.starts_with('.'))
143        .collect();
144    names.sort();
145    let omitted = names.len().saturating_sub(MAX_LISTED);
146    names.truncate(MAX_LISTED);
147
148    let mut scripts = Vec::new();
149    for name in names {
150        let path = dir.join(&name);
151        let Ok(canonical) = std::fs::canonicalize(&path) else {
152            continue;
153        };
154        let Ok(meta) = std::fs::metadata(&canonical) else {
155            continue;
156        };
157        if !meta.is_file() {
158            continue;
159        }
160        let escapes = !canonical_dir
161            .as_ref()
162            .is_some_and(|d| canonical.starts_with(d));
163        scripts.push(ScriptInfo {
164            description: if escapes {
165                None
166            } else {
167                read_head(&canonical).and_then(|h| first_comment(&h))
168            },
169            executable: is_executable(&meta),
170            name,
171            path,
172            escapes,
173        });
174    }
175    Ok(Listing {
176        scripts,
177        omitted,
178        exists: true,
179    })
180}
181
182/// Turn `name` into the file to run, or a sentence saying why it will not be.
183///
184/// The refusals, in the order they are checked: an empty name, an absolute path, a path
185/// separator, `..`, a file that does not exist, one that resolves outside `dir` once symlinks
186/// are followed, one that is not a regular file, and one that is not executable. The returned
187/// path is canonical, so what was checked is what runs.
188pub fn resolve(dir: &Path, name: &str) -> Result<PathBuf, String> {
189    let (canonical, meta) = locate(dir, name)?;
190    if !is_executable(&meta) {
191        return Err(format!(
192            "{} is not executable; make it so with `chmod +x {}` and call it again",
193            canonical.display(),
194            canonical.display()
195        ));
196    }
197    Ok(canonical)
198}
199
200/// As [`resolve`], without the executable check: the file `name` names, for reading it
201/// (`eclipse scripts cat`) rather than running it.
202pub fn locate_file(dir: &Path, name: &str) -> Result<PathBuf, String> {
203    locate(dir, name).map(|(path, _)| path)
204}
205
206fn locate(dir: &Path, name: &str) -> Result<(PathBuf, std::fs::Metadata), String> {
207    if name.trim().is_empty() {
208        return Err(
209            "the name is empty; give the file name of a script, or `list` to see them".into(),
210        );
211    }
212    if name.contains('\0') {
213        return Err("the name contains a NUL byte".into());
214    }
215    if Path::new(name).is_absolute() || name.starts_with('/') {
216        return Err(format!(
217            "it is an absolute path; a script is called by its file name inside the scripts directory ({})",
218            dir.display()
219        ));
220    }
221    if name.contains('/') || name.contains('\\') {
222        return Err(
223            "it contains a path separator; scripts are called by file name only, and the scripts directory has no subdirectories".into(),
224        );
225    }
226    if name.contains("..") {
227        return Err(
228            "it contains `..`; a script cannot be named by walking out of the scripts directory"
229                .into(),
230        );
231    }
232    let canonical_dir = std::fs::canonicalize(dir).map_err(|e| {
233        if e.kind() == std::io::ErrorKind::NotFound {
234            format!(
235                "the scripts directory {} does not exist yet, so there is no such script",
236                dir.display()
237            )
238        } else {
239            format!(
240                "the scripts directory {} cannot be resolved ({e})",
241                dir.display()
242            )
243        }
244    })?;
245    let canonical = std::fs::canonicalize(dir.join(name)).map_err(|e| {
246        if e.kind() == std::io::ErrorKind::NotFound {
247            format!(
248                "there is no such file in {} (or it is a symlink to nothing); `list` shows what exists",
249                dir.display()
250            )
251        } else {
252            format!("it cannot be resolved ({e})")
253        }
254    })?;
255    if !canonical.starts_with(&canonical_dir) {
256        return Err(format!(
257            "it resolves to {}, which is outside the scripts directory ({}); a symlink may not lead out of it",
258            canonical.display(),
259            canonical_dir.display()
260        ));
261    }
262    let meta = std::fs::metadata(&canonical)
263        .map_err(|e| format!("{} cannot be read ({e})", canonical.display()))?;
264    if !meta.is_file() {
265        return Err(format!("{} is not a regular file", canonical.display()));
266    }
267    Ok((canonical, meta))
268}
269
270/// `dir` placed on the `PATH` this process has, so a script is a command — *last*.
271///
272/// `None` when there is no `PATH` to put it on, or the result could not be written down as one
273/// (a `:` inside `dir`). A process with no `PATH` finds commands in a system default that
274/// naming only the scripts directory would replace, so leaving it alone is the safe answer.
275///
276/// **Last, not first** (`#427`). `write_file` is `Allow` and `shell` runs with this `PATH`, so a
277/// script named `git` used to run in place of the real `git` under every later `shell` call —
278/// including a call the person approved *by name*, which is the one case where they thought they
279/// knew what would run. A script now wins only where no command exists; to run one that shares a
280/// name with a real command, name it by path (`scripts/git`) or add a distinct name.
281pub fn path_with(dir: &Path) -> Option<OsString> {
282    let current = std::env::var_os("PATH")?;
283    // The directory holding *this* `eclipse` first, so a program can reach the tool bridge with
284    // `eclipse tool <name> '{json}'` even when it was started from `target/debug` or a path the
285    // user's shell does not have; then the inherited `PATH`, so a real command wins over a script;
286    // then the scripts directory.
287    let exe = std::env::current_exe()
288        .ok()
289        .and_then(|p| p.parent().map(Path::to_path_buf));
290    let paths = exe
291        .into_iter()
292        .chain(std::env::split_paths(&current))
293        .chain(std::iter::once(dir.to_path_buf()));
294    std::env::join_paths(paths).ok()
295}
296
297/// The process for `script` (already resolved by [`resolve`]) with `args`: run from the scripts
298/// directory, with that directory first on `PATH` and in [`ENV_SCRIPTS_DIR`]. Stdio is left for
299/// the caller — the tool pipes it, `eclipse scripts run` inherits it.
300pub fn command(dir: &Path, script: &Path, args: &[String]) -> std::process::Command {
301    let mut cmd = std::process::Command::new(script);
302    cmd.args(args).current_dir(dir).env(ENV_SCRIPTS_DIR, dir);
303    if let Some(path) = path_with(dir) {
304        cmd.env("PATH", path);
305    }
306    cmd
307}
308
309/// The command for a named script, after every refusal that can be decided without running it.
310/// Both the plain and the bridged path start here, so a name is vetted once.
311fn prepare(dir: &Path, name: &str, args: &[String]) -> Result<Run, ToolError> {
312    let script = resolve(dir, name)
313        .map_err(|why| ToolError::Failed(format!("script {name:?} refused: {why}")))?;
314    Ok(Run {
315        dir: dir.to_path_buf(),
316        script,
317        args: args.to_vec(),
318    })
319}
320
321/// A script to run, kept apart from the [`Command`](tokio::process::Command) that runs it.
322///
323/// A command cannot be cloned, and starting one can be refused with `ETXTBSY` — the file is still
324/// open for writing somewhere, usually in a child another thread forked a microsecond ago. Being
325/// able to build the command again is what makes trying again possible.
326struct Run {
327    dir: PathBuf,
328    script: PathBuf,
329    args: Vec<String>,
330}
331
332impl Run {
333    fn command(&self) -> tokio::process::Command {
334        tokio::process::Command::from(command(&self.dir, &self.script, &self.args))
335    }
336}
337
338/// Why a script could not be started, for the one failure that has a fix the agent can make.
339///
340/// A file with no `#!` line is "executable" to the mode check and then refused by the kernel
341/// with `ENOEXEC`. Eclipse does not guess an interpreter for it — `sh` is not always the right
342/// one — so the message says what to add.
343pub fn start_error(e: &std::io::Error) -> String {
344    #[cfg(unix)]
345    if e.raw_os_error() == Some(libc::ENOEXEC) {
346        return format!(
347            "failed to start: {e}. The file has no `#!` line, so there is no interpreter to run \
348it with: begin it with one, for example `#!/bin/sh` or `#!/usr/bin/env python3`"
349        );
350    }
351    format!("failed to start: {e}")
352}
353
354/// What a call asks for, with every argument type-checked.
355#[derive(Debug, PartialEq, Eq)]
356enum Action {
357    List,
358    Run { name: String, args: Vec<String> },
359}
360
361fn invalid(message: impl Into<String>) -> ToolError {
362    ToolError::InvalidArgs(message.into())
363}
364
365/// Read an optional argument: absent and `null` are the same, and anything else must be the
366/// right type. Guessing a default for a mistyped value is how `{"list": "yes"}` becomes a run.
367fn parse(args: &Value) -> Result<Action, ToolError> {
368    let list = match args.get("list") {
369        None | Some(Value::Null) => false,
370        Some(Value::Bool(b)) => *b,
371        Some(_) => return Err(invalid("`list` must be a boolean")),
372    };
373    let name = match args.get("name") {
374        None | Some(Value::Null) => None,
375        Some(Value::String(_)) => Some(str_arg(args, "name")?.to_string()),
376        Some(_) => return Err(invalid("`name` must be a string")),
377    };
378    let script_args = match args.get("args") {
379        None | Some(Value::Null) => None,
380        Some(Value::Array(items)) => {
381            let mut out = Vec::with_capacity(items.len());
382            for (i, item) in items.iter().enumerate() {
383                match item {
384                    Value::String(s) => out.push(s.clone()),
385                    _ => return Err(invalid(format!("`args[{i}]` must be a string"))),
386                }
387            }
388            Some(out)
389        }
390        Some(_) => return Err(invalid("`args` must be an array of strings")),
391    };
392    if list {
393        if name.is_some() || script_args.is_some() {
394            return Err(invalid(
395                "`list: true` cannot be combined with `name` or `args`: either list the scripts or run one",
396            ));
397        }
398        return Ok(Action::List);
399    }
400    match name {
401        Some(name) => Ok(Action::Run {
402            name,
403            args: script_args.unwrap_or_default(),
404        }),
405        None => Err(invalid(
406            "give `name` to run a script, or `list: true` to see what there is",
407        )),
408    }
409}
410
411/// `script`: list the scripts, or run one.
412pub struct ScriptTool {
413    dir: PathBuf,
414    timeout: Duration,
415    max_bytes: usize,
416    kill_grace: Duration,
417    /// Built once, when the registry is. `Tool::description` returns a borrowed string and
418    /// cannot be recomputed per call, so the names in it are the ones that existed then;
419    /// `{"list": true}` is what is there now.
420    description: String,
421}
422
423impl ScriptTool {
424    /// A tool over `dir`. The directory is read once, here, for the names in the description.
425    pub fn new(dir: PathBuf, timeout: Duration, max_bytes: usize) -> Self {
426        let description = describe_directory(&dir);
427        Self {
428            dir,
429            timeout,
430            max_bytes,
431            kill_grace: SHELL_KILL_GRACE,
432            description,
433        }
434    }
435
436    fn render_list(&self) -> Result<String, ToolError> {
437        let listing = list_scripts(&self.dir).map_err(ToolError::Failed)?;
438        let mut out = format!("scripts directory: {}\n", self.dir.display());
439        if !listing.exists {
440            out.push_str("it does not exist yet; `write_file` creates it with the first script\n");
441        }
442        if listing.scripts.is_empty() {
443            out.push_str("no scripts\n");
444            return Ok(out);
445        }
446        for script in &listing.scripts {
447            out.push_str(&script.name);
448            if script.escapes {
449                out.push_str(" (not runnable: a symlink that leads outside the directory)");
450            } else if !script.executable {
451                out.push_str(" (not executable: needs chmod +x)");
452            }
453            if let Some(d) = &script.description {
454                out.push_str(": ");
455                out.push_str(d);
456            }
457            out.push('\n');
458        }
459        if listing.omitted > 0 {
460            out.push_str(&format!("[{} more not listed]\n", listing.omitted));
461        }
462        Ok(out)
463    }
464}
465
466/// The tool's description for the directory as it is now.
467fn describe_directory(dir: &Path) -> String {
468    let mut text = format!(
469        "Run a script from the scripts directory ({dir}), or list what is there. A script is a \
470saved workflow: when you work out a procedure worth repeating, write it as a file in that \
471directory with `write_file`, make it executable with `chmod +x` through `shell`, and from then \
472on call it by name instead of working it out again. `{{\"list\": true}}` lists the scripts with \
473their first comment line; `{{\"name\": \"backup-media\", \"args\": [\"--dry-run\"]}}` runs one with \
474the scripts directory as its working directory and reports the exit code, stdout and stderr. A \
475name is a bare file name: no path, no `..`.",
476        dir = dir.display()
477    );
478    match list_scripts(dir) {
479        Ok(listing) if !listing.scripts.is_empty() => {
480            let total = listing.scripts.len() + listing.omitted;
481            let names: Vec<&str> = listing
482                .scripts
483                .iter()
484                .take(MAX_NAMED_IN_DESCRIPTION)
485                .map(|s| s.name.as_str())
486                .collect();
487            text.push_str(&format!(
488                " Scripts when this run started: {}",
489                names.join(", ")
490            ));
491            if total > names.len() {
492                text.push_str(&format!(" and {} more", total - names.len()));
493            }
494            text.push_str(". Call `list` for the current set.");
495        }
496        Ok(_) => text.push_str(" There are no scripts yet."),
497        Err(_) => {}
498    }
499    text
500}
501
502#[async_trait]
503impl Tool for ScriptTool {
504    fn name(&self) -> &str {
505        "script"
506    }
507
508    fn description(&self) -> &str {
509        &self.description
510    }
511
512    fn parameters(&self) -> Value {
513        json!({
514            "type": "object",
515            "properties": {
516                "list": {
517                    "type": "boolean",
518                    "description": "List the scripts and what each says it does. Cannot be combined with `name` or `args`."
519                },
520                "name": {
521                    "type": "string",
522                    "description": "The script's file name in the scripts directory, for example `backup-media.sh`: no path, no `..`."
523                },
524                "args": {
525                    "type": "array",
526                    "items": {"type": "string"},
527                    "description": "Arguments passed to the script, one string each."
528                }
529            }
530        })
531    }
532
533    fn describe_call(&self, args: &Value) -> String {
534        if args.get("list") == Some(&Value::Bool(true)) {
535            return "list the scripts".to_string();
536        }
537        let name = args.get("name").and_then(Value::as_str).unwrap_or("?");
538        match args
539            .get("args")
540            .filter(|a| a.as_array().is_some_and(|a| !a.is_empty()))
541        {
542            Some(a) => format!(
543                "run script {name:?} with arguments {a} from {}",
544                self.dir.display()
545            ),
546            None => format!("run script {name:?} from {}", self.dir.display()),
547        }
548    }
549
550    /// Listing is a read of a directory the user owns, so it is answered without asking even
551    /// under `ask`. This is the only place that says so; [`parse`] is what decides whether a
552    /// call is a listing, so a malformed call that merely mentions `list` is not one.
553    fn needs_approval(&self, args: &Value) -> bool {
554        !matches!(parse(args), Ok(Action::List))
555    }
556
557    async fn call(&self, args: Value) -> Result<String, ToolError> {
558        let (name, script_args) = match parse(&args)? {
559            Action::List => return self.render_list(),
560            Action::Run { name, args } => (name, args),
561        };
562        let run = prepare(&self.dir, &name, &script_args)?;
563        crate::tools::run_built(
564            || run.command(),
565            self.timeout,
566            self.max_bytes,
567            self.kill_grace,
568        )
569        .await
570    }
571
572    /// A run inside a run's scope gets a tool bridge: the script can call tools with
573    /// `eclipse tool <name> '{json}'`, through the same policy and approvals as a direct call.
574    /// Same process, same limits — only what it can reach is different.
575    async fn call_scoped(
576        &self,
577        args: Value,
578        scope: &crate::tools::CallScope<'_>,
579    ) -> Result<String, ToolError> {
580        let (name, script_args) = match parse(&args)? {
581            Action::List => return self.render_list(),
582            Action::Run { name, args } => (name, args),
583        };
584        let run = prepare(&self.dir, &name, &script_args)?;
585        crate::tools_bridge::run_with_bridge_built(
586            || run.command(),
587            self.max_bytes,
588            self.timeout,
589            self.kill_grace,
590            scope,
591        )
592        .await
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599    use crate::config::{Policy, ToolsConfig};
600    use crate::tools::{AllowAll, Approver, ToolRegistry};
601    use std::sync::atomic::{AtomicUsize, Ordering};
602    use std::sync::Arc;
603
604    /// `#427`: the scripts directory came *first* on `PATH`, and `write_file` is `Allow`, so a
605    /// model-written script named `git` ran in place of the real one under every later `shell` call
606    /// — including a call the person approved by name. It comes last now: a real command wins, and
607    /// a script fills only a name nothing else has.
608    #[test]
609    fn the_scripts_directory_is_last_on_path() {
610        let dir = Path::new("/tmp/eclipse-path-order/scripts");
611        let path = path_with(dir).expect("PATH is set in the test environment");
612        let entries: Vec<PathBuf> = std::env::split_paths(&path).collect();
613        assert_eq!(entries.last(), Some(&dir.to_path_buf()), "{entries:?}");
614        assert!(
615            entries.len() > 2,
616            "the inherited PATH and this binary's directory are still there: {entries:?}"
617        );
618        assert!(
619            !entries.contains(&PathBuf::from("/usr/bin")) || entries[0] != dir,
620            "the scripts directory is not first"
621        );
622    }
623
624    fn write_script(dir: &Path, name: &str, body: &str, mode: u32) -> PathBuf {
625        std::fs::create_dir_all(dir).unwrap();
626        let path = dir.join(name);
627        std::fs::write(&path, body).unwrap();
628        #[cfg(unix)]
629        {
630            use std::os::unix::fs::PermissionsExt;
631            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
632        }
633        let _ = mode;
634        path
635    }
636
637    #[cfg(unix)]
638    fn process_alive(pid: i32) -> bool {
639        // SAFETY: signal 0 only probes for existence.
640        let exists = unsafe { libc::kill(pid, 0) } == 0;
641        // A zombie nobody has reaped yet is already dead.
642        let zombie = std::fs::read_to_string(format!("/proc/{pid}/stat"))
643            .map(|s| {
644                s.rsplit(')')
645                    .next()
646                    .unwrap_or("")
647                    .trim_start()
648                    .starts_with('Z')
649            })
650            .unwrap_or(false);
651        exists && !zombie
652    }
653
654    fn tool(dir: &Path) -> ScriptTool {
655        ScriptTool::new(dir.to_path_buf(), Duration::from_secs(10), 4096)
656    }
657
658    async fn call(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
659        tool.call(args).await
660    }
661
662    /// A script written a moment ago can be exec'd too early: another thread's `fork` inherits this
663    /// thread's open-for-write fd and the exec comes back `ETXTBSY`, "Text file busy". Two
664    /// `./verify.sh` runs back to back caught it once, and it passes alone — it is the test
665    /// binary's threads racing, not the tool. Retried, because it says nothing about the tool and
666    /// a flake in the gate costs a re-run of a four-minute job.
667    async fn call_retrying(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
668        let mut last = None;
669        for attempt in 0..5 {
670            match call(tool, args.clone()).await {
671                Ok(out) if !out.contains("Text file busy") => return Ok(out),
672                Ok(out) => last = Some(Ok(out)),
673                Err(e) if !e.to_string().contains("Text file busy") => return Err(e),
674                Err(e) => last = Some(Err(e)),
675            }
676            tokio::time::sleep(std::time::Duration::from_millis(10 * (attempt + 1))).await;
677        }
678        last.unwrap()
679    }
680
681    fn refused(result: Result<String, ToolError>) -> String {
682        match result {
683            Err(e) => e.to_string(),
684            Ok(out) => panic!("expected a refusal, got: {out}"),
685        }
686    }
687
688    #[test]
689    fn a_description_is_the_first_comment_line_after_a_shebang() {
690        assert_eq!(
691            first_comment("#!/bin/sh\n# Back up the media\nset -e\n").as_deref(),
692            Some("Back up the media")
693        );
694        assert_eq!(
695            first_comment("## Title  \n").as_deref(),
696            Some("Title"),
697            "no shebang, several hashes, trailing spaces"
698        );
699        assert_eq!(
700            first_comment("#!/bin/sh\n\nset -e\n# later one\n").as_deref(),
701            Some("later one"),
702            "the first line that starts with a hash, wherever it is"
703        );
704        assert_eq!(
705            first_comment("#!/bin/sh\n#\n#####\n# real\n").as_deref(),
706            Some("real"),
707            "an empty comment is a separator, not a description"
708        );
709        assert_eq!(first_comment("#!/bin/sh\necho hi\n"), None);
710        assert_eq!(first_comment(""), None);
711        assert_eq!(
712            first_comment("#!/bin/sh\r\n# crlf\r\n").as_deref(),
713            Some("crlf")
714        );
715    }
716
717    #[test]
718    fn a_long_description_is_cut_and_says_so() {
719        let text = format!("# {}\n", "x".repeat(500));
720        let d = first_comment(&text).unwrap();
721        assert!(d.ends_with("..."));
722        assert_eq!(d.chars().count(), MAX_DESCRIPTION_CHARS + 3);
723    }
724
725    #[test]
726    fn a_missing_directory_lists_as_nothing_rather_than_an_error() {
727        let tmp = tempfile::tempdir().unwrap();
728        let listing = list_scripts(&tmp.path().join("scripts")).unwrap();
729        assert!(!listing.exists && listing.scripts.is_empty());
730    }
731
732    #[tokio::test]
733    async fn the_list_is_sorted_and_carries_each_scripts_description() {
734        let tmp = tempfile::tempdir().unwrap();
735        write_script(tmp.path(), "zeta.sh", "#!/bin/sh\n# Last one\n", 0o755);
736        write_script(tmp.path(), "alpha.sh", "#!/bin/sh\n# First one\n", 0o755);
737        write_script(tmp.path(), "bare", "echo no comment\n", 0o755);
738        write_script(tmp.path(), ".hidden", "# secret\n", 0o755);
739        std::fs::create_dir(tmp.path().join("subdir")).unwrap();
740
741        let out = call(&tool(tmp.path()), json!({"list": true}))
742            .await
743            .unwrap();
744        let lines: Vec<&str> = out.lines().skip(1).collect();
745        assert_eq!(
746            lines,
747            ["alpha.sh: First one", "bare", "zeta.sh: Last one"],
748            "{out}"
749        );
750        assert!(out.starts_with(&format!("scripts directory: {}", tmp.path().display())));
751    }
752
753    #[tokio::test]
754    async fn listing_an_empty_or_missing_directory_says_there_are_none() {
755        let tmp = tempfile::tempdir().unwrap();
756        let missing = tmp.path().join("scripts");
757        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
758        assert!(
759            out.contains("no scripts") && out.contains("does not exist yet"),
760            "{out}"
761        );
762        std::fs::create_dir(&missing).unwrap();
763        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
764        assert!(
765            out.contains("no scripts") && !out.contains("does not exist"),
766            "{out}"
767        );
768    }
769
770    #[cfg(unix)]
771    #[tokio::test]
772    async fn a_file_that_is_not_executable_is_listed_and_flagged() {
773        let tmp = tempfile::tempdir().unwrap();
774        write_script(tmp.path(), "later.sh", "# not yet\n", 0o644);
775        let out = call(&tool(tmp.path()), json!({"list": true}))
776            .await
777            .unwrap();
778        assert!(
779            out.contains("later.sh (not executable: needs chmod +x): not yet"),
780            "{out}"
781        );
782    }
783
784    #[cfg(unix)]
785    #[tokio::test]
786    async fn a_listing_never_reads_through_a_symlink_that_leaves_the_directory() {
787        let tmp = tempfile::tempdir().unwrap();
788        let outside = tempfile::tempdir().unwrap();
789        write_script(outside.path(), "secret", "# TOP-SECRET-LINE\n", 0o755);
790        let dir = tmp.path().join("scripts");
791        std::fs::create_dir(&dir).unwrap();
792        std::os::unix::fs::symlink(outside.path().join("secret"), dir.join("peek")).unwrap();
793        let out = call(&tool(&dir), json!({"list": true})).await.unwrap();
794        assert!(out.contains("peek (not runnable"), "{out}");
795        assert!(!out.contains("TOP-SECRET-LINE"), "{out}");
796    }
797
798    #[tokio::test]
799    async fn only_the_head_of_a_script_is_read_for_its_description() {
800        let tmp = tempfile::tempdir().unwrap();
801        let body = format!(
802            "#!/bin/sh\n{}\n# too late\n",
803            "x".repeat(HEAD_BYTES as usize * 4)
804        );
805        write_script(tmp.path(), "big.sh", &body, 0o755);
806        let listing = list_scripts(tmp.path()).unwrap();
807        assert_eq!(listing.scripts[0].description, None);
808    }
809
810    #[tokio::test]
811    async fn a_listing_stops_describing_after_a_ceiling_and_says_how_many_it_left_out() {
812        let tmp = tempfile::tempdir().unwrap();
813        for i in 0..MAX_LISTED + 5 {
814            write_script(tmp.path(), &format!("s{i:04}"), "# x\n", 0o755);
815        }
816        let out = call(&tool(tmp.path()), json!({"list": true}))
817            .await
818            .unwrap();
819        assert!(
820            out.contains("[5 more not listed]"),
821            "{}",
822            &out[out.len() - 60..]
823        );
824    }
825
826    #[tokio::test]
827    async fn list_combined_with_a_name_or_arguments_is_refused_rather_than_guessed() {
828        let tmp = tempfile::tempdir().unwrap();
829        let t = tool(tmp.path());
830        for args in [
831            json!({"list": true, "name": "x"}),
832            json!({"list": true, "args": []}),
833            json!({"list": true, "name": ""}),
834        ] {
835            let e = call(&t, args).await.unwrap_err();
836            assert!(
837                matches!(e, ToolError::InvalidArgs(ref m) if m.contains("cannot be combined")),
838                "{e}"
839            );
840        }
841        // `list: false` is the same as no `list`.
842        let e = refused(call(&t, json!({"list": false})).await);
843        assert!(e.contains("give `name`"), "{e}");
844        let e = refused(call(&t, json!({})).await);
845        assert!(e.contains("give `name`"), "{e}");
846    }
847
848    #[tokio::test]
849    async fn a_present_argument_of_the_wrong_type_is_invalid_not_defaulted() {
850        let tmp = tempfile::tempdir().unwrap();
851        let t = tool(tmp.path());
852        for (args, field) in [
853            (json!({"list": "yes"}), "`list`"),
854            (json!({"list": 1}), "`list`"),
855            (json!({"name": 5}), "`name`"),
856            (json!({"name": ["a"]}), "`name`"),
857            (json!({"name": "a", "args": "--x"}), "`args`"),
858            (json!({"name": "a", "args": ["ok", 3]}), "`args[1]`"),
859            (json!({"name": "a", "args": [null]}), "`args[0]`"),
860        ] {
861            let e = call(&t, args.clone()).await.unwrap_err();
862            assert!(
863                matches!(&e, ToolError::InvalidArgs(m) if m.contains(field)),
864                "{args}: {e}"
865            );
866        }
867    }
868
869    #[cfg(unix)]
870    #[tokio::test]
871    async fn a_script_runs_with_its_arguments_from_the_scripts_directory() {
872        let tmp = tempfile::tempdir().unwrap();
873        write_script(
874            tmp.path(),
875            "show.sh",
876            "#!/bin/sh\necho \"args: $1|$2\"\necho \"cwd: $(pwd)\"\necho \"dir: $ECLIPSE_SCRIPTS_DIR\"\necho oops >&2\nexit 3\n",
877            0o755,
878        );
879        let out = call(
880            &tool(tmp.path()),
881            json!({"name": "show.sh", "args": ["--dry-run", "two words"]}),
882        )
883        .await
884        .unwrap();
885        let canon = std::fs::canonicalize(tmp.path()).unwrap();
886        assert!(out.starts_with("exit code: 3\n"), "{out}");
887        assert!(out.contains("args: --dry-run|two words"), "{out}");
888        assert!(out.contains(&format!("cwd: {}", canon.display())), "{out}");
889        assert!(
890            out.contains(&format!("dir: {}", tmp.path().display())),
891            "{out}"
892        );
893        assert!(out.contains("stderr:\noops"), "{out}");
894    }
895
896    #[cfg(unix)]
897    #[tokio::test]
898    async fn a_script_has_no_stdin_and_sees_its_directory_first_on_path() {
899        let tmp = tempfile::tempdir().unwrap();
900        write_script(tmp.path(), "helper", "#!/bin/sh\necho from-helper\n", 0o755);
901        write_script(
902            tmp.path(),
903            "main.sh",
904            "#!/bin/sh\ncat | wc -c\nhelper\n",
905            0o755,
906        );
907        let out = call_retrying(&tool(tmp.path()), json!({"name": "main.sh"}))
908            .await
909            .unwrap();
910        assert!(out.contains("exit code: 0"), "{out}");
911        assert!(
912            out.contains("\n0\n"),
913            "stdin reads end-of-file at once: {out}"
914        );
915        assert!(out.contains("from-helper"), "{out}");
916    }
917
918    #[cfg(unix)]
919    #[tokio::test]
920    async fn a_name_that_is_not_a_plain_file_name_in_the_directory_is_refused_with_a_reason() {
921        let tmp = tempfile::tempdir().unwrap();
922        let dir = tmp.path().join("scripts");
923        write_script(&dir, "ok.sh", "#!/bin/sh\necho ok\n", 0o755);
924        write_script(&dir, "plain.txt", "echo no\n", 0o644);
925        write_script(tmp.path(), "outside.sh", "echo out\n", 0o755);
926        std::fs::create_dir(dir.join("adir")).unwrap();
927        let t = tool(&dir);
928
929        let absolute = tmp.path().join("outside.sh").display().to_string();
930        for (name, why) in [
931            ("", "empty"),
932            ("   ", "empty"),
933            ("../outside.sh", "path separator"),
934            ("sub/ok.sh", "path separator"),
935            ("sub\\ok.sh", "path separator"),
936            ("..", "`..`"),
937            ("a..b", "`..`"),
938            (absolute.as_str(), "absolute path"),
939            ("/etc/passwd", "absolute path"),
940            ("missing.sh", "no such file"),
941            ("adir", "not a regular file"),
942            ("plain.txt", "chmod +x"),
943        ] {
944            let e = refused(call(&t, json!({"name": name})).await);
945            assert!(
946                e.contains(&format!("script {name:?} refused")),
947                "{name:?}: {e}"
948            );
949            assert!(e.contains(why), "{name:?} should say {why:?}: {e}");
950        }
951        // The same tool still runs the good one.
952        assert!(call(&t, json!({"name": "ok.sh"}))
953            .await
954            .unwrap()
955            .contains("ok"));
956    }
957
958    #[cfg(unix)]
959    #[tokio::test]
960    async fn a_symlink_out_of_the_directory_is_refused_and_one_inside_is_not() {
961        let tmp = tempfile::tempdir().unwrap();
962        let dir = tmp.path().join("scripts");
963        let target = write_script(
964            tmp.path(),
965            "elsewhere.sh",
966            "#!/bin/sh\necho escaped\n",
967            0o755,
968        );
969        std::fs::create_dir_all(&dir).unwrap();
970        std::os::unix::fs::symlink(&target, dir.join("out")).unwrap();
971        write_script(&dir, "real.sh", "#!/bin/sh\necho real\n", 0o755);
972        std::os::unix::fs::symlink(dir.join("real.sh"), dir.join("alias")).unwrap();
973        std::os::unix::fs::symlink(dir.join("nowhere"), dir.join("dangling")).unwrap();
974        let t = tool(&dir);
975
976        let e = refused(call(&t, json!({"name": "out"})).await);
977        assert!(e.contains("outside the scripts directory"), "{e}");
978        let ok = call(&t, json!({"name": "alias"})).await.unwrap();
979        assert!(ok.contains("real"), "{ok}");
980        let e = refused(call(&t, json!({"name": "dangling"})).await);
981        assert!(e.contains("no such file"), "{e}");
982    }
983
984    #[cfg(unix)]
985    #[tokio::test]
986    async fn a_script_with_no_shebang_says_what_to_add_instead_of_a_bare_os_error() {
987        let tmp = tempfile::tempdir().unwrap();
988        write_script(tmp.path(), "bare.sh", "echo hi\n", 0o755);
989        let e = refused(call(&tool(tmp.path()), json!({"name": "bare.sh"})).await);
990        assert!(e.contains("no `#!` line") && e.contains("#!/bin/sh"), "{e}");
991    }
992
993    #[tokio::test]
994    async fn a_directory_that_does_not_exist_refuses_a_name_and_says_so() {
995        let tmp = tempfile::tempdir().unwrap();
996        let t = tool(&tmp.path().join("scripts"));
997        let e = refused(call(&t, json!({"name": "x.sh"})).await);
998        assert!(e.contains("does not exist yet"), "{e}");
999    }
1000
1001    #[cfg(unix)]
1002    #[tokio::test]
1003    async fn a_script_that_overruns_the_timeout_is_killed_with_the_child_it_started() {
1004        let tmp = tempfile::tempdir().unwrap();
1005        write_script(
1006            tmp.path(),
1007            "hang.sh",
1008            "#!/bin/sh\nsleep 300 &\necho $! > child.pid\nwait\n",
1009            0o755,
1010        );
1011        let mut t = tool(tmp.path());
1012        t.timeout = Duration::from_secs(1);
1013        t.kill_grace = Duration::from_millis(300);
1014        let started = std::time::Instant::now();
1015        let e = refused(call(&t, json!({"name": "hang.sh"})).await);
1016        assert!(e.contains("timed out after 1s"), "{e}");
1017        assert!(started.elapsed() < Duration::from_secs(8));
1018        let pid: i32 = std::fs::read_to_string(tmp.path().join("child.pid"))
1019            .unwrap()
1020            .trim()
1021            .parse()
1022            .unwrap();
1023        for _ in 0..100 {
1024            if !process_alive(pid) {
1025                break;
1026            }
1027            tokio::time::sleep(Duration::from_millis(50)).await;
1028        }
1029        let alive = process_alive(pid);
1030        assert!(!alive, "child {pid} survived the timeout");
1031    }
1032
1033    #[cfg(unix)]
1034    #[tokio::test]
1035    async fn a_script_that_floods_its_output_is_cut_at_the_cap() {
1036        let tmp = tempfile::tempdir().unwrap();
1037        write_script(tmp.path(), "flood.sh", "#!/bin/sh\nyes\n", 0o755);
1038        let t = ScriptTool::new(tmp.path().to_path_buf(), Duration::from_secs(10), 256);
1039        let out = call(&t, json!({"name": "flood.sh"})).await.unwrap();
1040        assert!(out.contains("[truncated]"), "{out}");
1041        assert!(out.len() < 400, "{}", out.len());
1042    }
1043
1044    #[test]
1045    fn an_approval_prompt_names_the_script_and_its_arguments() {
1046        let tmp = tempfile::tempdir().unwrap();
1047        let t = tool(tmp.path());
1048        let with = t.describe_call(&json!({"name": "backup-media", "args": ["--dry-run"]}));
1049        assert!(
1050            with.contains("backup-media") && with.contains("--dry-run"),
1051            "{with}"
1052        );
1053        assert!(with.contains(&tmp.path().display().to_string()), "{with}");
1054        let without = t.describe_call(&json!({"name": "backup-media"}));
1055        assert!(
1056            without.contains("backup-media") && !without.contains("arguments"),
1057            "{without}"
1058        );
1059        assert_eq!(t.describe_call(&json!({"list": true})), "list the scripts");
1060        // A hostile or mangled call still produces a readable line.
1061        let odd = t.describe_call(&json!({"name": "a\nb", "args": 5}));
1062        assert!(!odd.contains('\n'), "{odd}");
1063    }
1064
1065    struct Counting(AtomicUsize);
1066
1067    #[async_trait]
1068    impl Approver for Counting {
1069        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
1070            self.0.fetch_add(1, Ordering::SeqCst);
1071            crate::approvals::Decision::Deny("no".to_string())
1072        }
1073    }
1074
1075    #[tokio::test]
1076    async fn under_ask_a_listing_is_answered_without_a_prompt_and_a_run_is_not() {
1077        let tmp = tempfile::tempdir().unwrap();
1078        write_script(tmp.path(), "a.sh", "# a\n", 0o755);
1079        let mut registry = ToolRegistry::new(4096);
1080        registry.register(Arc::new(tool(tmp.path())), Policy::Ask);
1081        let approver = Counting(AtomicUsize::new(0));
1082
1083        let out = registry
1084            .dispatch("script", r#"{"list":true}"#, &approver)
1085            .await;
1086        assert!(
1087            !out.is_error && out.output.contains("a.sh: a"),
1088            "{}",
1089            out.output
1090        );
1091        assert_eq!(
1092            approver.0.load(Ordering::SeqCst),
1093            0,
1094            "a listing is not asked about"
1095        );
1096
1097        for call in [
1098            r#"{"name":"a.sh"}"#,
1099            r#"{"list":true,"name":"a.sh"}"#,
1100            r#"{"list":"yes","name":"a.sh"}"#,
1101            r#"{}"#,
1102        ] {
1103            let out = registry.dispatch("script", call, &approver).await;
1104            assert!(
1105                out.is_error && out.output.contains("declined"),
1106                "{call}: {}",
1107                out.output
1108            );
1109        }
1110        assert_eq!(approver.0.load(Ordering::SeqCst), 4);
1111
1112        // `deny` still means never, listing included.
1113        let mut registry = ToolRegistry::new(4096);
1114        registry.register(Arc::new(tool(tmp.path())), Policy::Deny);
1115        let out = registry
1116            .dispatch("script", r#"{"list":true}"#, &AllowAll)
1117            .await;
1118        assert!(out.is_error && out.output.contains("disabled by policy"));
1119    }
1120
1121    #[test]
1122    fn the_description_names_the_scripts_there_were_and_points_at_list_for_the_rest() {
1123        let tmp = tempfile::tempdir().unwrap();
1124        let empty = tool(tmp.path());
1125        assert!(empty.description().contains("no scripts yet"));
1126        assert!(empty
1127            .description()
1128            .contains(&tmp.path().display().to_string()));
1129
1130        for i in 0..MAX_NAMED_IN_DESCRIPTION + 3 {
1131            write_script(tmp.path(), &format!("s{i:02}.sh"), "# x\n", 0o755);
1132        }
1133        let full = tool(tmp.path());
1134        let d = full.description();
1135        assert!(d.contains("s00.sh") && d.contains("and 3 more"), "{d}");
1136        assert!(
1137            !d.contains(&format!("s{:02}.sh", MAX_NAMED_IN_DESCRIPTION)),
1138            "{d}"
1139        );
1140        assert!(d.contains("`list`"), "{d}");
1141    }
1142
1143    #[test]
1144    fn the_tool_registers_with_a_schema_that_needs_no_arguments_to_be_present() {
1145        let tmp = tempfile::tempdir().unwrap();
1146        let cfg = ToolsConfig::default();
1147        let registry = ToolRegistry::from_config_full(
1148            &cfg,
1149            tmp.path().to_path_buf(),
1150            Vec::new(),
1151            Some(tmp.path().join("scripts")),
1152        );
1153        let d = registry
1154            .descriptors()
1155            .into_iter()
1156            .find(|d| d.name == "script")
1157            .expect("script is registered");
1158        assert_eq!(d.policy, Policy::Ask);
1159        assert_eq!(
1160            d.parameters["properties"]["args"]["items"]["type"],
1161            "string"
1162        );
1163        assert!(d.parameters.get("required").is_none());
1164    }
1165}