extension_manifest.rs

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