Skip to main content

artifactize_core/config/
plugins.rs

1//! Toolsets that come with artifactize or a plugin. A plugin is a folder with a `plugin.toml`
2//! naming its namespace, its `.artf` files declaring that namespace's toolset and any macros,
3//! and optionally a viewer page.
4
5use std::{
6    collections::BTreeMap,
7    fs::File,
8    io::Read,
9    path::{Path, PathBuf},
10    sync::Arc,
11};
12
13use serde::{Deserialize, Serialize};
14
15use super::{ConfigError, LogicalPath, PluginName, discovery::DEFINITION_DIR};
16use crate::{platform, scope};
17
18pub(super) const DIRECTORY: &str = "plugins";
19const MANIFEST: &str = "plugin.toml";
20/// A viewer opens one web document. Bound what a launch copies across IPC.
21const DOCUMENT_BYTES: u64 = 8 * 1024 * 1024;
22/// A plugin's `.artf` files, bounded like any document a plugin carries.
23const MAX_SOURCES: usize = 64;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
26#[serde(rename_all = "lowercase")]
27pub enum BuiltinViewer {
28    Files,
29    Markdown,
30    Artifactize,
31}
32
33impl BuiltinViewer {
34    // Kept as text rather than `.artf` files: any `.artf` file marks its folder as a workspace.
35    const ALL: [(Self, &'static str, &'static str, &'static str); 3] = [
36        (
37            Self::Files,
38            "files",
39            "File Explorer",
40            r#"// The built-in File Explorer: an Artifact's files for agents and people.
41tool files = {
42  agent list = builtin(op = "list")
43  agent glob = builtin(op = "glob")
44  agent grep = builtin(op = "grep")
45  agent read = builtin(op = "read")
46  human view = viewer(description = "Open @{artf self} in File Explorer.")
47}
48"#,
49        ),
50        (
51            Self::Markdown,
52            "markdown",
53            "Markdown",
54            r#"// The built-in Markdown viewer.
55tool markdown = {
56  agent read = builtin(op = "read")
57  human view = viewer(description = "Open @{artf self} in Markdown.")
58}
59"#,
60        ),
61        (
62            Self::Artifactize,
63            "artifactize",
64            "Artifactize Viewer",
65            r#"// The built-in Artifactize Viewer of the definitions under .artifactize/.
66tool artifactize = {
67  agent declarations = builtin(op = "declarations", args = [])
68  human view = viewer(description = "Open @{artf self} in Artifactize Viewer.")
69}
70"#,
71        ),
72    ];
73}
74
75#[derive(Debug, Deserialize)]
76#[serde(deny_unknown_fields)]
77struct Manifest {
78    namespace: PluginName,
79    title: String,
80    viewer: Option<WebEntry>,
81}
82
83#[derive(Debug, Deserialize)]
84#[serde(deny_unknown_fields)]
85struct WebEntry {
86    entry: LogicalPath,
87}
88
89/// A viewer selected by its plugin, never by a path supplied by a web page.
90#[derive(Debug, Clone, Serialize)]
91#[serde(tag = "kind", rename_all = "lowercase")]
92pub enum ViewerEntry {
93    Builtin { viewer: BuiltinViewer },
94    Web { html: Arc<str> },
95}
96
97#[derive(Debug, Clone, Serialize)]
98#[serde(rename_all = "camelCase")]
99pub struct PluginInfo {
100    #[serde(rename = "namespace")]
101    pub name: PluginName,
102    pub title: String,
103    pub builtin: bool,
104    pub viewer: bool,
105}
106
107#[derive(Debug)]
108pub(crate) struct Plugin {
109    pub info: PluginInfo,
110    pub viewer: Option<ViewerEntry>,
111    /// Its `.artf` files, by their path under `plugins/<namespace>/`.
112    pub sources: Vec<(PathBuf, String)>,
113}
114
115impl Plugin {
116    pub(super) fn source_files(&self) -> impl Iterator<Item = super::lang::SourceFile> + '_ {
117        self.sources
118            .iter()
119            .map(|(path, text)| super::lang::SourceFile {
120                path: PathBuf::from(DIRECTORY)
121                    .join(self.info.name.as_str())
122                    .join(path),
123                text: text.clone(),
124                origin: super::lang::Origin::Plugin(super::lang::PluginSource {
125                    namespace: self.info.name.to_string(),
126                    viewer: self.viewer.is_some(),
127                }),
128            })
129    }
130}
131
132pub(crate) type Catalog = BTreeMap<PluginName, Arc<Plugin>>;
133
134pub(crate) fn read_document(file: File) -> Result<String, String> {
135    if !file
136        .metadata()
137        .map_err(|error| error.to_string())?
138        .is_file()
139    {
140        return Err("Expected a regular text file.".into());
141    }
142    let mut buffer = String::new();
143    file.take(DOCUMENT_BYTES + 1)
144        .read_to_string(&mut buffer)
145        .map_err(|error| error.to_string())?;
146    if buffer.len() as u64 > DOCUMENT_BYTES {
147        return Err("Viewer document exceeds 8 MiB.".into());
148    }
149    Ok(buffer)
150}
151
152fn builtins() -> impl Iterator<Item = Plugin> {
153    BuiltinViewer::ALL
154        .into_iter()
155        .map(|(viewer, name, title, source)| Plugin {
156            info: PluginInfo {
157                name: name.parse().expect("a built-in plugin name"),
158                title: title.into(),
159                builtin: true,
160                viewer: true,
161            },
162            viewer: Some(ViewerEntry::Builtin { viewer }),
163            sources: vec![(PathBuf::from(format!("{name}.artf")), source.into())],
164        })
165}
166
167fn definitions(root: &Path) -> Result<PathBuf, ConfigError> {
168    let root = platform::canonicalize(root).map_err(|error| ConfigError::new(root, error))?;
169    let definitions = root.join(DEFINITION_DIR);
170    if !platform::paths::reusable_directory(&root, DEFINITION_DIR)
171        .map_err(|error| ConfigError::new(&definitions, error))?
172    {
173        return Err(ConfigError::new(
174            &definitions,
175            "Not an Artifactize project.",
176        ));
177    }
178    Ok(definitions)
179}
180
181/// Read one plugin folder: its manifest, its viewer page and its `.artf` files.
182pub(super) fn read(directory: &Path) -> Result<Plugin, ConfigError> {
183    let manifest_path = directory.join(MANIFEST);
184    let source = scope::open_scoped(directory, MANIFEST)
185        .map_err(|error| ConfigError::new(&manifest_path, error))?;
186    let source = read_document(source).map_err(|error| ConfigError::new(&manifest_path, error))?;
187    let table: toml::Table =
188        toml::from_str(&source).map_err(|error| ConfigError::new(&manifest_path, error))?;
189    if table.contains_key("type") || table.contains_key("views") {
190        return Err(ConfigError::new(
191            &manifest_path,
192            "This plugin.toml is from before 0.27: it names its `namespace` now and declares its tools in an .artf file. Run artifactize config migrate in a project that has it installed, or update the plugin.",
193        ));
194    }
195    let manifest: Manifest =
196        toml::from_str(&source).map_err(|error| ConfigError::new(&manifest_path, error))?;
197    super::validation::text(&manifest.title, "Plugin title")
198        .map_err(|error| ConfigError::new(&manifest_path, error))?;
199    let viewer = manifest
200        .viewer
201        .map(|web| {
202            if Path::new(web.entry.as_str())
203                .extension()
204                .is_none_or(|extension| extension != "html")
205            {
206                return Err(
207                    "viewer.entry must name an .html file in the plugin directory.".to_owned(),
208                );
209            }
210            let file = scope::open_scoped(directory, web.entry.as_str())
211                .map_err(|error| format!("viewer.entry {}: {error}", web.entry))?;
212            Ok(ViewerEntry::Web {
213                html: read_document(file)?.into(),
214            })
215        })
216        .transpose()
217        .map_err(|error| ConfigError::new(&manifest_path, error))?;
218    let opened =
219        platform::open_directory(directory).map_err(|error| ConfigError::new(directory, error))?;
220    let mut sources = Vec::new();
221    for entry in platform::read_dir(&opened).map_err(|error| ConfigError::new(directory, error))? {
222        let entry = entry.map_err(|error| ConfigError::new(directory, error))?;
223        let name = entry.file_name();
224        if !name.as_encoded_bytes().ends_with(b".artf") {
225            continue;
226        }
227        let path = directory.join(&name);
228        if entry
229            .file_type()
230            .map_err(|error| ConfigError::new(&path, error))?
231            != platform::FileKind::File
232        {
233            return Err(ConfigError::new(
234                &path,
235                "A plugin's definition must be a regular file.",
236            ));
237        }
238        let text = super::discovery::read_regular_text(&path)
239            .map_err(|error| ConfigError::new(&path, error))?;
240        sources.push((PathBuf::from(name), text));
241    }
242    if sources.len() > MAX_SOURCES {
243        return Err(ConfigError::new(
244            directory,
245            format!("A plugin holds at most {MAX_SOURCES} .artf files."),
246        ));
247    }
248    sources.sort();
249    if sources.is_empty() {
250        return Err(ConfigError::new(
251            directory,
252            format!(
253                "Plugin {} declares no tools: add an .artf file with `tool {} = {{ … }}`.",
254                manifest.namespace, manifest.namespace
255            ),
256        ));
257    }
258    Ok(Plugin {
259        info: PluginInfo {
260            name: manifest.namespace,
261            title: manifest.title,
262            builtin: false,
263            viewer: viewer.is_some(),
264        },
265        viewer,
266        sources,
267    })
268}
269
270/// The built-in plugins alone.
271pub(crate) fn builtin_catalog() -> Catalog {
272    builtins()
273        .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
274        .collect()
275}
276
277/// The built-in plugins and those installed under `.artifactize/plugins/`.
278pub(crate) fn catalog(root: &Path) -> Result<Catalog, ConfigError> {
279    let mut plugins: Catalog = builtins()
280        .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
281        .collect();
282    let parent = root.join(DEFINITION_DIR);
283    let directory = parent.join(DIRECTORY);
284    if !platform::paths::reusable_directory(root, DEFINITION_DIR)
285        .map_err(|error| ConfigError::new(&parent, error))?
286    {
287        return Ok(plugins);
288    }
289    if !platform::paths::reusable_directory(&parent, DIRECTORY)
290        .map_err(|error| ConfigError::new(&directory, error))?
291    {
292        return Ok(plugins);
293    }
294    let opened = platform::open_directory(&directory)
295        .map_err(|error| ConfigError::new(&directory, error))?;
296    for entry in platform::read_dir(&opened).map_err(|error| ConfigError::new(&directory, error))? {
297        let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
298        let name = entry.file_name();
299        if name.as_encoded_bytes().starts_with(b".") {
300            continue; // Installer staging, not a discoverable plugin name.
301        }
302        let path = directory.join(&name);
303        let kind = entry
304            .file_type()
305            .map_err(|error| ConfigError::new(&path, error))?;
306        if kind == platform::FileKind::File {
307            continue;
308        }
309        if kind != platform::FileKind::Directory {
310            return Err(ConfigError::new(
311                &path,
312                "A plugin must be a real directory, not a link or special file.",
313            ));
314        }
315        let plugin = read(&path)?;
316        if name != plugin.info.name.as_str() {
317            return Err(ConfigError::new(
318                &path,
319                "The directory name must match the plugin's namespace.",
320            ));
321        }
322        if plugins.contains_key(&plugin.info.name) {
323            return Err(ConfigError::new(
324                &path,
325                "Built-in plugin namespaces are reserved.",
326            ));
327        }
328        plugins.insert(plugin.info.name.clone(), Arc::new(plugin));
329    }
330    Ok(plugins)
331}
332
333pub fn list(root: &Path) -> Result<Vec<PluginInfo>, ConfigError> {
334    let directory = definitions(root)?;
335    catalog(directory.parent().expect("workspace root"))
336        .map(|plugins| plugins.values().map(|plugin| plugin.info.clone()).collect())
337}
338
339/// A plugin's files must read on their own: its toolset and macros, with the built-ins.
340fn validate(plugin: &Plugin) -> Result<(), ConfigError> {
341    let files = builtins()
342        .chain(std::iter::once(Plugin {
343            info: plugin.info.clone(),
344            viewer: plugin.viewer.clone(),
345            sources: plugin.sources.clone(),
346        }))
347        .flat_map(|plugin| plugin.source_files().collect::<Vec<_>>())
348        .collect();
349    // A plugin declares toolsets and macros, never profiles: no environment to read.
350    let program =
351        super::lang::read(files, &|_| None).map_err(|(sources, error)| sources.error(error))?;
352    if !program.symbols.iter().any(|symbol| {
353        symbol.kind == "tool" && !symbol.is_macro && symbol.name == plugin.info.name.as_str()
354    }) {
355        return Err(ConfigError::new(
356            PathBuf::from(plugin.info.name.as_str()),
357            format!(
358                "Plugin {0} declares no `tool {0} = {{ … }}`.",
359                plugin.info.name
360            ),
361        ));
362    }
363    Ok(())
364}
365
366/// Install a complete folder, so readers can never observe a half-written plugin.
367pub fn add(root: &Path, source: &Path) -> Result<PluginInfo, ConfigError> {
368    let definitions = definitions(root)?;
369    let directory = definitions.join(DIRECTORY);
370    let source = platform::canonicalize(source).map_err(|error| ConfigError::new(source, error))?;
371    let plugin = read(&source)?;
372    validate(&plugin)?;
373    let installed = directory.join(plugin.info.name.as_str());
374    if builtins().any(|builtin| builtin.info.name == plugin.info.name) {
375        return Err(ConfigError::new(
376            &installed,
377            "Built-in plugin namespaces are reserved.",
378        ));
379    }
380    if platform::is_within(&source, &directory) || platform::is_within(&directory, &source) {
381        return Err(ConfigError::new(
382            &source,
383            "The source must be outside the installed plugins directory and cannot contain it.",
384        ));
385    }
386    ensure_directory(&definitions, DIRECTORY)
387        .map_err(|error| ConfigError::new(&directory, error))?;
388    if platform::paths::reusable_directory(&directory, plugin.info.name.as_str())
389        .map_err(|error| ConfigError::new(&installed, error))?
390    {
391        return Err(ConfigError::new(
392            &installed,
393            "Plugin already installed; remove it before adding a replacement.",
394        ));
395    }
396    let staged = tempfile::Builder::new()
397        .prefix(".install-")
398        .tempdir_in(&directory)
399        .map_err(|error| ConfigError::new(&directory, error))?;
400    let payload = staged.path().join("plugin");
401    let source =
402        platform::open_directory(&source).map_err(|error| ConfigError::new(&source, error))?;
403    platform::paths::copy_portable_tree(&source, &payload)
404        .map_err(|error| ConfigError::new(&installed, error))?;
405    let validated = read(&payload)?;
406    if validated.info.name != plugin.info.name {
407        return Err(ConfigError::new(
408            &installed,
409            "Plugin namespace changed during installation.",
410        ));
411    }
412    platform::paths::rename_open_file(&payload, &installed)
413        .map_err(|error| ConfigError::new(&installed, error))?;
414    Ok(validated.info)
415}
416
417fn ensure_directory(parent: &Path, name: &str) -> std::io::Result<()> {
418    if !platform::paths::reusable_directory(parent, name)? {
419        match std::fs::create_dir(parent.join(name)) {
420            Err(error)
421                if error.kind() == std::io::ErrorKind::AlreadyExists
422                    && platform::paths::reusable_directory(parent, name)? =>
423            {
424                Ok(())
425            }
426            result => result,
427        }
428    } else {
429        Ok(())
430    }
431}
432
433/// Remove an installed package, even if its manifest is no longer valid.
434pub fn remove(root: &Path, name: &PluginName) -> Result<(), ConfigError> {
435    let definitions = definitions(root)?;
436    let directory = definitions.join(DIRECTORY);
437    let path = directory.join(name.as_str());
438    if builtins().any(|builtin| builtin.info.name == *name) {
439        return Err(ConfigError::new(
440            &path,
441            "A built-in plugin cannot be removed.",
442        ));
443    }
444    if !platform::paths::reusable_directory(&definitions, DIRECTORY)
445        .and_then(|exists| {
446            if exists {
447                platform::paths::reusable_directory(&directory, name.as_str())
448            } else {
449                Ok(false)
450            }
451        })
452        .map_err(|error| ConfigError::new(&path, error))?
453    {
454        return Err(ConfigError::new(&path, "Plugin is not installed."));
455    }
456    let staged = platform::private_tempdir_in(".remove-", &directory)
457        .map_err(|error| ConfigError::new(&path, error))?;
458    platform::paths::rename_open_file(&path, &staged.path().join("plugin"))
459        .map_err(|error| ConfigError::new(&path, error))?;
460    staged
461        .close()
462        .map_err(|error| ConfigError::new(&path, error))
463}
464
465/// The plugins a migration reads with: the built-ins, the current ones as installed, and each
466/// one installed before 0.27 converted in memory. Returns the files a converted plugin is
467/// written as: its new manifest and its toolset.
468pub(super) fn migrate(root: &Path) -> Result<(Catalog, Vec<(PathBuf, String)>), ConfigError> {
469    let mut plugins: Catalog = builtins()
470        .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
471        .collect();
472    let mut writes = Vec::new();
473    let directory = root.join(DEFINITION_DIR).join(DIRECTORY);
474    if !platform::paths::reusable_directory(root, DEFINITION_DIR)
475        .map_err(|error| ConfigError::new(root.join(DEFINITION_DIR), error))?
476        || !platform::paths::reusable_directory(&root.join(DEFINITION_DIR), DIRECTORY)
477            .map_err(|error| ConfigError::new(&directory, error))?
478    {
479        return Ok((plugins, writes));
480    }
481    let opened = platform::open_directory(&directory)
482        .map_err(|error| ConfigError::new(&directory, error))?;
483    for entry in platform::read_dir(&opened).map_err(|error| ConfigError::new(&directory, error))? {
484        let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
485        let name = entry.file_name();
486        let path = directory.join(&name);
487        if name.as_encoded_bytes().starts_with(b".")
488            || entry
489                .file_type()
490                .map_err(|error| ConfigError::new(&path, error))?
491                != platform::FileKind::Directory
492        {
493            continue;
494        }
495        let manifest_path = path.join(MANIFEST);
496        let source = super::discovery::read_regular_text(&manifest_path)
497            .map_err(|error| ConfigError::new(&manifest_path, error))?;
498        let table: toml::Table =
499            toml::from_str(&source).map_err(|error| ConfigError::new(&manifest_path, error))?;
500        if !table.contains_key("type") && !table.contains_key("views") {
501            let plugin = read(&path)?;
502            plugins.insert(plugin.info.name.clone(), Arc::new(plugin));
503            continue;
504        }
505        let invalid = |message: &str| ConfigError::new(&manifest_path, message);
506        let namespace: PluginName = table
507            .get("type")
508            .and_then(toml::Value::as_str)
509            .ok_or_else(|| invalid("An old plugin.toml names its `type`."))?
510            .parse()
511            .map_err(|error: String| invalid(&error))?;
512        let title = table
513            .get("title")
514            .and_then(toml::Value::as_str)
515            .ok_or_else(|| invalid("A plugin.toml has a `title`."))?
516            .to_owned();
517        let entry = table
518            .get("viewer")
519            .and_then(|viewer| viewer.get("entry"))
520            .and_then(toml::Value::as_str)
521            .map(str::to_owned);
522        let views = serde_json::to_value(
523            table
524                .get("views")
525                .cloned()
526                .unwrap_or_else(|| toml::Table::new().into()),
527        )
528        .expect("TOML is JSON");
529        let tools = super::convert::toolset_text(namespace.as_str(), &views, entry.is_some())
530            .map_err(|error| invalid(&error))?;
531        let mut manifest = toml::Table::new();
532        manifest.insert("namespace".into(), namespace.to_string().into());
533        manifest.insert("title".into(), title.clone().into());
534        if let Some(entry) = &entry {
535            let mut viewer = toml::Table::new();
536            viewer.insert("entry".into(), entry.clone().into());
537            manifest.insert("viewer".into(), viewer.into());
538        }
539        let viewer = entry
540            .map(|entry| {
541                let file = scope::open_scoped(&path, &entry)
542                    .map_err(|error| invalid(&format!("viewer.entry {entry}: {error}")))?;
543                Ok::<_, ConfigError>(ViewerEntry::Web {
544                    html: read_document(file).map_err(|error| invalid(&error))?.into(),
545                })
546            })
547            .transpose()?;
548        let file = PathBuf::from(format!("{namespace}.artf"));
549        let plugin = Plugin {
550            info: PluginInfo {
551                name: namespace.clone(),
552                title,
553                builtin: false,
554                viewer: viewer.is_some(),
555            },
556            viewer,
557            sources: vec![(file.clone(), tools.clone())],
558        };
559        validate(&plugin)?;
560        writes.push((
561            manifest_path.clone(),
562            toml::to_string(&manifest).expect("a manifest is TOML"),
563        ));
564        writes.push((path.join(file), tools));
565        plugins.insert(namespace, Arc::new(plugin));
566    }
567    Ok((plugins, writes))
568}