eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
//! The `script` tool: workflows the agent writes once and then calls by name.
//!
//! A script is an executable file in the scripts directory (`<config dir>/scripts/`, or the
//! profile's own under a profile). The agent works something out, writes it there, and the next
//! run — or the next minute — it is a command: `script` runs it, and `shell` finds it on `PATH`.
//! This module is the one place that decides what a script *is*: [`list_scripts`] says what is
//! in the directory, [`resolve`] turns a name into a file that is safe to run or a sentence
//! saying why not, and [`command`] builds the process. The tool and `eclipse scripts run` both
//! go through those three, so the CLI cannot run something the tool would refuse.
//!
//! What a name may be is deliberately narrow. Scripts are flat — no `/`, no `\`, no `..` — and
//! the file is canonicalised before it runs: a symlink that leads out of the directory is
//! refused rather than followed, because the directory is writable by the agent and a link in it
//! would otherwise be a way to run anything. The directory itself is the user's own config
//! directory, which is why `write_file` may write there at all.
//!
//! The process limits are `shell`'s, by sharing its code: `[tools] shell_timeout_secs`, a
//! process-group kill so a background child cannot outlive the run, and output capped at
//! `[tools] max_output_bytes`.
//!
//! Nothing reads more of a file than it needs. A listing takes the first few kilobytes of each
//! script for its description and no more, so a directory holding a large file costs what a
//! small one does.

use crate::tools::{str_arg, Tool, ToolError, SHELL_KILL_GRACE};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

/// The environment variable that carries the scripts directory to everything Eclipse starts:
/// scripts, `shell` commands and plugin tool processes.
pub const ENV_SCRIPTS_DIR: &str = "ECLIPSE_SCRIPTS_DIR";

/// How much of a script is read to find its description. A description is the first comment
/// line; if it is not in the first few kilobytes there is no description worth showing.
const HEAD_BYTES: u64 = 4096;
/// The longest description shown, in characters.
const MAX_DESCRIPTION_CHARS: usize = 200;
/// The most scripts a listing describes. Past this the listing says how many it left out.
const MAX_LISTED: usize = 200;
/// The most names the tool's own description carries; `{"list": true}` is the full answer.
const MAX_NAMED_IN_DESCRIPTION: usize = 20;

/// One file in the scripts directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScriptInfo {
    pub name: String,
    /// The first comment line, after any shebang. `None` when the script has no comment.
    pub description: Option<String>,
    pub path: PathBuf,
    /// Whether the file's mode lets it run. A file that is not is still listed, so a script
    /// written without `chmod +x` is visible rather than mysteriously absent.
    pub executable: bool,
    /// Set when the file is a symlink that leads out of the directory: listed so it is
    /// visible, never read and never run.
    pub escapes: bool,
}

/// What [`list_scripts`] found.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Listing {
    pub scripts: Vec<ScriptInfo>,
    /// Scripts beyond [`MAX_LISTED`] that were not described.
    pub omitted: usize,
    /// False when the directory does not exist (yet). That is not an error: nothing has been
    /// written.
    pub exists: bool,
}

/// The description a script gives itself: its first comment line.
///
/// A `#!` shebang on the first line is skipped; then the first line that starts with `#`, with
/// the `#` characters and surrounding spaces removed. A comment line with nothing on it
/// (`#` alone, or a ruled `#####`) is a separator rather than a description and is skipped.
pub fn first_comment(head: &str) -> Option<String> {
    let mut lines = head.lines();
    let first = lines.next()?;
    let rest = if first.starts_with("#!") {
        lines
    } else {
        head.lines()
    };
    for line in rest {
        if !line.starts_with('#') {
            continue;
        }
        let text = line.trim_start_matches('#').trim();
        if text.is_empty() {
            continue;
        }
        let mut chars = text.chars();
        let kept: String = chars.by_ref().take(MAX_DESCRIPTION_CHARS).collect();
        return Some(if chars.next().is_some() {
            format!("{kept}...")
        } else {
            kept
        });
    }
    None
}

/// Read at most [`HEAD_BYTES`] of `path`. The file is the agent's to write, so its size is not
/// known to be small, and nothing here reads the rest.
fn read_head(path: &Path) -> Option<String> {
    let mut buf = Vec::new();
    std::fs::File::open(path)
        .ok()?
        .take(HEAD_BYTES)
        .read_to_end(&mut buf)
        .ok()?;
    Some(String::from_utf8_lossy(&buf).into_owned())
}

#[cfg(unix)]
fn is_executable(meta: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::PermissionsExt;
    meta.permissions().mode() & 0o111 != 0
}

#[cfg(not(unix))]
fn is_executable(_: &std::fs::Metadata) -> bool {
    true
}

/// The scripts in `dir`, sorted by name.
///
/// Regular files only, dotfiles skipped (editor swap files, `.DS_Store`). A missing directory
/// gives an empty listing; any other failure to read it is an error.
pub fn list_scripts(dir: &Path) -> Result<Listing, String> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Listing::default()),
        Err(e) => return Err(format!("cannot read {}: {e}", dir.display())),
    };
    let canonical_dir = std::fs::canonicalize(dir).ok();
    let mut names: Vec<String> = entries
        .flatten()
        .filter_map(|e| e.file_name().into_string().ok())
        .filter(|n| !n.starts_with('.'))
        .collect();
    names.sort();
    let omitted = names.len().saturating_sub(MAX_LISTED);
    names.truncate(MAX_LISTED);

    let mut scripts = Vec::new();
    for name in names {
        let path = dir.join(&name);
        let Ok(canonical) = std::fs::canonicalize(&path) else {
            continue;
        };
        let Ok(meta) = std::fs::metadata(&canonical) else {
            continue;
        };
        if !meta.is_file() {
            continue;
        }
        let escapes = !canonical_dir
            .as_ref()
            .is_some_and(|d| canonical.starts_with(d));
        scripts.push(ScriptInfo {
            description: if escapes {
                None
            } else {
                read_head(&canonical).and_then(|h| first_comment(&h))
            },
            executable: is_executable(&meta),
            name,
            path,
            escapes,
        });
    }
    Ok(Listing {
        scripts,
        omitted,
        exists: true,
    })
}

/// Turn `name` into the file to run, or a sentence saying why it will not be.
///
/// The refusals, in the order they are checked: an empty name, an absolute path, a path
/// separator, `..`, a file that does not exist, one that resolves outside `dir` once symlinks
/// are followed, one that is not a regular file, and one that is not executable. The returned
/// path is canonical, so what was checked is what runs.
pub fn resolve(dir: &Path, name: &str) -> Result<PathBuf, String> {
    let (canonical, meta) = locate(dir, name)?;
    if !is_executable(&meta) {
        return Err(format!(
            "{} is not executable; make it so with `chmod +x {}` and call it again",
            canonical.display(),
            canonical.display()
        ));
    }
    Ok(canonical)
}

/// As [`resolve`], without the executable check: the file `name` names, for reading it
/// (`eclipse scripts cat`) rather than running it.
pub fn locate_file(dir: &Path, name: &str) -> Result<PathBuf, String> {
    locate(dir, name).map(|(path, _)| path)
}

fn locate(dir: &Path, name: &str) -> Result<(PathBuf, std::fs::Metadata), String> {
    if name.trim().is_empty() {
        return Err(
            "the name is empty; give the file name of a script, or `list` to see them".into(),
        );
    }
    if name.contains('\0') {
        return Err("the name contains a NUL byte".into());
    }
    if Path::new(name).is_absolute() || name.starts_with('/') {
        return Err(format!(
            "it is an absolute path; a script is called by its file name inside the scripts directory ({})",
            dir.display()
        ));
    }
    if name.contains('/') || name.contains('\\') {
        return Err(
            "it contains a path separator; scripts are called by file name only, and the scripts directory has no subdirectories".into(),
        );
    }
    if name.contains("..") {
        return Err(
            "it contains `..`; a script cannot be named by walking out of the scripts directory"
                .into(),
        );
    }
    let canonical_dir = std::fs::canonicalize(dir).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            format!(
                "the scripts directory {} does not exist yet, so there is no such script",
                dir.display()
            )
        } else {
            format!(
                "the scripts directory {} cannot be resolved ({e})",
                dir.display()
            )
        }
    })?;
    let canonical = std::fs::canonicalize(dir.join(name)).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            format!(
                "there is no such file in {} (or it is a symlink to nothing); `list` shows what exists",
                dir.display()
            )
        } else {
            format!("it cannot be resolved ({e})")
        }
    })?;
    if !canonical.starts_with(&canonical_dir) {
        return Err(format!(
            "it resolves to {}, which is outside the scripts directory ({}); a symlink may not lead out of it",
            canonical.display(),
            canonical_dir.display()
        ));
    }
    let meta = std::fs::metadata(&canonical)
        .map_err(|e| format!("{} cannot be read ({e})", canonical.display()))?;
    if !meta.is_file() {
        return Err(format!("{} is not a regular file", canonical.display()));
    }
    Ok((canonical, meta))
}

/// `dir` placed on the `PATH` this process has, so a script is a command — *last*.
///
/// `None` when there is no `PATH` to put it on, or the result could not be written down as one
/// (a `:` inside `dir`). A process with no `PATH` finds commands in a system default that
/// naming only the scripts directory would replace, so leaving it alone is the safe answer.
///
/// **Last, not first** (`#427`). `write_file` is `Allow` and `shell` runs with this `PATH`, so a
/// script named `git` used to run in place of the real `git` under every later `shell` call —
/// including a call the person approved *by name*, which is the one case where they thought they
/// knew what would run. A script now wins only where no command exists; to run one that shares a
/// name with a real command, name it by path (`scripts/git`) or add a distinct name.
pub fn path_with(dir: &Path) -> Option<OsString> {
    let current = std::env::var_os("PATH")?;
    // The directory holding *this* `eclipse` first, so a program can reach the tool bridge with
    // `eclipse tool <name> '{json}'` even when it was started from `target/debug` or a path the
    // user's shell does not have; then the inherited `PATH`, so a real command wins over a script;
    // then the scripts directory.
    let exe = std::env::current_exe()
        .ok()
        .and_then(|p| p.parent().map(Path::to_path_buf));
    let paths = exe
        .into_iter()
        .chain(std::env::split_paths(&current))
        .chain(std::iter::once(dir.to_path_buf()));
    std::env::join_paths(paths).ok()
}

/// The process for `script` (already resolved by [`resolve`]) with `args`: run from the scripts
/// directory, with that directory first on `PATH` and in [`ENV_SCRIPTS_DIR`]. Stdio is left for
/// the caller — the tool pipes it, `eclipse scripts run` inherits it.
pub fn command(dir: &Path, script: &Path, args: &[String]) -> std::process::Command {
    let mut cmd = std::process::Command::new(script);
    cmd.args(args).current_dir(dir).env(ENV_SCRIPTS_DIR, dir);
    if let Some(path) = path_with(dir) {
        cmd.env("PATH", path);
    }
    cmd
}

/// The command for a named script, after every refusal that can be decided without running it.
/// Both the plain and the bridged path start here, so a name is vetted once.
fn prepare(dir: &Path, name: &str, args: &[String]) -> Result<Run, ToolError> {
    let script = resolve(dir, name)
        .map_err(|why| ToolError::Failed(format!("script {name:?} refused: {why}")))?;
    Ok(Run {
        dir: dir.to_path_buf(),
        script,
        args: args.to_vec(),
    })
}

/// A script to run, kept apart from the [`Command`](tokio::process::Command) that runs it.
///
/// A command cannot be cloned, and starting one can be refused with `ETXTBSY` — the file is still
/// open for writing somewhere, usually in a child another thread forked a microsecond ago. Being
/// able to build the command again is what makes trying again possible.
struct Run {
    dir: PathBuf,
    script: PathBuf,
    args: Vec<String>,
}

impl Run {
    /// The program and arguments to run, re-planned through the sandbox exactly as `shell` does
    /// (#550). Fallible only for a mode that refuses, which is the point: a script must not run
    /// uncontained where `shell` refuses to.
    fn plan(
        &self,
        sandbox: &crate::sandbox::Sandbox,
        extra_rw: &[PathBuf],
    ) -> Result<crate::sandbox::Plan, ToolError> {
        let args: Vec<std::ffi::OsString> =
            self.args.iter().map(std::ffi::OsString::from).collect();
        sandbox.plan_with(self.script.as_os_str(), &args, &self.dir, extra_rw)
    }

    /// A command for one attempt. Infallible: a retry after `ETXTBSY` rebuilds the same plan
    /// rather than deciding it again.
    fn command(&self, plan: &crate::sandbox::Plan) -> tokio::process::Command {
        let mut cmd = tokio::process::Command::new(&plan.program);
        cmd.args(&plan.args).current_dir(&self.dir);
        apply_env(&mut cmd, &self.dir);
        cmd
    }
}

/// The environment a run gets: the scripts directory by name, and on `PATH` after the real
/// commands. Shared so `execute_code` — which builds its own command over the same directory —
/// cannot drift from what `script` gives one (#550).
pub fn apply_env(cmd: &mut tokio::process::Command, dir: &Path) {
    cmd.env(ENV_SCRIPTS_DIR, dir);
    if let Some(path) = path_with(dir) {
        cmd.env("PATH", path);
    }
}

/// Why a script could not be started, for the one failure that has a fix the agent can make.
///
/// A file with no `#!` line is "executable" to the mode check and then refused by the kernel
/// with `ENOEXEC`. Eclipse does not guess an interpreter for it — `sh` is not always the right
/// one — so the message says what to add.
pub fn start_error(e: &std::io::Error) -> String {
    #[cfg(unix)]
    if e.raw_os_error() == Some(libc::ENOEXEC) {
        return format!(
            "failed to start: {e}. The file has no `#!` line, so there is no interpreter to run \
it with: begin it with one, for example `#!/bin/sh` or `#!/usr/bin/env python3`"
        );
    }
    format!("failed to start: {e}")
}

/// What a call asks for, with every argument type-checked.
#[derive(Debug, PartialEq, Eq)]
enum Action {
    List,
    Run { name: String, args: Vec<String> },
}

fn invalid(message: impl Into<String>) -> ToolError {
    ToolError::InvalidArgs(message.into())
}

/// Read an optional argument: absent and `null` are the same, and anything else must be the
/// right type. Guessing a default for a mistyped value is how `{"list": "yes"}` becomes a run.
fn parse(args: &Value) -> Result<Action, ToolError> {
    let list = match args.get("list") {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(_) => return Err(invalid("`list` must be a boolean")),
    };
    let name = match args.get("name") {
        None | Some(Value::Null) => None,
        Some(Value::String(_)) => Some(str_arg(args, "name")?.to_string()),
        Some(_) => return Err(invalid("`name` must be a string")),
    };
    let script_args = match args.get("args") {
        None | Some(Value::Null) => None,
        Some(Value::Array(items)) => {
            let mut out = Vec::with_capacity(items.len());
            for (i, item) in items.iter().enumerate() {
                match item {
                    Value::String(s) => out.push(s.clone()),
                    _ => return Err(invalid(format!("`args[{i}]` must be a string"))),
                }
            }
            Some(out)
        }
        Some(_) => return Err(invalid("`args` must be an array of strings")),
    };
    if list {
        if name.is_some() || script_args.is_some() {
            return Err(invalid(
                "`list: true` cannot be combined with `name` or `args`: either list the scripts or run one",
            ));
        }
        return Ok(Action::List);
    }
    match name {
        Some(name) => Ok(Action::Run {
            name,
            args: script_args.unwrap_or_default(),
        }),
        None => Err(invalid(
            "give `name` to run a script, or `list: true` to see what there is",
        )),
    }
}

/// `script`: list the scripts, or run one.
pub struct ScriptTool {
    dir: PathBuf,
    timeout: Duration,
    max_bytes: usize,
    kill_grace: Duration,
    /// The policy `shell` enforces, so a script runs under the same containment (#550). `off`
    /// until a registry hands in the profile's own sandbox, which is what the CLI does not do:
    /// `eclipse scripts run` is the person running their own script.
    sandbox: crate::sandbox::Sandbox,
    /// Built once, when the registry is. `Tool::description` returns a borrowed string and
    /// cannot be recomputed per call, so the names in it are the ones that existed then;
    /// `{"list": true}` is what is there now.
    description: String,
}

impl ScriptTool {
    /// A tool over `dir`. The directory is read once, here, for the names in the description.
    pub fn new(dir: PathBuf, timeout: Duration, max_bytes: usize) -> Self {
        let description = describe_directory(&dir);
        Self {
            dir,
            timeout,
            max_bytes,
            kill_grace: SHELL_KILL_GRACE,
            sandbox: crate::sandbox::Sandbox::off(),
            description,
        }
    }

    /// Run this tool's scripts under the same sandbox the `shell` tool got (#550).
    pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
        self.sandbox = sandbox;
        self
    }

    fn render_list(&self) -> Result<String, ToolError> {
        let listing = list_scripts(&self.dir).map_err(ToolError::Failed)?;
        let mut out = format!("scripts directory: {}\n", self.dir.display());
        if !listing.exists {
            out.push_str("it does not exist yet; `write_file` creates it with the first script\n");
        }
        if listing.scripts.is_empty() {
            out.push_str("no scripts\n");
            return Ok(out);
        }
        for script in &listing.scripts {
            out.push_str(&script.name);
            if script.escapes {
                out.push_str(" (not runnable: a symlink that leads outside the directory)");
            } else if !script.executable {
                out.push_str(" (not executable: needs chmod +x)");
            }
            if let Some(d) = &script.description {
                out.push_str(": ");
                out.push_str(d);
            }
            out.push('\n');
        }
        if listing.omitted > 0 {
            out.push_str(&format!("[{} more not listed]\n", listing.omitted));
        }
        Ok(out)
    }
}

/// The tool's description for the directory as it is now.
fn describe_directory(dir: &Path) -> String {
    let mut text = format!(
        "Run a script from the scripts directory ({dir}), or list what is there. A script is a \
saved workflow: when you work out a procedure worth repeating, write it as a file in that \
directory with `write_file`, make it executable with `chmod +x` through `shell`, and from then \
on call it by name instead of working it out again. `{{\"list\": true}}` lists the scripts with \
their first comment line; `{{\"name\": \"backup-media\", \"args\": [\"--dry-run\"]}}` runs one with \
the scripts directory as its working directory and reports the exit code, stdout and stderr. A \
name is a bare file name: no path, no `..`.",
        dir = dir.display()
    );
    match list_scripts(dir) {
        Ok(listing) if !listing.scripts.is_empty() => {
            let total = listing.scripts.len() + listing.omitted;
            let names: Vec<&str> = listing
                .scripts
                .iter()
                .take(MAX_NAMED_IN_DESCRIPTION)
                .map(|s| s.name.as_str())
                .collect();
            text.push_str(&format!(
                " Scripts when this run started: {}",
                names.join(", ")
            ));
            if total > names.len() {
                text.push_str(&format!(" and {} more", total - names.len()));
            }
            text.push_str(". Call `list` for the current set.");
        }
        Ok(_) => text.push_str(" There are no scripts yet."),
        Err(_) => {}
    }
    text
}

#[async_trait]
impl Tool for ScriptTool {
    fn name(&self) -> &str {
        "script"
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "list": {
                    "type": "boolean",
                    "description": "List the scripts and what each says it does. Cannot be combined with `name` or `args`."
                },
                "name": {
                    "type": "string",
                    "description": "The script's file name in the scripts directory, for example `backup-media.sh`: no path, no `..`."
                },
                "args": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Arguments passed to the script, one string each."
                }
            }
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        if args.get("list") == Some(&Value::Bool(true)) {
            return "list the scripts".to_string();
        }
        let name = args.get("name").and_then(Value::as_str).unwrap_or("?");
        match args
            .get("args")
            .filter(|a| a.as_array().is_some_and(|a| !a.is_empty()))
        {
            Some(a) => format!(
                "run script {name:?} with arguments {a} from {}",
                self.dir.display()
            ),
            None => format!("run script {name:?} from {}", self.dir.display()),
        }
    }

    /// Listing is a read of a directory the user owns, so it is answered without asking even
    /// under `ask`. This is the only place that says so; [`parse`] is what decides whether a
    /// call is a listing, so a malformed call that merely mentions `list` is not one.
    fn needs_approval(&self, args: &Value) -> bool {
        !matches!(parse(args), Ok(Action::List))
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let (name, script_args) = match parse(&args)? {
            Action::List => return self.render_list(),
            Action::Run { name, args } => (name, args),
        };
        let run = prepare(&self.dir, &name, &script_args)?;
        let plan = run.plan(&self.sandbox, &[])?;
        crate::tools::run_built(
            || run.command(&plan),
            self.timeout,
            self.max_bytes,
            self.kill_grace,
        )
        .await
    }

    /// A run inside a run's scope gets a tool bridge: the script can call tools with
    /// `eclipse tool <name> '{json}'`, through the same policy and approvals as a direct call.
    /// Same process, same limits — only what it can reach is different.
    async fn call_scoped(
        &self,
        args: Value,
        scope: &crate::tools::CallScope<'_>,
    ) -> Result<String, ToolError> {
        let (name, script_args) = match parse(&args)? {
            Action::List => return self.render_list(),
            Action::Run { name, args } => (name, args),
        };
        let run = prepare(&self.dir, &name, &script_args)?;
        // Bound before the plan, so the run can mount the socket's directory: under
        // `shell_isolate = "fs"` the child gets a fresh `/tmp`, and a socket it cannot see is a
        // bridge it cannot call (#550).
        let bridge = crate::tools_bridge::Bridge::bind()?;
        let plan = run.plan(&self.sandbox, &[bridge.dir().to_path_buf()])?;
        crate::tools_bridge::run_with_bridge_built(
            || run.command(&plan),
            &bridge,
            self.max_bytes,
            self.timeout,
            self.kill_grace,
            scope,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Policy, ToolsConfig};
    use crate::tools::{AllowAll, Approver, ToolRegistry};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    /// `#427`: the scripts directory came *first* on `PATH`, and `write_file` is `Allow`, so a
    /// model-written script named `git` ran in place of the real one under every later `shell` call
    /// — including a call the person approved by name. It comes last now: a real command wins, and
    /// a script fills only a name nothing else has.
    #[test]
    fn the_scripts_directory_is_last_on_path() {
        let dir = Path::new("/tmp/eclipse-path-order/scripts");
        let path = path_with(dir).expect("PATH is set in the test environment");
        let entries: Vec<PathBuf> = std::env::split_paths(&path).collect();
        assert_eq!(entries.last(), Some(&dir.to_path_buf()), "{entries:?}");
        assert!(
            entries.len() > 2,
            "the inherited PATH and this binary's directory are still there: {entries:?}"
        );
        assert!(
            !entries.contains(&PathBuf::from("/usr/bin")) || entries[0] != dir,
            "the scripts directory is not first"
        );
    }

    fn write_script(dir: &Path, name: &str, body: &str, mode: u32) -> PathBuf {
        std::fs::create_dir_all(dir).unwrap();
        let path = dir.join(name);
        std::fs::write(&path, body).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
        }
        let _ = mode;
        path
    }

    #[cfg(unix)]
    fn process_alive(pid: i32) -> bool {
        // SAFETY: signal 0 only probes for existence.
        let exists = unsafe { libc::kill(pid, 0) } == 0;
        // A zombie nobody has reaped yet is already dead.
        let zombie = std::fs::read_to_string(format!("/proc/{pid}/stat"))
            .map(|s| {
                s.rsplit(')')
                    .next()
                    .unwrap_or("")
                    .trim_start()
                    .starts_with('Z')
            })
            .unwrap_or(false);
        exists && !zombie
    }

    fn tool(dir: &Path) -> ScriptTool {
        ScriptTool::new(dir.to_path_buf(), Duration::from_secs(10), 4096)
    }

    async fn call(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
        tool.call(args).await
    }

    /// A script written a moment ago can be exec'd too early: another thread's `fork` inherits this
    /// thread's open-for-write fd and the exec comes back `ETXTBSY`, "Text file busy". Two
    /// `./verify.sh` runs back to back caught it once, and it passes alone — it is the test
    /// binary's threads racing, not the tool. Retried, because it says nothing about the tool and
    /// a flake in the gate costs a re-run of a four-minute job.
    async fn call_retrying(tool: &ScriptTool, args: Value) -> Result<String, ToolError> {
        let mut last = None;
        for attempt in 0..5 {
            match call(tool, args.clone()).await {
                Ok(out) if !out.contains("Text file busy") => return Ok(out),
                Ok(out) => last = Some(Ok(out)),
                Err(e) if !e.to_string().contains("Text file busy") => return Err(e),
                Err(e) => last = Some(Err(e)),
            }
            tokio::time::sleep(std::time::Duration::from_millis(10 * (attempt + 1))).await;
        }
        last.unwrap()
    }

    fn refused(result: Result<String, ToolError>) -> String {
        match result {
            Err(e) => e.to_string(),
            Ok(out) => panic!("expected a refusal, got: {out}"),
        }
    }

    #[test]
    fn a_description_is_the_first_comment_line_after_a_shebang() {
        assert_eq!(
            first_comment("#!/bin/sh\n# Back up the media\nset -e\n").as_deref(),
            Some("Back up the media")
        );
        assert_eq!(
            first_comment("## Title  \n").as_deref(),
            Some("Title"),
            "no shebang, several hashes, trailing spaces"
        );
        assert_eq!(
            first_comment("#!/bin/sh\n\nset -e\n# later one\n").as_deref(),
            Some("later one"),
            "the first line that starts with a hash, wherever it is"
        );
        assert_eq!(
            first_comment("#!/bin/sh\n#\n#####\n# real\n").as_deref(),
            Some("real"),
            "an empty comment is a separator, not a description"
        );
        assert_eq!(first_comment("#!/bin/sh\necho hi\n"), None);
        assert_eq!(first_comment(""), None);
        assert_eq!(
            first_comment("#!/bin/sh\r\n# crlf\r\n").as_deref(),
            Some("crlf")
        );
    }

    #[test]
    fn a_long_description_is_cut_and_says_so() {
        let text = format!("# {}\n", "x".repeat(500));
        let d = first_comment(&text).unwrap();
        assert!(d.ends_with("..."));
        assert_eq!(d.chars().count(), MAX_DESCRIPTION_CHARS + 3);
    }

    #[test]
    fn a_missing_directory_lists_as_nothing_rather_than_an_error() {
        let tmp = tempfile::tempdir().unwrap();
        let listing = list_scripts(&tmp.path().join("scripts")).unwrap();
        assert!(!listing.exists && listing.scripts.is_empty());
    }

    #[tokio::test]
    async fn the_list_is_sorted_and_carries_each_scripts_description() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "zeta.sh", "#!/bin/sh\n# Last one\n", 0o755);
        write_script(tmp.path(), "alpha.sh", "#!/bin/sh\n# First one\n", 0o755);
        write_script(tmp.path(), "bare", "echo no comment\n", 0o755);
        write_script(tmp.path(), ".hidden", "# secret\n", 0o755);
        std::fs::create_dir(tmp.path().join("subdir")).unwrap();

        let out = call(&tool(tmp.path()), json!({"list": true}))
            .await
            .unwrap();
        let lines: Vec<&str> = out.lines().skip(1).collect();
        assert_eq!(
            lines,
            ["alpha.sh: First one", "bare", "zeta.sh: Last one"],
            "{out}"
        );
        assert!(out.starts_with(&format!("scripts directory: {}", tmp.path().display())));
    }

    #[tokio::test]
    async fn listing_an_empty_or_missing_directory_says_there_are_none() {
        let tmp = tempfile::tempdir().unwrap();
        let missing = tmp.path().join("scripts");
        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
        assert!(
            out.contains("no scripts") && out.contains("does not exist yet"),
            "{out}"
        );
        std::fs::create_dir(&missing).unwrap();
        let out = call(&tool(&missing), json!({"list": true})).await.unwrap();
        assert!(
            out.contains("no scripts") && !out.contains("does not exist"),
            "{out}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_file_that_is_not_executable_is_listed_and_flagged() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "later.sh", "# not yet\n", 0o644);
        let out = call(&tool(tmp.path()), json!({"list": true}))
            .await
            .unwrap();
        assert!(
            out.contains("later.sh (not executable: needs chmod +x): not yet"),
            "{out}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_listing_never_reads_through_a_symlink_that_leaves_the_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        write_script(outside.path(), "secret", "# TOP-SECRET-LINE\n", 0o755);
        let dir = tmp.path().join("scripts");
        std::fs::create_dir(&dir).unwrap();
        std::os::unix::fs::symlink(outside.path().join("secret"), dir.join("peek")).unwrap();
        let out = call(&tool(&dir), json!({"list": true})).await.unwrap();
        assert!(out.contains("peek (not runnable"), "{out}");
        assert!(!out.contains("TOP-SECRET-LINE"), "{out}");
    }

    #[tokio::test]
    async fn only_the_head_of_a_script_is_read_for_its_description() {
        let tmp = tempfile::tempdir().unwrap();
        let body = format!(
            "#!/bin/sh\n{}\n# too late\n",
            "x".repeat(HEAD_BYTES as usize * 4)
        );
        write_script(tmp.path(), "big.sh", &body, 0o755);
        let listing = list_scripts(tmp.path()).unwrap();
        assert_eq!(listing.scripts[0].description, None);
    }

    #[tokio::test]
    async fn a_listing_stops_describing_after_a_ceiling_and_says_how_many_it_left_out() {
        let tmp = tempfile::tempdir().unwrap();
        for i in 0..MAX_LISTED + 5 {
            write_script(tmp.path(), &format!("s{i:04}"), "# x\n", 0o755);
        }
        let out = call(&tool(tmp.path()), json!({"list": true}))
            .await
            .unwrap();
        assert!(
            out.contains("[5 more not listed]"),
            "{}",
            &out[out.len() - 60..]
        );
    }

    #[tokio::test]
    async fn list_combined_with_a_name_or_arguments_is_refused_rather_than_guessed() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tool(tmp.path());
        for args in [
            json!({"list": true, "name": "x"}),
            json!({"list": true, "args": []}),
            json!({"list": true, "name": ""}),
        ] {
            let e = call(&t, args).await.unwrap_err();
            assert!(
                matches!(e, ToolError::InvalidArgs(ref m) if m.contains("cannot be combined")),
                "{e}"
            );
        }
        // `list: false` is the same as no `list`.
        let e = refused(call(&t, json!({"list": false})).await);
        assert!(e.contains("give `name`"), "{e}");
        let e = refused(call(&t, json!({})).await);
        assert!(e.contains("give `name`"), "{e}");
    }

    #[tokio::test]
    async fn a_present_argument_of_the_wrong_type_is_invalid_not_defaulted() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tool(tmp.path());
        for (args, field) in [
            (json!({"list": "yes"}), "`list`"),
            (json!({"list": 1}), "`list`"),
            (json!({"name": 5}), "`name`"),
            (json!({"name": ["a"]}), "`name`"),
            (json!({"name": "a", "args": "--x"}), "`args`"),
            (json!({"name": "a", "args": ["ok", 3]}), "`args[1]`"),
            (json!({"name": "a", "args": [null]}), "`args[0]`"),
        ] {
            let e = call(&t, args.clone()).await.unwrap_err();
            assert!(
                matches!(&e, ToolError::InvalidArgs(m) if m.contains(field)),
                "{args}: {e}"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_script_runs_with_its_arguments_from_the_scripts_directory() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(
            tmp.path(),
            "show.sh",
            "#!/bin/sh\necho \"args: $1|$2\"\necho \"cwd: $(pwd)\"\necho \"dir: $ECLIPSE_SCRIPTS_DIR\"\necho oops >&2\nexit 3\n",
            0o755,
        );
        let out = call(
            &tool(tmp.path()),
            json!({"name": "show.sh", "args": ["--dry-run", "two words"]}),
        )
        .await
        .unwrap();
        let canon = std::fs::canonicalize(tmp.path()).unwrap();
        assert!(out.starts_with("exit code: 3\n"), "{out}");
        assert!(out.contains("args: --dry-run|two words"), "{out}");
        assert!(out.contains(&format!("cwd: {}", canon.display())), "{out}");
        assert!(
            out.contains(&format!("dir: {}", tmp.path().display())),
            "{out}"
        );
        assert!(out.contains("stderr:\noops"), "{out}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_read_only_promise_without_bubblewrap_refuses_a_script_too() {
        // `shell_isolate = "fs"` promises a read-only machine, and `shell` refuses to run when
        // bubblewrap is missing. `script` is the same act with the words already written down, so
        // it has to give the same answer rather than run the file uncontained (#550).
        let tmp = tempfile::tempdir().unwrap();
        let marker = tmp.path().join("ran");
        write_script(
            tmp.path(),
            "touch-marker.sh",
            &format!("#!/bin/sh\ntouch {}\n", marker.display()),
            0o755,
        );
        let tool = tool(tmp.path()).with_sandbox(crate::sandbox::Sandbox::without_bwrap(
            crate::config::ShellIsolate::Fs,
        ));
        let e = call(&tool, json!({"name": "touch-marker.sh"}))
            .await
            .unwrap_err()
            .to_string();
        assert!(e.contains("which is not on PATH"), "{e}");
        assert!(!marker.exists(), "the script must not have run");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_script_has_no_stdin_and_sees_its_directory_first_on_path() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "helper", "#!/bin/sh\necho from-helper\n", 0o755);
        write_script(
            tmp.path(),
            "main.sh",
            "#!/bin/sh\ncat | wc -c\nhelper\n",
            0o755,
        );
        let out = call_retrying(&tool(tmp.path()), json!({"name": "main.sh"}))
            .await
            .unwrap();
        assert!(out.contains("exit code: 0"), "{out}");
        assert!(
            out.contains("\n0\n"),
            "stdin reads end-of-file at once: {out}"
        );
        assert!(out.contains("from-helper"), "{out}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_name_that_is_not_a_plain_file_name_in_the_directory_is_refused_with_a_reason() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("scripts");
        write_script(&dir, "ok.sh", "#!/bin/sh\necho ok\n", 0o755);
        write_script(&dir, "plain.txt", "echo no\n", 0o644);
        write_script(tmp.path(), "outside.sh", "echo out\n", 0o755);
        std::fs::create_dir(dir.join("adir")).unwrap();
        let t = tool(&dir);

        let absolute = tmp.path().join("outside.sh").display().to_string();
        for (name, why) in [
            ("", "empty"),
            ("   ", "empty"),
            ("../outside.sh", "path separator"),
            ("sub/ok.sh", "path separator"),
            ("sub\\ok.sh", "path separator"),
            ("..", "`..`"),
            ("a..b", "`..`"),
            (absolute.as_str(), "absolute path"),
            ("/etc/passwd", "absolute path"),
            ("missing.sh", "no such file"),
            ("adir", "not a regular file"),
            ("plain.txt", "chmod +x"),
        ] {
            let e = refused(call(&t, json!({"name": name})).await);
            assert!(
                e.contains(&format!("script {name:?} refused")),
                "{name:?}: {e}"
            );
            assert!(e.contains(why), "{name:?} should say {why:?}: {e}");
        }
        // The same tool still runs the good one.
        assert!(call(&t, json!({"name": "ok.sh"}))
            .await
            .unwrap()
            .contains("ok"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_symlink_out_of_the_directory_is_refused_and_one_inside_is_not() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("scripts");
        let target = write_script(
            tmp.path(),
            "elsewhere.sh",
            "#!/bin/sh\necho escaped\n",
            0o755,
        );
        std::fs::create_dir_all(&dir).unwrap();
        std::os::unix::fs::symlink(&target, dir.join("out")).unwrap();
        write_script(&dir, "real.sh", "#!/bin/sh\necho real\n", 0o755);
        std::os::unix::fs::symlink(dir.join("real.sh"), dir.join("alias")).unwrap();
        std::os::unix::fs::symlink(dir.join("nowhere"), dir.join("dangling")).unwrap();
        let t = tool(&dir);

        let e = refused(call(&t, json!({"name": "out"})).await);
        assert!(e.contains("outside the scripts directory"), "{e}");
        let ok = call(&t, json!({"name": "alias"})).await.unwrap();
        assert!(ok.contains("real"), "{ok}");
        let e = refused(call(&t, json!({"name": "dangling"})).await);
        assert!(e.contains("no such file"), "{e}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_script_with_no_shebang_says_what_to_add_instead_of_a_bare_os_error() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "bare.sh", "echo hi\n", 0o755);
        let e = refused(call(&tool(tmp.path()), json!({"name": "bare.sh"})).await);
        assert!(e.contains("no `#!` line") && e.contains("#!/bin/sh"), "{e}");
    }

    #[tokio::test]
    async fn a_directory_that_does_not_exist_refuses_a_name_and_says_so() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tool(&tmp.path().join("scripts"));
        let e = refused(call(&t, json!({"name": "x.sh"})).await);
        assert!(e.contains("does not exist yet"), "{e}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_script_that_overruns_the_timeout_is_killed_with_the_child_it_started() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(
            tmp.path(),
            "hang.sh",
            "#!/bin/sh\nsleep 300 &\necho $! > child.pid\nwait\n",
            0o755,
        );
        let mut t = tool(tmp.path());
        t.timeout = Duration::from_secs(1);
        t.kill_grace = Duration::from_millis(300);
        let started = std::time::Instant::now();
        let e = refused(call(&t, json!({"name": "hang.sh"})).await);
        assert!(e.contains("timed out after 1s"), "{e}");
        assert!(started.elapsed() < Duration::from_secs(8));
        let pid: i32 = std::fs::read_to_string(tmp.path().join("child.pid"))
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        for _ in 0..100 {
            if !process_alive(pid) {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        let alive = process_alive(pid);
        assert!(!alive, "child {pid} survived the timeout");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn a_script_that_floods_its_output_is_cut_at_the_cap() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "flood.sh", "#!/bin/sh\nyes\n", 0o755);
        let t = ScriptTool::new(tmp.path().to_path_buf(), Duration::from_secs(10), 256);
        let out = call(&t, json!({"name": "flood.sh"})).await.unwrap();
        assert!(out.contains("[truncated]"), "{out}");
        assert!(out.len() < 400, "{}", out.len());
    }

    #[test]
    fn an_approval_prompt_names_the_script_and_its_arguments() {
        let tmp = tempfile::tempdir().unwrap();
        let t = tool(tmp.path());
        let with = t.describe_call(&json!({"name": "backup-media", "args": ["--dry-run"]}));
        assert!(
            with.contains("backup-media") && with.contains("--dry-run"),
            "{with}"
        );
        assert!(with.contains(&tmp.path().display().to_string()), "{with}");
        let without = t.describe_call(&json!({"name": "backup-media"}));
        assert!(
            without.contains("backup-media") && !without.contains("arguments"),
            "{without}"
        );
        assert_eq!(t.describe_call(&json!({"list": true})), "list the scripts");
        // A hostile or mangled call still produces a readable line.
        let odd = t.describe_call(&json!({"name": "a\nb", "args": 5}));
        assert!(!odd.contains('\n'), "{odd}");
    }

    struct Counting(AtomicUsize);

    #[async_trait]
    impl Approver for Counting {
        async fn decide(&self, _: &crate::approvals::Pending) -> crate::approvals::Decision {
            self.0.fetch_add(1, Ordering::SeqCst);
            crate::approvals::Decision::Deny("no".to_string())
        }
    }

    #[tokio::test]
    async fn under_ask_a_listing_is_answered_without_a_prompt_and_a_run_is_not() {
        let tmp = tempfile::tempdir().unwrap();
        write_script(tmp.path(), "a.sh", "# a\n", 0o755);
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(tool(tmp.path())), Policy::Ask);
        let approver = Counting(AtomicUsize::new(0));

        let out = registry
            .dispatch("script", r#"{"list":true}"#, &approver)
            .await;
        assert!(
            !out.is_error && out.output.contains("a.sh: a"),
            "{}",
            out.output
        );
        assert_eq!(
            approver.0.load(Ordering::SeqCst),
            0,
            "a listing is not asked about"
        );

        for call in [
            r#"{"name":"a.sh"}"#,
            r#"{"list":true,"name":"a.sh"}"#,
            r#"{"list":"yes","name":"a.sh"}"#,
            r#"{}"#,
        ] {
            let out = registry.dispatch("script", call, &approver).await;
            assert!(
                out.is_error && out.output.contains("declined"),
                "{call}: {}",
                out.output
            );
        }
        assert_eq!(approver.0.load(Ordering::SeqCst), 4);

        // `deny` still means never, listing included.
        let mut registry = ToolRegistry::new(4096);
        registry.register(Arc::new(tool(tmp.path())), Policy::Deny);
        let out = registry
            .dispatch("script", r#"{"list":true}"#, &AllowAll)
            .await;
        assert!(out.is_error && out.output.contains("disabled by policy"));
    }

    #[test]
    fn the_description_names_the_scripts_there_were_and_points_at_list_for_the_rest() {
        let tmp = tempfile::tempdir().unwrap();
        let empty = tool(tmp.path());
        assert!(empty.description().contains("no scripts yet"));
        assert!(empty
            .description()
            .contains(&tmp.path().display().to_string()));

        for i in 0..MAX_NAMED_IN_DESCRIPTION + 3 {
            write_script(tmp.path(), &format!("s{i:02}.sh"), "# x\n", 0o755);
        }
        let full = tool(tmp.path());
        let d = full.description();
        assert!(d.contains("s00.sh") && d.contains("and 3 more"), "{d}");
        assert!(
            !d.contains(&format!("s{:02}.sh", MAX_NAMED_IN_DESCRIPTION)),
            "{d}"
        );
        assert!(d.contains("`list`"), "{d}");
    }

    #[test]
    fn the_tool_registers_with_a_schema_that_needs_no_arguments_to_be_present() {
        let tmp = tempfile::tempdir().unwrap();
        let cfg = ToolsConfig::default();
        let registry = ToolRegistry::from_config_full(
            &cfg,
            tmp.path().to_path_buf(),
            Vec::new(),
            Some(tmp.path().join("scripts")),
        );
        let d = registry
            .descriptors()
            .into_iter()
            .find(|d| d.name == "script")
            .expect("script is registered");
        assert_eq!(d.policy, Policy::Ask);
        assert_eq!(
            d.parameters["properties"]["args"]["items"]["type"],
            "string"
        );
        assert!(d.parameters.get("required").is_none());
    }
}