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
//! The skill tools: `skill_view`, which loads a skill (or a file it links) into the conversation;
//! `skill_search`, which finds one the index had no room to name (`#350`); and `skill_manage`,
//! which lets the agent write one.
//!
//! They are separate because their risk is: reading a skill the agent was told about in its own
//! prompt is `allow`, while writing into the user's skills directory is `ask` — unlike
//! `MEMORY.md`, a skill is the user's procedure, and one that changes under them is worth a
//! prompt. Both discover skills on every call, so a skill created a moment ago is visible
//! without a restart (the prompt index, built once per agent, is the only thing that waits).
//!
//! Every path an argument names is resolved with [`skills::resolve_inside`]: a skill can only
//! ever read or write inside its own directory, and a refusal says which skill and why.

use crate::skills::{self, Found, Root, Source, SKILL_FILE, SUPPORT_DIRS};
use crate::tools::{replace_file, str_arg, Tool, ToolError};
use crate::tools_patch as patch_tool;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::io::Write;
use std::path::PathBuf;

/// The largest body or supporting file `skill_manage` will write. A skill is a procedure, not a
/// data store; a model that wants to write more than this is usually looping.
const MAX_WRITE_BYTES: usize = 256 * 1024;

/// The longest skill name. Names become directory names.
const MAX_NAME_CHARS: usize = 64;

fn failed(message: String) -> ToolError {
    ToolError::Failed(message)
}

fn invalid(message: String) -> ToolError {
    ToolError::InvalidArgs(message)
}

/// The names that exist, for an error that helps the model correct itself.
fn available(report: &skills::Report) -> String {
    let mut names: Vec<&str> = report.active().map(|(f, _)| f.name.as_str()).collect();
    names.sort_unstable();
    if names.is_empty() {
        "none".into()
    } else {
        names.join(", ")
    }
}

/// `skill_view`: read a skill's body, or one file it links.
pub struct SkillViewTool {
    roots: Vec<Root>,
    /// `[bots.<name>].skills` (`#509`): the names this run may see. `None` is every root, which is
    /// the human's agent; a set list is exactly those names.
    only: Option<Vec<String>>,
}

impl SkillViewTool {
    pub fn new(roots: Vec<Root>) -> Self {
        Self { roots, only: None }
    }

    /// Narrow this tool to the skills `only` names, or widen it back with `None`.
    pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
        self.only = only;
        self
    }
}

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

    fn description(&self) -> &str {
        "Load a saved skill by name: its instructions, and the list of files it links. Pass \
`path` (for example `references/api.md`) to read one of those files instead. A skill's scripts \
are run with the `shell` tool, with `cwd` set to the skill's directory."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "The skill's name, as listed in the skills index"
                },
                "path": {
                    "type": "string",
                    "description": "A file the skill links, relative to its directory: references/…, scripts/… or templates/…. Omit to read the skill itself."
                }
            },
            "required": ["name"]
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        let name = args["name"].as_str().unwrap_or("?");
        match args["path"].as_str() {
            Some(path) => format!("skill_view {name} {path}"),
            None => format!("skill_view {name}"),
        }
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let name = str_arg(&args, "name")?;
        let report = skills::discover_only(&self.roots, self.only.as_deref());
        let found = report.get(name).ok_or_else(|| {
            failed(format!(
                "no skill named {name:?}. Available: {}",
                available(&report)
            ))
        })?;
        if let Some(reason) = found.broken_reason() {
            return Err(failed(format!(
                "skill {name:?} is broken and cannot be loaded: {reason} ({})",
                found.path.display()
            )));
        }
        match args.get("path").filter(|v| !v.is_null()) {
            None => Ok(render_skill(found)),
            Some(Value::String(path)) => read_linked(found, path),
            Some(_) => Err(invalid("`path` must be a string".into())),
        }
    }
}

fn render_skill(found: &Found) -> String {
    let body = found.skill().map(|s| s.body.as_str()).unwrap_or_default();
    let mut out = format!(
        "# skill: {} ({}, {})\n\n{body}\n",
        found.name,
        found.source.label(),
        found.dir.display()
    );
    let linked = skills::linked_files(&found.dir);
    if !linked.is_empty() {
        out.push_str("\nLinked files (read one with `skill_view` and `path`):\n");
        for file in &linked {
            out.push_str(&format!("- {file}\n"));
        }
    }
    out
}

fn read_linked(found: &Found, path: &str) -> Result<String, ToolError> {
    let refuse = |why: String| failed(format!("skill {:?}: refused {path:?}: {why}", found.name));
    let resolved = skills::resolve_inside(&found.dir, path).map_err(refuse)?;
    let meta = std::fs::metadata(&resolved).map_err(|e| {
        let linked = skills::linked_files(&found.dir);
        let hint = if linked.is_empty() {
            "this skill links no files".to_string()
        } else {
            format!("it links: {}", linked.join(", "))
        };
        refuse(format!("cannot read it ({e}); {hint}"))
    })?;
    if !meta.is_file() {
        return Err(refuse("it is not a regular file".into()));
    }
    if meta.len() > skills::MAX_SKILL_FILE_BYTES {
        return Err(refuse(format!(
            "it is {} bytes and the limit for a file a skill loads is {}",
            meta.len(),
            skills::MAX_SKILL_FILE_BYTES
        )));
    }
    let bytes = std::fs::read(&resolved).map_err(|e| refuse(format!("cannot read it: {e}")))?;
    let text = String::from_utf8(bytes).map_err(|_| refuse("it is not UTF-8 text".into()))?;
    Ok(format!("# skill: {} — {path}\n\n{text}", found.name))
}

/// `skill_search`: the fourth verb, for the skills the index could not fit (`#350`).
///
/// Deliberately not a router. A matcher that runs before every turn costs a model round trip per
/// turn and buys back fewer tokens than it spends; this costs nothing until the model asks, and
/// the index tells it when asking is worth it. Same shape as `tool_search`: never touches a skill,
/// `allow` policy, and a miss says how many it looked at rather than "nothing found".
pub const SKILL_SEARCH: &str = "skill_search";

/// How many matches one search returns by default, and at most.
const SEARCH_DEFAULT_LIMIT: usize = 8;
const SEARCH_MAX_LIMIT: usize = 20;

pub struct SkillSearchTool {
    roots: Vec<Root>,
    /// See [`SkillViewTool::only`].
    only: Option<Vec<String>>,
}

impl SkillSearchTool {
    pub fn new(roots: Vec<Root>) -> Self {
        Self { roots, only: None }
    }

    pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
        self.only = only;
        self
    }

    /// Skills matching `query`, best first: the name contains the whole query, then every word in
    /// the name, then every word in the name-or-description, then a tag, then some of the words
    /// ranked by how many matched. Ties break on name, which is stable and therefore reviewable.
    fn ranked<'a>(
        &self,
        active: &'a [(&'a Found, &'a skills::Skill)],
        query: &str,
    ) -> Vec<&'a Found> {
        let query = query.trim().to_lowercase();
        let words: Vec<&str> = query.split_whitespace().collect();
        let mut scored: Vec<(u8, std::cmp::Reverse<usize>, &Found)> = Vec::new();
        for (found, skill) in active {
            let name = found.name.to_lowercase();
            let description = skill.meta.description.to_lowercase();
            let tags = skill.meta.tags.join(" ").to_lowercase();
            let text = format!("{name} {description} {tags}");
            if words.is_empty() {
                scored.push((5, std::cmp::Reverse(0), found));
                continue;
            }
            let in_name = words.iter().filter(|w| name.contains(**w)).count();
            let in_text = words.iter().filter(|w| text.contains(**w)).count();
            let in_tags = words.iter().filter(|w| tags.contains(**w)).count();
            let tier = if name.contains(&query) {
                0
            } else if in_name == words.len() {
                1
            } else if in_text == words.len() {
                2
            } else if in_tags > 0 {
                3
            } else if in_text > 0 {
                4
            } else {
                continue;
            };
            scored.push((tier, std::cmp::Reverse(in_name + in_text), found));
        }
        scored.sort_by(|a, b| {
            a.0.cmp(&b.0)
                .then(a.1.cmp(&b.1))
                .then(a.2.name.cmp(&b.2.name))
        });
        scored.into_iter().map(|(_, _, found)| found).collect()
    }
}

#[async_trait]
impl Tool for SkillSearchTool {
    fn name(&self) -> &str {
        SKILL_SEARCH
    }

    fn description(&self) -> &str {
        "Find a skill the index did not have room to list: keyword search over every skill's \
name, description and tags. Use it when the index says skills were left out, then call \
`skill_view` on the one that fits. A skill already named in the index needs neither."
    }

    fn parameters(&self) -> Value {
        json!({"type":"object","properties":{
            "query":{"type":"string","description":"Words from the task: a subject, a tool name, a format. Empty lists every skill that loaded."},
            "limit":{"type":"integer","description":format!("How many to return at most. Default {SEARCH_DEFAULT_LIMIT}, maximum {SEARCH_MAX_LIMIT}.")}
        },"required":[]})
    }

    fn describe_call(&self, args: &Value) -> String {
        format!(
            "skill_search {:?}",
            args["query"].as_str().unwrap_or("(everything)")
        )
    }

    fn needs_approval(&self, _args: &Value) -> bool {
        false
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        let query = args["query"].as_str().unwrap_or("").to_string();
        let limit = args["limit"]
            .as_u64()
            .map(|n| (n as usize).clamp(1, SEARCH_MAX_LIMIT))
            .unwrap_or(SEARCH_DEFAULT_LIMIT);

        // Fresh on every call, like `skill_view`: a skill created a moment ago is findable, and
        // the index in the prompt (built once per agent) is the only thing that waits.
        let report = skills::discover_only(&self.roots, self.only.as_deref());
        let active: Vec<(&Found, &skills::Skill)> = report.active().collect();
        if active.is_empty() {
            return Ok(format!(
                "No skills loaded from {} root(s), so there is nothing to find.",
                self.roots.len()
            ));
        }
        let found = self.ranked(&active, &query);
        if found.is_empty() {
            // A miss says how much was looked at: "nothing found" alone reads like an empty box.
            return Ok(format!(
                "Nothing matched {query:?} among {} skill(s) that loaded. Try fewer words, or \
                 the name of the tool or format the task uses.",
                active.len()
            ));
        }
        let mut out = format!("{} of {} skill(s) matched", found.len(), active.len());
        if found.len() > limit {
            out.push_str(&format!(" ({limit} shown)"));
        }
        out.push(':');
        for found in found.iter().take(limit) {
            let skill = found.skill().expect("active() yields loaded skills only");
            out.push('\n');
            out.push_str(&skills::entry_line(&skill.meta));
        }
        out.push_str("\n\n`skill_view` loads one by name.");
        Ok(out)
    }
}

/// `skill_manage`: create a skill, patch one, or write a file under its `references/`,
/// `scripts/` or `templates/`.
pub struct SkillManageTool {
    roots: Vec<Root>,
    /// See [`SkillViewTool::only`]. A skill this tool creates is not in the list, so it is written
    /// to disk and stays out of the bot's index until its declaration names it — the point of a
    /// list is that the run cannot grow its own reach.
    only: Option<Vec<String>>,
}

impl SkillManageTool {
    pub fn new(roots: Vec<Root>) -> Self {
        Self { roots, only: None }
    }

    pub fn with_only(mut self, only: Option<Vec<String>>) -> Self {
        self.only = only;
        self
    }

    fn create(&self, args: &Value) -> Result<String, ToolError> {
        let name = str_arg(args, "name")?;
        let description = str_arg(args, "description")?;
        let body = str_arg(args, "body")?;
        validate_name(name)?;
        if description.trim().is_empty() || description.contains(['\n', '\r']) {
            return Err(invalid(
                "`description` must be one non-empty line: it is what the skills index shows"
                    .into(),
            ));
        }
        if body.len() > MAX_WRITE_BYTES {
            return Err(invalid(format!(
                "`body` is {} bytes; the limit is {MAX_WRITE_BYTES}",
                body.len()
            )));
        }
        let root = skills::user_root(&self.roots).ok_or_else(|| {
            failed("cannot create a skill: there is no user skills directory (is HOME set?)".into())
        })?;

        let report = skills::discover_only(&self.roots, self.only.as_deref());
        if let Some(existing) = report.found.iter().find(|f| f.name == name) {
            return Err(failed(format!(
                "a skill named {name:?} already exists at {} ({}); `create` never overwrites. \
Use `patch` to change it, or choose another name",
                existing.path.display(),
                existing.source.label()
            )));
        }

        let text = format!(
            "---\nname: {name}\ndescription: \"{}\"\n---\n\n{}\n",
            description.replace('\\', "\\\\").replace('"', "\\\""),
            body.trim()
        );
        // The text we are about to write has to load as the skill the caller described.
        match skills::parse(&text) {
            Ok(skill)
                if skill.meta.name == name && skill.meta.description == description.trim() => {}
            Ok(_) => {
                return Err(invalid(
                    "the description did not survive being written as frontmatter; simplify it"
                        .into(),
                ))
            }
            Err(reason) => return Err(invalid(format!("this would be a broken skill: {reason}"))),
        }

        let dir = root.dir.join(name);
        std::fs::create_dir_all(&root.dir)
            .map_err(|e| failed(format!("cannot create {}: {e}", root.dir.display())))?;
        // `create_dir` fails when the directory exists, which makes the check above atomic: two
        // creates of one name cannot both succeed.
        std::fs::create_dir(&dir).map_err(|e| {
            failed(format!(
                "cannot create {}: {e} (a directory of that name may already exist)",
                dir.display()
            ))
        })?;
        let path = dir.join(SKILL_FILE);
        let written = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .and_then(|mut f| f.write_all(text.as_bytes()));
        if let Err(e) = written {
            let _ = std::fs::remove_dir(&dir);
            return Err(failed(format!("cannot write {}: {e}", path.display())));
        }
        Ok(format!(
            "created skill {name:?} ({}) at {}\nIt is loadable now with `skill_view`; the skills index in the prompt picks it up next session.",
            root.source.label(),
            path.display()
        ))
    }

    fn patch(&self, args: &Value) -> Result<String, ToolError> {
        let name = str_arg(args, "name")?;
        let old = str_arg(args, "old")?;
        // An argument that is present but of the wrong type is an error: reading it as "absent"
        // would turn a malformed `new` into a silent deletion.
        let new = match args.get("new").filter(|v| !v.is_null()) {
            None => "",
            Some(Value::String(new)) => new.as_str(),
            Some(_) => {
                return Err(invalid(
                    "`new` must be a string; omit it to delete `old`".into(),
                ))
            }
        };
        let rel = match args.get("path").filter(|v| !v.is_null()) {
            None => SKILL_FILE,
            Some(Value::String(rel)) => rel.as_str(),
            Some(_) => return Err(invalid("`path` must be a string".into())),
        };
        if old.is_empty() {
            return Err(invalid("`old` must not be empty".into()));
        }
        let (found, target) = self.writable(name, rel)?;
        let current = std::fs::read(&target)
            .map_err(|e| failed(format!("cannot read {}: {e}", target.display())))?;
        let current = String::from_utf8(current)
            .map_err(|_| failed(format!("{} is not UTF-8 text", target.display())))?;
        // The same matcher `patch` uses, so the two cannot forgive different things: exact
        // first, then indentation-blind, and never a second place.
        let locations = patch_tool::hits(&current, old);
        match locations.len() {
            1 => {}
            0 => {
                return Err(failed(format!(
                    "`old` does not occur in {} (skill {name:?}); view it with `skill_view` and copy the text exactly",
                    target.display()
                )))
            }
            n => {
                return Err(failed(format!(
                    "`old` occurs {n} times in {} (skill {name:?}); include more surrounding text so it matches once",
                    target.display()
                )))
            }
        }
        let updated = patch_tool::splice(&current, &locations, new);
        if rel == SKILL_FILE {
            match skills::parse(&updated) {
                Err(reason) if found.skill().is_some() => {
                    return Err(failed(format!(
                    "refused: this patch would break skill {name:?}: {reason}. Nothing was written"
                )))
                }
                Ok(skill) if skill.meta.name != found.name => {
                    return Err(failed(format!(
                    "refused: this patch would rename skill {name:?} to {:?}. Nothing was written",
                    skill.meta.name
                )))
                }
                _ => {}
            }
        }
        replace_file(&target, &updated)?;
        Ok(format!(
            "patched {rel} of skill {name:?}: wrote {}",
            target.display()
        ))
    }

    fn write_file(&self, args: &Value) -> Result<String, ToolError> {
        let name = str_arg(args, "name")?;
        let rel = str_arg(args, "path")?;
        let content = str_arg(args, "content")?;
        if content.len() > MAX_WRITE_BYTES {
            return Err(invalid(format!(
                "`content` is {} bytes; the limit is {MAX_WRITE_BYTES}",
                content.len()
            )));
        }
        let (found, target) = self.writable(name, rel)?;
        if rel == SKILL_FILE {
            return Err(invalid(
                "use `patch` to change SKILL.md; `write_file` is for references/, scripts/ and templates/".into(),
            ));
        }
        let existed = match std::fs::symlink_metadata(&target) {
            Ok(meta) if meta.file_type().is_symlink() => {
                return Err(failed(format!(
                    "skill {:?}: refused {rel:?}: it is a symlink, and a write through one could land outside the skill",
                    found.name
                )))
            }
            Ok(meta) if meta.is_dir() => {
                return Err(failed(format!(
                    "skill {:?}: refused {rel:?}: it is a directory",
                    found.name
                )))
            }
            Ok(_) => true,
            Err(_) => false,
        };
        if let Some(parent) = target.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| failed(format!("cannot create {}: {e}", parent.display())))?;
        }
        replace_file(&target, content)?;
        Ok(format!(
            "{} {rel} of skill {name:?} ({} bytes): wrote {}",
            if existed { "replaced" } else { "created" },
            content.len(),
            target.display()
        ))
    }

    /// The skill `name` and the file `rel` inside it, if both may be written: the skill must
    /// exist and not belong to a plugin, and the file must be `SKILL.md` or sit under one of
    /// the supporting directories.
    fn writable(&self, name: &str, rel: &str) -> Result<(Found, PathBuf), ToolError> {
        let report = skills::discover_only(&self.roots, self.only.as_deref());
        let found = report.get(name).ok_or_else(|| {
            failed(format!(
                "no skill named {name:?}. Available: {}. Use `create` to make one",
                available(&report)
            ))
        })?;
        if let Source::Plugin(plugin) = &found.source {
            return Err(failed(format!(
                "skill {name:?} belongs to plugin {plugin:?} ({}); a plugin's files are not edited from here",
                found.dir.display()
            )));
        }
        let refuse = |why: &str| failed(format!("skill {name:?}: refused {rel:?}: {why}"));
        let normalised = rel.replace('\\', "/");
        let mut parts = normalised.split('/').filter(|p| !p.is_empty() && *p != ".");
        let first = parts.next().unwrap_or("");
        let rest = parts.count();
        let allowed =
            (first == SKILL_FILE && rest == 0) || (SUPPORT_DIRS.contains(&first) && rest >= 1);
        if !allowed {
            return Err(refuse(
                "only SKILL.md and files under references/, scripts/ and templates/ can be written",
            ));
        }
        let target = skills::resolve_inside(&found.dir, rel).map_err(|why| refuse(&why))?;
        Ok((found.clone(), target))
    }
}

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

    fn description(&self) -> &str {
        "Save or improve a skill — a reusable procedure for a kind of task. `create` makes a new \
skill (name, description, body); it refuses a name that exists. `patch` replaces one exact \
occurrence of `old` with `new` in SKILL.md or in a supporting file. `write_file` writes a file \
under the skill's references/, scripts/ or templates/. Each reports the path it wrote."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["create", "patch", "write_file"],
                    "description": "create a new skill; patch text in an existing one; or write a supporting file"
                },
                "name": {
                    "type": "string",
                    "description": "The skill's name: letters, digits, `-` and `_`"
                },
                "description": {
                    "type": "string",
                    "description": "For create: one line saying what the skill is for and when to use it"
                },
                "body": {
                    "type": "string",
                    "description": "For create: the instructions, in Markdown"
                },
                "old": {
                    "type": "string",
                    "description": "For patch: the exact text to replace; it must occur once"
                },
                "new": {
                    "type": "string",
                    "description": "For patch: the replacement (omit to delete `old`)"
                },
                "path": {
                    "type": "string",
                    "description": "For patch: the file to change (default SKILL.md). For write_file: where to write, under references/, scripts/ or templates/"
                },
                "content": {
                    "type": "string",
                    "description": "For write_file: the file's whole content"
                }
            },
            "required": ["action", "name"]
        })
    }

    fn describe_call(&self, args: &Value) -> String {
        let action = args["action"].as_str().unwrap_or("?");
        let name = args["name"].as_str().unwrap_or("?");
        let short =
            |key: &str| -> String { args[key].as_str().unwrap_or("").chars().take(60).collect() };
        match action {
            "create" => {
                let at = skills::user_root(&self.roots)
                    .map(|r| r.dir.join(name).join(SKILL_FILE).display().to_string())
                    .unwrap_or_else(|| "?".into());
                let body = args["body"].as_str().unwrap_or("");
                format!(
                    "skill_manage create {name} at {at} ({:?}, {} chars of body, opens {:?})",
                    short("description"),
                    body.chars().count(),
                    opening(body, 80)
                )
            }
            "patch" => format!(
                "skill_manage patch {name} {}: {:?} -> {:?}",
                args["path"].as_str().unwrap_or(SKILL_FILE),
                short("old"),
                short("new")
            ),
            "write_file" => {
                let path = args["path"].as_str().unwrap_or("?");
                let content = args["content"].as_str().unwrap_or("");
                // A file under `scripts/` is a program `shell` will run later with no prompt, so
                // its opening line is the thing the person is actually approving (`#427`).
                let runs = if path.starts_with("scripts/") || path.ends_with(".sh") {
                    " — a script: `shell` can run it without asking again"
                } else {
                    ""
                };
                format!(
                    "skill_manage write_file {name} {path} ({} bytes, opens {:?}){runs}",
                    content.len(),
                    opening(content, 80)
                )
            }
            _ => format!("skill_manage {action} {name}"),
        }
    }

    async fn call(&self, args: Value) -> Result<String, ToolError> {
        match str_arg(&args, "action")? {
            "create" => self.create(&args),
            "patch" => self.patch(&args),
            "write_file" => self.write_file(&args),
            other => Err(invalid(format!(
                "unknown action {other:?}: use create, patch or write_file"
            ))),
        }
    }
}

/// The opening of some content, whitespace collapsed and clipped, for an approval summary.
///
/// A person approving a write is deciding what will exist on disk; a byte count is not that. Runs
/// of whitespace become one space so the first line of a script is not swallowed by indentation,
/// and the clip is by `char`, never by byte, so it cannot split one (`#427`).
fn opening(content: &str, max: usize) -> String {
    let collapsed = content.split_whitespace().collect::<Vec<_>>().join(" ");
    let mut clipped: String = collapsed.chars().take(max).collect();
    if collapsed.chars().count() > max {
        clipped.push('…');
    }
    clipped
}

fn validate_name(name: &str) -> Result<(), ToolError> {
    let ok = !name.is_empty()
        && name.chars().count() <= MAX_NAME_CHARS
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if ok {
        Ok(())
    } else {
        Err(invalid(format!(
            "{name:?} is not a usable skill name: use 1 to {MAX_NAME_CHARS} letters, digits, `-` or `_`"
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    fn root(dir: &Path) -> Vec<Root> {
        vec![Root {
            source: Source::Shared,
            dir: dir.join("skills"),
        }]
    }

    fn write(path: &Path, body: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).unwrap();
        }
        std::fs::write(path, body).unwrap();
    }

    fn backup(dir: &Path) {
        let skill = dir.join("skills/backup");
        write(
            &skill.join("SKILL.md"),
            "---\nname: backup\ndescription: back things up\n---\nRun the script.\n",
        );
        write(&skill.join("references/layout.md"), "the layout");
        write(&skill.join("scripts/backup.sh"), "echo hi");
    }

    fn err(result: Result<String, ToolError>) -> String {
        result.unwrap_err().to_string()
    }

    /// `#350`: the fourth verb. A skill the index could not name is still reachable by words from
    /// the task, and a miss says how much it looked at instead of "nothing found".
    #[tokio::test]
    async fn skill_search_finds_a_skill_the_index_could_not_name_and_says_what_it_scanned() {
        let tmp = tempfile::tempdir().unwrap();
        for (name, description) in [
            ("pipeline-step-01", "stage one of the media pipeline"),
            ("pipeline-step-31", "stage thirty-one of the media pipeline"),
            ("pipeline-step-40", "the last stage of the media pipeline"),
            ("ledger", "write a ledger entry"),
        ] {
            write(
                &tmp.path().join(format!("skills/{name}/SKILL.md")),
                &format!(
                    "---\nname: {name}\ndescription: {description}\ntags: [media]\n---\nBody.\n"
                ),
            );
        }
        let tool = SkillSearchTool::new(root(tmp.path()));

        // The whole point: the index has no room for step 31, and search finds it anyway.
        let (index, _) = skills::index(
            &skills::discover(&root(tmp.path())),
            // Room for the preamble and one entry, so `pipeline-step-31` is provably not listed.
            skills::PREAMBLE.chars().count() + 60,
        );
        let listed = index.map(|i| i.names).unwrap_or_default();
        assert!(
            !listed.iter().any(|n| n == "pipeline-step-31"),
            "{listed:?}"
        );

        let out = tool
            .call(json!({"query": "media pipeline stage thirty-one"}))
            .await
            .unwrap();
        assert!(out.contains("pipeline-step-31"), "{out}");
        assert!(out.contains("of 4 skill(s) matched"), "the count: {out}");

        // A tag is words too — the index does not carry tags, search does.
        let out = tool.call(json!({"query": "media"})).await.unwrap();
        assert_eq!(out.matches("pipeline-step").count(), 3, "{out}");

        // A name beats a description, and the limit is honoured.
        let out = tool.call(json!({"query": "ledger"})).await.unwrap();
        assert!(out.starts_with("1 of 4"), "{out}");

        // A miss names the corpus: "nothing found" alone reads like an empty box.
        let out = tool.call(json!({"query": "kubernetes"})).await.unwrap();
        assert!(out.contains("Nothing matched"), "{out}");
        assert!(out.contains("among 4 skill(s)"), "{out}");
    }

    #[tokio::test]
    async fn viewing_a_skill_returns_its_body_and_lists_the_files_it_links() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let out = SkillViewTool::new(root(tmp.path()))
            .call(json!({"name": "backup"}))
            .await
            .unwrap();
        assert!(out.contains("Run the script."), "{out}");
        assert!(
            !out.contains("description:"),
            "the frontmatter is not the body: {out}"
        );
        assert!(out.contains("- references/layout.md"), "{out}");
        assert!(out.contains("- scripts/backup.sh"), "{out}");
    }

    #[tokio::test]
    async fn a_linked_file_is_readable_and_parent_traversal_is_refused_naming_the_skill() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        write(&tmp.path().join("secret.txt"), "not yours");
        let tool = SkillViewTool::new(root(tmp.path()));

        let out = tool
            .call(json!({"name": "backup", "path": "references/layout.md"}))
            .await
            .unwrap();
        assert!(out.contains("the layout"), "{out}");

        for path in ["../../secret.txt", "references/../../../secret.txt"] {
            let message = err(tool.call(json!({"name": "backup", "path": path})).await);
            assert!(message.contains("backup"), "names the skill: {message}");
            assert!(message.contains("`..`"), "gives the reason: {message}");
        }
        let message = err(tool
            .call(json!({"name": "backup", "path": "/etc/passwd"}))
            .await);
        assert!(message.contains("absolute"), "{message}");
    }

    #[tokio::test]
    async fn a_symlink_that_leaves_the_skill_directory_is_refused() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let outside = tmp.path().join("outside");
        write(&outside.join("loot.txt"), "loot");
        let skill = tmp.path().join("skills/backup");
        std::os::unix::fs::symlink(&outside, skill.join("references/out")).unwrap();
        std::os::unix::fs::symlink(outside.join("loot.txt"), skill.join("references/loot"))
            .unwrap();

        let tool = SkillViewTool::new(root(tmp.path()));
        for path in ["references/out/loot.txt", "references/loot"] {
            let message = err(tool.call(json!({"name": "backup", "path": path})).await);
            assert!(
                message.contains("outside the skill's directory"),
                "{message}"
            );
        }
    }

    #[tokio::test]
    async fn an_unknown_skill_lists_what_exists_and_a_broken_one_says_why() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        write(
            &tmp.path().join("skills/bad/SKILL.md"),
            "---\ndescription: x\n---\nbody\n",
        );
        let tool = SkillViewTool::new(root(tmp.path()));

        let message = err(tool.call(json!({"name": "nope"})).await);
        assert!(message.contains("Available: backup"), "{message}");

        let message = err(tool.call(json!({"name": "bad"})).await);
        assert!(
            message.contains("broken") && message.contains("name"),
            "{message}"
        );
    }

    #[tokio::test]
    async fn a_linked_file_over_the_size_limit_is_refused_rather_than_read() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let big = tmp.path().join("skills/backup/templates/big.txt");
        write(&big, &"x".repeat(skills::MAX_SKILL_FILE_BYTES as usize + 1));
        let tool = SkillViewTool::new(root(tmp.path()));
        let message = err(tool
            .call(json!({"name": "backup", "path": "templates/big.txt"}))
            .await);
        assert!(message.contains("limit"), "{message}");
        assert!(message.contains("backup"), "names the skill: {message}");
    }

    #[tokio::test]
    async fn an_argument_of_the_wrong_type_is_an_error_rather_than_a_silent_default() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let view = SkillViewTool::new(root(tmp.path()));
        let message = err(view.call(json!({"name": "backup", "path": 7})).await);
        assert!(message.contains("`path` must be a string"), "{message}");

        let manage = SkillManageTool::new(root(tmp.path()));
        let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
        let message = err(manage
            .call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": 7}))
            .await);
        assert!(message.contains("`new` must be a string"), "{message}");
        let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
        assert_eq!(before, after, "nothing was written");
    }

    #[tokio::test]
    async fn creating_a_skill_writes_a_loadable_file_and_reports_the_path() {
        let tmp = tempfile::tempdir().unwrap();
        let manage = SkillManageTool::new(root(tmp.path()));
        let out = manage
            .call(json!({
                "action": "create", "name": "greet",
                "description": "say \"hello\": nicely",
                "body": "1. Say hello."
            }))
            .await
            .unwrap();
        let path = tmp.path().join("skills/greet/SKILL.md");
        assert!(out.contains(&path.display().to_string()), "{out}");

        let seen = SkillViewTool::new(root(tmp.path()))
            .call(json!({"name": "greet"}))
            .await
            .unwrap();
        assert!(seen.contains("1. Say hello."), "{seen}");
        let skill = skills::parse(&std::fs::read_to_string(path).unwrap()).unwrap();
        assert_eq!(skill.meta.description, "say \"hello\": nicely");
    }

    #[tokio::test]
    async fn creating_a_skill_refuses_an_existing_name_and_leaves_it_untouched() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let manage = SkillManageTool::new(root(tmp.path()));
        let message = err(manage
            .call(json!({
                "action": "create", "name": "backup",
                "description": "x", "body": "replacement"
            }))
            .await);
        assert!(message.contains("already exists"), "{message}");
        assert!(
            message.contains("skills/backup/SKILL.md"),
            "names the path: {message}"
        );
        let kept = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
        assert!(kept.contains("Run the script."), "{kept}");
    }

    #[tokio::test]
    async fn a_broken_skill_still_blocks_a_create_of_its_name() {
        let tmp = tempfile::tempdir().unwrap();
        write(&tmp.path().join("skills/bad/SKILL.md"), "---\nname: bad\n");
        let manage = SkillManageTool::new(root(tmp.path()));
        let message = err(manage
            .call(json!({"action": "create", "name": "bad", "description": "x", "body": "b"}))
            .await);
        assert!(message.contains("already exists"), "{message}");
    }

    #[tokio::test]
    async fn create_rejects_names_that_could_leave_the_skills_directory_and_multiline_descriptions()
    {
        let tmp = tempfile::tempdir().unwrap();
        let manage = SkillManageTool::new(root(tmp.path()));
        for name in ["../evil", "a/b", "", "has space"] {
            let result = manage
                .call(json!({"action": "create", "name": name, "description": "d", "body": "b"}))
                .await;
            assert!(matches!(result, Err(ToolError::InvalidArgs(_))), "{name:?}");
        }
        let result = manage
            .call(json!({"action": "create", "name": "ok", "description": "a\nb", "body": "b"}))
            .await;
        assert!(matches!(result, Err(ToolError::InvalidArgs(_))));
        let result = manage
            .call(json!({"action": "create", "name": "ok", "description": "d", "body": "  "}))
            .await;
        assert!(result.is_err(), "an empty body would be a broken skill");
        assert!(!tmp.path().join("skills").exists() || !tmp.path().join("skills/ok").exists());
    }

    #[tokio::test]
    async fn patching_replaces_exactly_one_occurrence_and_refuses_zero_or_many() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        write(
            &tmp.path().join("skills/backup/references/layout.md"),
            "a b a",
        );
        let manage = SkillManageTool::new(root(tmp.path()));

        let out = manage
            .call(json!({"action": "patch", "name": "backup", "old": "Run the script.", "new": "Run it twice."}))
            .await
            .unwrap();
        assert!(out.contains("skills/backup/SKILL.md"), "{out}");
        let text = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
        assert!(text.contains("Run it twice."), "{text}");

        let message = err(manage
            .call(json!({"action": "patch", "name": "backup", "path": "references/layout.md", "old": "a", "new": "z"}))
            .await);
        assert!(message.contains("occurs 2 times"), "{message}");
        let message = err(manage
            .call(json!({"action": "patch", "name": "backup", "old": "absent", "new": "z"}))
            .await);
        assert!(message.contains("does not occur"), "{message}");
    }

    #[tokio::test]
    async fn a_patch_that_would_break_or_rename_the_skill_is_refused_and_writes_nothing() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let manage = SkillManageTool::new(root(tmp.path()));
        let before = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();

        let message = err(manage
            .call(json!({"action": "patch", "name": "backup", "old": "name: backup\n", "new": ""}))
            .await);
        assert!(message.contains("would break"), "{message}");
        let message = err(manage
            .call(json!({"action": "patch", "name": "backup", "old": "name: backup", "new": "name: other"}))
            .await);
        assert!(message.contains("rename"), "{message}");

        let after = std::fs::read_to_string(tmp.path().join("skills/backup/SKILL.md")).unwrap();
        assert_eq!(before, after);
    }

    #[tokio::test]
    async fn writing_a_supporting_file_stays_inside_the_three_directories_and_the_skill() {
        let tmp = tempfile::tempdir().unwrap();
        backup(tmp.path());
        let manage = SkillManageTool::new(root(tmp.path()));

        let out = manage
            .call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo new"}))
            .await
            .unwrap();
        assert!(
            out.contains("created") && out.contains("scripts/new.sh"),
            "{out}"
        );
        let out = manage
            .call(json!({"action": "write_file", "name": "backup", "path": "scripts/new.sh", "content": "echo newer"}))
            .await
            .unwrap();
        assert!(out.contains("replaced"), "{out}");

        for path in [
            "../x.md",
            "notes.md",
            "SKILL.md",
            "/tmp/x",
            "scripts/../../x",
        ] {
            let result = manage
                .call(
                    json!({"action": "write_file", "name": "backup", "path": path, "content": "x"}),
                )
                .await;
            assert!(result.is_err(), "{path} should be refused");
        }

        let outside = tmp.path().join("outside");
        std::fs::create_dir_all(&outside).unwrap();
        std::os::unix::fs::symlink(&outside, tmp.path().join("skills/backup/templates")).unwrap();
        let message = err(manage
            .call(json!({"action": "write_file", "name": "backup", "path": "templates/x", "content": "x"}))
            .await);
        assert!(
            message.contains("outside the skill's directory"),
            "{message}"
        );
        assert!(!outside.join("x").exists());
    }

    #[tokio::test]
    async fn a_plugins_skill_cannot_be_edited_from_here() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            &tmp.path().join("plug/skills/p/SKILL.md"),
            "---\nname: p\n---\nbody\n",
        );
        let roots = vec![
            Root {
                source: Source::Shared,
                dir: tmp.path().join("skills"),
            },
            Root {
                source: Source::Plugin("plug".into()),
                dir: tmp.path().join("plug/skills"),
            },
        ];
        let message = err(SkillManageTool::new(roots)
            .call(json!({"action": "patch", "name": "p", "old": "body", "new": "x"}))
            .await);
        assert!(message.contains("plugin"), "{message}");
    }

    #[tokio::test]
    async fn with_a_profile_a_new_skill_goes_to_the_profile_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let roots = vec![
            Root {
                source: Source::Shared,
                dir: tmp.path().join("skills"),
            },
            Root {
                source: Source::Profile("work".into()),
                dir: tmp.path().join("profiles/work/skills"),
            },
            Root {
                source: Source::Workspace,
                dir: tmp.path().join("ws/.eclipse/skills"),
            },
        ];
        let out = SkillManageTool::new(roots)
            .call(json!({"action": "create", "name": "n", "description": "d", "body": "b"}))
            .await
            .unwrap();
        assert!(out.contains("profiles/work/skills/n/SKILL.md"), "{out}");
    }

    #[test]
    fn the_approval_prompt_says_where_a_create_will_write() {
        let tmp = tempfile::tempdir().unwrap();
        let manage = SkillManageTool::new(root(tmp.path()));
        let line = manage.describe_call(&json!({
            "action": "create", "name": "greet", "description": "d", "body": "abc"
        }));
        assert!(
            line.contains(
                &tmp.path()
                    .join("skills/greet/SKILL.md")
                    .display()
                    .to_string()
            ),
            "{line}"
        );
    }

    /// `#427`: a file written under `scripts/` is a program `shell` runs later with no prompt, so
    /// "412 bytes" is not what a person is approving. The summary carries what it opens with, and
    /// says plainly that it can be run.
    #[test]
    fn the_approval_prompt_shows_what_a_script_starts_with_and_says_it_runs() {
        let tmp = tempfile::tempdir().unwrap();
        let manage = SkillManageTool::new(root(tmp.path()));
        let line = manage.describe_call(&json!({
            "action": "write_file",
            "name": "greet",
            "path": "scripts/deploy.sh",
            "content": "#!/bin/sh\nset -eu\nrm -rf build\n"
        }));
        assert!(line.contains("scripts/deploy.sh"), "{line}");
        assert!(line.contains("#!/bin/sh set -eu rm -rf build"), "{line}");
        assert!(
            line.contains("`shell` can run it without asking again"),
            "the summary says the file is runnable: {line}"
        );

        // A reference is not a program, and does not carry the warning.
        let line = manage.describe_call(&json!({
            "action": "write_file",
            "name": "greet",
            "path": "references/api.md",
            "content": "# API\n"
        }));
        assert!(!line.contains("can run it"), "{line}");
        assert!(line.contains("# API"), "{line}");
    }

    /// The opening is clipped by character, so a multi-byte body cannot split one.
    #[test]
    fn the_preview_clips_by_char_and_collapses_whitespace() {
        assert_eq!(opening("a\n\n   b\t c", 40), "a b c");
        assert_eq!(opening(&"日".repeat(10), 3), "日日日…");
        assert_eq!(opening("short", 40), "short");
    }
}