Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(skills): add a reqwest RegistryTransport for the tinyskills registry

oxoxDevc5c2d6cc0ff4
diff --git a/crates/openhuman-core/src/skills/catalog/mod.rs b/crates/openhuman-core/src/skills/catalog/mod.rs
index a9d0bbaef7..813312f361 100644
--- a/crates/openhuman-core/src/skills/catalog/mod.rs
+++ b/crates/openhuman-core/src/skills/catalog/mod.rs
@@ -24,8 +24,13 @@ pub mod store;
#[cfg(feature = "skills")]
pub mod tools;
#[cfg(feature = "skills")]
+mod transport;
+#[cfg(feature = "skills")]
pub mod types;
+#[cfg(feature = "skills")]
+pub use transport::ReqwestTransport;
+
#[cfg(feature = "skills")]
pub use schemas::{
all_skill_registry_controller_schemas, all_skill_registry_registered_controllers,
diff --git a/crates/openhuman-core/src/skills/catalog/transport.rs b/crates/openhuman-core/src/skills/catalog/transport.rs
new file mode 100644
index 0000000000..cba421ce99
--- /dev/null
+++ b/crates/openhuman-core/src/skills/catalog/transport.rs
@@ -0,0 +1,169 @@
+//! `reqwest` implementation of the tinyskills [`RegistryTransport`].
+//!
+//! The registry's guard has already validated the URL and resolved the host.
+//! This transport keeps the contract: it connects only to the pinned
+//! addresses, never follows a redirect, reports the requested URL as the
+//! final URL, applies the connect budget and streams the body lazily.
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::sync::{Mutex, PoisonError};
+use std::time::Duration;
+
+use tinyskills::{
+ BodyChunks, BoxFuture, HttpMethod, RegistryTransport, TransportError, TransportRequest,
+ TransportResponse,
+};
+
+const MAX_CACHED_CLIENTS: usize = 32;
+
+type ClientKey = (String, Vec<SocketAddr>, Duration);
+
+/// A [`RegistryTransport`] over `reqwest` with OpenHuman's per-OS TLS backend.
+///
+/// Holds no host state; clients are cached per pinned host so repeated
+/// requests to one host reuse their connection pool.
+#[derive(Default)]
+pub struct ReqwestTransport {
+ clients: Mutex<HashMap<ClientKey, reqwest::Client>>,
+}
+
+impl std::fmt::Debug for ReqwestTransport {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ReqwestTransport").finish_non_exhaustive()
+ }
+}
+
+impl ReqwestTransport {
+ /// A transport with an empty client cache.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ fn client_for(
+ &self,
+ host: &str,
+ pinned: &[SocketAddr],
+ connect_timeout: Duration,
+ ) -> Result<reqwest::Client, TransportError> {
+ let key = (host.to_owned(), pinned.to_vec(), connect_timeout);
+ let mut clients = self.clients.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(client) = clients.get(&key) {
+ return Ok(client.clone());
+ }
+ let client = crate::util::tls::tls_client_builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .no_proxy()
+ .connect_timeout(connect_timeout)
+ .resolve_to_addrs(host, pinned)
+ .build()
+ .map_err(|error| TransportError::Connect(error.to_string()))?;
+ if clients.len() >= MAX_CACHED_CLIENTS {
+ clients.clear();
+ }
+ clients.insert(key, client.clone());
+ Ok(client)
+ }
+
+ async fn exchange(
+ &self,
+ method: HttpMethod,
+ raw_url: String,
+ pinned: &[SocketAddr],
+ headers: &[(String, String)],
+ connect_timeout: Duration,
+ ) -> Result<TransportResponse, TransportError> {
+ let url = reqwest::Url::parse(&raw_url)
+ .map_err(|error| TransportError::Io(format!("invalid url: {error}")))?;
+ let host = url
+ .host_str()
+ .ok_or_else(|| TransportError::Io("url has no host".to_owned()))?
+ .to_owned();
+ let client = self.client_for(&host, pinned, connect_timeout)?;
+ let verb = match method {
+ HttpMethod::Head => reqwest::Method::HEAD,
+ _ => reqwest::Method::GET,
+ };
+ tracing::trace!(
+ method = method.as_str(),
+ host = %host,
+ pinned = pinned.len(),
+ "[skill_registry][transport] send"
+ );
+ let mut builder = client.request(verb, url);
+ for (name, value) in headers {
+ builder = builder.header(name.as_str(), value.as_str());
+ }
+ let response = builder.send().await.map_err(|error| {
+ let mapped = map_send_error(&error);
+ tracing::debug!(
+ host = %host,
+ error = %mapped,
+ "[skill_registry][transport] send failed"
+ );
+ mapped
+ })?;
+ let status = response.status().as_u16();
+ let response_headers = response
+ .headers()
+ .iter()
+ .filter_map(|(name, value)| {
+ Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
+ })
+ .collect();
+ tracing::trace!(host = %host, status, "[skill_registry][transport] response");
+ Ok(TransportResponse::new(
+ status,
+ raw_url,
+ response_headers,
+ Box::new(ReqwestBody(response)),
+ ))
+ }
+}
+
+fn map_send_error(error: &reqwest::Error) -> TransportError {
+ if error.is_timeout() {
+ TransportError::Timeout
+ } else if error.is_connect() {
+ TransportError::Connect(error.to_string())
+ } else {
+ TransportError::Io(error.to_string())
+ }
+}
+
+impl RegistryTransport for ReqwestTransport {
+ fn send(
+ &self,
+ request: TransportRequest,
+ ) -> BoxFuture<'_, Result<TransportResponse, TransportError>> {
+ Box::pin(async move {
+ self.exchange(
+ request.method,
+ request.url,
+ &request.pinned,
+ &request.headers,
+ request.connect_timeout,
+ )
+ .await
+ })
+ }
+}
+
+struct ReqwestBody(reqwest::Response);
+
+impl BodyChunks for ReqwestBody {
+ fn next_chunk(&mut self) -> BoxFuture<'_, Result<Option<Vec<u8>>, TransportError>> {
+ Box::pin(async move {
+ self.0
+ .chunk()
+ .await
+ .map(|chunk| chunk.map(|bytes| bytes.to_vec()))
+ .map_err(|error| map_send_error(&error))
+ })
+ }
+}
+
+#[cfg(test)]
+#[path = "transport_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/skills/catalog/transport_tests.rs b/crates/openhuman-core/src/skills/catalog/transport_tests.rs
new file mode 100644
index 0000000000..8eeec6dd6a
--- /dev/null
+++ b/crates/openhuman-core/src/skills/catalog/transport_tests.rs
@@ -0,0 +1,241 @@
+use super::*;
+
+use std::sync::Arc;
+
+use axum::http::{HeaderMap, StatusCode};
+use axum::response::IntoResponse;
+use axum::routing::get;
+use axum::Router;
+use tinyskills::{
+ fetch_skill_document, FetchPolicy, RegistryError, RegistryLimits, RegistryTimeouts,
+ SystemResolver,
+};
+
+const SKILL_MD: &str =
+ "---\nname: pinned-skill\ndescription: Served over loopback.\n---\n\n# Pinned\n";
+
+async fn serve(app: Router) -> SocketAddr {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ addr
+}
+
+fn fixture() -> Router {
+ Router::new()
+ .route("/SKILL.md", get(|| async { SKILL_MD }))
+ .route(
+ "/moved.md",
+ get(|| async {
+ (
+ StatusCode::MOVED_PERMANENTLY,
+ [("location", "/SKILL.md")],
+ "",
+ )
+ }),
+ )
+ .route("/unchanged", get(|| async { StatusCode::NOT_MODIFIED }))
+ .route(
+ "/echo",
+ get(|headers: HeaderMap| async move {
+ headers
+ .get("x-registry-probe")
+ .and_then(|value| value.to_str().ok())
+ .unwrap_or("missing")
+ .to_owned()
+ .into_response()
+ }),
+ )
+}
+
+async fn read_body(response: &mut TransportResponse) -> Vec<u8> {
+ let mut body = Vec::new();
+ while let Some(chunk) = response.body.next_chunk().await.unwrap() {
+ body.extend_from_slice(&chunk);
+ }
+ body
+}
+
+async fn get_from(
+ transport: &ReqwestTransport,
+ url: String,
+ pinned: SocketAddr,
+ headers: &[(String, String)],
+) -> TransportResponse {
+ transport
+ .exchange(
+ HttpMethod::Get,
+ url,
+ &[pinned],
+ headers,
+ Duration::from_secs(5),
+ )
+ .await
+ .expect("exchange")
+}
+
+#[tokio::test]
+async fn connects_to_the_pinned_address_not_the_url_host() {
+ let addr = serve(fixture()).await;
+ let transport = ReqwestTransport::new();
+ let url = format!("http://registry.invalid:{}/SKILL.md", addr.port());
+ let mut response = get_from(&transport, url.clone(), addr, &[]).await;
+ assert_eq!(response.status, 200);
+ assert_eq!(response.final_url, url);
+ assert_eq!(read_body(&mut response).await, SKILL_MD.as_bytes());
+}
+
+#[tokio::test]
+async fn returns_a_redirect_without_following_it() {
+ let addr = serve(fixture()).await;
+ let transport = ReqwestTransport::new();
+ let url = format!("http://127.0.0.1:{}/moved.md", addr.port());
+ let response = get_from(&transport, url.clone(), addr, &[]).await;
+ assert_eq!(response.status, 301);
+ assert_eq!(response.header("location"), Some("/SKILL.md"));
+ assert_eq!(response.final_url, url, "final_url is the requested url");
+}
+
+#[tokio::test]
+async fn passes_a_not_modified_answer_through() {
+ let addr = serve(fixture()).await;
+ let transport = ReqwestTransport::new();
+ let url = format!("http://127.0.0.1:{}/unchanged", addr.port());
+ let mut response = get_from(&transport, url, addr, &[]).await;
+ assert_eq!(response.status, 304);
+ assert!(read_body(&mut response).await.is_empty());
+}
+
+#[tokio::test]
+async fn sends_every_request_header() {
+ let addr = serve(fixture()).await;
+ let transport = ReqwestTransport::new();
+ let url = format!("http://127.0.0.1:{}/echo", addr.port());
+ let headers = vec![("X-Registry-Probe".to_owned(), "present".to_owned())];
+ let mut response = get_from(&transport, url, addr, &headers).await;
+ assert_eq!(read_body(&mut response).await, b"present");
+}
+
+#[tokio::test]
+async fn head_requests_carry_no_body() {
+ let addr = serve(fixture()).await;
+ let transport = ReqwestTransport::new();
+ let url = format!("http://127.0.0.1:{}/SKILL.md", addr.port());
+ let mut response = transport
+ .exchange(HttpMethod::Head, url, &[addr], &[], Duration::from_secs(5))
+ .await
+ .unwrap();
+ assert_eq!(response.status, 200);
+ assert!(read_body(&mut response).await.is_empty());
+}
+
+#[tokio::test]
+async fn an_unreachable_pinned_address_is_a_connect_error() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ drop(listener);
+ let transport = ReqwestTransport::new();
+ let error = transport
+ .exchange(
+ HttpMethod::Get,
+ format!("http://127.0.0.1:{}/SKILL.md", addr.port()),
+ &[addr],
+ &[],
+ Duration::from_secs(5),
+ )
+ .await
+ .err()
+ .expect("nothing listens there");
+ assert!(matches!(error, TransportError::Connect(_)), "{error:?}");
+}
+
+fn loopback_policy() -> FetchPolicy {
+ let mut policy = FetchPolicy::default();
+ policy.allow_loopback_http = true;
+ policy
+}
+
+async fn fetch_through_guard(
+ url: String,
+ timeouts: RegistryTimeouts,
+ limits: RegistryLimits,
+) -> Result<tinyskills::RegistryDocument, RegistryError> {
+ fetch_skill_document(
+ Arc::new(ReqwestTransport::new()),
+ Arc::new(SystemResolver),
+ &url,
+ &loopback_policy(),
+ &timeouts,
+ &limits,
+ )
+ .await
+}
+
+#[tokio::test]
+async fn the_guard_follows_a_redirect_through_the_transport() {
+ let addr = serve(fixture()).await;
+ let document = fetch_through_guard(
+ format!("http://127.0.0.1:{}/moved.md", addr.port()),
+ RegistryTimeouts::default(),
+ RegistryLimits::default(),
+ )
+ .await
+ .expect("document");
+ assert_eq!(document.document.slug, "pinned-skill");
+}
+
+#[tokio::test]
+async fn an_oversized_body_stops_the_stream() {
+ let app = Router::new().route("/SKILL.md", get(|| async { "x".repeat(64 * 1024) }));
+ let addr = serve(app).await;
+ let mut limits = RegistryLimits::default();
+ limits.max_document_bytes = 1024;
+ let error = fetch_through_guard(
+ format!("http://127.0.0.1:{}/SKILL.md", addr.port()),
+ RegistryTimeouts::default(),
+ limits,
+ )
+ .await
+ .expect_err("body exceeds the limit");
+ assert!(matches!(error, RegistryError::TooLarge { .. }), "{error:?}");
+}
+
+#[tokio::test]
+async fn a_slow_upstream_times_out() {
+ let app = Router::new().route(
+ "/SKILL.md",
+ get(|| async {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ SKILL_MD
+ }),
+ );
+ let addr = serve(app).await;
+ let mut timeouts = RegistryTimeouts::default();
+ timeouts.document = Duration::from_millis(200);
+ let error = fetch_through_guard(
+ format!("http://127.0.0.1:{}/SKILL.md", addr.port()),
+ timeouts,
+ RegistryLimits::default(),
+ )
+ .await
+ .expect_err("slow upstream");
+ assert!(error.is_timeout(), "{error:?}");
+}
+
+#[test]
+fn clients_are_reused_per_pinned_host() {
+ let transport = ReqwestTransport::new();
+ let pinned: SocketAddr = "127.0.0.1:443".parse().unwrap();
+ transport
+ .client_for("a.example", &[pinned], Duration::from_secs(5))
+ .unwrap();
+ transport
+ .client_for("a.example", &[pinned], Duration::from_secs(5))
+ .unwrap();
+ transport
+ .client_for("b.example", &[pinned], Duration::from_secs(5))
+ .unwrap();
+ assert_eq!(transport.clients.lock().unwrap().len(), 2);
+}