Skip to content

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

refactor(multimodal): remove file attachment handling

Steven Enamakelf0d591b625e8
diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rs
index d615dd087c..555bbae92a 100644
--- a/crates/openhuman-core/src/agent/multimodal.rs
+++ b/crates/openhuman-core/src/agent/multimodal.rs
@@ -14,20 +14,19 @@ use async_trait::async_trait;
use reqwest::Client;
use crate::config::{
- build_runtime_proxy_client_with_timeouts, MultimodalConfig, MultimodalFileConfig,
+ build_runtime_proxy_client_with_timeouts, MultimodalConfig,
};
use tinyagents_session::transcript::{TranscriptMessage, TranscriptPart};
use tinyagents_harness::multimodal::{
self as mm,
- config::{FileLimits, ImageLimits},
+ config::ImageLimits,
markers,
payload::sha256_prefix,
- resolve::{resolve_file, resolve_image, TextExtractor},
+ resolve::{resolve_image, TextExtractor},
BlobAttachmentStash,
};
-use tinyagents_harness::multimodal::{FilePayload, MultimodalError};
/// 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
@@ -40,17 +39,6 @@ use tinyagents_harness::multimodal::{FilePayload, MultimodalError};
#[cfg(feature = "documents")]
const PDF_EXTRACTION_TIMEOUT: Duration = Duration::from_secs(60);
-/// The result of resolving every marker in a turn's messages.
-#[derive(Debug, Clone)]
-pub struct PreparedMessages {
- /// The messages with every marker resolved into a payload.
- pub messages: Vec<TranscriptMessage>,
- /// Whether the turn carried any image markers.
- pub contains_images: bool,
- /// Whether the turn carried any file markers.
- pub contains_files: bool,
-}
-
// ── Config mapping ───────────────────────────────────────────────────────
// Follows the `session_config_from` precedent in `openhuman::tinyagents::config`:
// the crate owns the struct, the host maps its schema into it. The clamping
@@ -66,21 +54,6 @@ fn image_limits(config: &MultimodalConfig) -> ImageLimits {
}
}
-/// Map the host file config onto the crate's limits.
-///
-/// `max_files` is copied verbatim, including the `0` hard-disable sentinel that
-/// [`MultimodalFileConfig::for_untrusted_channel_input`] sets — the crate
-/// checks it before its own clamp.
-fn file_limits(config: &MultimodalFileConfig) -> FileLimits {
- FileLimits {
- max_files: config.max_files,
- max_file_size_mb: config.max_file_size_mb,
- max_extracted_text_chars: config.max_extracted_text_chars,
- allow_remote_fetch: config.allow_remote_fetch,
- allowed_mime_types: config.allowed_mime_types.clone(),
- }
-}
-
/// The HTTP client remote references are fetched with.
///
/// Built per call rather than cached because the runtime proxy configuration
@@ -189,229 +162,8 @@ fn latest_user_message(messages: &[TranscriptMessage]) -> Option<&TranscriptMess
messages.iter().rev().find(|m| m.role == "user")
}
-// ── Provider dispatch ────────────────────────────────────────────────────
-
-/// Resolve every marker in `messages` into a provider-ready payload.
-///
-/// Counts are checked against the raw markers before any read happens: a cap
-/// enforced after the fetch is not a cap.
-pub async fn prepare_messages_for_provider(
- ctx: &DispatchCtx,
- messages: &[TranscriptMessage],
- image_config: &MultimodalConfig,
- file_config: &MultimodalFileConfig,
-) -> anyhow::Result<PreparedMessages> {
- let images = image_limits(image_config);
- let files = file_limits(file_config);
-
- let (max_images, _) = images.effective();
- let max_image_bytes = images.max_image_bytes();
-
- let (max_files, _, max_extracted_text_chars) = files.effective();
- let max_file_bytes = files.max_file_bytes();
-
- let found_images = count_image_markers(messages);
- if found_images > max_images {
- return Err(MultimodalError::TooManyImages {
- max_images,
- found: found_images,
- }
- .into());
- }
-
- let found_files = count_file_markers(messages);
- // Hard-zero gate: `MultimodalFileConfig::for_untrusted_channel_input()`
- // (and the triage arm) sets `max_files: 0` as a sentinel meaning "reject
- // every `[FILE:…]` marker before any disk read." The crate's clamp lifts
- // 0 → 1, so without this pre-check a single attacker-supplied
- // `[FILE:/etc/passwd]` would slip through (`1 > 1` is false). Honour the
- // raw value here so the channel / triage hardening is actually enforced.
- if files.files_disabled() && found_files > 0 {
- return Err(MultimodalError::TooManyFiles {
- max_files: 0,
- found: found_files,
- }
- .into());
- }
- if found_files > max_files {
- return Err(MultimodalError::TooManyFiles {
- max_files,
- found: found_files,
- }
- .into());
- }
-
- tracing::debug!(
- target: "multimodal",
- found_images,
- found_files,
- "[multimodal] preparing messages"
- );
-
- if found_images == 0 && found_files == 0 {
- return Ok(PreparedMessages {
- messages: messages.to_vec(),
- contains_images: false,
- contains_files: false,
- });
- }
-
- let client = remote_client();
-
- let mut normalized_messages = Vec::with_capacity(messages.len());
- for message in messages {
- if message.role != "user" {
- normalized_messages.push(message.clone());
- continue;
- }
-
- let (text_after_images, image_refs) = markers::parse_image_markers(&message.content);
- let (cleaned_text, file_refs) = markers::parse_file_markers(&text_after_images);
-
- if image_refs.is_empty() && file_refs.is_empty() {
- normalized_messages.push(message.clone());
- continue;
- }
-
- let mut normalized_image_refs = Vec::with_capacity(image_refs.len());
- for reference in image_refs {
- // A `data:` image is an inline byte payload, not a fetchable URL.
- // Keep the wire contract strict before handing it to TinyAgents:
- // accepting a non-base64 form silently turned malformed image
- // input into a provider-visible marker after the resolver update.
- if reference.trim_start().starts_with("data:") && !data_uri_uses_base64(&reference) {
- return Err(anyhow::anyhow!("only base64 data URIs are supported"));
- }
- normalized_image_refs
- .push(resolve_image(&reference, &images, max_image_bytes, &client).await?);
- }
-
- let mut file_payloads = Vec::with_capacity(file_refs.len());
- for reference in file_refs {
- file_payloads.push(
- resolve_file(
- &reference,
- &files,
- max_file_bytes,
- max_extracted_text_chars,
- &client,
- &DocumentsTextExtractor { ctx },
- )
- .await?,
- );
- }
-
- let content =
- mm::compose_multimodal_message(&cleaned_text, &normalized_image_refs, &file_payloads);
- normalized_messages.push(TranscriptMessage {
- content,
- cache_breakpoints: Vec::new(),
- ..message.clone()
- });
- }
-
- Ok(PreparedMessages {
- messages: normalized_messages,
- contains_images: found_images > 0,
- contains_files: found_files > 0,
- })
-}
-
-/// Whether a `data:` URI declares a base64 payload before its first comma.
-///
-/// Callers first establish that the value starts with `data:`; ordinary image
-/// paths and remote URLs intentionally do not pass through this check.
-fn data_uri_uses_base64(reference: &str) -> bool {
- reference
- .split_once(',')
- .map(|(header, _)| {
- header
- .split(';')
- .any(|parameter| parameter.trim().eq_ignore_ascii_case("base64"))
- })
- .unwrap_or(false)
-}
-
// ── Ingress ──────────────────────────────────────────────────────────────
-/// Ingress-time file extraction.
-///
-/// Replaces every `[FILE:…]` marker in a raw user message with its
-/// extracted-text block, or a content-less `[FILE-ATTACHED: …]` placeholder
-/// when extraction fails. `[IMAGE:…]` markers are deliberately left untouched
-/// here — they are handled at provider dispatch, where vision needs the inline
-/// data URI.
-///
-/// Run this at channel ingress, BEFORE the message is persisted to history,
-/// auto-saved to the memory store, appended to the cross-thread JSONL, or
-/// scanned for prompt injection — so the multi-MB base64 data URI never
-/// survives past the front door. Idempotent: a message with no `[FILE:` marker
-/// (already-rewritten `[FILE-EXTRACTED]` text included) is returned unchanged.
-pub async fn inline_file_attachments(
- ctx: &DispatchCtx,
- message: &str,
- file_config: &MultimodalFileConfig,
-) -> String {
- if !message.contains(markers::FILE_MARKER_PREFIX) {
- return message.to_string();
- }
- let (cleaned, file_refs) = markers::parse_file_markers(message);
- if file_refs.is_empty() {
- return message.to_string();
- }
-
- let files = file_limits(file_config);
- let (max_files, _, max_extracted_text_chars) = files.effective();
- let max_file_bytes = files.max_file_bytes();
- // Enforce the per-turn file cap at ingress: rewriting the markers removes
- // the count check `prepare_messages_for_provider` would otherwise do.
- // `files_disabled()` is the hard-disable sentinel — read nothing. Over-cap
- // refs degrade to a content-less placeholder rather than being read.
- let read_cap = if files.files_disabled() { 0 } else { max_files };
- let client = remote_client();
-
- let mut payloads = Vec::with_capacity(file_refs.len());
- for (idx, reference) in file_refs.iter().enumerate() {
- if idx >= read_cap {
- payloads.push(FilePayload::placeholder(
- "attachment (over file limit)",
- "skipped",
- ));
- continue;
- }
- match resolve_file(
- reference,
- &files,
- max_file_bytes,
- max_extracted_text_chars,
- &client,
- &DocumentsTextExtractor { ctx },
- )
- .await
- {
- Ok(payload) => payloads.push(payload),
- Err(err) => {
- tracing::warn!(
- target: "multimodal",
- reason = %err,
- "[multimodal::files][ingress] file marker could not be normalized; emitting bare placeholder"
- );
- payloads.push(FilePayload::placeholder("attachment", "unavailable"));
- }
- }
- }
-
- let rewritten = mm::compose_multimodal_message(&cleaned, &[], &payloads);
- tracing::info!(
- target: "multimodal",
- files = payloads.len(),
- before_chars = message.chars().count(),
- after_chars = rewritten.chars().count(),
- "[multimodal::files][ingress] inlined file attachments — data URI replaced with extracted text/placeholder before persistence"
- );
- rewritten
-}
-
/// Ingress-time image stashing. Replaces every `[IMAGE:data:…]` marker with a
/// `[Image: image #att:<id>]` placeholder and stashes the decoded canonical
/// data URI, so the multi-MB base64 never persists. Idempotent (no `[IMAGE:`