1use 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";
20const DOCUMENT_BYTES: u64 = 8 * 1024 * 1024;
22const 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 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#[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 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
181pub(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
270pub(crate) fn builtin_catalog() -> Catalog {
272 builtins()
273 .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
274 .collect()
275}
276
277pub(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; }
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
339fn 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 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
366pub 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 platform::paths::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 = platform::private_tempdir_in(".install-", &directory)
397 .map_err(|error| ConfigError::new(&directory, error))?;
398 let payload = staged.path().join("plugin");
399 let source =
400 platform::open_directory(&source).map_err(|error| ConfigError::new(&source, error))?;
401 platform::paths::copy_portable_tree(&source, &payload)
402 .map_err(|error| ConfigError::new(&installed, error))?;
403 let validated = read(&payload)?;
404 if validated.info.name != plugin.info.name {
405 return Err(ConfigError::new(
406 &installed,
407 "Plugin namespace changed during installation.",
408 ));
409 }
410 platform::paths::rename_open_file(&payload, &installed)
411 .map_err(|error| ConfigError::new(&installed, error))?;
412 Ok(validated.info)
413}
414
415pub fn remove(root: &Path, name: &PluginName) -> Result<(), ConfigError> {
417 let definitions = definitions(root)?;
418 let directory = definitions.join(DIRECTORY);
419 let path = directory.join(name.as_str());
420 if builtins().any(|builtin| builtin.info.name == *name) {
421 return Err(ConfigError::new(
422 &path,
423 "A built-in plugin cannot be removed.",
424 ));
425 }
426 if !platform::paths::reusable_directory(&definitions, DIRECTORY)
427 .and_then(|exists| {
428 if exists {
429 platform::paths::reusable_directory(&directory, name.as_str())
430 } else {
431 Ok(false)
432 }
433 })
434 .map_err(|error| ConfigError::new(&path, error))?
435 {
436 return Err(ConfigError::new(&path, "Plugin is not installed."));
437 }
438 let staged = platform::private_tempdir_in(".remove-", &directory)
439 .map_err(|error| ConfigError::new(&path, error))?;
440 platform::paths::rename_open_file(&path, &staged.path().join("plugin"))
441 .map_err(|error| ConfigError::new(&path, error))?;
442 staged
443 .close()
444 .map_err(|error| ConfigError::new(&path, error))
445}
446
447pub(super) fn migrate(root: &Path) -> Result<(Catalog, Vec<(PathBuf, String)>), ConfigError> {
451 let mut plugins: Catalog = builtins()
452 .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
453 .collect();
454 let mut writes = Vec::new();
455 let directory = root.join(DEFINITION_DIR).join(DIRECTORY);
456 if !platform::paths::reusable_directory(root, DEFINITION_DIR)
457 .map_err(|error| ConfigError::new(root.join(DEFINITION_DIR), error))?
458 || !platform::paths::reusable_directory(&root.join(DEFINITION_DIR), DIRECTORY)
459 .map_err(|error| ConfigError::new(&directory, error))?
460 {
461 return Ok((plugins, writes));
462 }
463 let opened = platform::open_directory(&directory)
464 .map_err(|error| ConfigError::new(&directory, error))?;
465 for entry in platform::read_dir(&opened).map_err(|error| ConfigError::new(&directory, error))? {
466 let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
467 let name = entry.file_name();
468 let path = directory.join(&name);
469 if name.as_encoded_bytes().starts_with(b".")
470 || entry
471 .file_type()
472 .map_err(|error| ConfigError::new(&path, error))?
473 != platform::FileKind::Directory
474 {
475 continue;
476 }
477 let manifest_path = path.join(MANIFEST);
478 let source = super::discovery::read_regular_text(&manifest_path)
479 .map_err(|error| ConfigError::new(&manifest_path, error))?;
480 let table: toml::Table =
481 toml::from_str(&source).map_err(|error| ConfigError::new(&manifest_path, error))?;
482 if !table.contains_key("type") && !table.contains_key("views") {
483 let plugin = read(&path)?;
484 plugins.insert(plugin.info.name.clone(), Arc::new(plugin));
485 continue;
486 }
487 let invalid = |message: &str| ConfigError::new(&manifest_path, message);
488 let namespace: PluginName = table
489 .get("type")
490 .and_then(toml::Value::as_str)
491 .ok_or_else(|| invalid("An old plugin.toml names its `type`."))?
492 .parse()
493 .map_err(|error: String| invalid(&error))?;
494 let title = table
495 .get("title")
496 .and_then(toml::Value::as_str)
497 .ok_or_else(|| invalid("A plugin.toml has a `title`."))?
498 .to_owned();
499 let entry = table
500 .get("viewer")
501 .and_then(|viewer| viewer.get("entry"))
502 .and_then(toml::Value::as_str)
503 .map(str::to_owned);
504 let views = serde_json::to_value(
505 table
506 .get("views")
507 .cloned()
508 .unwrap_or_else(|| toml::Table::new().into()),
509 )
510 .expect("TOML is JSON");
511 let tools = super::convert::toolset_text(namespace.as_str(), &views, entry.is_some())
512 .map_err(|error| invalid(&error))?;
513 let mut manifest = toml::Table::new();
514 manifest.insert("namespace".into(), namespace.to_string().into());
515 manifest.insert("title".into(), title.clone().into());
516 if let Some(entry) = &entry {
517 let mut viewer = toml::Table::new();
518 viewer.insert("entry".into(), entry.clone().into());
519 manifest.insert("viewer".into(), viewer.into());
520 }
521 let viewer = entry
522 .map(|entry| {
523 let file = scope::open_scoped(&path, &entry)
524 .map_err(|error| invalid(&format!("viewer.entry {entry}: {error}")))?;
525 Ok::<_, ConfigError>(ViewerEntry::Web {
526 html: read_document(file).map_err(|error| invalid(&error))?.into(),
527 })
528 })
529 .transpose()?;
530 let file = PathBuf::from(format!("{namespace}.artf"));
531 let plugin = Plugin {
532 info: PluginInfo {
533 name: namespace.clone(),
534 title,
535 builtin: false,
536 viewer: viewer.is_some(),
537 },
538 viewer,
539 sources: vec![(file.clone(), tools.clone())],
540 };
541 validate(&plugin)?;
542 writes.push((
543 manifest_path.clone(),
544 toml::to_string(&manifest).expect("a manifest is TOML"),
545 ));
546 writes.push((path.join(file), tools));
547 plugins.insert(namespace, Arc::new(plugin));
548 }
549 Ok((plugins, writes))
550}