agent_registry_store.rs

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