Skip to content

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

feat(cli): add managed embedding support

Steven Enamakel5dc8fc8c9abe
diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.toml
index 9faf6e1148..0a42cd82fa 100644
--- a/crates/openhuman-cli/Cargo.toml
+++ b/crates/openhuman-cli/Cargo.toml
@@ -181,8 +181,8 @@ path = "../../tests/memory_cortexdb_live.rs"
[[test]]
name = "json_rpc_e2e"
path = "../../tests/json_rpc_e2e.rs"
-# `voice::reply_speech::{test_seam, TEST_SEAM_ENV}` — the reply-speech seam
-# only exists in the real voice module, not the stub.
+# `openhuman_tinyhumans::voice::reply_speech::{test_seam, TEST_SEAM_ENV}` — the
+# reply-speech seam only exists with the voice feature (hosted TTS provider).
required-features = ["voice"]
[[test]]
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs
index fcce501a16..e0ad2804b3 100644
--- a/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs
+++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding.rs
@@ -31,14 +31,31 @@ pub struct ManagedEmbeddingModel {
impl ManagedEmbeddingModel {
/// Builds the embedder for the credential scope `request` carries.
pub fn from_request(request: &EmbeddingRequest<'_>) -> Self {
- let api_url = request.config.and_then(|config| config.api_url.clone());
+ Self::new(
+ request.config.and_then(|config| config.api_url.clone()),
+ request.state_dir.clone(),
+ request.secrets_encrypt,
+ request.model,
+ request.dimensions,
+ request.chat.clone(),
+ )
+ }
+
+ /// Builds the embedder against `api_url` (or the default backend) with
+ /// credentials read from `state_dir`.
+ pub fn new(
+ api_url: Option<String>,
+ state_dir: std::path::PathBuf,
+ secrets_encrypt: bool,
+ model: &str,
+ dimensions: usize,
+ chat: Option<ApprovalChatContext>,
+ ) -> Self {
let base_url = format!(
"{}/openai/v1",
effective_api_url(&api_url).trim_end_matches('/')
);
let key_endpoint = base_url.clone();
- let state_dir = request.state_dir.clone();
- let secrets_encrypt = request.secrets_encrypt;
let bearer: BearerResolver = Arc::new(move || {
// A stored TinyHumans API key is the bearer outright, with the
// plaintext guard: never put the key on a non-HTTPS, non-loopback wire.
@@ -69,16 +86,28 @@ impl ManagedEmbeddingModel {
)
})
});
- let model = request.model.to_string();
+ let model = model.to_string();
Self {
inner: Arc::new(CloudEmbeddingModel::new(
base_url,
model.clone(),
- request.dimensions,
+ dimensions,
bearer,
)),
model,
- chat: request.chat.clone(),
+ chat,
+ }
+ }
+
+ /// This embedder with its egress disclosures routed to `chat` (the turn's
+ /// thread and client); `None` leaves them unrouted. Shares the transport,
+ /// so it is cheap to do per turn.
+ #[must_use]
+ pub fn routed_to(&self, chat: Option<ApprovalChatContext>) -> Self {
+ Self {
+ inner: Arc::clone(&self.inner),
+ model: self.model.clone(),
+ chat,
}
}
diff --git a/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs b/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs
new file mode 100644
index 0000000000..67e494f924
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/inference/managed_embedding_tests.rs
@@ -0,0 +1,203 @@
+use super::*;
+use tinyinference_embeddings::DEFAULT_CLOUD_DIMENSIONS;
+
+/// A stored TinyHumans API key authenticates cloud embeddings on its own (no
+/// session), sent as `Authorization: Bearer <key>` like managed inference.
+#[tokio::test]
+async fn api_key_alone_authenticates_cloud_embeddings() {
+ use axum::{http::HeaderMap, routing::post, Json, Router};
+ use std::sync::{Arc, Mutex};
+
+ let seen: Arc<Mutex<Option<String>>> = Arc::default();
+ let app = Router::new().route(
+ "/openai/v1/embeddings",
+ post({
+ let seen = Arc::clone(&seen);
+ move |headers: HeaderMap| async move {
+ *seen.lock().unwrap() = headers
+ .get("authorization")
+ .and_then(|v| v.to_str().ok())
+ .map(str::to_owned);
+ Json(serde_json::json!({
+ "object": "list",
+ "data": [{ "object": "embedding", "index": 0, "embedding": [0.5, 0.25] }],
+ "model": "m"
+ }))
+ }
+ }),
+ );
+ 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() });
+
+ let state = tempfile::tempdir().unwrap();
+ openhuman_embed::__host::security::credentials::api_key::store_api_key_in(state.path(), false, "tiny_test_emb")
+ .unwrap();
+ let provider = ManagedEmbeddingModel::new(
+ Some(format!("http://{addr}")),
+ state.path().to_path_buf(),
+ false,
+ "m",
+ 2,
+ None,
+ );
+
+ let vectors = provider
+ .embed(&["hello".to_string()])
+ .await
+ .expect("an API key alone embeds");
+ assert_eq!(vectors.len(), 1);
+ assert_eq!(
+ seen.lock().unwrap().as_deref(),
+ Some("Bearer tiny_test_emb")
+ );
+}
+
+/// The key is never put on a plaintext non-loopback wire.
+#[tokio::test]
+async fn api_key_is_refused_over_plaintext_non_loopback() {
+ let state = tempfile::tempdir().unwrap();
+ openhuman_embed::__host::security::credentials::api_key::store_api_key_in(state.path(), false, "tiny_test_emb")
+ .unwrap();
+ let provider = ManagedEmbeddingModel::new(
+ Some("http://embeddings.example.test".into()),
+ state.path().to_path_buf(),
+ false,
+ "m",
+ 2,
+ None,
+ );
+ let err = provider.embed(&["hello".to_string()]).await.unwrap_err();
+ assert!(
+ err.to_string()
+ .contains("refusing to send the TinyHumans API key"),
+ "{err}"
+ );
+}
+
+/// Drains `rx` until the cloud-embedding disclosure for `marker` arrives.
+/// Tolerates unrelated events: the bus is process-wide.
+async fn find_embedding_disclosure(
+ rx: &mut tinybus_events_placeholder<openhuman_embed::__host::core::events::DomainEvent>,
+ marker: &str,
+) -> (Option<String>, Option<String>, Option<String>) {
+ loop {
+ match rx.recv().await {
+ Some(openhuman_embed::__host::core::events::DomainEvent::ExternalTransferPending {
+ descriptor,
+ thread_id,
+ client_id,
+ request_id,
+ }) if descriptor.service == marker => return (thread_id, client_id, request_id),
+ Some(_) => continue,
+ None => panic!("the bus closed before the disclosure arrived"),
+ }
+ }
+}
+
+fn unreachable_embedder(model: &str) -> ManagedEmbeddingModel {
+ ManagedEmbeddingModel::new(
+ Some("http://127.0.0.1:0".into()),
+ std::env::temp_dir().join("openhuman_embeddings_routing_state"),
+ false,
+ model,
+ DEFAULT_CLOUD_DIMENSIONS,
+ None,
+ )
+}
+
+/// A cloud-embedding call made during a web-chat turn discloses its egress to
+/// that chat. The chat rides the embedder explicitly (built for the turn from
+/// its approval context); it is not read from the running task, which is why
+/// this call, awaited on a plain test task, still routes.
+#[tokio::test]
+async fn a_cloud_embedding_call_in_a_chat_turn_discloses_to_that_chat() {
+ openhuman_embed::__host::core::bus::init().await.expect("bus init");
+ let mut rx = openhuman_embed::__host::core::bus::BUS.get().unwrap().receiver();
+ let marker = "embed-routed-to-the-turns-chat";
+ let chat = ApprovalChatContext {
+ thread_id: "thread-embed".into(),
+ client_id: "client-embed".into(),
+ request_id: Some("req-embed".into()),
+ };
+ let embedder = unreachable_embedder(marker).routed_to(Some(chat));
+
+ // The transport has nowhere to go; the disclosure precedes it.
+ let _ = embedder
+ .embed(&["what did I say about invoices?".to_string()])
+ .await;
+
+ let (thread_id, client_id, request_id) = find_embedding_disclosure(&mut rx, marker).await;
+ assert_eq!(thread_id.as_deref(), Some("thread-embed"));
+ assert_eq!(client_id.as_deref(), Some("client-embed"));
+ assert_eq!(request_id.as_deref(), Some("req-embed"));
+}
+
+/// An embedder built with no chat (background sync, the embedding RPC) still
+/// discloses, unrouted, and a blank or empty batch discloses nothing because
+/// nothing leaves.
+#[tokio::test]
+async fn an_unrouted_embedder_discloses_without_a_chat() {
+ openhuman_embed::__host::core::bus::init().await.expect("bus init");
+ let mut rx = openhuman_embed::__host::core::bus::BUS.get().unwrap().receiver();
+ let marker = "embed-without-a-chat";
+ let embedder = unreachable_embedder(marker);
+
+ let _ = embedder.embed(&[]).await;
+ let _ = embedder.embed(&[" ".to_string()]).await;
+ let _ = embedder.embed(&["real text".to_string()]).await;
+
+ // The first disclosure for this marker is the third call's: the empty and
+ // blank batches published nothing.
+ let (thread_id, client_id, request_id) = find_embedding_disclosure(&mut rx, marker).await;
+ assert_eq!((thread_id, client_id, request_id), (None, None, None));
+ assert!(
+ tokio::time::timeout(
+ std::time::Duration::from_millis(200),
+ find_embedding_disclosure(&mut rx, marker)
+ )
+ .await
+ .is_err(),
+ "only the batch that leaves is disclosed"
+ );
+}
+
+/// `routed_to` re-routes a shared embedder per turn without touching the
+/// original: each turn's disclosure reaches its own chat.
+#[tokio::test]
+async fn routing_is_per_embedder_not_shared() {
+ openhuman_embed::__host::core::bus::init().await.expect("bus init");
+ let mut rx = openhuman_embed::__host::core::bus::BUS.get().unwrap().receiver();
+ let marker = "embed-routed-per-turn";
+ let base = unreachable_embedder(marker);
+ let chat = |thread: &str| ApprovalChatContext {
+ thread_id: thread.into(),
+ client_id: "c".into(),
+ request_id: None,
+ };
+
+ let _ = base
+ .routed_to(Some(chat("thread-a")))
+ .embed(&["a".into()])
+ .await;
+ assert_eq!(
+ find_embedding_disclosure(&mut rx, marker)
+ .await
+ .0
+ .as_deref(),
+ Some("thread-a")
+ );
+ let _ = base
+ .routed_to(Some(chat("thread-b")))
+ .embed(&["b".into()])
+ .await;
+ assert_eq!(
+ find_embedding_disclosure(&mut rx, marker)
+ .await
+ .0
+ .as_deref(),
+ Some("thread-b")
+ );
+ let _ = base.embed(&["c".into()]).await;
+ assert_eq!(find_embedding_disclosure(&mut rx, marker).await.0, None);
+}
diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rs
index 44e546b3ef..36888f199c 100644
--- a/tests/json_rpc_e2e.rs
+++ b/tests/json_rpc_e2e.rs
@@ -11972,6 +11972,9 @@ fn json_rpc_channel_web_chat_with_speak_reply_invokes_reply_speech() {
async fn json_rpc_channel_web_chat_with_speak_reply_invokes_reply_speech_inner() {
let _env_lock = json_rpc_e2e_env_lock_async().await;
+ // The hosted `cloud` TTS provider (and its test seam) is registered by the
+ // TinyHumans layer, not built into the core.
+ tinyhumans_boot::boot();
let tmp = tempdir().expect("tempdir");
let home = tmp.path();
let openhuman_home = home.join(".openhuman");
@@ -11982,9 +11985,9 @@ async fn json_rpc_channel_web_chat_with_speak_reply_invokes_reply_speech_inner()
let _vite_backend_guard = EnvVarGuard::unset("VITE_BACKEND_URL");
// Activate the reply_speech test seam so synthesize_reply records and
// short-circuits instead of calling the hosted backend.
- let _seam_guard = EnvVarGuard::set(openhuman_core::voice::reply_speech::TEST_SEAM_ENV, "1");
+ let _seam_guard = EnvVarGuard::set(openhuman_tinyhumans::voice::reply_speech::TEST_SEAM_ENV, "1");
- openhuman_core::voice::reply_speech::test_seam::clear();
+ openhuman_tinyhumans::voice::reply_speech::test_seam::clear();
let (mock_addr, mock_join) = serve_on_ephemeral(mock_upstream_router()).await;
let mock_origin = format!("http://{}", mock_addr);
@@ -12054,7 +12057,7 @@ async fn json_rpc_channel_web_chat_with_speak_reply_invokes_reply_speech_inner()
// because the bridge task may finish slightly after chat_done.
let mut observed: Vec<String> = Vec::new();
for _ in 0..50 {
- observed = openhuman_core::voice::reply_speech::test_seam::observed();
+ observed = openhuman_tinyhumans::voice::reply_speech::test_seam::observed();
if !observed.is_empty() {
break;
}