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}
302
303impl ExtensionManifest {
304 pub async fn load(fs: Arc<dyn Fs>, extension_dir: &Path) -> Result<Self> {
305 let extension_name = extension_dir
306 .file_name()
307 .and_then(OsStr::to_str)
308 .context("invalid extension name")?;
309
310 let extension_manifest_path = extension_dir.join("extension.toml");
311 if fs.is_file(&extension_manifest_path).await {
312 let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
313 format!("loading {extension_name} extension.toml, {extension_manifest_path:?}")
314 })?;
315 toml::from_str(&manifest_content).map_err(|err| {
316 anyhow!("Invalid extension.toml for extension {extension_name}:\n{err}")
317 })
318 } else if let extension_manifest_path = extension_manifest_path.with_extension("json")
319 && fs.is_file(&extension_manifest_path).await
320 {
321 let manifest_content = fs.load(&extension_manifest_path).await.with_context(|| {
322 format!("loading {extension_name} extension.json, {extension_manifest_path:?}")
323 })?;
324
325 serde_json::from_str::<OldExtensionManifest>(&manifest_content)
326 .with_context(|| format!("invalid extension.json for extension {extension_name}"))
327 .map(|manifest_json| manifest_from_old_manifest(manifest_json, extension_name))
328 } else {
329 anyhow::bail!("No extension manifest found for extension {extension_name}")
330 }
331 }
332}
333
334fn manifest_from_old_manifest(
335 manifest_json: OldExtensionManifest,
336 extension_id: &str,
337) -> ExtensionManifest {
338 ExtensionManifest {
339 id: extension_id.into(),
340 name: manifest_json.name,
341 version: manifest_json.version,
342 description: manifest_json.description,
343 repository: manifest_json.repository,
344 authors: manifest_json.authors,
345 schema_version: SchemaVersion::ZERO,
346 lib: Default::default(),
347 themes: {
348 let mut themes = manifest_json.themes.into_values().collect::<Vec<_>>();
349 themes.sort();
350 themes.dedup();
351 themes
352 },
353 icon_themes: Vec::new(),
354 languages: {
355 let mut languages = manifest_json.languages.into_values().collect::<Vec<_>>();
356 languages.sort();
357 languages.dedup();
358 languages
359 },
360 grammars: manifest_json
361 .grammars
362 .into_keys()
363 .map(|grammar_name| (grammar_name, Default::default()))
364 .collect(),
365 language_servers: Default::default(),
366 context_servers: BTreeMap::default(),
367 agent_servers: BTreeMap::default(),
368 slash_commands: BTreeMap::default(),
369 snippets: None,
370 capabilities: Vec::new(),
371 debug_adapters: Default::default(),
372 debug_locators: Default::default(),
373 language_model_providers: Default::default(),
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use pretty_assertions::assert_eq;
380
381 use crate::ProcessExecCapability;
382
383 use super::*;
384
385 fn extension_manifest() -> ExtensionManifest {
386 ExtensionManifest {
387 id: "test".into(),
388 name: "Test".to_string(),
389 version: "1.0.0".into(),
390 schema_version: SchemaVersion::ZERO,
391 description: None,
392 repository: None,
393 authors: vec![],
394 lib: Default::default(),
395 themes: vec![],
396 icon_themes: vec![],
397 languages: vec![],
398 grammars: BTreeMap::default(),
399 language_servers: BTreeMap::default(),
400 context_servers: BTreeMap::default(),
401 agent_servers: BTreeMap::default(),
402 slash_commands: BTreeMap::default(),
403 snippets: None,
404 capabilities: vec![],
405 debug_adapters: Default::default(),
406 debug_locators: Default::default(),
407 language_model_providers: BTreeMap::default(),
408 }
409 }
410
411 #[test]
412 fn test_build_adapter_schema_path_with_schema_path() {
413 let adapter_name = Arc::from("my_adapter");
414 let entry = DebugAdapterManifestEntry {
415 schema_path: Some(PathBuf::from("foo/bar")),
416 };
417
418 let path = build_debug_adapter_schema_path(&adapter_name, &entry);
419 assert_eq!(path, PathBuf::from("foo/bar"));
420 }
421
422 #[test]
423 fn test_build_adapter_schema_path_without_schema_path() {
424 let adapter_name = Arc::from("my_adapter");
425 let entry = DebugAdapterManifestEntry { schema_path: None };
426
427 let path = build_debug_adapter_schema_path(&adapter_name, &entry);
428 assert_eq!(
429 path,
430 PathBuf::from("debug_adapter_schemas").join("my_adapter.json")
431 );
432 }
433
434 #[test]
435 fn test_allow_exec_exact_match() {
436 let manifest = ExtensionManifest {
437 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
438 command: "ls".to_string(),
439 args: vec!["-la".to_string()],
440 })],
441 ..extension_manifest()
442 };
443
444 assert!(manifest.allow_exec("ls", &["-la"]).is_ok());
445 assert!(manifest.allow_exec("ls", &["-l"]).is_err());
446 assert!(manifest.allow_exec("pwd", &[] as &[&str]).is_err());
447 }
448
449 #[test]
450 fn test_allow_exec_wildcard_arg() {
451 let manifest = ExtensionManifest {
452 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
453 command: "git".to_string(),
454 args: vec!["*".to_string()],
455 })],
456 ..extension_manifest()
457 };
458
459 assert!(manifest.allow_exec("git", &["status"]).is_ok());
460 assert!(manifest.allow_exec("git", &["commit"]).is_ok());
461 assert!(manifest.allow_exec("git", &["status", "-s"]).is_err()); // too many args
462 assert!(manifest.allow_exec("npm", &["install"]).is_err()); // wrong command
463 }
464
465 #[test]
466 fn test_allow_exec_double_wildcard() {
467 let manifest = ExtensionManifest {
468 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
469 command: "cargo".to_string(),
470 args: vec!["test".to_string(), "**".to_string()],
471 })],
472 ..extension_manifest()
473 };
474
475 assert!(manifest.allow_exec("cargo", &["test"]).is_ok());
476 assert!(manifest.allow_exec("cargo", &["test", "--all"]).is_ok());
477 assert!(
478 manifest
479 .allow_exec("cargo", &["test", "--all", "--no-fail-fast"])
480 .is_ok()
481 );
482 assert!(manifest.allow_exec("cargo", &["build"]).is_err()); // wrong first arg
483 }
484
485 #[test]
486 fn test_allow_exec_mixed_wildcards() {
487 let manifest = ExtensionManifest {
488 capabilities: vec![ExtensionCapability::ProcessExec(ProcessExecCapability {
489 command: "docker".to_string(),
490 args: vec!["run".to_string(), "*".to_string(), "**".to_string()],
491 })],
492 ..extension_manifest()
493 };
494
495 assert!(manifest.allow_exec("docker", &["run", "nginx"]).is_ok());
496 assert!(manifest.allow_exec("docker", &["run"]).is_err());
497 assert!(
498 manifest
499 .allow_exec("docker", &["run", "ubuntu", "bash"])
500 .is_ok()
501 );
502 assert!(
503 manifest
504 .allow_exec("docker", &["run", "alpine", "sh", "-c", "echo hello"])
505 .is_ok()
506 );
507 assert!(manifest.allow_exec("docker", &["ps"]).is_err()); // wrong first arg
508 }
509 #[test]
510 fn parse_manifest_with_agent_server_archive_launcher() {
511 let toml_src = r#"
512id = "example.agent-server-ext"
513name = "Agent Server Example"
514version = "1.0.0"
515schema_version = 0
516
517[agent_servers.foo]
518name = "Foo Agent"
519
520[agent_servers.foo.targets.linux-x86_64]
521archive = "https://example.com/agent-linux-x64.tar.gz"
522cmd = "./agent"
523args = ["--serve"]
524"#;
525
526 let manifest: ExtensionManifest = toml::from_str(toml_src).expect("manifest should parse");
527 assert_eq!(manifest.id.as_ref(), "example.agent-server-ext");
528 assert!(manifest.agent_servers.contains_key("foo"));
529 let entry = manifest.agent_servers.get("foo").unwrap();
530 assert!(entry.targets.contains_key("linux-x86_64"));
531 let target = entry.targets.get("linux-x86_64").unwrap();
532 assert_eq!(target.archive, "https://example.com/agent-linux-x64.tar.gz");
533 assert_eq!(target.cmd, "./agent");
534 assert_eq!(target.args, vec!["--serve"]);
535 }
536}