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    /// Path to an SVG icon file relative to the extension root (e.g., "icons/provider.svg").
299    #[serde(default)]
300    pub icon: Option<String>,
301    /// Hardcoded models to always show (as opposed to a model list loaded over the network).
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    pub max_token_count: u64,
318    /// Maximum output tokens (optional).
319    pub max_output_tokens: Option<u64>,
320    /// Whether the model supports image inputs.
321    pub supports_images: bool,
322    /// Whether the model supports tool/function calling.
323    pub supports_tools: bool,
324    /// Whether the model supports extended thinking/reasoning.
325    pub supports_thinking: bool,
326}
327
328/// Authentication configuration for a language model provider.
329#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
330pub struct LanguageModelAuthConfig {
331    /// Human-readable name for the credential shown in the UI input field (e.g. "API Key", "Access Token").
332    pub credential_label: Option<String>,
333    /// Environment variable names for the API key (if env var auth supported).
334    /// Multiple env vars can be specified; they will be checked in order.
335    #[serde(default)]
336    pub env_vars: Option<Vec<String>>,
337    /// OAuth configuration for web-based authentication flows.
338    #[serde(default)]
339    pub oauth: Option<OAuthConfig>,
340}
341
342/// OAuth configuration for web-based authentication.
343#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
344pub struct OAuthConfig {
345    /// The text to display on the sign-in button (e.g. "Sign in with GitHub").
346    pub sign_in_button_label: Option<String>,
347    /// The Zed icon path to display on the sign-in button (e.g. "github").
348    #[serde(default)]
349    pub sign_in_button_icon: Option<String>,
350}
351
352impl ExtensionManifest {
353    pub async fn load(fs: Arc<dyn Fs>, extension_dir: &Path) -> Result<Self> {
354        let extension_name = extension_dir
355            .file_name()
356            .and_then(OsStr::to_str)
357            .context("invalid extension name")?;
358
359        let extension_manifest_path = extension_dir.join("extension.toml");
360        if fs.is_file(&extension_manifest_path).await {
361            let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
362                format!("loading {extension_name} extension.toml, {extension_manifest_path:?}")
363            })?;
364            toml::from_str(&manifest_content).map_err(|err| {
365                anyhow!("Invalid extension.toml for extension {extension_name}:\n{err}")
366            })
367        } else if let extension_manifest_path = extension_manifest_path.with_extension("json")
368            && fs.is_file(&extension_manifest_path).await
369        {
370            let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
371                format!("loading {extension_name} extension.json, {extension_manifest_path:?}")
372            })?;
373
374            serde_json::from_str::<OldExtensionManifest>(&manifest_content)
375                .with_context(|| format!("invalid extension.json for extension {extension_name}"))
376                .map(|manifest_json| manifest_from_old_manifest(manifest_json, extension_name))
377        } else {
378            anyhow::bail!("No extension manifest found for extension {extension_name}")
379        }
380    }
381}
382
383fn manifest_from_old_manifest(
384    manifest_json: OldExtensionManifest,
385    extension_id: &str,
386) -> ExtensionManifest {
387    ExtensionManifest {
388        id: extension_id.into(),
389        name: manifest_json.name,
390        version: manifest_json.version,
391        description: manifest_json.description,
392        repository: manifest_json.repository,
393        authors: manifest_json.authors,
394        schema_version: SchemaVersion::ZERO,
395        lib: Default::default(),
396        themes: {
397            let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
398            themes.sort();
399            themes.dedup();
400            themes
401        },
402        icon_themes: Vec::new(),
403        languages: {
404            let mut languages = manifest_json.languages.into_values().collect::<Vec<_>>();
405            languages.sort();
406            languages.dedup();
407            languages
408        },
409        grammars: manifest_json
410            .grammars
411            .into_keys()
412            .map(|grammar_name| (grammar_name, Default::default()))
413            .collect(),
414        language_servers: Default::default(),
415        context_servers: BTreeMap::default(),
416        agent_servers: BTreeMap::default(),
417        slash_commands: BTreeMap::default(),
418        snippets: None,
419        capabilities: Vec::new(),
420        debug_adapters: Default::default(),
421        debug_locators: Default::default(),
422        language_model_providers: Default::default(),
423    }
424}
425
426#[cfg(test)]
427mod tests {
428    use pretty_assertions::assert_eq;
429
430    use crate::ProcessExecCapability;
431
432    use super::*;
433
434    fn extension_manifest() -> ExtensionManifest {
435        ExtensionManifest {
436            id: "test".into(),
437            name: "Test".to_string(),
438            version: "1.0.0".into(),
439            schema_version: SchemaVersion::ZERO,
440            description: None,
441            repository: None,
442            authors: vec![],
443            lib: Default::default(),
444            themes: vec![],
445            icon_themes: vec![],
446            languages: vec![],
447            grammars: BTreeMap::default(),
448            language_servers: BTreeMap::default(),
449            context_servers: BTreeMap::default(),
450            agent_servers: BTreeMap::default(),
451            slash_commands: BTreeMap::default(),
452            snippets: None,
453            capabilities: vec![],
454            debug_adapters: Default::default(),
455            debug_locators: Default::default(),
456            language_model_providers: BTreeMap::default(),
457        }
458    }
459
460    #[test]
461    fn test_build_adapter_schema_path_with_schema_path() {
462        let adapter_name = Arc::from("my_adapter");
463        let entry = DebugAdapterManifestEntry {
464            schema_path: Some(PathBuf::from("foo/bar")),
465        };
466
467        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
468        assert_eq!(path, PathBuf::from("foo/bar"));
469    }
470
471    #[test]
472    fn test_build_adapter_schema_path_without_schema_path() {
473        let adapter_name = Arc::from("my_adapter");
474        let entry = DebugAdapterManifestEntry { schema_path: None };
475
476        let path = build_debug_adapter_schema_path(&adapter_name, &entry);
477        assert_eq!(
478            path,
479            PathBuf::from("debug_adapter_schemas").join("my_adapter.json")
480        );
481    }
482
483    #[test]
484    fn test_allow_exec_exact_match() {
485        let manifest = ExtensionManifest {
486            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
487                command: "ls".to_string(),
488                args: vec!["-la".to_string()],
489            })],
490            ..extension_manifest()
491        };
492
493        assert!(manifest.allow_exec("ls", &["-la"]).is_ok());
494        assert!(manifest.allow_exec("ls", &["-l"]).is_err());
495        assert!(manifest.allow_exec("pwd", &[] as &[&str]).is_err());
496    }
497
498    #[test]
499    fn test_allow_exec_wildcard_arg() {
500        let manifest = ExtensionManifest {
501            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
502                command: "git".to_string(),
503                args: vec!["*".to_string()],
504            })],
505            ..extension_manifest()
506        };
507
508        assert!(manifest.allow_exec("git", &["status"]).is_ok());
509        assert!(manifest.allow_exec("git", &["commit"]).is_ok());
510        assert!(manifest.allow_exec("git", &["status", "-s"]).is_err()); // too many args
511        assert!(manifest.allow_exec("npm", &["install"]).is_err()); // wrong command
512    }
513
514    #[test]
515    fn test_allow_exec_double_wildcard() {
516        let manifest = ExtensionManifest {
517            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
518                command: "cargo".to_string(),
519                args: vec!["test".to_string(), "**".to_string()],
520            })],
521            ..extension_manifest()
522        };
523
524        assert!(manifest.allow_exec("cargo", &["test"]).is_ok());
525        assert!(manifest.allow_exec("cargo", &["test", "--all"]).is_ok());
526        assert!(
527            manifest
528                .allow_exec("cargo", &["test", "--all", "--no-fail-fast"])
529                .is_ok()
530        );
531        assert!(manifest.allow_exec("cargo", &["build"]).is_err()); // wrong first arg
532    }
533
534    #[test]
535    fn test_allow_exec_mixed_wildcards() {
536        let manifest = ExtensionManifest {
537            capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
538                command: "docker".to_string(),
539                args: vec!["run".to_string(), "*".to_string(), "**".to_string()],
540            })],
541            ..extension_manifest()
542        };
543
544        assert!(manifest.allow_exec("docker", &["run", "nginx"]).is_ok());
545        assert!(manifest.allow_exec("docker", &["run"]).is_err());
546        assert!(
547            manifest
548                .allow_exec("docker", &["run", "ubuntu", "bash"])
549                .is_ok()
550        );
551        assert!(
552            manifest
553                .allow_exec("docker", &["run", "alpine", "sh", "-c", "echo hello"])
554                .is_ok()
555        );
556        assert!(manifest.allow_exec("docker", &["ps"]).is_err()); // wrong first arg
557    }
558    #[test]
559    fn parse_manifest_with_agent_server_archive_launcher() {
560        let toml_src = r#"
561id = "example.agent-server-ext"
562name = "Agent Server Example"
563version = "1.0.0"
564schema_version = 0
565
566[agent_servers.foo]
567name = "Foo Agent"
568
569[agent_servers.foo.targets.linux-x86_64]
570archive = "https://example.com/agent-linux-x64.tar.gz"
571cmd = "./agent"
572args = ["--serve"]
573"#;
574
575        let manifest: ExtensionManifest = toml::from_str(toml_src).expect("manifest should parse");
576        assert_eq!(manifest.id.as_ref(), "example.agent-server-ext");
577        assert!(manifest.agent_servers.contains_key("foo"));
578        let entry = manifest.agent_servers.get("foo").unwrap();
579        assert!(entry.targets.contains_key("linux-x86_64"));
580        let target = entry.targets.get("linux-x86_64").unwrap();
581        assert_eq!(target.archive, "https://example.com/agent-linux-x64.tar.gz");
582        assert_eq!(target.cmd, "./agent");
583        assert_eq!(target.args, vec!["--serve"]);
584    }
585}