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