Skip to main content

base/
command.rs

1//! Slash-command names the engine answers itself, the plugin commands
2//! (`[[command]]`) a session runs through `RunExt` and as `/name args`, the
3//! plugin functions (`[[function]]`) only the host calls, and the host
4//! libraries (`uses`) a package's code may need.
5
6use std::path::PathBuf;
7
8/// The engine's own `/name` commands, with what each does. A plugin command
9/// may not take one of these names.
10pub const BUILTIN_COMMANDS: &[(&str, &str)] = &[
11    ("help", "List all available slash commands"),
12    ("skills", "List all available skills"),
13    ("clear", "Clear the current session context"),
14    ("compact", "Trigger context compaction now"),
15    ("cost", "Show the tokens and calls this session has spent"),
16];
17
18/// Where a package comes from, as the engine's registry of packages knows
19/// it — unlike its name, which the package's own `plugin.toml` gives.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum PackageSource {
23    /// `plugin.install`: anyone who can install a package, under any name.
24    #[default]
25    Installed,
26    /// One of the embedding host's own packages, from a directory it named.
27    Host,
28}
29
30/// One command an enabled package declares, as the session runs it.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct ExtCommand {
33    pub name: String,
34    pub description: String,
35    pub plugin: String,
36    pub plugin_version: String,
37    pub source: PackageSource,
38    /// The package's unpacked directory.
39    pub root: PathBuf,
40    /// The entry file, inside `root`.
41    pub file: PathBuf,
42    /// The function the entry file defines that the command calls.
43    pub function: String,
44    /// Argument prefixes, whole words each, that make a call read-only; `""`
45    /// is the call with no arguments.
46    pub read_only: Vec<String>,
47    /// Globs relative to the project root that the command may write.
48    pub writes: Vec<String>,
49    /// The host libraries the package declares, by namespace.
50    pub uses: Vec<String>,
51    /// Where compiled entries are kept between runs; `None` compiles every run.
52    pub bytecode_dir: Option<PathBuf>,
53}
54
55/// One function an enabled package declares for the host to call, never the
56/// model: `<plugin>.<name>`.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct PluginFunction {
59    pub name: String,
60    pub plugin: String,
61    pub plugin_version: String,
62    pub source: PackageSource,
63    pub description: String,
64    /// The package's unpacked directory.
65    pub root: PathBuf,
66    /// The entry file, inside `root`.
67    pub file: PathBuf,
68    /// The function the entry file defines, called as `(input, ctx)`.
69    pub function: String,
70    /// Globs relative to the project root that a writing call may write.
71    pub writes: Vec<String>,
72    /// The JSON Schema `input` is checked against before the call.
73    pub input_schema: Option<serde_json::Value>,
74    /// The host libraries the package declares, by namespace.
75    pub uses: Vec<String>,
76    /// Where compiled entries are kept between runs; `None` compiles every run.
77    pub bytecode_dir: Option<PathBuf>,
78}
79
80impl PluginFunction {
81    /// The name a host calls it by.
82    pub fn call_name(&self) -> String {
83        format!("{}.{}", self.plugin, self.name)
84    }
85}
86
87/// A JavaScript library the host provides to plugin code, as a package's
88/// `uses` names it and its install disclosure describes it.
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct HostLibrary {
91    pub name: String,
92    pub description: Option<String>,
93}
94
95impl ExtCommand {
96    /// Whether a call with `args` is read-only: they start with one of the
97    /// `read_only` prefixes, word for word, or there are none and `""` is
98    /// one of them.
99    pub fn is_read_only(&self, args: &[String]) -> bool {
100        self.read_only.iter().any(|prefix| {
101            let words: Vec<&str> = prefix.split_whitespace().collect();
102            if words.is_empty() {
103                return args.is_empty();
104            }
105            words.len() <= args.len() && words.iter().zip(args).all(|(w, a)| *w == a)
106        })
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    fn command(read_only: &[&str]) -> ExtCommand {
115        ExtCommand {
116            name: "forge".into(),
117            description: String::new(),
118            plugin: "forge".into(),
119            plugin_version: "1.0.0".into(),
120            source: PackageSource::Installed,
121            root: PathBuf::new(),
122            file: PathBuf::new(),
123            function: "main".into(),
124            read_only: read_only.iter().map(|s| s.to_string()).collect(),
125            writes: Vec::new(),
126            uses: Vec::new(),
127            bytecode_dir: None,
128        }
129    }
130
131    fn args(line: &str) -> Vec<String> {
132        line.split_whitespace().map(str::to_string).collect()
133    }
134
135    #[test]
136    fn a_read_only_prefix_matches_whole_words_only() {
137        let c = command(&["help", "spec list"]);
138        assert!(c.is_read_only(&args("help")));
139        assert!(c.is_read_only(&args("spec list --status draft")));
140        assert!(!c.is_read_only(&args("spec listall")));
141        assert!(!c.is_read_only(&args("spec")));
142        assert!(!c.is_read_only(&args("helpme")));
143        assert!(!c.is_read_only(&[]));
144    }
145
146    #[test]
147    fn an_empty_prefix_is_the_call_with_no_arguments_only() {
148        let bare = command(&[""]);
149        assert!(bare.is_read_only(&[]));
150        assert!(!bare.is_read_only(&args("anything")));
151        assert!(!bare.is_read_only(&args("help")));
152    }
153}