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