1use std::{collections::BTreeMap, fs::File, io::Read, path::Path, sync::Arc};
4
5use serde::{Deserialize, Serialize};
6
7use super::{Artifact, ArtifactKind, ConfigError, LogicalPath, Views, discovery::DEFINITION_DIR};
8use crate::{platform, scope};
9
10pub(super) const DIRECTORY: &str = "plugins";
11const MANIFEST: &str = "plugin.toml";
12const DOCUMENT_BYTES: u64 = 8 * 1024 * 1024;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
16#[serde(rename_all = "lowercase")]
17pub enum BuiltinViewer {
18 Files,
19 Markdown,
20 Artifactize,
21}
22
23impl BuiltinViewer {
24 const MANIFESTS: [(Self, &str); 3] = [
25 (Self::Files, include_str!("plugins/files.toml")),
26 (Self::Markdown, include_str!("plugins/markdown.toml")),
27 (Self::Artifactize, include_str!("plugins/artifactize.toml")),
28 ];
29}
30
31#[derive(Debug, Deserialize)]
32#[serde(deny_unknown_fields)]
33struct Manifest {
34 #[serde(rename = "type")]
35 name: super::ArtifactType,
36 title: String,
37 #[serde(default)]
38 views: Views,
39 viewer: Option<WebEntry>,
40}
41
42#[derive(Debug, Deserialize)]
43#[serde(deny_unknown_fields)]
44struct WebEntry {
45 entry: LogicalPath,
46}
47
48#[derive(Debug, Clone, Serialize)]
50#[serde(tag = "kind", rename_all = "lowercase")]
51pub enum ViewerEntry {
52 Builtin { viewer: BuiltinViewer },
53 Web { html: Arc<str> },
54}
55
56#[derive(Debug, Clone, Serialize)]
57#[serde(rename_all = "camelCase")]
58pub struct PluginInfo {
59 #[serde(rename = "type")]
60 pub name: super::ArtifactType,
61 pub title: String,
62 pub builtin: bool,
63 pub viewer: bool,
64}
65
66#[derive(Debug)]
67pub(crate) struct Plugin {
68 pub info: PluginInfo,
69 pub viewer: Option<ViewerEntry>,
70 views: Views,
71}
72
73impl Plugin {
74 fn parse(
75 source: &str,
76 viewer: Option<BuiltinViewer>,
77 directory: Option<&Path>,
78 ) -> Result<Self, String> {
79 let manifest: Manifest = toml::from_str(source).map_err(|error| error.to_string())?;
80 super::validation::text(&manifest.title, "Plugin title")?;
81 let table = toml::de::DeTable::parse(source).map_err(|error| error.to_string())?;
82 let document =
83 toml::Spanned::new(table.span(), toml::de::DeValue::Table(table.into_inner()));
84 manifest.views.validate(
85 &super::location::Location::root(source, &document).child("views"),
86 &mut super::schemas::Schemas::default(),
87 None,
88 )?;
89 let entry = match (viewer, &manifest.viewer, directory) {
90 (Some(viewer), None, None) => Some(ViewerEntry::Builtin { viewer }),
91 (None, Some(web), Some(directory)) => {
92 if Path::new(web.entry.as_str())
93 .extension()
94 .is_none_or(|extension| extension != "html")
95 {
96 return Err(
97 "viewer.entry must name an .html file in the plugin directory.".into(),
98 );
99 }
100 let file = scope::open_scoped(directory, web.entry.as_str())
101 .map_err(|error| format!("viewer.entry {}: {error}", web.entry))?;
102 Some(ViewerEntry::Web {
103 html: read_document(file)?.into(),
104 })
105 }
106 (None, None, Some(_)) => None,
107 _ => return Err("Invalid plugin viewer entry.".into()),
108 };
109 let declares_viewer = manifest
110 .views
111 .human_tools
112 .values()
113 .any(|tool| matches!(tool, super::HumanTool::Viewer(_)));
114 if declares_viewer != entry.is_some() {
115 return Err(
116 "A viewer entry and a Human tool with kind = \"viewer\" must be declared together."
117 .into(),
118 );
119 }
120 Ok(Self {
121 info: PluginInfo {
122 name: manifest.name,
123 title: manifest.title,
124 builtin: viewer.is_some(),
125 viewer: entry.is_some(),
126 },
127 viewer: entry,
128 views: manifest.views,
129 })
130 }
131
132 pub(super) fn apply(self: &Arc<Self>, artifact: &mut Artifact) -> Result<(), String> {
133 if artifact.kind() == ArtifactKind::Live && (self.info.viewer || self.views.agent_tools.values().any(|tool| {
134 matches!(tool, super::AgentTool::Builtin(tool) if !matches!(tool.builtin, super::Builtin::Graph | super::Builtin::Help | super::Builtin::Open))
135 }) || self.views.human_tools.values().any(|tool| {
136 matches!(tool, super::HumanTool::Builtin(tool) if !matches!(tool.builtin, super::Builtin::Graph | super::Builtin::Help | super::Builtin::Open))
137 })) {
138 return Err("This plugin needs a local Artifact target, not a Live URI.".into());
139 }
140 if matches!(
141 self.viewer,
142 Some(ViewerEntry::Builtin {
143 viewer: BuiltinViewer::Artifactize
144 })
145 ) && !artifact
146 .path
147 .local()
148 .is_some_and(|path| path.starts_with(DEFINITION_DIR))
149 {
150 return Err(
151 "type = \"artifactize\" must target definitions under .artifactize/.".into(),
152 );
153 }
154 inherit(
155 &mut artifact.views.agent_tools,
156 &self.views.agent_tools,
157 "Agent tool",
158 )?;
159 inherit(
160 &mut artifact.views.agent_sessions,
161 &self.views.agent_sessions,
162 "Agent tool session",
163 )?;
164 inherit(
165 &mut artifact.views.human_tools,
166 &self.views.human_tools,
167 "Human tool",
168 )?;
169 artifact.plugin = Some(Arc::clone(self));
170 Ok(())
171 }
172}
173
174fn inherit<T: Clone>(
175 own: &mut BTreeMap<super::ToolOperationName, T>,
176 inherited: &BTreeMap<super::ToolOperationName, T>,
177 kind: &str,
178) -> Result<(), String> {
179 for (name, tool) in inherited {
180 if own.insert(name.clone(), tool.clone()).is_some() {
181 return Err(format!(
182 "{kind} {name} is already provided by the plugin; remove or rename your declaration."
183 ));
184 }
185 }
186 Ok(())
187}
188
189pub(crate) fn read_document(file: File) -> Result<String, String> {
190 if !file
191 .metadata()
192 .map_err(|error| error.to_string())?
193 .is_file()
194 {
195 return Err("Expected a regular text file.".into());
196 }
197 let mut buffer = String::new();
198 file.take(DOCUMENT_BYTES + 1)
199 .read_to_string(&mut buffer)
200 .map_err(|error| error.to_string())?;
201 if buffer.len() as u64 > DOCUMENT_BYTES {
202 return Err("Viewer document exceeds 8 MiB.".into());
203 }
204 Ok(buffer)
205}
206
207fn builtins() -> impl Iterator<Item = Plugin> {
208 BuiltinViewer::MANIFESTS
209 .into_iter()
210 .map(|(viewer, source)| {
211 Plugin::parse(source, Some(viewer), None).expect("embedded plugin manifest")
212 })
213}
214
215fn definitions(root: &Path) -> Result<std::path::PathBuf, ConfigError> {
216 let root = platform::canonicalize(root).map_err(|error| ConfigError::new(root, error))?;
217 let definitions = root.join(DEFINITION_DIR);
218 if !platform::paths::reusable_directory(&root, DEFINITION_DIR)
219 .map_err(|error| ConfigError::new(&definitions, error))?
220 {
221 return Err(ConfigError::new(
222 &definitions,
223 "Not an Artifactize project.",
224 ));
225 }
226 Ok(definitions)
227}
228
229fn read(directory: &Path) -> Result<Plugin, ConfigError> {
230 let manifest = directory.join(MANIFEST);
231 let source = scope::open_scoped(directory, MANIFEST)
232 .map_err(|error| ConfigError::new(&manifest, error))?;
233 let source = read_document(source).map_err(|error| ConfigError::new(&manifest, error))?;
234 Plugin::parse(&source, None, Some(directory))
235 .map_err(|error| ConfigError::new(&manifest, error))
236}
237
238pub(super) fn catalog(
239 root: &Path,
240) -> Result<BTreeMap<super::ArtifactType, Arc<Plugin>>, ConfigError> {
241 let mut plugins: BTreeMap<_, _> = builtins()
242 .map(|plugin| (plugin.info.name.clone(), Arc::new(plugin)))
243 .collect();
244 let parent = root.join(DEFINITION_DIR);
245 let directory = parent.join(DIRECTORY);
246 if !platform::paths::reusable_directory(root, DEFINITION_DIR)
247 .map_err(|error| ConfigError::new(&parent, error))?
248 {
249 return Ok(plugins);
250 }
251 if !platform::paths::reusable_directory(&parent, DIRECTORY)
252 .map_err(|error| ConfigError::new(&directory, error))?
253 {
254 return Ok(plugins);
255 }
256 let opened = platform::open_directory(&directory)
257 .map_err(|error| ConfigError::new(&directory, error))?;
258 for entry in platform::read_dir(&opened).map_err(|error| ConfigError::new(&directory, error))? {
259 let entry = entry.map_err(|error| ConfigError::new(&directory, error))?;
260 let name = entry.file_name();
261 if name.as_encoded_bytes().starts_with(b".") {
262 continue; }
264 let path = directory.join(&name);
265 let kind = entry
266 .file_type()
267 .map_err(|error| ConfigError::new(&path, error))?;
268 if kind == platform::FileKind::File {
269 continue;
270 }
271 if kind != platform::FileKind::Directory {
272 return Err(ConfigError::new(
273 &path,
274 "A plugin must be a real directory, not a link or special file.",
275 ));
276 }
277 let plugin = read(&path)?;
278 if name != plugin.info.name.as_str() {
279 return Err(ConfigError::new(
280 &path,
281 "The directory name must match the plugin's type.",
282 ));
283 }
284 if plugins.contains_key(&plugin.info.name) {
285 return Err(ConfigError::new(
286 &path,
287 "Built-in plugin types are reserved.",
288 ));
289 }
290 plugins.insert(plugin.info.name.clone(), Arc::new(plugin));
291 }
292 Ok(plugins)
293}
294
295pub fn list(root: &Path) -> Result<Vec<PluginInfo>, ConfigError> {
296 let directory = definitions(root)?;
297 catalog(directory.parent().expect("workspace root"))
298 .map(|plugins| plugins.values().map(|plugin| plugin.info.clone()).collect())
299}
300
301pub fn add(root: &Path, source: &Path) -> Result<PluginInfo, ConfigError> {
303 let definitions = definitions(root)?;
304 let directory = definitions.join(DIRECTORY);
305 let source = platform::canonicalize(source).map_err(|error| ConfigError::new(source, error))?;
306 let plugin = read(&source)?;
307 let installed = directory.join(plugin.info.name.as_str());
308 if builtins().any(|builtin| builtin.info.name == plugin.info.name) {
309 return Err(ConfigError::new(
310 &installed,
311 "Built-in plugin types are reserved.",
312 ));
313 }
314 ensure_directory(&definitions, DIRECTORY)
315 .map_err(|error| ConfigError::new(&directory, error))?;
316 if platform::paths::reusable_directory(&directory, plugin.info.name.as_str())
317 .map_err(|error| ConfigError::new(&installed, error))?
318 {
319 return Err(ConfigError::new(
320 &installed,
321 "Plugin already installed; remove it before adding a replacement.",
322 ));
323 }
324 let staged = tempfile::Builder::new()
325 .prefix(".install-")
326 .tempdir_in(&directory)
327 .map_err(|error| ConfigError::new(&directory, error))?;
328 let payload = staged.path().join("plugin");
329 if source.starts_with(&directory) || directory.starts_with(&source) {
330 return Err(ConfigError::new(
331 &source,
332 "The source must be outside the installed plugins directory and cannot contain it.",
333 ));
334 }
335 let source =
336 platform::open_directory(&source).map_err(|error| ConfigError::new(&source, error))?;
337 platform::paths::copy_portable_tree(&source, &payload)
338 .map_err(|error| ConfigError::new(&installed, error))?;
339 let validated = read(&payload)?;
340 if validated.info.name != plugin.info.name {
341 return Err(ConfigError::new(
342 &installed,
343 "Plugin type changed during installation.",
344 ));
345 }
346 platform::paths::rename_open_file(&payload, &installed)
347 .map_err(|error| ConfigError::new(&installed, error))?;
348 Ok(validated.info)
349}
350
351fn ensure_directory(parent: &Path, name: &str) -> std::io::Result<()> {
352 if !platform::paths::reusable_directory(parent, name)? {
353 match std::fs::create_dir(parent.join(name)) {
354 Err(error)
355 if error.kind() == std::io::ErrorKind::AlreadyExists
356 && platform::paths::reusable_directory(parent, name)? =>
357 {
358 Ok(())
359 }
360 result => result,
361 }
362 } else {
363 Ok(())
364 }
365}
366
367pub fn remove(root: &Path, name: &super::ArtifactType) -> Result<(), ConfigError> {
369 let definitions = definitions(root)?;
370 let directory = definitions.join(DIRECTORY);
371 let path = directory.join(name.as_str());
372 if builtins().any(|builtin| builtin.info.name == *name) {
373 return Err(ConfigError::new(
374 &path,
375 "A built-in plugin cannot be removed.",
376 ));
377 }
378 if !platform::paths::reusable_directory(&definitions, DIRECTORY)
379 .and_then(|exists| {
380 if exists {
381 platform::paths::reusable_directory(&directory, name.as_str())
382 } else {
383 Ok(false)
384 }
385 })
386 .map_err(|error| ConfigError::new(&path, error))?
387 {
388 return Err(ConfigError::new(&path, "Plugin is not installed."));
389 }
390 let staged = platform::private_tempdir_in(".remove-", &directory)
391 .map_err(|error| ConfigError::new(&path, error))?;
392 platform::paths::rename_open_file(&path, &staged.path().join("plugin"))
393 .map_err(|error| ConfigError::new(&path, error))?;
394 staged
395 .close()
396 .map_err(|error| ConfigError::new(&path, error))
397}