extension_manifest.rs

  1use anyhow::{Context as _, Result, anyhow, bail};
  2use collections::{BTreeMap, HashMap};
  3use fs::Fs;
  4use language::LanguageName;
  5use lsp::LanguageServerName;
  6use semver::Version;
  7use serde::{Deserialize, Serialize};
  8use std::{
  9    ffi::OsStr,
 10    fmt,
 11    path::{Path, PathBuf},
 12    sync::Arc,
 13};
 14
 15use crate::ExtensionCapability;
 16
 17/// This is the old version of the extension manifest, from when it was `extension.json`.
 18#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
 19pub struct OldExtensionManifest {
 20    pub name: String,
 21    pub version: Arc<str>,
 22
 23    #[serde(default)]
 24    pub description: Option<String>,
 25    #[serde(default)]
 26    pub repository: Option<String>,
 27    #[serde(default)]
 28    pub authors: Vec<String>,
 29
 30    #[serde(default)]
 31    pub themes: BTreeMap<Arc<str>, PathBuf>,
 32    #[serde(default)]
 33    pub languages: BTreeMap<Arc<str>, PathBuf>,
 34    #[serde(default)]
 35    pub grammars: BTreeMap<Arc<str>, PathBuf>,
 36}
 37
 38/// The schema version of the [`ExtensionManifest`].
 39#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
 40pub struct SchemaVersion(pub i32);
 41
 42impl fmt::Display for SchemaVersion {
 43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 44        write!(f, "{}", self.0)
 45    }
 46}
 47
 48impl SchemaVersion {
 49    pub const ZERO: Self = Self(0);
 50
 51    pub fn is_v0(&self) -> bool {
 52        self == &Self::ZERO
 53    }
 54}
 55
 56#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
 57pub struct ExtensionManifest {
 58    pub id: Arc<str>,
 59    pub name: String,
 60    pub version: Arc<str>,
 61    pub schema_version: SchemaVersion,
 62
 63    #[serde(default)]
 64    pub description: Option<String>,
 65    #[serde(default)]
 66    pub repository: Option<String>,
 67    #[serde(default)]
 68    pub authors: Vec<String>,
 69    #[serde(default)]
 70    pub lib: LibManifestEntry,
 71
 72    #[serde(default)]
 73    pub themes: Vec<PathBuf>,
 74    #[serde(default)]
 75    pub icon_themes: Vec<PathBuf>,
 76    #[serde(default)]
 77    pub languages: Vec<PathBuf>,
 78    #[serde(default)]
 79    pub grammars: BTreeMap<Arc<str>, GrammarManifestEntry>,
 80    #[serde(default)]
 81    pub language_servers: BTreeMap<LanguageServerName, LanguageServerManifestEntry>,
 82    #[serde(default)]
 83    pub context_servers: BTreeMap<Arc<str>, ContextServerManifestEntry>,
 84    #[serde(default)]
 85    pub agent_servers: BTreeMap<Arc<str>, AgentServerManifestEntry>,
 86    #[serde(default)]
 87    pub slash_commands: BTreeMap<Arc<str>, SlashCommandManifestEntry>,
 88    #[serde(default)]
 89    pub snippets: Option<PathBuf>,
 90    #[serde(default)]
 91    pub capabilities: Vec<ExtensionCapability>,
 92    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
 93    pub debug_adapters: BTreeMap<Arc<str>, DebugAdapterManifestEntry>,
 94    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
 95    pub debug_locators: BTreeMap<Arc<str>, DebugLocatorManifestEntry>,
 96    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
 97    pub language_model_providers: BTreeMap<Arc<str>, LanguageModelProviderManifestEntry>,
 98}
 99
100impl ExtensionManifest {
101    pub fn allow_exec(
102        &self,
103        desired_command: &str,
104        desired_args: &[impl AsRef<str> + std::fmt::Debug],
105    ) -> Result<()> {
106        let is_allowed = self.capabilities.iter().any(|capability| match capability {
107            ExtensionCapability::ProcessExec(capability) => {
108                capability.allows(desired_command, desired_args)
109            }
110            _ => false,
111        });
112
113        if !is_allowed {
114            bail!(
115                "capability for process:exec {desired_command} {desired_args:?} was not listed in the extension manifest",
116            );
117        }
118
119        Ok(())
120    }
121
122    pub fn allow_remote_load(&self) -> bool {
123        !self.language_servers.is_empty()
124            || !self.debug_adapters.is_empty()
125            || !self.debug_locators.is_empty()
126    }
127}
128
129pub fn build_debug_adapter_schema_path(
130    adapter_name: &Arc<str>,
131    meta: &DebugAdapterManifestEntry,
132) -> PathBuf {
133    meta.schema_path.clone().unwrap_or_else(|| {
134        Path::new("debug_adapter_schemas")
135            .join(Path::new(adapter_name.as_ref()).with_extension("json"))
136    })
137}
138
139#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
140pub struct LibManifestEntry {
141    pub kind: Option<ExtensionLibraryKind>,
142    pub version: Option<Version>,
143}
144
145#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
146pub struct AgentServerManifestEntry {
147    /// Display name for the agent (shown in menus).
148    pub name: String,
149    /// Environment variables to set when launching the agent server.
150    #[serde(default)]
151    pub env: HashMap<String, String>,
152    /// Optional icon path (relative to extension root, e.g., "ai.svg").
153    /// Should be a small SVG icon for display in menus.
154    #[serde(default)]
155    pub icon: Option<String>,
156    /// Per-target configuration for archive-based installation.
157    /// The key format is "{os}-{arch}" where:
158    /// - os: "darwin" (macOS), "linux", "windows"
159    /// - arch: "aarch64" (arm64), "x86_64"
160    ///
161    /// Example:
162    /// ```toml
163    /// [agent_servers.myagent.targets.darwin-aarch64]
164    /// archive = "https://example.com/myagent-darwin-arm64.zip"
165    /// cmd = "./myagent"
166    /// args = ["--serve"]
167    /// sha256 = "abc123..."  # optional
168    /// ```
169    ///
170    /// For Node.js-based agents, you can use "node" as the cmd to automatically
171    /// use Zed's managed Node.js runtime instead of relying on the user's PATH:
172    /// ```toml
173    /// [agent_servers.nodeagent.targets.darwin-aarch64]
174    /// archive = "https://example.com/nodeagent.zip"
175    /// cmd = "node"
176    /// args = ["index.js", "--port", "3000"]
177    /// ```
178    ///
179    /// Note: All commands are executed with the archive extraction directory as the
180    /// working directory, so relative paths in args (like "index.js") will resolve
181    /// relative to the extracted archive contents.
182    pub targets: HashMap<String, TargetConfig>,
183}
184
185#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
186pub struct TargetConfig {
187    /// URL to download the archive from (e.g., "https://github.com/owner/repo/releases/download/v1.0.0/myagent-darwin-arm64.zip")
188    pub archive: String,
189    /// Command to run (e.g., "./myagent" or "./myagent.exe")
190    pub cmd: String,
191    /// Command-line arguments to pass to the agent server.
192    #[serde(default)]
193    pub args: Vec<String>,
194    /// Optional SHA-256 hash of the archive for verification.
195    /// If not provided and the URL is a GitHub release, we'll attempt to fetch it from GitHub.
196    #[serde(default)]
197    pub sha256: Option<String>,
198    /// Environment variables to set when launching the agent server.
199    /// These target-specific env vars will override any env vars set at the agent level.
200    #[serde(default)]
201    pub env: HashMap<String, String>,
202}
203
204impl TargetConfig {
205    pub fn from_proto(proto: proto::ExternalExtensionAgentTarget) -> Self {
206        Self {
207            archive: proto.archive,
208            cmd: proto.cmd,
209            args: proto.args,
210            sha256: proto.sha256,
211            env: proto.env.into_iter().collect(),
212        }
213    }
214
215    pub fn to_proto(&self) -> proto::ExternalExtensionAgentTarget {
216        proto::ExternalExtensionAgentTarget {
217            archive: self.archive.clone(),
218            cmd: self.cmd.clone(),
219            args: self.args.clone(),
220            sha256: self.sha256.clone(),
221            env: self
222                .env
223                .iter()
224                .map(|(k, v)| (k.clone(), v.clone()))
225                .collect(),
226        }
227    }
228}
229
230#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
231pub enum ExtensionLibraryKind {
232    Rust,
233}
234
235#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
236pub struct GrammarManifestEntry {
237    pub repository: String,
238    #[serde(alias = "commit")]
239    pub rev: String,
240    #[serde(default)]
241    pub path: Option<String>,
242}
243
244#[derive(Clone, Default, PartialEq, Eq, Debug, Deserialize, Serialize)]
245pub struct LanguageServerManifestEntry {
246    /// Deprecated in favor of `languages`.
247    #[serde(default)]
248    language: Option<LanguageName>,
249    /// The list of languages this language server should work with.
250    #[serde(default)]
251    languages: Vec<LanguageName>,
252    #[serde(default)]
253    pub language_ids: HashMap<LanguageName, String>,
254    #[serde(default)]
255    pub code_action_kinds: Option<Vec<lsp::CodeActionKind>>,
256}
257
258impl LanguageServerManifestEntry {
259    /// Returns the list of languages for the language server.
260    ///
261    /// Prefer this over accessing the `language` or `languages` fields directly,
262    /// as we currently support both.
263    ///
264    /// We can replace this with just field access for the `languages` field once
265    /// we have removed `language`.
266    pub fn languages(&self) -> impl IntoIterator<Item = LanguageName> + '_ {
267        let language = if self.languages.is_empty() {
268            self.language.clone()
269        } else {
270            None
271        };
272        self.languages.iter().cloned().chain(language)
273    }
274}
275
276#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
277pub struct ContextServerManifestEntry {}
278
279#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
280pub struct SlashCommandManifestEntry {
281    pub description: String,
282    pub requires_argument: bool,
283}
284
285#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
286pub struct DebugAdapterManifestEntry {
287    pub schema_path: Option<PathBuf>,
288}
289
290#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
291pub struct DebugLocatorManifestEntry {}
292
293/// Manifest entry for a language model provider.
294#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
295pub struct LanguageModelProviderManifestEntry {
296    /// Display name for the provider.
297    pub name: String,
298    /// Icon name from Zed's icon set (optional).
299    #[serde(default)]
300    pub icon: Option<String>,
301    /// Default models to show even before API connection.
302    #[serde(default)]
303    pub models: Vec<LanguageModelManifestEntry>,
304    /// Authentication configuration.
305    #[serde(default)]
306    pub auth: Option<LanguageModelAuthConfig>,
307}
308
309/// Manifest entry for a language model.
310#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
311pub struct LanguageModelManifestEntry {
312    /// Unique identifier for the model.
313    pub id: String,
314    /// Display name for the model.
315    pub name: String,
316    /// Maximum input token count.
317    #[serde(default)]
318    pub max_token_count: u64,
319    /// Maximum output tokens (optional).
320    #[serde(default)]
321    pub max_output_tokens: Option<u64>,
322    /// Whether the model supports image inputs.
323    #[serde(default)]
324    pub supports_images: bool,
325    /// Whether the model supports tool/function calling.
326    #[serde(default)]
327    pub supports_tools: bool,
328    /// Whether the model supports extended thinking/reasoning.
329    #[serde(default)]
330    pub supports_thinking: bool,
331}
332
333/// Authentication configuration for a language model provider.
334#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
335pub struct LanguageModelAuthConfig {
336    /// Environment variable name for the API key.
337    #[serde(default)]
338    pub env_var: Option<String>,
339    /// Human-readable name for the credential shown in the UI input field (e.g., "API Key", "Access Token").
340    #[serde(default)]
341    pub credential_label: Option<String>,
342}
343
344impl ExtensionManifest {
345    pub async fn load(fs: Arc<dyn Fs>, extension_dir: &Path) -> Result<Self> {
346        let extension_name = extension_dir
347            .file_name()
348            .and_then(OsStr::to_str)
349            .context("invalid extension name")?;
350
351        let extension_manifest_path = extension_dir.join("extension.toml");
352        if fs.is_file(&extension_manifest_path).await {
353            let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
354                format!("loading {extension_name} extension.toml, {extension_manifest_path:?}")
355            })?;
356            toml::from_str(&manifest_content).map_err(|err| {
357                anyhow!("Invalid extension.toml for extension {extension_name}:\n{err}")
358            })
359        } else if let extension_manifest_path = extension_manifest_path.with_extension("json")
360            && fs.is_file(&extension_manifest_path).await
361        {
362            let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
363                format!("loading {extension_name} extension.json, {extension_manifest_path:?}")
364            })?;
365
366            serde_json::from_str::<OldExtensionManifest>(&manifest_content)
367                .with_context(|| format!("invalid extension.json for extension {extension_name}"))
368                .map(|manifest_json| manifest_from_old_manifest(manifest_json, extension_name))
369        } else {
370            anyhow::bail!("No extension manifest found for extension {extension_name}")
371        }
372    }
373}
374
375fn manifest_from_old_manifest(
376    manifest_json: OldExtensionManifest,
377    extension_id: &str,
378) -> ExtensionManifest {
379    ExtensionManifest {
380        id: extension_id.into(),
381        name: manifest_json.name,
382        version: manifest_json.version,
383        description: manifest_json.description,
384        repository: manifest_json.repository,
385        authors: manifest_json.authors,
386        schema_version: SchemaVersion::ZERO,
387        lib: Default::default(),
388        themes: {
389            let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
390            themes.sort();
391            themes.dedup();
392            themes
393        },
394        icon_themes: Vec::new(),
395        languages: {
396            let mut languages = manifest_json.languages.into_values().collect::<Vec<_>>();
397            languages.sort();
398            languages.dedup();
399            languages
400        },
401        grammars: manifest_json
402            .grammars
403            .into_keys()
404            .map(|grammar_name| (grammar_name, Default::default()))
405            .collect(),
406        language_servers: Default::default(),
407        context_servers: BTreeMap::default(),
408        agent_servers: BTreeMap::default(),
409        slash_commands: BTreeMap::default(),
410        snippets: None,
411        capabilities: Vec::new(),
412        debug_adapters: Default::default(),
413        debug_locators: Default::default(),
414        language_model_providers: Default::default(),
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use pretty_assertions::assert_eq;
421
422    use crate::ProcessExecCapability;
423
424    use super::*;
425
426    fn extension_manifest() -> ExtensionManifest {
427        ExtensionManifest {
428            id: "test".into(),
429            name: "Test".to_string(),
430            version: "1.0.0".into(),
431            schema_version: SchemaVersion::ZERO,
432            description: None,
433            repository: None,
434            authors: vec![],
435            lib: Default::default(),
436            themes: vec![],
437            icon_themes: vec![],
438            languages: vec![],
439            grammars: BTreeMap::default(),
440            language_servers: BTreeMap::default(),
441            context_servers: BTreeMap::default(),
442            agent_servers: BTreeMap::default(),
443            slash_commands: BTreeMap::default(),
444            snippets: None,
445            capabilities: vec![],
446            debug_adapters: Default::default(),
447            debug_locators: Default::default(),
448            language_model_providers: BTreeMap::default(),
449        }
450    }
451
452    #[test]
453    fn test_build_adapter_schema_path_with_schema_path() {
454        let adapter_name = Arc::from("my_adapter");
455        let entry = DebugAdapterManifestEntry {
456            schema_path: Some(PathBuf::from("foo/bar")),
457        };
458
459        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
460        assert_eq!(path, PathBuf::from("foo/bar"));
461    }
462
463    #[test]
464    fn test_build_adapter_schema_path_without_schema_path() {
465        let adapter_name = Arc::from("my_adapter");
466        let entry = DebugAdapterManifestEntry { schema_path: None };
467
468        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
469        assert_eq!(
470            path,
471            PathBuf::from("debug_adapter_schemas").join("my_adapter.json")
472        );
473    }
474
475    #[test]
476    fn test_allow_exec_exact_match() {
477        let manifest = ExtensionManifest {
478            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
479                command: "ls".to_string(),
480                args: vec!["-la".to_string()],
481            })],
482            ..extension_manifest()
483        };
484
485        assert!(manifest.allow_exec("ls", &["-la"]).is_ok());
486        assert!(manifest.allow_exec("ls", &["-l"]).is_err());
487        assert!(manifest.allow_exec("pwd", &[] as &[&str]).is_err());
488    }
489
490    #[test]
491    fn test_allow_exec_wildcard_arg() {
492        let manifest = ExtensionManifest {
493            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
494                command: "git".to_string(),
495                args: vec!["*".to_string()],
496            })],
497            ..extension_manifest()
498        };
499
500        assert!(manifest.allow_exec("git", &["status"]).is_ok());
501        assert!(manifest.allow_exec("git", &["commit"]).is_ok());
502        assert!(manifest.allow_exec("git", &["status", "-s"]).is_err()); // too many args
503        assert!(manifest.allow_exec("npm", &["install"]).is_err()); // wrong command
504    }
505
506    #[test]
507    fn test_allow_exec_double_wildcard() {
508        let manifest = ExtensionManifest {
509            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
510                command: "cargo".to_string(),
511                args: vec!["test".to_string(), "**".to_string()],
512            })],
513            ..extension_manifest()
514        };
515
516        assert!(manifest.allow_exec("cargo", &["test"]).is_ok());
517        assert!(manifest.allow_exec("cargo", &["test", "--all"]).is_ok());
518        assert!(
519            manifest
520                .allow_exec("cargo", &["test", "--all", "--no-fail-fast"])
521                .is_ok()
522        );
523        assert!(manifest.allow_exec("cargo", &["build"]).is_err()); // wrong first arg
524    }
525
526    #[test]
527    fn test_allow_exec_mixed_wildcards() {
528        let manifest = ExtensionManifest {
529            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
530                command: "docker".to_string(),
531                args: vec!["run".to_string(), "*".to_string(), "**".to_string()],
532            })],
533            ..extension_manifest()
534        };
535
536        assert!(manifest.allow_exec("docker", &["run", "nginx"]).is_ok());
537        assert!(manifest.allow_exec("docker", &["run"]).is_err());
538        assert!(
539            manifest
540                .allow_exec("docker", &["run", "ubuntu", "bash"])
541                .is_ok()
542        );
543        assert!(
544            manifest
545                .allow_exec("docker", &["run", "alpine", "sh", "-c", "echo hello"])
546                .is_ok()
547        );
548        assert!(manifest.allow_exec("docker", &["ps"]).is_err()); // wrong first arg
549    }
550    #[test]
551    fn parse_manifest_with_agent_server_archive_launcher() {
552        let toml_src = r#"
553id = "example.agent-server-ext"
554name = "Agent Server Example"
555version = "1.0.0"
556schema_version = 0
557
558[agent_servers.foo]
559name = "Foo Agent"
560
561[agent_servers.foo.targets.linux-x86_64]
562archive = "https://example.com/agent-linux-x64.tar.gz"
563cmd = "./agent"
564args = ["--serve"]
565"#;
566
567        let manifest: ExtensionManifest = toml::from_str(toml_src).expect("manifest should parse");
568        assert_eq!(manifest.id.as_ref(), "example.agent-server-ext");
569        assert!(manifest.agent_servers.contains_key("foo"));
570        let entry = manifest.agent_servers.get("foo").unwrap();
571        assert!(entry.targets.contains_key("linux-x86_64"));
572        let target = entry.targets.get("linux-x86_64").unwrap();
573        assert_eq!(target.archive, "https://example.com/agent-linux-x64.tar.gz");
574        assert_eq!(target.cmd, "./agent");
575        assert_eq!(target.args, vec!["--serve"]);
576    }
577}