1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4
5use anyhow::{Context as _, Result, bail};
6use collections::HashMap;
7use fs::Fs;
8use futures::AsyncReadExt;
9use gpui::{App, AppContext as _, Context, Entity, Global, SharedString, Task};
10use http_client::{AsyncBody, HttpClient};
11use serde::Deserialize;
12use settings::Settings as _;
13
14use crate::DisableAiSettings;
15
16const REGISTRY_URL: &str = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
17const REFRESH_THROTTLE_DURATION: Duration = Duration::from_secs(60 * 60);
18
19#[derive(Clone, Debug)]
20pub struct RegistryAgentMetadata {
21 pub id: SharedString,
22 pub name: SharedString,
23 pub description: SharedString,
24 pub version: SharedString,
25 pub repository: Option<SharedString>,
26 pub icon_path: Option<SharedString>,
27}
28
29#[derive(Clone, Debug)]
30pub struct RegistryBinaryAgent {
31 pub metadata: RegistryAgentMetadata,
32 pub targets: HashMap<String, RegistryTargetConfig>,
33 pub supports_current_platform: bool,
34}
35
36#[derive(Clone, Debug)]
37pub struct RegistryNpxAgent {
38 pub metadata: RegistryAgentMetadata,
39 pub package: SharedString,
40 pub args: Vec<String>,
41 pub env: HashMap<String, String>,
42}
43
44#[derive(Clone, Debug)]
45pub enum RegistryAgent {
46 Binary(RegistryBinaryAgent),
47 Npx(RegistryNpxAgent),
48}
49
50impl RegistryAgent {
51 pub fn metadata(&self) -> &RegistryAgentMetadata {
52 match self {
53 RegistryAgent::Binary(agent) => &agent.metadata,
54 RegistryAgent::Npx(agent) => &agent.metadata,
55 }
56 }
57
58 pub fn id(&self) -> &SharedString {
59 &self.metadata().id
60 }
61
62 pub fn name(&self) -> &SharedString {
63 &self.metadata().name
64 }
65
66 pub fn description(&self) -> &SharedString {
67 &self.metadata().description
68 }
69
70 pub fn version(&self) -> &SharedString {
71 &self.metadata().version
72 }
73
74 pub fn repository(&self) -> Option<&SharedString> {
75 self.metadata().repository.as_ref()
76 }
77
78 pub fn icon_path(&self) -> Option<&SharedString> {
79 self.metadata().icon_path.as_ref()
80 }
81
82 pub fn supports_current_platform(&self) -> bool {
83 match self {
84 RegistryAgent::Binary(agent) => agent.supports_current_platform,
85 RegistryAgent::Npx(_) => true,
86 }
87 }
88}
89
90#[derive(Clone, Debug)]
91pub struct RegistryTargetConfig {
92 pub archive: String,
93 pub cmd: String,
94 pub args: Vec<String>,
95 pub sha256: Option<String>,
96 pub env: HashMap<String, String>,
97}
98
99struct GlobalAgentRegistryStore(Entity<AgentRegistryStore>);
100
101impl Global for GlobalAgentRegistryStore {}
102
103pub struct AgentRegistryStore {
104 fs: Arc<dyn Fs>,
105 http_client: Arc<dyn HttpClient>,
106 agents: Vec<RegistryAgent>,
107 is_fetching: bool,
108 fetch_error: Option<SharedString>,
109 pending_refresh: Option<Task<()>>,
110 last_refresh: Option<Instant>,
111}
112
113impl AgentRegistryStore {
114 /// Initialize the global AgentRegistryStore.
115 ///
116 /// This loads the cached registry from disk. If the cache is empty but there
117 /// are registry agents configured in settings, it will trigger a network fetch.
118 /// Otherwise, call `refresh()` explicitly when you need fresh data
119 /// (e.g., when opening the Agent Registry page).
120 pub fn init_global(
121 cx: &mut App,
122 fs: Arc<dyn Fs>,
123 http_client: Arc<dyn HttpClient>,
124 ) -> Entity<Self> {
125 if let Some(store) = Self::try_global(cx) {
126 return store;
127 }
128
129 let store = cx.new(|cx| Self::new(fs, http_client, cx));
130 cx.set_global(GlobalAgentRegistryStore(store.clone()));
131
132 store.update(cx, |store, cx| {
133 if store.agents.is_empty() {
134 store.refresh(cx);
135 }
136 });
137
138 store
139 }
140
141 pub fn global(cx: &App) -> Entity<Self> {
142 cx.global::<GlobalAgentRegistryStore>().0.clone()
143 }
144
145 pub fn try_global(cx: &App) -> Option<Entity<Self>> {
146 cx.try_global::<GlobalAgentRegistryStore>()
147 .map(|store| store.0.clone())
148 }
149
150 pub fn agents(&self) -> &[RegistryAgent] {
151 &self.agents
152 }
153
154 pub fn agent(&self, id: &str) -> Option<&RegistryAgent> {
155 self.agents.iter().find(|agent| agent.id().as_ref() == id)
156 }
157
158 pub fn is_fetching(&self) -> bool {
159 self.is_fetching
160 }
161
162 pub fn fetch_error(&self) -> Option<SharedString> {
163 self.fetch_error.clone()
164 }
165
166 /// Refresh the registry from the network.
167 ///
168 /// This will fetch the latest registry data and update the cache.
169 pub fn refresh(&mut self, cx: &mut Context<Self>) {
170 if self.pending_refresh.is_some() {
171 return;
172 }
173
174 if DisableAiSettings::get_global(cx).disable_ai {
175 return;
176 }
177
178 self.is_fetching = true;
179 self.fetch_error = None;
180 self.last_refresh = Some(Instant::now());
181 cx.notify();
182
183 let fs = self.fs.clone();
184 let http_client = self.http_client.clone();
185
186 self.pending_refresh = Some(cx.spawn(async move |this, cx| {
187 let result = match fetch_registry_index(http_client.clone()).await {
188 Ok(data) => {
189 build_registry_agents(fs.clone(), http_client, data.index, data.raw_body, true)
190 .await
191 }
192 Err(error) => {
193 log::error!("AgentRegistryStore::refresh: fetch failed: {error:#}");
194 Err(error)
195 }
196 };
197
198 this.update(cx, |this, cx| {
199 this.pending_refresh = None;
200 this.is_fetching = false;
201 match result {
202 Ok(agents) => {
203 this.agents = agents;
204 this.fetch_error = None;
205 }
206 Err(error) => {
207 this.fetch_error = Some(SharedString::from(error.to_string()));
208 }
209 }
210 cx.notify();
211 })
212 .ok();
213 }));
214 }
215
216 /// Refresh the registry if it hasn't been refreshed recently.
217 ///
218 /// This is useful to call when using a registry-based agent to check for
219 /// updates without making too many network requests. The refresh is
220 /// throttled to at most once per hour.
221 pub fn refresh_if_stale(&mut self, cx: &mut Context<Self>) {
222 let should_refresh = self
223 .last_refresh
224 .map(|last| last.elapsed() >= REFRESH_THROTTLE_DURATION)
225 .unwrap_or(true);
226
227 if should_refresh {
228 self.refresh(cx);
229 }
230 }
231
232 fn new(fs: Arc<dyn Fs>, http_client: Arc<dyn HttpClient>, cx: &mut Context<Self>) -> Self {
233 let mut store = Self {
234 fs: fs.clone(),
235 http_client,
236 agents: Vec::new(),
237 is_fetching: false,
238 fetch_error: None,
239 pending_refresh: None,
240 last_refresh: None,
241 };
242
243 store.load_cached_registry(fs, store.http_client.clone(), cx);
244
245 store
246 }
247
248 fn load_cached_registry(
249 &mut self,
250 fs: Arc<dyn Fs>,
251 http_client: Arc<dyn HttpClient>,
252 cx: &mut Context<Self>,
253 ) {
254 if DisableAiSettings::get_global(cx).disable_ai {
255 return;
256 }
257
258 cx.spawn(async move |this, cx| -> Result<()> {
259 let cache_path = registry_cache_path();
260 if !fs.is_file(&cache_path).await {
261 return Ok(());
262 }
263
264 let bytes = fs
265 .load_bytes(&cache_path)
266 .await
267 .context("reading cached registry")?;
268 let index: RegistryIndex =
269 serde_json::from_slice(&bytes).context("parsing cached registry")?;
270
271 let agents = build_registry_agents(fs, http_client, index, bytes, false).await?;
272
273 this.update(cx, |this, cx| {
274 this.agents = agents;
275 cx.notify();
276 })?;
277
278 Ok(())
279 })
280 .detach_and_log_err(cx);
281 }
282}
283
284struct RegistryFetchResult {
285 index: RegistryIndex,
286 raw_body: Vec<u8>,
287}
288
289async fn fetch_registry_index(http_client: Arc<dyn HttpClient>) -> Result<RegistryFetchResult> {
290 let mut response = http_client
291 .get(REGISTRY_URL, AsyncBody::default(), true)
292 .await
293 .context("requesting ACP registry")?;
294
295 let mut body = Vec::new();
296 response
297 .body_mut()
298 .read_to_end(&mut body)
299 .await
300 .context("reading ACP registry response")?;
301
302 if response.status().is_client_error() {
303 let text = String::from_utf8_lossy(body.as_slice());
304 bail!(
305 "registry status error {}, response: {text:?}",
306 response.status().as_u16()
307 );
308 }
309
310 let index: RegistryIndex = serde_json::from_slice(&body).context("parsing ACP registry")?;
311 Ok(RegistryFetchResult {
312 index,
313 raw_body: body,
314 })
315}
316
317async fn build_registry_agents(
318 fs: Arc<dyn Fs>,
319 http_client: Arc<dyn HttpClient>,
320 index: RegistryIndex,
321 raw_body: Vec<u8>,
322 update_cache: bool,
323) -> Result<Vec<RegistryAgent>> {
324 let cache_dir = registry_cache_dir();
325 fs.create_dir(&cache_dir).await?;
326
327 let cache_path = cache_dir.join("registry.json");
328 if update_cache {
329 fs.write(&cache_path, &raw_body).await?;
330 }
331
332 let icons_dir = cache_dir.join("icons");
333 if update_cache {
334 fs.create_dir(&icons_dir).await?;
335 }
336
337 let current_platform = current_platform_key();
338
339 let mut agents = Vec::new();
340 for entry in index.agents {
341 let icon_path = resolve_icon_path(
342 &entry,
343 &icons_dir,
344 update_cache,
345 fs.clone(),
346 http_client.clone(),
347 )
348 .await?;
349
350 let metadata = RegistryAgentMetadata {
351 id: entry.id.into(),
352 name: entry.name.into(),
353 description: entry.description.into(),
354 version: entry.version.into(),
355 repository: entry.repository.map(Into::into),
356 icon_path,
357 };
358
359 let binary_agent = entry.distribution.binary.as_ref().and_then(|binary| {
360 if binary.is_empty() {
361 return None;
362 }
363
364 let mut targets = HashMap::default();
365 for (platform, target) in binary.iter() {
366 targets.insert(
367 platform.clone(),
368 RegistryTargetConfig {
369 archive: target.archive.clone(),
370 cmd: target.cmd.clone(),
371 args: target.args.clone(),
372 sha256: None,
373 env: target.env.clone(),
374 },
375 );
376 }
377
378 let supports_current_platform = current_platform
379 .as_ref()
380 .is_some_and(|platform| targets.contains_key(*platform));
381
382 Some(RegistryBinaryAgent {
383 metadata: metadata.clone(),
384 targets,
385 supports_current_platform,
386 })
387 });
388
389 let npx_agent = entry.distribution.npx.as_ref().map(|npx| RegistryNpxAgent {
390 metadata: metadata.clone(),
391 package: npx.package.clone().into(),
392 args: npx.args.clone(),
393 env: npx.env.clone(),
394 });
395
396 let agent = match (binary_agent, npx_agent) {
397 (Some(binary_agent), Some(npx_agent)) => {
398 if binary_agent.supports_current_platform {
399 RegistryAgent::Binary(binary_agent)
400 } else {
401 RegistryAgent::Npx(npx_agent)
402 }
403 }
404 (Some(binary_agent), None) => RegistryAgent::Binary(binary_agent),
405 (None, Some(npx_agent)) => RegistryAgent::Npx(npx_agent),
406 (None, None) => continue,
407 };
408
409 agents.push(agent);
410 }
411
412 Ok(agents)
413}
414
415async fn resolve_icon_path(
416 entry: &RegistryEntry,
417 icons_dir: &Path,
418 update_cache: bool,
419 fs: Arc<dyn Fs>,
420 http_client: Arc<dyn HttpClient>,
421) -> Result<Option<SharedString>> {
422 let icon_url = resolve_icon_url(entry);
423 let Some(icon_url) = icon_url else {
424 return Ok(None);
425 };
426
427 let icon_path = icons_dir.join(format!("{}.svg", entry.id));
428 if update_cache && !fs.is_file(&icon_path).await {
429 if let Err(error) = download_icon(fs.clone(), http_client, &icon_url, entry).await {
430 log::warn!(
431 "Failed to download ACP registry icon for {}: {error:#}",
432 entry.id
433 );
434 }
435 }
436
437 if fs.is_file(&icon_path).await {
438 Ok(Some(SharedString::from(
439 icon_path.to_string_lossy().into_owned(),
440 )))
441 } else {
442 Ok(None)
443 }
444}
445
446async fn download_icon(
447 fs: Arc<dyn Fs>,
448 http_client: Arc<dyn HttpClient>,
449 icon_url: &str,
450 entry: &RegistryEntry,
451) -> Result<()> {
452 let mut response = http_client
453 .get(icon_url, AsyncBody::default(), true)
454 .await
455 .with_context(|| format!("requesting icon for {}", entry.id))?;
456
457 let mut body = Vec::new();
458 response
459 .body_mut()
460 .read_to_end(&mut body)
461 .await
462 .with_context(|| format!("reading icon for {}", entry.id))?;
463
464 if response.status().is_client_error() {
465 let text = String::from_utf8_lossy(body.as_slice());
466 bail!(
467 "icon status error {}, response: {text:?}",
468 response.status().as_u16()
469 );
470 }
471
472 let icon_path = registry_cache_dir()
473 .join("icons")
474 .join(format!("{}.svg", entry.id));
475 fs.write(&icon_path, &body).await?;
476 Ok(())
477}
478
479fn resolve_icon_url(entry: &RegistryEntry) -> Option<String> {
480 let icon = entry.icon.as_ref()?;
481 if icon.starts_with("https://") || icon.starts_with("http://") {
482 return Some(icon.to_string());
483 }
484
485 let relative_icon = icon.trim_start_matches("./");
486 Some(format!(
487 "https://raw.githubusercontent.com/agentclientprotocol/registry/main/{}/{relative_icon}",
488 entry.id
489 ))
490}
491
492fn current_platform_key() -> Option<&'static str> {
493 let os = if cfg!(target_os = "macos") {
494 "darwin"
495 } else if cfg!(target_os = "linux") {
496 "linux"
497 } else if cfg!(target_os = "windows") {
498 "windows"
499 } else {
500 return None;
501 };
502
503 let arch = if cfg!(target_arch = "aarch64") {
504 "aarch64"
505 } else if cfg!(target_arch = "x86_64") {
506 "x86_64"
507 } else {
508 return None;
509 };
510
511 Some(match os {
512 "darwin" => match arch {
513 "aarch64" => "darwin-aarch64",
514 "x86_64" => "darwin-x86_64",
515 _ => return None,
516 },
517 "linux" => match arch {
518 "aarch64" => "linux-aarch64",
519 "x86_64" => "linux-x86_64",
520 _ => return None,
521 },
522 "windows" => match arch {
523 "aarch64" => "windows-aarch64",
524 "x86_64" => "windows-x86_64",
525 _ => return None,
526 },
527 _ => return None,
528 })
529}
530
531fn registry_cache_dir() -> PathBuf {
532 paths::external_agents_dir().join("registry")
533}
534
535fn registry_cache_path() -> PathBuf {
536 registry_cache_dir().join("registry.json")
537}
538
539#[derive(Deserialize)]
540struct RegistryIndex {
541 #[serde(rename = "version")]
542 _version: String,
543 agents: Vec<RegistryEntry>,
544}
545
546#[derive(Deserialize)]
547struct RegistryEntry {
548 id: String,
549 name: String,
550 version: String,
551 description: String,
552 #[serde(default)]
553 repository: Option<String>,
554 #[serde(default)]
555 icon: Option<String>,
556 distribution: RegistryDistribution,
557}
558
559#[derive(Deserialize)]
560struct RegistryDistribution {
561 #[serde(default)]
562 binary: Option<HashMap<String, RegistryBinaryTarget>>,
563 #[serde(default)]
564 npx: Option<RegistryNpxDistribution>,
565}
566
567#[derive(Deserialize)]
568struct RegistryBinaryTarget {
569 archive: String,
570 cmd: String,
571 #[serde(default)]
572 args: Vec<String>,
573 #[serde(default)]
574 env: HashMap<String, String>,
575}
576
577#[derive(Deserialize)]
578struct RegistryNpxDistribution {
579 package: String,
580 #[serde(default)]
581 args: Vec<String>,
582 #[serde(default)]
583 env: HashMap<String, String>,
584}