Skip to content

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

fix(agent): handle multimodal input in agent core

Steven Enamakel7d95dba43ad7
diff --git a/crates/openhuman-core/src/agent/multimodal.rs b/crates/openhuman-core/src/agent/multimodal.rs
index 7f7dcfcdb9..5464b266eb 100644
--- a/crates/openhuman-core/src/agent/multimodal.rs
+++ b/crates/openhuman-core/src/agent/multimodal.rs
@@ -608,20 +608,19 @@ fn attachments_dir() -> PathBuf {
.unwrap_or_else(fallback_attachments_dir)
}
-/// Whether a provider image reference points inside this process' managed
-/// attachment stash. Raw channel-supplied filesystem paths are never trusted.
-pub fn is_managed_attachment_path(path: &str) -> bool {
- managed_attachment_path(path).is_some()
+/// The stash over the resolved attachments directory. The mechanism (atomic
+/// dedup'd writes, cap eviction, TTL sweep, index, managed-path check) is
+/// `tinyagents_harness::multimodal::AttachmentStash`; the directory, cap and TTL
+/// are this host's policy.
+fn stash() -> AttachmentStash {
+ AttachmentStash::new(attachments_dir(), ATTACHMENTS_MAX_BYTES, ATTACHMENTS_TTL)
}
/// Return the canonical path when `path` resolves inside the managed stash.
/// Callers should use this returned path for subsequent reads so the checked
/// path, rather than an attacker-controlled spelling, is what gets opened.
pub fn managed_attachment_path(path: &str) -> Option<PathBuf> {
- let candidate = Path::new(path);
- let candidate = candidate.canonicalize().ok()?;
- let root = attachments_dir().canonicalize().ok()?;
- candidate.starts_with(root).then_some(candidate)
+ stash().managed_path(path)
}
#[cfg(test)]
@@ -640,131 +639,15 @@ fn fallback_attachments_dir() -> PathBuf {
.unwrap_or_else(|| std::env::temp_dir().join("openhuman-attachments"))
}
-/// Persist a canonical image data URI to `<dir>/<id>.<ext>`, content-addressed
-/// by `id`. Atomic (temp file + rename); deduped (skips the write when the
-/// target already exists). Returns the written path. After writing, enforces
-/// [`ATTACHMENTS_MAX_BYTES`].
-async fn write_attachment(id: &str, data_uri: &str) -> anyhow::Result<PathBuf> {
- let parsed = mm::data_uri::parse_data_uri(data_uri)
- .map_err(|reason| anyhow::anyhow!("cannot decode stashed data URI: {reason}"))?;
- let ext = mm_mime::image_ext_from_mime(&parsed.mime).unwrap_or("img");
- let dir = attachments_dir();
- tokio::fs::create_dir_all(&dir).await?;
- let final_path = dir.join(format!("{id}.{ext}"));
- if tokio::fs::try_exists(&final_path).await.unwrap_or(false) {
- // Content-addressing deduplicates identical images, but a new message
- // can legitimately reference a file whose previous reference is older
- // than the startup TTL. Refresh its mtime so the immediately following
- // sweep cannot reclaim an attachment that was just reused.
- let touch_path = final_path.clone();
- tokio::task::spawn_blocking(move || -> std::io::Result<()> {
- std::fs::File::open(touch_path)?
- .set_times(std::fs::FileTimes::new().set_modified(std::time::SystemTime::now()))
- })
- .await??;
- return Ok(final_path); // content-addressed: already persisted
- }
- let tmp_path = dir.join(format!(".{id}.{ext}.tmp"));
- tokio::fs::write(&tmp_path, &parsed.bytes).await?;
- tokio::fs::rename(&tmp_path, &final_path).await?;
- enforce_attachments_cap(&dir).await;
- Ok(final_path)
-}
-
-/// Build an `id → path` index from a single read of the attachments dir. Skips
-/// in-flight `.tmp` files. Sync (called from the sync rehydrate path).
+/// Build an `id -> path` index from a single read of the attachments dir.
fn build_attachment_index() -> HashMap<String, PathBuf> {
- let dir = attachments_dir();
- let mut map = HashMap::new();
- let Ok(entries) = std::fs::read_dir(&dir) else {
- return map;
- };
- for entry in entries.flatten() {
- let name = entry.file_name();
- let name = name.to_string_lossy();
- if name.starts_with('.') {
- continue; // skip `.<id>.<ext>.tmp` in-flight writes
- }
- if let Some(stem) = name.split('.').next() {
- if !stem.is_empty() {
- map.insert(stem.to_string(), entry.path());
- }
- }
- }
- map
-}
-
-/// Evict oldest attachments (by mtime) until the dir is under
-/// [`ATTACHMENTS_MAX_BYTES`]. Best-effort.
-async fn enforce_attachments_cap(dir: &Path) {
- let mut files: Vec<(PathBuf, std::time::SystemTime, u64)> = Vec::new();
- let mut total: u64 = 0;
- let Ok(mut rd) = tokio::fs::read_dir(dir).await else {
- return;
- };
- while let Ok(Some(entry)) = rd.next_entry().await {
- // Skip in-flight `.<id>.<ext>.tmp` writes (mirrors
- // `build_attachment_index`) so concurrent atomic writes aren't evicted
- // out from under a rename.
- if entry.file_name().to_string_lossy().starts_with('.') {
- continue;
- }
- if let Ok(meta) = entry.metadata().await {
- if meta.is_file() {
- let mtime = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
- total = total.saturating_add(meta.len());
- files.push((entry.path(), mtime, meta.len()));
- }
- }
- }
- if total <= ATTACHMENTS_MAX_BYTES {
- return;
- }
- files.sort_by_key(|(_, mtime, _)| *mtime); // oldest first
- for (path, _, len) in files {
- if total <= ATTACHMENTS_MAX_BYTES {
- break;
- }
- if tokio::fs::remove_file(&path).await.is_ok() {
- total = total.saturating_sub(len);
- tracing::debug!(
- target: "multimodal",
- path = %path.display(),
- "[multimodal::images][gc] evicted attachment over size cap"
- );
- }
- }
+ stash().build_index()
}
/// Delete attachments older than [`ATTACHMENTS_TTL`]. Best-effort startup sweep
/// fired by [`init_attachments_dir`].
pub async fn sweep_stale_attachments() {
- let dir = attachments_dir();
- let Ok(mut rd) = tokio::fs::read_dir(&dir).await else {
- return;
- };
- let now = std::time::SystemTime::now();
- let mut reclaimed = 0u64;
- while let Ok(Some(entry)) = rd.next_entry().await {
- let Ok(meta) = entry.metadata().await else {
- continue;
- };
- if !meta.is_file() {
- continue;
- }
- let mtime = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
- let age = now.duration_since(mtime).unwrap_or(Duration::ZERO);
- if age > ATTACHMENTS_TTL && tokio::fs::remove_file(entry.path()).await.is_ok() {
- reclaimed = reclaimed.saturating_add(meta.len());
- }
- }
- if reclaimed > 0 {
- tracing::info!(
- target: "multimodal",
- reclaimed_bytes = reclaimed,
- "[multimodal::images][gc] startup sweep removed stale attachments"
- );
- }
+ stash().sweep_stale().await;
}
#[cfg(test)]
diff --git a/vendor/tinyagents b/vendor/tinyagents
index eb84399735..1ed8d5dedb 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit eb8439973599d452963ea6e84039b128cfc699e2
+Subproject commit 1ed8d5dedb1ad4a529fb07a7eaf6394dbfc68761