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    /// The program and arguments to run, re-planned through the sandbox exactly as `shell` does
334    /// (#550). Fallible only for a mode that refuses, which is the point: a script must not run
335    /// uncontained where `shell` refuses to.
336    fn plan(
337        &self,
338        sandbox: &crate::sandbox::Sandbox,
339        extra_rw: &[PathBuf],
340    ) -> Result<crate::sandbox::Plan, ToolError> {
341        let args: Vec<std::ffi::OsString> =
342            self.args.iter().map(std::ffi::OsString::from).collect();
343        sandbox.plan_with(self.script.as_os_str(), &args, &self.dir, extra_rw)
344    }
345
346    /// A command for one attempt. Infallible: a retry after `ETXTBSY` rebuilds the same plan
347    /// rather than deciding it again.
348    fn command(&self, plan: &crate::sandbox::Plan) -> tokio::process::Command {
349        let mut cmd = tokio::process::Command::new(&plan.program);
350        cmd.args(&plan.args).current_dir(&self.dir);
351        apply_env(&mut cmd, &self.dir);
352        cmd
353    }
354}
355
356/// The environment a run gets: the scripts directory by name, and on `PATH` after the real
357/// commands. Shared so `execute_code` — which builds its own command over the same directory —
358/// cannot drift from what `script` gives one (#550).
359pub fn apply_env(cmd: &mut tokio::process::Command, dir: &Path) {
360    cmd.env(ENV_SCRIPTS_DIR, dir);
361    if let Some(path) = path_with(dir) {
362        cmd.env("PATH", path);
363    }
364}
365
366/// Why a script could not be started, for the one failure that has a fix the agent can make.
367///
368/// A file with no `#!` line is "executable" to the mode check and then refused by the kernel
369/// with `ENOEXEC`. Eclipse does not guess an interpreter for it — `sh` is not always the right
370/// one — so the message says what to add.
371pub fn start_error(e: &std::io::Error) -> String {
372    #[cfg(unix)]
373    if e.raw_os_error() == Some(libc::ENOEXEC) {
374        return format!(
375            "failed to start: {e}. The file has no `#!` line, so there is no interpreter to run \
376it with: begin it with one, for example `#!/bin/sh` or `#!/usr/bin/env python3`"
377        );
378    }
379    format!("failed to start: {e}")
380}
381
382/// What a call asks for, with every argument type-checked.
383#[derive(Debug, PartialEq, Eq)]
384enum Action {
385    List,
386    Run { name: String, args: Vec<String> },
387}
388
389fn invalid(message: impl Into<String>) -> ToolError {
390    ToolError::InvalidArgs(message.into())
391}
392
393/// Read an optional argument: absent and `null` are the same, and anything else must be the
394/// right type. Guessing a default for a mistyped value is how `{"list": "yes"}` becomes a run.
395fn parse(args: &Value) -> Result<Action, ToolError> {
396    let list = match args.get("list") {
397        None | Some(Value::Null) => false,
398        Some(Value::Bool(b)) => *b,
399        Some(_) => return Err(invalid("`list` must be a boolean")),
400    };
401    let name = match args.get("name") {
402        None | Some(Value::Null) => None,
403        Some(Value::String(_)) => Some(str_arg(args, "name")?.to_string()),
404        Some(_) => return Err(invalid("`name` must be a string")),
405    };
406    let script_args = match args.get("args") {
407        None | Some(Value::Null) => None,
408        Some(Value::Array(items)) => {
409            let mut out = Vec::with_capacity(items.len());
410            for (i, item) in items.iter().enumerate() {
411                match item {
412                    Value::String(s) => out.push(s.clone()),
413                    _ => return Err(invalid(format!("`args[{i}]` must be a string"))),
414                }
415            }
416            Some(out)
417        }
418        Some(_) => return Err(invalid("`args` must be an array of strings")),
419    };
420    if list {
421        if name.is_some() || script_args.is_some() {
422            return Err(invalid(
423                "`list: true` cannot be combined with `name` or `args`: either list the scripts or run one",
424            ));
425        }
426        return Ok(Action::List);
427    }
428    match name {
429        Some(name) => Ok(Action::Run {
430            name,
431            args: script_args.unwrap_or_default(),
432        }),
433        None => Err(invalid(
434            "give `name` to run a script, or `list: true` to see what there is",
435        )),
436    }
437}
438
439/// `script`: list the scripts, or run one.
440pub struct ScriptTool {
441    dir: PathBuf,
442    timeout: Duration,
443    max_bytes: usize,
444    kill_grace: Duration,
445    /// The policy `shell` enforces, so a script runs under the same containment (#550). `off`
446    /// until a registry hands in the profile's own sandbox, which is what the CLI does not do:
447    /// `eclipse scripts run` is the person running their own script.
448    sandbox: crate::sandbox::Sandbox,
449    /// Built once, when the registry is. `Tool::description` returns a borrowed string and
450    /// cannot be recomputed per call, so the names in it are the ones that existed then;
451    /// `{"list": true}` is what is there now.
452    description: String,
453}
454
455impl ScriptTool {
456    /// A tool over `dir`. The directory is read once, here, for the names in the description.
457    pub fn new(dir: PathBuf, timeout: Duration, max_bytes: usize) -> Self {
458        let description = describe_directory(&dir);
459        Self {
460            dir,
461            timeout,
462            max_bytes,
463            kill_grace: SHELL_KILL_GRACE,
464            sandbox: crate::sandbox::Sandbox::off(),
465            description,
466        }
467    }
468
469    /// Run this tool's scripts under the same sandbox the `shell` tool got (#550).
470    pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
471        self.sandbox = sandbox;
472        self
473    }
474
475    fn render_list(&self) -> Result<String, ToolError> {
476        let listing = list_scripts(&self.dir).map_err(ToolError::Failed)?;
477        let mut out = format!("scripts directory: {}\n", self.dir.display());
478        if !listing.exists {
479            out.push_str("it does not exist yet; `write_file` creates it with the first script\n");
480        }
481        if listing.scripts.is_empty() {
482            out.push_str("no scripts\n");
483            return Ok(out);
484        }
485        for script in &listing.scripts {
486            out.push_str(&script.name);
487            if script.escapes {
488                out.push_str(" (not runnable: a symlink that leads outside the directory)");
489            } else if !script.executable {
490                out.push_str(" (not executable: needs chmod +x)");
491            }
492            if let Some(d) = &script.description {
493                out.push_str(": ");
494                out.push_str(d);
495            }
496            out.push('\n');
497        }
498        if listing.omitted > 0 {
499            out.push_str(&format!("[{} more not listed]\n", listing.omitted));
500        }
501        Ok(out)
502    }
503}
504
505/// The tool's description for the directory as it is now.
506fn describe_directory(dir: &Path) -> String {
507    let mut text = format!(
508        "Run a script from the scripts directory ({dir}), or list what is there. A script is a \
509saved workflow: when you work out a procedure worth repeating, write it as a file in that \
510directory with `write_file`, make it executable with `chmod +x` through `shell`, and from then \
511on call it by name instead of working it out again. `{{\"list\": true}}` lists the scripts with \
512their first comment line; `{{\"name\": \"backup-media\", \"args\": [\"--dry-run\"]}}` runs one with \
513the scripts directory as its working directory and reports the exit code, stdout and stderr. A \
514name is a bare file name: no path, no `..`.",
515        dir = dir.display()
516    );
517    match list_scripts(dir) {
518        Ok(listing) if !listing.scripts.is_empty() => {
519            let total = listing.scripts.len() + listing.omitted;
520            let names: Vec<&str> = listing
521                .scripts
522                .iter()
523                .take(MAX_NAMED_IN_DESCRIPTION)
524                .map(|s| s.name.as_str())
525                .collect();
526            text.push_str(&format!(
527                " Scripts when this run started: {}",
528                names.join(", ")
529            ));
530            if total > names.len() {
531                text.push_str(&format!(" and {} more", total - names.len()));
532            }
533            text.push_str(". Call `list` for the current set.");
534        }
535        Ok(_) => text.push_str(" There are no scripts yet."),
536        Err(_) => {}
537    }
538    text
539}
540
541#[async_trait]
542impl Tool for ScriptTool {
543    fn name(&self) -> &str {
544        "script"
545    }
546
547    fn description(&self) -> &str {
548        &self.description
549    }
550
551    fn parameters(&self) -> Value {
552        json!({
553            "type": "object",
554            "properties": {
555                "list": {
556                    "type": "boolean",
557                    "description": "List the scripts and what each says it does. Cannot be combined with `name` or `args`."
558                },
559                "name": {
560                    "type": "string",
561                    "description": "The script's file name in the scripts directory, for example `backup-media.sh`: no path, no `..`."
562                },
563                "args": {
564                    "type": "array",
565                    "items": {"type": "string"},
566                    "description": "Arguments passed to the script, one string each."
567                }
568            }
569        })
570    }
571
572    fn describe_call(&self, args: &Value) -> String {
573        if args.get("list") == Some(&Value::Bool(true)) {
574            return "list the scripts".to_string();
575        }
576        let name = args.get("name").and_then(Value::as_str).unwrap_or("?");
577        match args
578            .get("args")
579            .filter(|a| a.as_array().is_some_and(|a| !a.is_empty()))
580        {
581            Some(a) => format!(
582                "run script {name:?} with arguments {a} from {}",
583                self.dir.display()
584            ),
585            None => format!("run script {name:?} from {}", self.dir.display()),
586        }
587    }
588
589    /// Listing is a read of a directory the user owns, so it is answered without asking even
590    /// under `ask`. This is the only place that says so; [`parse`] is what decides whether a
591    /// call is a listing, so a malformed call that merely mentions `list` is not one.
592    fn needs_approval(&self, args: &Value) -> bool {
593        !matches!(parse(args), Ok(Action::List))
594    }
595
596    async fn call(&self, args: Value) -> Result<String, ToolError> {
597        let (name, script_args) = match parse(&args)? {
598            Action::List => return self.render_list(),
599            Action::Run { name, args } => (name, args),
600        };
601        let run = prepare(&self.dir, &name, &script_args)?;
602        let plan = run.plan(&self.sandbox, &[])?;
603        crate::tools::run_built(
604            || run.command(&plan),
605            self.timeout,
606            self.max_bytes,
607            self.kill_grace,
608        )
609        .await
610    }
611
612    /// A run inside a run's scope gets a tool bridge: the script can call tools with
613    /// `eclipse tool <name> '{json}'`, through the same policy and approvals as a direct call.
614    /// Same process, same limits — only what it can reach is different.
615    async fn call_scoped(
616        &self,
617        args: Value,
618        scope: &crate::tools::CallScope<'_>,
619    ) -> Result<String, ToolError> {
620        let (name, script_args) = match parse(&args)? {
621            Action::List => return self.render_list(),
622            Action::Run { name, args } => (name, args),
623        };
624        let run = prepare(&self.dir, &name, &script_args)?;
625        // Bound before the plan, so the run can mount the socket's directory: under
626        // `shell_isolate = "fs"` the child gets a fresh `/tmp`, and a socket it cannot see is a
627        // bridge it cannot call (#550).
628        let bridge = crate::tools_bridge::Bridge::bind()?;
629        let plan = run.plan(&self.sandbox, &[bridge.dir().to_path_buf()])?;
630        crate::tools_bridge::run_with_bridge_built(
631            || run.command(&plan),
632            &bridge,
633            self.max_bytes,
634            self.timeout,
635            self.kill_grace,
636            scope,
637        )
638        .await
639    }
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645    use crate::config::{Policy, ToolsConfig};
646    use crate::tools::{AllowAll, Approver, ToolRegistry};
647    use std::sync::atomic::{AtomicUsize, Ordering};
648    use std::sync::Arc;
649
650    /// `#427`: the scripts directory came *first* on `PATH`, and `write_file` is `Allow`, so a
651    /// model-written script named `git` ran in place of the real one under every later `shell` call
652    /// — including a call the person approved by name. It comes last now: a real command wins, and
653    /// a script fills only a name nothing else has.
654    #[test]
655    fn the_scripts_directory_is_last_on_path() {
656        let dir = Path::new("/tmp/eclipse-path-order/scripts");
657        let path = path_with(dir).expect("PATH is set in the test environment");
658        let entries: Vec<PathBuf> = std::env::split_paths(&path).collect();
659        assert_eq!(entries.last(), Some(&dir.to_path_buf()), "{entries:?}");
660        assert!(
661            entries.len() > 2,
662            "the inherited PATH and this binary's directory are still there: {entries:?}"
663        );
664        assert!(
665            !entries.contains(&PathBuf::from("/usr/bin")) || entries[0] != dir,
666            "the scripts directory is not first"
667        );
668    }
669
670    fn write_script(dir: &Path, name: &str, body: &str, mode: u32) -> PathBuf {
671        std::fs::create_dir_all(dir).unwrap();
672        let path = dir.join(name);
673        std::fs::write(&path, body).unwrap();
674        #[cfg(unix)]
675        {
676            use std::os::unix::fs::PermissionsExt;
677            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
678        }
679        let _ = mode;
680        path
681    }
682
683    #[cfg(unix)]
684    fn process_alive(pid: i32) -> bool {
685        // SAFETY: signal 0 only probes for existence.
686        let exists = unsafe { libc::kill(pid, 0) } == 0;
687        // A zombie nobody has reaped yet is already dead.
688        let zombie = std::fs::read_to_string(format!("/proc/{pid}/stat"))
689            .map(|s| {
690                s.rsplit(')')
691                    .next()
692                    .unwrap_or("")
693                    .trim_start()
694                    .starts_with('Z')
695            })
696            .unwrap_or(false);
697        exists && !zombie
698    }
699
700    fn tool(dir: &Path) -> ScriptTool {
701        ScriptTool::new(dir.to_path_buf(), Duration::from_secs(10), 4096)
702    }
703
704    async fn call(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
705        tool.call(args).await
706    }
707
708    /// A script written a moment ago can be exec'd too early: another thread's `fork` inherits this
709    /// thread's open-for-write fd and the exec comes back `ETXTBSY`, "Text file busy". Two
710    /// `./verify.sh` runs back to back caught it once, and it passes alone — it is the test
711    /// binary's threads racing, not the tool. Retried, because it says nothing about the tool and
712    /// a flake in the gate costs a re-run of a four-minute job.
713    async fn call_retrying(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
714        let mut last = None;
715        for attempt in 0..5 {
716            match call(tool, args.clone()).await {
717                Ok(out) if !out.contains("Text file busy") => return Ok(out),
718                Ok(out) => last = Some(Ok(out)),
719                Err(e) if !e.to_string().contains("Text file busy") => return Err(e),
720                Err(e) => last = Some(Err(e)),
721            }
722            tokio::time::sleep(std::time::Duration::from_millis(10 * (attempt + 1))).await;
723        }
724        last.unwrap()
725    }
726
727    fn refused(result: Result<String, ToolError>) -> String {
728        match result {
729            Err(e) => e.to_string(),
730            Ok(out) => panic!("expected a refusal, got: {out}"),
731        }
732    }
733
734    #[test]
735    fn a_description_is_the_first_comment_line_after_a_shebang() {
736        assert_eq!(
737            first_comment("#!/bin/sh\n# Back up the media\nset -e\n").as_deref(),
738            Some("Back up the media")
739        );
740        assert_eq!(
741            first_comment("## Title  \n").as_deref(),
742            Some("Title"),
743            "no shebang, several hashes, trailing spaces"
744        );
745        assert_eq!(
746            first_comment("#!/bin/sh\n\nset -e\n# later one\n").as_deref(),
747            Some("later one"),
748            "the first line that starts with a hash, wherever it is"
749        );
750        assert_eq!(
751            first_comment("#!/bin/sh\n#\n#####\n# real\n").as_deref(),
752            Some("real"),
753            "an empty comment is a separator, not a description"
754        );
755        assert_eq!(first_comment("#!/bin/sh\necho hi\n"), None);
756        assert_eq!(first_comment(""), None);
757        assert_eq!(
758            first_comment("#!/bin/sh\r\n# crlf\r\n").as_deref(),
759            Some("crlf")
760        );
761    }
762
763    #[test]
764    fn a_long_description_is_cut_and_says_so() {
765        let text = format!("# {}\n", "x".repeat(500));
766        let d = first_comment(&text).unwrap();
767        assert!(d.ends_with("..."));
768        assert_eq!(d.chars().count(), MAX_DESCRIPTION_CHARS + 3);
769    }
770
771    #[test]
772    fn a_missing_directory_lists_as_nothing_rather_than_an_error() {
773        let tmp = tempfile::tempdir().unwrap();
774        let listing = list_scripts(&tmp.path().join("scripts")).unwrap();
775        assert!(!listing.exists && listing.scripts.is_empty());
776    }
777
778    #[tokio::test]
779    async fn the_list_is_sorted_and_carries_each_scripts_description() {
780        let tmp = tempfile::tempdir().unwrap();
781        write_script(tmp.path(), "zeta.sh", "#!/bin/sh\n# Last one\n", 0o755);
782        write_script(tmp.path(), "alpha.sh", "#!/bin/sh\n# First one\n", 0o755);
783        write_script(tmp.path(), "bare", "echo no comment\n", 0o755);
784        write_script(tmp.path(), ".hidden", "# secret\n", 0o755);
785        std::fs::create_dir(tmp.path().join("subdir")).unwrap();
786
787        let out = call(&tool(tmp.path()), json!({"list": true}))
788            .await
789            .unwrap();
790        let lines: Vec<&str> = out.lines().skip(1).collect();
791        assert_eq!(
792            lines,
793            ["alpha.sh: First one", "bare", "zeta.sh: Last one"],
794            "{out}"
795        );
796        assert!(out.starts_with(&format!("scripts directory: {}", tmp.path().display())));
797    }
798
799    #[tokio::test]
800    async fn listing_an_empty_or_missing_directory_says_there_are_none() {
801        let tmp = tempfile::tempdir().unwrap();
802        let missing = tmp.path().join("scripts");
803        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
804        assert!(
805            out.contains("no scripts") && out.contains("does not exist yet"),
806            "{out}"
807        );
808        std::fs::create_dir(&missing).unwrap();
809        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
810        assert!(
811            out.contains("no scripts") && !out.contains("does not exist"),
812            "{out}"
813        );
814    }
815
816    #[cfg(unix)]
817    #[tokio::test]
818    async fn a_file_that_is_not_executable_is_listed_and_flagged() {
819        let tmp = tempfile::tempdir().unwrap();
820        write_script(tmp.path(), "later.sh", "# not yet\n", 0o644);
821        let out = call(&tool(tmp.path()), json!({"list": true}))
822            .await
823            .unwrap();
824        assert!(
825            out.contains("later.sh (not executable: needs chmod +x): not yet"),
826            "{out}"
827        );
828    }
829
830    #[cfg(unix)]
831    #[tokio::test]
832    async fn a_listing_never_reads_through_a_symlink_that_leaves_the_directory() {
833        let tmp = tempfile::tempdir().unwrap();
834        let outside = tempfile::tempdir().unwrap();
835        write_script(outside.path(), "secret", "# TOP-SECRET-LINE\n", 0o755);
836        let dir = tmp.path().join("scripts");
837        std::fs::create_dir(&dir).unwrap();
838        std::os::unix::fs::symlink(outside.path().join("secret"), dir.join("peek")).unwrap();
839        let out = call(&tool(&dir), json!({"list": true})).await.unwrap();
840        assert!(out.contains("peek (not runnable"), "{out}");
841        assert!(!out.contains("TOP-SECRET-LINE"), "{out}");
842    }
843
844    #[tokio::test]
845    async fn only_the_head_of_a_script_is_read_for_its_description() {
846        let tmp = tempfile::tempdir().unwrap();
847        let body = format!(
848            "#!/bin/sh\n{}\n# too late\n",
849            "x".repeat(HEAD_BYTES as usize * 4)
850        );
851        write_script(tmp.path(), "big.sh", &body, 0o755);
852        let listing = list_scripts(tmp.path()).unwrap();
853        assert_eq!(listing.scripts[0].description, None);
854    }
855
856    #[tokio::test]
857    async fn a_listing_stops_describing_after_a_ceiling_and_says_how_many_it_left_out() {
858        let tmp = tempfile::tempdir().unwrap();
859        for i in 0..MAX_LISTED + 5 {
860            write_script(tmp.path(), &format!("s{i:04}"), "# x\n", 0o755);
861        }
862        let out = call(&tool(tmp.path()), json!({"list": true}))
863            .await
864            .unwrap();
865        assert!(
866            out.contains("[5 more not listed]"),
867            "{}",
868            &out[out.len() - 60..]
869        );
870    }
871
872    #[tokio::test]
873    async fn list_combined_with_a_name_or_arguments_is_refused_rather_than_guessed() {
874        let tmp = tempfile::tempdir().unwrap();
875        let t = tool(tmp.path());
876        for args in [
877            json!({"list": true, "name": "x"}),
878            json!({"list": true, "args": []}),
879            json!({"list": true, "name": ""}),
880        ] {
881            let e = call(&t, args).await.unwrap_err();
882            assert!(
883                matches!(e, ToolError::InvalidArgs(ref m) if m.contains("cannot be combined")),
884                "{e}"
885            );
886        }
887        // `list: false` is the same as no `list`.
888        let e = refused(call(&t, json!({"list": false})).await);
889        assert!(e.contains("give `name`"), "{e}");
890        let e = refused(call(&t, json!({})).await);
891        assert!(e.contains("give `name`"), "{e}");
892    }
893
894    #[tokio::test]
895    async fn a_present_argument_of_the_wrong_type_is_invalid_not_defaulted() {
896        let tmp = tempfile::tempdir().unwrap();
897        let t = tool(tmp.path());
898        for (args, field) in [
899            (json!({"list": "yes"}), "`list`"),
900            (json!({"list": 1}), "`list`"),
901            (json!({"name": 5}), "`name`"),
902            (json!({"name": ["a"]}), "`name`"),
903            (json!({"name": "a", "args": "--x"}), "`args`"),
904            (json!({"name": "a", "args": ["ok", 3]}), "`args[1]`"),
905            (json!({"name": "a", "args": [null]}), "`args[0]`"),
906        ] {
907            let e = call(&t, args.clone()).await.unwrap_err();
908            assert!(
909                matches!(&e, ToolError::InvalidArgs(m) if m.contains(field)),
910                "{args}: {e}"
911            );
912        }
913    }
914
915    #[cfg(unix)]
916    #[tokio::test]
917    async fn a_script_runs_with_its_arguments_from_the_scripts_directory() {
918        let tmp = tempfile::tempdir().unwrap();
919        write_script(
920            tmp.path(),
921            "show.sh",
922            "#!/bin/sh\necho \"args: $1|$2\"\necho \"cwd: $(pwd)\"\necho \"dir: $ECLIPSE_SCRIPTS_DIR\"\necho oops >&2\nexit 3\n",
923            0o755,
924        );
925        let out = call(
926            &tool(tmp.path()),
927            json!({"name": "show.sh", "args": ["--dry-run", "two words"]}),
928        )
929        .await
930        .unwrap();
931        let canon = std::fs::canonicalize(tmp.path()).unwrap();
932        assert!(out.starts_with("exit code: 3\n"), "{out}");
933        assert!(out.contains("args: --dry-run|two words"), "{out}");
934        assert!(out.contains(&format!("cwd: {}", canon.display())), "{out}");
935        assert!(
936            out.contains(&format!("dir: {}", tmp.path().display())),
937            "{out}"
938        );
939        assert!(out.contains("stderr:\noops"), "{out}");
940    }
941
942    #[cfg(unix)]
943    #[tokio::test]
944    async fn a_read_only_promise_without_bubblewrap_refuses_a_script_too() {
945        // `shell_isolate = "fs"` promises a read-only machine, and `shell` refuses to run when
946        // bubblewrap is missing. `script` is the same act with the words already written down, so
947        // it has to give the same answer rather than run the file uncontained (#550).
948        let tmp = tempfile::tempdir().unwrap();
949        let marker = tmp.path().join("ran");
950        write_script(
951            tmp.path(),
952            "touch-marker.sh",
953            &format!("#!/bin/sh\ntouch {}\n", marker.display()),
954            0o755,
955        );
956        let tool = tool(tmp.path()).with_sandbox(crate::sandbox::Sandbox::without_bwrap(
957            crate::config::ShellIsolate::Fs,
958        ));
959        let e = call(&tool, json!({"name": "touch-marker.sh"}))
960            .await
961            .unwrap_err()
962            .to_string();
963        assert!(e.contains("which is not on PATH"), "{e}");
964        assert!(!marker.exists(), "the script must not have run");
965    }
966
967    #[cfg(unix)]
968    #[tokio::test]
969    async fn a_script_has_no_stdin_and_sees_its_directory_first_on_path() {
970        let tmp = tempfile::tempdir().unwrap();
971        write_script(tmp.path(), "helper", "#!/bin/sh\necho from-helper\n", 0o755);
972        write_script(
973            tmp.path(),
974            "main.sh",
975            "#!/bin/sh\ncat | wc -c\nhelper\n",
976            0o755,
977        );
978        let out = call_retrying(&tool(tmp.path()), json!({"name": "main.sh"}))
979            .await
980            .unwrap();
981        assert!(out.contains("exit code: 0"), "{out}");
982        assert!(
983            out.contains("\n0\n"),
984            "stdin reads end-of-file at once: {out}"
985        );
986        assert!(out.contains("from-helper"), "{out}");
987    }
988
989    #[cfg(unix)]
990    #[tokio::test]
991    async fn a_name_that_is_not_a_plain_file_name_in_the_directory_is_refused_with_a_reason() {
992        let tmp = tempfile::tempdir().unwrap();
993        let dir = tmp.path().join("scripts");
994        write_script(&dir, "ok.sh", "#!/bin/sh\necho ok\n", 0o755);
995        write_script(&dir, "plain.txt", "echo no\n", 0o644);
996        write_script(tmp.path(), "outside.sh", "echo out\n", 0o755);
997        std::fs::create_dir(dir.join("adir")).unwrap();
998        let t = tool(&dir);
999
1000        let absolute = tmp.path().join("outside.sh").display().to_string();
1001        for (name, why) in [
1002            ("", "empty"),
1003            ("   ", "empty"),
1004            ("../outside.sh", "path separator"),
1005            ("sub/ok.sh", "path separator"),
1006            ("sub\\ok.sh", "path separator"),
1007            ("..", "`..`"),
1008            ("a..b", "`..`"),
1009            (absolute.as_str(), "absolute path"),
1010            ("/etc/passwd", "absolute path"),
1011            ("missing.sh", "no such file"),
1012            ("adir", "not a regular file"),
1013            ("plain.txt", "chmod +x"),
1014        ] {
1015            let e = refused(call(&t, json!({"name": name})).await);
1016            assert!(
1017                e.contains(&format!("script {name:?} refused")),
1018                "{name:?}: {e}"
1019            );
1020            assert!(e.contains(why), "{name:?} should say {why:?}: {e}");
1021        }
1022        // The same tool still runs the good one.
1023        assert!(call(&t, json!({"name": "ok.sh"}))
1024            .await
1025            .unwrap()
1026            .contains("ok"));
1027    }
1028
1029    #[cfg(unix)]
1030    #[tokio::test]
1031    async fn a_symlink_out_of_the_directory_is_refused_and_one_inside_is_not() {
1032        let tmp = tempfile::tempdir().unwrap();
1033        let dir = tmp.path().join("scripts");
1034        let target = write_script(
1035            tmp.path(),
1036            "elsewhere.sh",
1037            "#!/bin/sh\necho escaped\n",
1038            0o755,
1039        );
1040        std::fs::create_dir_all(&dir).unwrap();
1041        std::os::unix::fs::symlink(&target, dir.join("out")).unwrap();
1042        write_script(&dir, "real.sh", "#!/bin/sh\necho real\n", 0o755);
1043        std::os::unix::fs::symlink(dir.join("real.sh"), dir.join("alias")).unwrap();
1044        std::os::unix::fs::symlink(dir.join("nowhere"), dir.join("dangling")).unwrap();
1045        let t = tool(&dir);
1046
1047        let e = refused(call(&t, json!({"name": "out"})).await);
1048        assert!(e.contains("outside the scripts directory"), "{e}");
1049        let ok = call(&t, json!({"name": "alias"})).await.unwrap();
1050        assert!(ok.contains("real"), "{ok}");
1051        let e = refused(call(&t, json!({"name": "dangling"})).await);
1052        assert!(e.contains("no such file"), "{e}");
1053    }
1054
1055    #[cfg(unix)]
1056    #[tokio::test]
1057    async fn a_script_with_no_shebang_says_what_to_add_instead_of_a_bare_os_error() {
1058        let tmp = tempfile::tempdir().unwrap();
1059        write_script(tmp.path(), "bare.sh", "echo hi\n", 0o755);
1060        let e = refused(call(&tool(tmp.path()), json!({"name": "bare.sh"})).await);
1061        assert!(e.contains("no `#!` line") && e.contains("#!/bin/sh"), "{e}");
1062    }
1063
1064    #[tokio::test]
1065    async fn a_directory_that_does_not_exist_refuses_a_name_and_says_so() {
1066        let tmp = tempfile::tempdir().unwrap();
1067        let t = tool(&tmp.path().join("scripts"));
1068        let e = refused(call(&t, json!({"name": "x.sh"})).await);
1069        assert!(e.contains("does not exist yet"), "{e}");
1070    }
1071
1072    #[cfg(unix)]
1073    #[tokio::test]
1074    async fn a_script_that_overruns_the_timeout_is_killed_with_the_child_it_started() {
1075        let tmp = tempfile::tempdir().unwrap();
1076        write_script(
1077            tmp.path(),
1078            "hang.sh",
1079            "#!/bin/sh\nsleep 300 &\necho $! > child.pid\nwait\n",
1080            0o755,
1081        );
1082        let mut t = tool(tmp.path());
1083        t.timeout = Duration::from_secs(1);
1084        t.kill_grace = Duration::from_millis(300);
1085        let started = std::time::Instant::now();
1086        let e = refused(call(&t, json!({"name": "hang.sh"})).await);
1087        assert!(e.contains("timed out after 1s"), "{e}");
1088        assert!(started.elapsed() < Duration::from_secs(8));
1089        let pid: i32 = std::fs::read_to_string(tmp.path().join("child.pid"))
1090            .unwrap()
1091            .trim()
1092            .parse()
1093            .unwrap();
1094        for _ in 0..100 {
1095            if !process_alive(pid) {
1096                break;
1097            }
1098            tokio::time::sleep(Duration::from_millis(50)).await;
1099        }
1100        let alive = process_alive(pid);
1101        assert!(!alive, "child {pid} survived the timeout");
1102    }
1103
1104    #[cfg(unix)]
1105    #[tokio::test]
1106    async fn a_script_that_floods_its_output_is_cut_at_the_cap() {
1107        let tmp = tempfile::tempdir().unwrap();
1108        write_script(tmp.path(), "flood.sh", "#!/bin/sh\nyes\n", 0o755);
1109        let t = ScriptTool::new(tmp.path().to_path_buf(), Duration::from_secs(10), 256);
1110        let out = call(&t, json!({"name": "flood.sh"})).await.unwrap();
1111        assert!(out.contains("[truncated]"), "{out}");
1112        assert!(out.len() < 400, "{}", out.len());
1113    }
1114
1115    #[test]
1116    fn an_approval_prompt_names_the_script_and_its_arguments() {
1117        let tmp = tempfile::tempdir().unwrap();
1118        let t = tool(tmp.path());
1119        let with = t.describe_call(&json!({"name": "backup-media", "args": ["--dry-run"]}));
1120        assert!(
1121            with.contains("backup-media") && with.contains("--dry-run"),
1122            "{with}"
1123        );
1124        assert!(with.contains(&tmp.path().display().to_string()), "{with}");
1125        let without = t.describe_call(&json!({"name": "backup-media"}));
1126        assert!(
1127            without.contains("backup-media") && !without.contains("arguments"),
1128            "{without}"
1129        );
1130        assert_eq!(t.describe_call(&json!({"list": true})), "list the scripts");
1131        // A hostile or mangled call still produces a readable line.
1132        let odd = t.describe_call(&json!({"name": "a\nb", "args": 5}));
1133        assert!(!odd.contains('\n'), "{odd}");
1134    }
1135
1136    struct Counting(AtomicUsize);
1137
1138    #[async_trait]
1139    impl Approver for Counting {
1140        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
1141            self.0.fetch_add(1, Ordering::SeqCst);
1142            crate::approvals::Decision::Deny("no".to_string())
1143        }
1144    }
1145
1146    #[tokio::test]
1147    async fn under_ask_a_listing_is_answered_without_a_prompt_and_a_run_is_not() {
1148        let tmp = tempfile::tempdir().unwrap();
1149        write_script(tmp.path(), "a.sh", "# a\n", 0o755);
1150        let mut registry = ToolRegistry::new(4096);
1151        registry.register(Arc::new(tool(tmp.path())), Policy::Ask);
1152        let approver = Counting(AtomicUsize::new(0));
1153
1154        let out = registry
1155            .dispatch("script", r#"{"list":true}"#, &approver)
1156            .await;
1157        assert!(
1158            !out.is_error && out.output.contains("a.sh: a"),
1159            "{}",
1160            out.output
1161        );
1162        assert_eq!(
1163            approver.0.load(Ordering::SeqCst),
1164            0,
1165            "a listing is not asked about"
1166        );
1167
1168        for call in [
1169            r#"{"name":"a.sh"}"#,
1170            r#"{"list":true,"name":"a.sh"}"#,
1171            r#"{"list":"yes","name":"a.sh"}"#,
1172            r#"{}"#,
1173        ] {
1174            let out = registry.dispatch("script", call, &approver).await;
1175            assert!(
1176                out.is_error && out.output.contains("declined"),
1177                "{call}: {}",
1178                out.output
1179            );
1180        }
1181        assert_eq!(approver.0.load(Ordering::SeqCst), 4);
1182
1183        // `deny` still means never, listing included.
1184        let mut registry = ToolRegistry::new(4096);
1185        registry.register(Arc::new(tool(tmp.path())), Policy::Deny);
1186        let out = registry
1187            .dispatch("script", r#"{"list":true}"#, &AllowAll)
1188            .await;
1189        assert!(out.is_error && out.output.contains("disabled by policy"));
1190    }
1191
1192    #[test]
1193    fn the_description_names_the_scripts_there_were_and_points_at_list_for_the_rest() {
1194        let tmp = tempfile::tempdir().unwrap();
1195        let empty = tool(tmp.path());
1196        assert!(empty.description().contains("no scripts yet"));
1197        assert!(empty
1198            .description()
1199            .contains(&tmp.path().display().to_string()));
1200
1201        for i in 0..MAX_NAMED_IN_DESCRIPTION + 3 {
1202            write_script(tmp.path(), &format!("s{i:02}.sh"), "# x\n", 0o755);
1203        }
1204        let full = tool(tmp.path());
1205        let d = full.description();
1206        assert!(d.contains("s00.sh") && d.contains("and 3 more"), "{d}");
1207        assert!(
1208            !d.contains(&format!("s{:02}.sh", MAX_NAMED_IN_DESCRIPTION)),
1209            "{d}"
1210        );
1211        assert!(d.contains("`list`"), "{d}");
1212    }
1213
1214    #[test]
1215    fn the_tool_registers_with_a_schema_that_needs_no_arguments_to_be_present() {
1216        let tmp = tempfile::tempdir().unwrap();
1217        let cfg = ToolsConfig::default();
1218        let registry = ToolRegistry::from_config_full(
1219            &cfg,
1220            tmp.path().to_path_buf(),
1221            Vec::new(),
1222            Some(tmp.path().join("scripts")),
1223        );
1224        let d = registry
1225            .descriptors()
1226            .into_iter()
1227            .find(|d| d.name == "script")
1228            .expect("script is registered");
1229        assert_eq!(d.policy, Policy::Ask);
1230        assert_eq!(
1231            d.parameters["properties"]["args"]["items"]["type"],
1232            "string"
1233        );
1234        assert!(d.parameters.get("required").is_none());
1235    }
1236}