agent_hub_runtime/core/task_browser/
discovery.rs1use super::{Binding, Provider};
4use crate::core::{platforms::hosts::known_hosts, skill_store::SkillStore};
5use anyhow::Result;
6use sha2::{Digest, Sha256};
7use std::collections::HashSet;
8
9pub(super) use crate::core::platforms::hosts::refresh_hosts;
10#[cfg(all(test, feature = "github", feature = "gitlab"))]
11use crate::core::platforms::hosts::status_hosts;
12
13const EXCLUDED: &str = "task_browser_excluded_sources_v1";
14fn excluded(store: &SkillStore) -> Result<HashSet<String>> {
15 Ok(store
16 .get_setting(EXCLUDED)?
17 .map(|text| serde_json::from_str(&text))
18 .transpose()?
19 .unwrap_or_default())
20}
21
22pub(super) fn exclude(store: &SkillStore, id: &str, binding: Option<&Binding>) -> Result<()> {
23 let mut ids = excluded(store)?;
24 ids.insert(id.into());
25 if let Some(binding) = binding {
26 ids.insert(source_id(
27 &binding.project_id,
28 &binding.host,
29 &binding.repository,
30 ));
31 }
32 store.set_setting(EXCLUDED, &serde_json::to_string(&ids)?)
33}
34
35fn source(
36 project_id: &str,
37 remote: &str,
38 github: &HashSet<String>,
39 gitlab: &HashSet<String>,
40) -> Option<Binding> {
41 let (host, repository) = remote.split_once('/')?;
42 let host = host.to_ascii_lowercase();
43 let provider = match (github.contains(&host), gitlab.contains(&host)) {
44 (true, false) => Provider::Github,
45 (false, true) => Provider::Gitlab,
46 _ => return None, };
48 let binding = Binding {
49 id: source_id(project_id, &host, repository),
50 project_id: project_id.into(),
51 provider,
52 host,
53 repository: repository.into(),
54 launcher: None,
55 };
56 binding.validate().ok()?;
57 Some(binding)
58}
59
60#[derive(serde::Serialize)]
61pub struct RemoteCandidate {
62 pub remote: String,
63 pub provider: Option<Provider>,
64}
65
66pub fn remote_candidates(store: &SkillStore, project_id: &str) -> Result<Vec<RemoteCandidate>> {
67 let remotes = super::remotes(store, project_id)?;
68 let (mut github, mut gitlab) = hosts_for(&remotes);
69 include_remembered_hosts(store, &mut github, &mut gitlab)?;
70 Ok(remotes
71 .into_iter()
72 .map(|remote| {
73 let provider =
74 source(project_id, &remote, &github, &gitlab).map(|binding| binding.provider);
75 RemoteCandidate { remote, provider }
76 })
77 .collect())
78}
79
80fn default_hosts() -> (HashSet<String>, HashSet<String>) {
81 (
82 if Provider::Github.enabled() {
83 HashSet::from(["github.com".into()])
84 } else {
85 HashSet::new()
86 },
87 if Provider::Gitlab.enabled() {
88 HashSet::from(["gitlab.com".into()])
89 } else {
90 HashSet::new()
91 },
92 )
93}
94
95fn authenticated_hosts() -> (HashSet<String>, HashSet<String>) {
96 std::thread::scope(|scope| {
97 let github = scope.spawn(|| known_hosts("gh", "github.com"));
98 let gitlab = known_hosts("glab", "gitlab.com");
99 (github.join().unwrap_or_else(|_| default_hosts().0), gitlab)
100 })
101}
102
103fn hosts_for(remotes: &[String]) -> (HashSet<String>, HashSet<String>) {
104 if remotes.iter().any(|remote| !is_public_remote(remote)) {
105 authenticated_hosts()
106 } else {
107 default_hosts()
108 }
109}
110
111fn is_public_remote(remote: &str) -> bool {
112 remote.split_once('/').is_some_and(|(host, _)| {
113 host.eq_ignore_ascii_case("github.com") || host.eq_ignore_ascii_case("gitlab.com")
114 })
115}
116
117fn include_remembered_hosts(
118 store: &SkillStore,
119 github: &mut HashSet<String>,
120 gitlab: &mut HashSet<String>,
121) -> Result<()> {
122 for (provider, host) in crate::core::platforms::accounts::remembered_hosts(store)? {
123 match provider {
124 Provider::Github => {
125 github.insert(host);
126 }
127 Provider::Gitlab => {
128 gitlab.insert(host);
129 }
130 }
131 }
132 Ok(())
133}
134
135fn source_id(project_id: &str, host: &str, repository: &str) -> String {
136 let host = host.to_ascii_lowercase();
137 let digest = Sha256::digest(format!("task-source\0{project_id}\0{host}\0{repository}"));
138 let mut bytes = [0; 16];
139 bytes.copy_from_slice(&digest[..16]);
140 uuid::Uuid::from_bytes(bytes).to_string()
141}
142
143pub(super) fn bindings(store: &SkillStore, saved: Vec<Binding>) -> Result<Vec<Binding>> {
144 discover(store, saved, authenticated_hosts)
145}
146
147pub(super) fn binding(
148 store: &SkillStore,
149 saved: Vec<Binding>,
150 id: &str,
151) -> Result<Option<Binding>> {
152 Ok(
153 discover_matching(store, saved, authenticated_hosts, Some(id))?
154 .into_iter()
155 .find(|binding| binding.id == id),
156 )
157}
158
159fn discover(
160 store: &SkillStore,
161 saved: Vec<Binding>,
162 hosts: impl FnOnce() -> (HashSet<String>, HashSet<String>),
163) -> Result<Vec<Binding>> {
164 discover_matching(store, saved, hosts, None)
165}
166
167fn discover_matching(
168 store: &SkillStore,
169 mut saved: Vec<Binding>,
170 hosts: impl FnOnce() -> (HashSet<String>, HashSet<String>),
171 wanted: Option<&str>,
172) -> Result<Vec<Binding>> {
173 saved.retain(|binding| binding.provider.enabled());
174 let projects = store.get_all_projects()?;
175 let projects: Vec<_> = projects
176 .into_iter()
177 .filter(|project| !saved.iter().any(|binding| binding.project_id == project.id))
178 .collect();
179 if projects.is_empty() {
180 return Ok(saved);
181 }
182 let excluded = excluded(store)?;
183 let candidates: Vec<_> = projects
184 .into_iter()
185 .filter_map(|project| {
186 let remotes = super::remotes(store, &project.id).ok()?;
187 if remotes.len() != 1 {
188 return None;
189 }
190 let remote = remotes.into_iter().next()?;
191 let (host, repository) = remote.split_once('/')?;
192 let id = source_id(&project.id, host, repository);
193 if excluded.contains(&id) || wanted.is_some_and(|wanted| wanted != id) {
194 return None;
195 }
196 Some((project.id, remote))
197 })
198 .collect();
199 let (mut github, mut gitlab) = if candidates
201 .iter()
202 .any(|(_, remote)| !is_public_remote(remote))
203 {
204 hosts()
205 } else {
206 default_hosts()
207 };
208 include_remembered_hosts(store, &mut github, &mut gitlab)?;
209 for (project_id, remote) in candidates {
210 if let Some(binding) = source(&project_id, &remote, &github, &gitlab) {
211 saved.push(binding);
212 }
213 }
214 Ok(saved)
215}
216
217#[cfg(all(test, feature = "github", feature = "gitlab"))]
218mod tests;