The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(attachments): reindent document fallback and tidy provider formatting
Steven Enamakelfc6ae7931701
diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rsindex cd8f538429..cc21549dc0 100644--- a/crates/openhuman-core/src/agent/multimodal.rs+++ b/crates/openhuman-core/src/agent/multimodal.rs@@ -13,9 +13,7 @@ use std::time::Duration;use async_trait::async_trait;use reqwest::Client;-use crate::config::{- build_runtime_proxy_client_with_timeouts, MultimodalConfig,-};+use crate::config::{build_runtime_proxy_client_with_timeouts, MultimodalConfig};use tinyagents_session::transcript::{TranscriptMessage, TranscriptPart};use tinyagents_harness::multimodal::{@@ -26,7 +24,6 @@ use tinyagents_harness::multimodal::{BlobAttachmentStash,};-/// Hard upper bound on how long the `tinydocs` module may spend extracting a/// PDF's text layer before the attempt is abandoned and the file degrades to a/// metadata-only reference.diff --git a/crates/openhuman-core/src/agent/multimodal_attachment_handling_tests.rs b/crates/openhuman-core/src/agent/multimodal_attachment_handling_tests.rsindex 305c7df43c..be0c29eab4 100644--- a/crates/openhuman-core/src/agent/multimodal_attachment_handling_tests.rs+++ b/crates/openhuman-core/src/agent/multimodal_attachment_handling_tests.rs@@ -30,8 +30,14 @@ async fn image_placeholder_rehydrates_to_inline_data_uri() {let rehydrated = rehydrate_image_placeholders(&messages).await;assert_eq!(rehydrated.len(), 1);let content = &rehydrated[0].content;- assert!(content.contains("[IMAGE:data:image/png;base64,"), "{content}");- assert!(!content.contains("#att:"), "placeholder consumed: {content}");+ assert!(+ content.contains("[IMAGE:data:image/png;base64,"),+ "{content}"+ );+ assert!(+ !content.contains("#att:"),+ "placeholder consumed: {content}"+ );}#[tokio::test]@@ -55,7 +61,10 @@ async fn stash_image_attachments_caps_at_max_images() {};let out = stash_image_attachments(&msg, &config).await;assert!(out.contains("#att:"), "first image stashed: {out}");- assert!(out.contains("over image limit"), "second image capped: {out}");+ assert!(+ out.contains("over image limit"),+ "second image capped: {out}"+ );}#[test]@@ -68,7 +77,9 @@ fn extract_image_placeholders_pulls_attachment_tokens_in_order() {"[Image: image #att:bbb222]".to_string()]);- assert!(markers::extract_image_placeholders_in_text("[Image: (could not be processed)]").is_empty());+ assert!(+ markers::extract_image_placeholders_in_text("[Image: (could not be processed)]").is_empty()+ );assert!(markers::extract_image_placeholders_in_text("no images here").is_empty());}@@ -87,7 +98,10 @@ async fn sweep_keeps_fresh_attachments() {sweep_stale_attachments().await;let index = build_attachment_index(&[TranscriptMessage::user(placeholdered)]).await;- assert!(index.contains_key(&id), "fresh attachment retained after sweep");+ assert!(+ index.contains_key(&id),+ "fresh attachment retained after sweep"+ );}#[test]diff --git a/crates/openhuman-core/src/attachments/provider.rs b/crates/openhuman-core/src/attachments/provider.rsindex 6f56190caf..0da60eee11 100644--- a/crates/openhuman-core/src/attachments/provider.rs+++ b/crates/openhuman-core/src/attachments/provider.rs@@ -62,12 +62,7 @@ pub(crate) fn wrap(}profile.modalities.image_in |=crate::inference::model_context::model_vision_enabled(model, &config);- owner::wrap(- ctx,- inner,- config,- profile,- )+ owner::wrap(ctx, inner, config, profile)}/// Injected models supply their own selected-model facts through ModelProfile.@@ -158,7 +153,6 @@ impl AttachmentModel {}Ok(bytes)}-}fn historical_source_hint(block: &ContentBlock, scope: &AttachmentAccessScope) -> String {diff --git a/crates/openhuman-core/src/attachments/provider_context_tests.rs b/crates/openhuman-core/src/attachments/provider_context_tests.rsindex 6da8d687ac..c81267ffe2 100644--- a/crates/openhuman-core/src/attachments/provider_context_tests.rs+++ b/crates/openhuman-core/src/attachments/provider_context_tests.rs@@ -31,6 +31,9 @@ fn owner_media_wrapper_does_not_keep_a_turn_context_alive() {);drop(dispatch);drop(context);- assert!(weak.upgrade().is_none(), "the provider wrapper retains only weak turn context");+ assert!(+ weak.upgrade().is_none(),+ "the provider wrapper retains only weak turn context"+ );drop(wrapper);}diff --git a/crates/openhuman-core/src/attachments/provider_fallback.rs b/crates/openhuman-core/src/attachments/provider_fallback.rsindex 7a2ef7836d..2d28554734 100644--- a/crates/openhuman-core/src/attachments/provider_fallback.rs+++ b/crates/openhuman-core/src/attachments/provider_fallback.rs@@ -17,152 +17,148 @@ impl AttachmentModel {let _ = (mime, bytes);#[cfg(feature = "documents")]{- use tinydocs_bus::DocumentFormat;- let format = match mime {- "application/pdf" => Some(DocumentFormat::Pdf),- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => {- Some(DocumentFormat::Docx)- }- "application/vnd.openxmlformats-officedocument.presentationml.presentation" => {- Some(DocumentFormat::Pptx)- }- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => {- Some(DocumentFormat::Xlsx)- }- _ => None,- };- if format.is_some() && !self.config.components.documents {- log::debug!(- "[attachments] document extraction skipped: component 'documents' disabled"- );- cacheable = false;- text.push_str(&format!(+ use tinydocs_bus::DocumentFormat;+ let format = match mime {+ "application/pdf" => Some(DocumentFormat::Pdf),+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => {+ Some(DocumentFormat::Docx)+ }+ "application/vnd.openxmlformats-officedocument.presentationml.presentation" => {+ Some(DocumentFormat::Pptx)+ }+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => {+ Some(DocumentFormat::Xlsx)+ }+ _ => None,+ };+ if format.is_some() && !self.config.components.documents {+ log::debug!(+ "[attachments] document extraction skipped: component 'documents' disabled"+ );+ cacheable = false;+ text.push_str(&format!("Document extraction is disabled ([components] documents = false); original remains available."));- } else if let Some(format) = format {- let (_, _, limit) = self.config.multimodal_files.effective_limits();- let mut spec = tinydocs_bus::ExtractDocumentSpec::new(format);- spec.max_text_bytes = limit.min(200_000) as u32;- let result = tokio::time::timeout(- std::time::Duration::from_secs(60),- crate::modules::documents::extract_document(&self.config, bytes, &spec),- )- .await;- match result {- Ok(Ok(document)) => {- let scanned: Vec<_> = document- .sections- .iter()- .filter(|s| s.scanned_candidate)- .map(|s| s.index)- .take(4)- .collect();- for section in &document.sections {- text.push_str(&format!("\n{}:\n{}", section.source, section.text));- }- if !scanned.is_empty() {- let spec = tinydocs_bus::RenderPdfSpec {- pages: scanned,- max_dimension: 2048,- max_total_pixels: 16_000_000,- max_output_bytes: 32 * 1024 * 1024,- };- match tokio::time::timeout(- std::time::Duration::from_secs(60),- crate::modules::documents::render_pdf(- &self.config,- bytes,- &spec,- ),- )- .await- {- Ok(Ok(pages)) => {- for (page, png) in pages {- match self.image_readout("image/png", &png).await {- Ok(readout) => {- text.push_str(&format!("\nScanned PDF page {page} image readout:\n{readout}"));- }- Err(error) => {- cacheable = false;- text.push_str(&format!(- "\nPage {page} readout unavailable: {error}"- ));- }- }- }- }- Ok(Err(error)) => {- cacheable = false;- text.push_str(&format!(- "\nScanned PDF rendering unavailable: {error}"- ));- }- Err(_) => {- cacheable = false;- text.push_str("\nScanned PDF rendering timed out");- }- }- if document- .sections- .iter()- .filter(|s| s.scanned_candidate)- .count()- > 4- {- text.push_str(- "\n[Scanned page readout limited to four selected pages]",- );- }- }- if document.truncated {- text.push_str("\n[Document truncated]");- }+ } else if let Some(format) = format {+ let (_, _, limit) = self.config.multimodal_files.effective_limits();+ let mut spec = tinydocs_bus::ExtractDocumentSpec::new(format);+ spec.max_text_bytes = limit.min(200_000) as u32;+ let result = tokio::time::timeout(+ std::time::Duration::from_secs(60),+ crate::modules::documents::extract_document(&self.config, bytes, &spec),+ )+ .await;+ match result {+ Ok(Ok(document)) => {+ let scanned: Vec<_> = document+ .sections+ .iter()+ .filter(|s| s.scanned_candidate)+ .map(|s| s.index)+ .take(4)+ .collect();+ for section in &document.sections {+ text.push_str(&format!("\n{}:\n{}", section.source, section.text));}- Ok(Err(crate::modules::documents::DocumentCallError::Unavailable(- error,- ))) if format == DocumentFormat::Pdf => {- text.push_str(&format!("{error}; using the published PDF text-layer reader. Scanned-page rendering is unavailable."));+ if !scanned.is_empty() {+ let spec = tinydocs_bus::RenderPdfSpec {+ pages: scanned,+ max_dimension: 2048,+ max_total_pixels: 16_000_000,+ max_output_bytes: 32 * 1024 * 1024,+ };match tokio::time::timeout(std::time::Duration::from_secs(60),- crate::modules::documents::extract_text(&self.config, bytes),+ crate::modules::documents::render_pdf(&self.config, bytes, &spec),).await{- Ok(Ok(extracted)) => {- text.push_str("\nPDF text layer (untrusted):\n");- text.extend(extracted.chars().take(limit));- if extracted.chars().count() > limit {- text.push_str("\n[Text truncated]");- }- if extracted.trim().is_empty() {- text.push_str("\n[No extractable text layer; original PDF remains available]");+ Ok(Ok(pages)) => {+ for (page, png) in pages {+ match self.image_readout("image/png", &png).await {+ Ok(readout) => {+ text.push_str(&format!("\nScanned PDF page {page} image readout:\n{readout}"));+ }+ Err(error) => {+ cacheable = false;+ text.push_str(&format!(+ "\nPage {page} readout unavailable: {error}"+ ));+ }+ }}}Ok(Err(error)) => {cacheable = false;text.push_str(&format!(- "\nPDF text extraction unavailable: {error}"+ "\nScanned PDF rendering unavailable: {error}"));}Err(_) => {cacheable = false;- text.push_str("\nPDF text extraction timed out");+ text.push_str("\nScanned PDF rendering timed out");}}+ if document+ .sections+ .iter()+ .filter(|s| s.scanned_candidate)+ .count()+ > 4+ {+ text.push_str(+ "\n[Scanned page readout limited to four selected pages]",+ );+ }}- Ok(Err(error)) => {- cacheable = false;- text.push_str(&format!("Document extraction unavailable: {error}. Original remains available."));+ if document.truncated {+ text.push_str("\n[Document truncated]");}- Err(_) => {- cacheable = false;- text.push_str(- "Document extraction timed out; original remains available.",- );+ }+ Ok(Err(crate::modules::documents::DocumentCallError::Unavailable(error)))+ if format == DocumentFormat::Pdf =>+ {+ text.push_str(&format!("{error}; using the published PDF text-layer reader. Scanned-page rendering is unavailable."));+ match tokio::time::timeout(+ std::time::Duration::from_secs(60),+ crate::modules::documents::extract_text(&self.config, bytes),+ )+ .await+ {+ Ok(Ok(extracted)) => {+ text.push_str("\nPDF text layer (untrusted):\n");+ text.extend(extracted.chars().take(limit));+ if extracted.chars().count() > limit {+ text.push_str("\n[Text truncated]");+ }+ if extracted.trim().is_empty() {+ text.push_str("\n[No extractable text layer; original PDF remains available]");+ }+ }+ Ok(Err(error)) => {+ cacheable = false;+ text.push_str(&format!(+ "\nPDF text extraction unavailable: {error}"+ ));+ }+ Err(_) => {+ cacheable = false;+ text.push_str("\nPDF text extraction timed out");+ }}}+ Ok(Err(error)) => {+ cacheable = false;+ text.push_str(&format!(+ "Document extraction unavailable: {error}. Original remains available."+ ));+ }+ Err(_) => {+ cacheable = false;+ text.push_str("Document extraction timed out; original remains available.");+ }}+ }}Ok((self.limit_context(text), cacheable))}@@ -176,7 +172,11 @@ impl AttachmentModel {text}- pub(super) async fn image_readout(&self, mime: &str, bytes: &[u8]) -> tinyinference_llm::Result<String> {+ pub(super) async fn image_readout(+ &self,+ mime: &str,+ bytes: &[u8],+ ) -> tinyinference_llm::Result<String> {if bytes.is_empty() {return Err(tinyinference_llm::Error::Model("image reference has no bytes".into(),diff --git a/crates/openhuman-core/src/attachments/provider_injected_tests.rs b/crates/openhuman-core/src/attachments/provider_injected_tests.rsindex f1078639f3..da629386dc 100644--- a/crates/openhuman-core/src/attachments/provider_injected_tests.rs+++ b/crates/openhuman-core/src/attachments/provider_injected_tests.rs@@ -108,4 +108,3 @@ fn bare_injected_builder_does_not_load_operator_config() {.unwrap();assert!(agent.runtime_config().is_none());}-diff --git a/crates/openhuman-core/src/attachments/provider_owner.rs b/crates/openhuman-core/src/attachments/provider_owner.rsindex 90497065dd..c7d68cbf7e 100644--- a/crates/openhuman-core/src/attachments/provider_owner.rs+++ b/crates/openhuman-core/src/attachments/provider_owner.rs@@ -2,9 +2,9 @@use super::*;use async_trait::async_trait;use tinyagents_harness::multimodal::{- config::{FileLimits, ImageLimits}, MediaFallbackCache, MediaFallbackRenderer,- MediaHistoryFallback, MediaRequestConfig, MediaRequestModel, MediaSourceResolver,- ResolvedAttachment, ResolvedMedia, TextExtractor,+ config::{FileLimits, ImageLimits},+ MediaFallbackCache, MediaFallbackRenderer, MediaHistoryFallback, MediaRequestConfig,+ MediaRequestModel, MediaSourceResolver, ResolvedAttachment, ResolvedMedia, TextExtractor,};pub(super) fn wrap(@@ -27,7 +27,11 @@ pub(super) fn wrap(allow_remote_fetch: config.multimodal.allow_remote_fetch,},files: FileLimits {- max_files: if config.multimodal_files.max_files == 0 { 0 } else { max_files },+ max_files: if config.multimodal_files.max_files == 0 {+ 0+ } else {+ max_files+ },max_file_size_mb: file_mb,max_extracted_text_chars: text_limit,allow_remote_fetch: config.multimodal_files.allow_remote_fetch,@@ -35,7 +39,9 @@ pub(super) fn wrap(},max_historical_media_items: MAX_HISTORICAL_MEDIA_BLOCKS,};- let extractor = Arc::new(OwnedDocumentsExtractor { ctx: ctx.downgrade() });+ let extractor = Arc::new(OwnedDocumentsExtractor {+ ctx: ctx.downgrade(),+ });let model = MediaRequestModel::new(inner,request_config,@@ -87,9 +93,15 @@ impl MediaSourceResolver<AttachmentAccessScope> for AttachmentModel {|| source.starts_with("http://")|| source.starts_with("https://"){- MediaRef::Url { url: source.to_owned(), media_type: mime_hint.map(str::to_owned) }+ MediaRef::Url {+ url: source.to_owned(),+ media_type: mime_hint.map(str::to_owned),+ }} else {- MediaRef::Path { path: source.to_owned(), media_type: mime_hint.map(str::to_owned) }+ MediaRef::Path {+ path: source.to_owned(),+ media_type: mime_hint.map(str::to_owned),+ }};match modality {InputModality::Audio => ContentBlock::Audio(media),@@ -98,8 +110,10 @@ impl MediaSourceResolver<AttachmentAccessScope> for AttachmentModel {}}};- let Some((resolved_modality, path, mut mime, bytes, recovered)) =- self.resolve_block(&block, scope).await.map_err(|error| error.to_string())?+ let Some((resolved_modality, path, mut mime, bytes, recovered)) = self+ .resolve_block(&block, scope)+ .await+ .map_err(|error| error.to_string())?else {return Err("unsupported media source".into());};@@ -109,11 +123,13 @@ impl MediaSourceResolver<AttachmentAccessScope> for AttachmentModel {if modality == InputModality::Image {mime = tinyagents_harness::multimodal::mime::image_mime_from_magic(&bytes).map(str::to_owned)- .or_else(|| tinyagents_harness::multimodal::mime::detect_image_mime(- Some(std::path::Path::new(&path)),- &bytes,- None,- ))+ .or_else(|| {+ tinyagents_harness::multimodal::mime::detect_image_mime(+ Some(std::path::Path::new(&path)),+ &bytes,+ None,+ )+ }).ok_or_else(|| "image attachment type cannot be determined".to_string())?;} else if let Some(mime_hint) = mime_hint {// Typed per-block metadata is authoritative for that reference.@@ -121,11 +137,11 @@ impl MediaSourceResolver<AttachmentAccessScope> for AttachmentModel {mime = mime_hint.to_owned();} else if mime == "application/octet-stream" {mime = tinyagents_harness::multimodal::mime::detect_file_mime(- Some(std::path::Path::new(&path)),- &bytes,- None,- )- .unwrap_or(mime);+ Some(std::path::Path::new(&path)),+ &bytes,+ None,+ )+ .unwrap_or(mime);}let mut resolved = ResolvedMedia::new(ResolvedAttachment {size_bytes: bytes.len(),@@ -136,9 +152,7 @@ impl MediaSourceResolver<AttachmentAccessScope> for AttachmentModel {if recovered {let annotation = format!("[Recovered attachment: {}; {} bytes; workspace path: {}]",- resolved.attachment.mime,- resolved.attachment.size_bytes,- resolved.attachment.name+ resolved.attachment.mime, resolved.attachment.size_bytes, resolved.attachment.name);resolved = resolved.with_annotation(annotation);}@@ -170,18 +184,20 @@ impl MediaFallbackRenderer<AttachmentAccessScope> for AttachmentModel {return Ok(Some(text));}#[cfg(feature = "documents")]- if matches!(attachment.mime.as_str(), "application/pdf"- | "application/vnd.openxmlformats-officedocument.wordprocessingml.document"- | "application/vnd.openxmlformats-officedocument.presentationml.presentation"- | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")- {+ if matches!(+ attachment.mime.as_str(),+ "application/pdf"+ | "application/vnd.openxmlformats-officedocument.wordprocessingml.document"+ | "application/vnd.openxmlformats-officedocument.presentationml.presentation"+ | "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"+ ) {if let Some(text) = MediaFallbackCache::get(self, _scope, modality, attachment).await {return Ok(Some(text));}- let (body, cacheable) = self.document_fallback(- &attachment.mime,- &attachment.bytes,- ).await.map_err(|error| error.to_string())?;+ let (body, cacheable) = self+ .document_fallback(&attachment.mime, &attachment.bytes)+ .await+ .map_err(|error| error.to_string())?;let text = format!("{}\n{body}", attachment_header(attachment));if cacheable {MediaFallbackCache::put(self, _scope, modality, attachment, &text).await;@@ -229,12 +245,18 @@ impl MediaFallbackCache<AttachmentAccessScope> for AttachmentModel {if let Ok(mut cache) = self.fallback_cache.lock() {cache.insert(key.clone(), text.to_owned());}- self.save_fallback(&attachment.name, &key, text, scope).await;+ self.save_fallback(&attachment.name, &key, text, scope)+ .await;}}impl MediaHistoryFallback<AttachmentAccessScope> for AttachmentModel {- fn omitted(&self, scope: &AttachmentAccessScope, modality: InputModality, source: &str) -> String {+ fn omitted(+ &self,+ scope: &AttachmentAccessScope,+ modality: InputModality,+ source: &str,+ ) -> String {let block = history_source_block(modality, source);let hint = super::historical_source_hint(&block, scope);format!("[Earlier attachment omitted by history budget; workspace path: {hint}]")@@ -256,7 +278,9 @@ impl MediaHistoryFallback<AttachmentAccessScope> for AttachmentModel {}let block = history_source_block(modality, source);let hint = super::historical_source_hint(&block, scope);- Some(format!("[Earlier attachment unavailable or omitted at workspace path: {hint}]") )+ Some(format!(+ "[Earlier attachment unavailable or omitted at workspace path: {hint}]"+ ))}}@@ -297,11 +321,14 @@ struct OwnedDocumentsExtractor {#[async_trait]impl TextExtractor for OwnedDocumentsExtractor {- fn handles(&self, mime: &str) -> bool { mime == "application/pdf" }+ fn handles(&self, mime: &str) -> bool {+ mime == "application/pdf"+ }async fn extract(&self, mime: &str, bytes: &[u8]) -> Result<String, String> {let ctx = crate::core::runtime::DispatchCtx::from_weak(self.ctx.as_ref());crate::agent::multimodal::DocumentsTextExtractor { ctx: &ctx }- .extract(mime, bytes).await+ .extract(mime, bytes)+ .await}}diff --git a/crates/openhuman-core/src/attachments/provider_routing_tests.rs b/crates/openhuman-core/src/attachments/provider_routing_tests.rsindex 8024171555..44a9691cec 100644--- a/crates/openhuman-core/src/attachments/provider_routing_tests.rs+++ b/crates/openhuman-core/src/attachments/provider_routing_tests.rs@@ -33,11 +33,7 @@ impl ChatModel<()> for CaptureModel {&& self.transport_inputs.contains(&modality)&& matches!(mime,- "audio/wav"- | "application/pdf"- | "text/plain"- | "text/markdown"- | "image/jpeg"+ "audio/wav" | "application/pdf" | "text/plain" | "text/markdown" | "image/jpeg")}async fn invoke(@@ -106,11 +102,7 @@ async fn typed_document_mime_hints_are_per_block_and_markers_use_source_detectio.await.unwrap();let transport = Arc::new(CaptureModel::new(vec![InputModality::Document]));- let model = controlled_wrapper(- transport.clone(),- config,- &[InputModality::Document],- );+ let model = controlled_wrapper(transport.clone(), config, &[InputModality::Document]);model.invoke(@@ -294,7 +286,9 @@ async fn disabled_tinydocs_fallback_runs_through_the_owner_wrapper_without_cachilet temp = tempfile::tempdir().unwrap();let relative = "uploads/thread/id/brief.pdf";let path = temp.path().join(relative);- tokio::fs::create_dir_all(path.parent().unwrap()).await.unwrap();+ tokio::fs::create_dir_all(path.parent().unwrap())+ .await+ .unwrap();tokio::fs::write(&path, b"%PDF-1.4 original bytes").await.unwrap();@@ -421,10 +415,7 @@ async fn image_readout_for_unmanaged_sources_uses_the_wrapper_memory_cache() {model.invoke(&(), request).await.unwrap();assert_eq!(vision.requests.lock().unwrap().len(), 1);- assert!(!temp- .path()- .join(".openhuman-derived/readout.txt")- .exists());+ assert!(!temp.path().join(".openhuman-derived/readout.txt").exists());}#[tokio::test]