Skip to content

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

fix: file blob-backed generated media as artifacts

Steven Enamakel9ac8e39827e4
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs
index 4cfcd5366e..29266a2242 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@ -5,12 +5,12 @@
//! `tools/impl/presentation/mod.rs` use for their own producers
//! (`create_artifact` → write bytes → `finalize_artifact`/`fail_artifact`).
//!
-//! The inner tool already writes bytes under
-//! `<action_dir>/generated-media/...` (see [`super::tools::media_tools_from`])
-//! and reports each saved file in its JSON result's `artifacts` array
+//! The inner tool writes bytes to its `MediaOutput` blob store and reports
+//! each blob key in its JSON result's `artifacts` array
//! (`{"type": "image"|"video", "path", "media_type"|"format", "bytes"}`, see
-//! `tinyagents_harness::media::{GenerateImageTool, GenerateVideoTool}`). This
-//! wrapper runs the inner tool unchanged, then for every reported file:
+//! `tinyagents_harness::media::{GenerateImageTool, GenerateVideoTool}`). Host
+//! adapters may also report absolute file paths. This wrapper runs the inner
+//! tool unchanged, then for every reported output:
//! reserves an artifact via `create_artifact_for_call` (recording the
//! provider-assigned tool-call id so `ArtifactPending`/`Ready`/`Failed`
//! correlate with the tool-call bubble, #C5), moves the file into the
@@ -28,6 +28,7 @@
//! producer.
use std::path::{Path, PathBuf};
+use std::sync::Arc;
use async_trait::async_trait;
use serde_json::{json, Value};
@@ -35,6 +36,7 @@ use tinytools::{
PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolContent, ToolPolicy, ToolResult,
ToolRunContext, ToolScope, ToolTimeout,
};
+use tokio::io::AsyncWriteExt;
use crate::agent::artifacts::{
create_artifact_for_call, fail_artifact, finalize_artifact, ArtifactKind,
@@ -52,6 +54,7 @@ pub struct MediaArtifactTool<T: Tool> {
workspace_dir: PathBuf,
/// Visible folder each generated file is moved into (#5505).
files_dir: crate::agent::artifacts::FileRoots,
+ blobs: Option<Arc<dyn tinystoragedrivers::BlobStore>>,
}
impl<T: Tool> MediaArtifactTool<T> {
@@ -70,9 +73,19 @@ impl<T: Tool> MediaArtifactTool<T> {
kind,
workspace_dir: workspace_dir.into(),
files_dir: files_dir.into(),
+ blobs: None,
}
}
+ /// Reads generated outputs addressed by blob key from the media tool's
+ /// backing store. This keeps TinyAgents' blob-backed output contract
+ /// separate from the host's visible Files-folder artifact store.
+ #[must_use]
+ pub fn with_blobs(mut self, blobs: Arc<dyn tinystoragedrivers::BlobStore>) -> Self {
+ self.blobs = Some(blobs);
+ self
+ }
+
/// Derives a human-readable artifact title from the call's `prompt`
/// argument, suffixed with `(i/n)` when the call produced more than one
/// file (`n > 1`).
@@ -161,7 +174,12 @@ impl<T: Tool> MediaArtifactTool<T> {
return;
}
};
- match move_or_copy(src, &dest).await {
+ let stored = if src.is_absolute() {
+ move_or_copy(src, &dest).await
+ } else {
+ self.file_blob(src, &dest).await
+ };
+ match stored {
Ok(size_bytes) => {
match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes).await {
Ok(updated) => {
@@ -188,6 +206,49 @@ impl<T: Tool> MediaArtifactTool<T> {
}
}
}
+
+ async fn file_blob(&self, key: &Path, dest: &Path) -> Result<u64, String> {
+ let key = key
+ .to_str()
+ .ok_or_else(|| "generated media blob key is not valid UTF-8".to_string())?;
+ let blobs = self.blobs.as_ref().ok_or_else(|| {
+ format!("generated media returned blob key {key:?} without a blob store")
+ })?;
+ let mut blob = blobs
+ .get_stream(key)
+ .await
+ .map_err(|error| format!("failed to read generated media blob {key:?}: {error}"))?
+ .ok_or_else(|| format!("generated media blob {key:?} was not found"))?;
+ let mut file = tokio::fs::OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .open(dest)
+ .await
+ .map_err(|error| {
+ format!(
+ "failed to open artifact destination {}: {error}",
+ dest.display()
+ )
+ })?;
+ let size = tokio::io::copy(&mut blob.reader, &mut file)
+ .await
+ .map_err(|error| format!("failed to copy generated media blob {key:?}: {error}"))?;
+ file.flush().await.map_err(|error| {
+ format!(
+ "failed to flush artifact destination {}: {error}",
+ dest.display()
+ )
+ })?;
+ if let Err(error) = blobs.delete(key).await {
+ tracing::warn!(
+ target: "media_generation",
+ %error,
+ blob_key = key,
+ "[media_generation] filed media but could not discard its source blob"
+ );
+ }
+ Ok(size)
+ }
}
fn set_artifact_error(entry: &mut Value, message: &str) {
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
index fbd3ab8c0c..18fe36411a 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
@@ -1,5 +1,8 @@
use async_trait::async_trait;
use serde_json::{json, Value};
+use std::sync::Arc;
+use tinyagents_harness::media::MediaOutput;
+use tinystoragedrivers::BlobStore;
use tinytools::{PermissionLevel, Tool, ToolCategory, ToolContent, ToolResult};
use super::MediaArtifactTool;
@@ -55,6 +58,44 @@ impl Tool for StubMediaTool {
}
}
+/// TinyAgents' production media output is a blob key, not a filesystem path.
+struct BlobBackedMediaTool {
+ blobs: Arc<dyn BlobStore>,
+}
+
+#[async_trait]
+impl Tool for BlobBackedMediaTool {
+ fn name(&self) -> &str {
+ "blob_generate"
+ }
+
+ fn description(&self) -> &str {
+ "blob-backed media stub"
+ }
+
+ fn parameters_schema(&self) -> Value {
+ json!({ "type": "object" })
+ }
+
+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
+ let key = "generated-media/stub-0.png";
+ self.blobs
+ .put(key, b"blob-media-bytes".to_vec(), Some("image/png"))
+ .await?;
+ Ok(ToolResult::success_with_markdown(
+ json!({
+ "artifacts": [{
+ "type": "image",
+ "path": key,
+ "media_type": "image/png",
+ "bytes": 16
+ }]
+ }),
+ "generated blob-backed media",
+ ))
+ }
+}
+
fn json_payload(result: &ToolResult) -> Value {
result
.content
@@ -66,6 +107,41 @@ fn json_payload(result: &ToolResult) -> Value {
.expect("json content block")
}
+#[tokio::test]
+async fn files_a_blob_backed_generated_artifact() {
+ let root = tempfile::tempdir().unwrap();
+ let workspace = root.path().join("workspace");
+ let files_dir = root.path().join("Files");
+ let blobs = MediaOutput::new(root.path()).blobs.clone();
+ let wrapped = MediaArtifactTool::new(
+ BlobBackedMediaTool {
+ blobs: Arc::clone(&blobs),
+ },
+ ArtifactKind::Image,
+ workspace.clone(),
+ files_dir.clone(),
+ )
+ .with_blobs(Arc::clone(&blobs));
+
+ let result = wrapped.execute(json!({})).await.unwrap();
+ assert!(!result.is_error, "{result:?}");
+ let payload = json_payload(&result);
+ let artifact = &payload["artifacts"][0];
+ let artifact_id = artifact["artifact_id"]
+ .as_str()
+ .unwrap_or_else(|| panic!("blob-backed media was not filed: {artifact:?}"));
+ let record = crate::agent::artifacts::store::get_artifact(&workspace, artifact_id)
+ .await
+ .expect("artifact record");
+ let file = record.file.expect("visible file");
+ assert_eq!(std::fs::read(file).unwrap(), b"blob-media-bytes");
+ assert!(blobs
+ .get("generated-media/stub-0.png")
+ .await
+ .unwrap()
+ .is_none());
+}
+
#[tokio::test]
async fn files_a_single_generated_artifact() {
let root = tempfile::tempdir().unwrap();
diff --git a/crates/openhuman-core/src/media/generation/tools.rs b/crates/openhuman-core/src/media/generation/tools.rs
index 87599f67c6..914c9d722c 100644
--- a/crates/openhuman-core/src/media/generation/tools.rs
+++ b/crates/openhuman-core/src/media/generation/tools.rs
@@ -76,28 +76,35 @@ pub fn media_tools_from(
let MediaGenerators { image, video } = generators;
let output = MediaOutput::new(action_dir)
.with_reference_policy(reference_policy(action_dir, workspace_dir));
+ let output_blobs = Arc::clone(&output.blobs);
let tools: Vec<Box<dyn Tool>> = vec![
- Box::new(MediaArtifactTool::new(
- GenerateImageTool::new(Arc::clone(&image), output.clone())
- .with_name(IMAGE_TOOL_NAME)
- .with_description(IMAGE_DESCRIPTION)
- .with_permission_level(PermissionLevel::Execute)
- .with_category(ToolCategory::Workflow),
- ArtifactKind::Image,
- workspace_dir.to_path_buf(),
- files.clone(),
- )),
- Box::new(MediaArtifactTool::new(
- GenerateVideoTool::new(Arc::clone(&video), output)
- .with_name(VIDEO_TOOL_NAME)
- .with_description(VIDEO_DESCRIPTION)
- .with_permission_level(PermissionLevel::Execute)
- .with_category(ToolCategory::Workflow)
- .with_wait_policy(video_wait),
- ArtifactKind::Video,
- workspace_dir.to_path_buf(),
- files,
- )),
+ Box::new(
+ MediaArtifactTool::new(
+ GenerateImageTool::new(Arc::clone(&image), output.clone())
+ .with_name(IMAGE_TOOL_NAME)
+ .with_description(IMAGE_DESCRIPTION)
+ .with_permission_level(PermissionLevel::Execute)
+ .with_category(ToolCategory::Workflow),
+ ArtifactKind::Image,
+ workspace_dir.to_path_buf(),
+ files.clone(),
+ )
+ .with_blobs(Arc::clone(&output_blobs)),
+ ),
+ Box::new(
+ MediaArtifactTool::new(
+ GenerateVideoTool::new(Arc::clone(&video), output)
+ .with_name(VIDEO_TOOL_NAME)
+ .with_description(VIDEO_DESCRIPTION)
+ .with_permission_level(PermissionLevel::Execute)
+ .with_category(ToolCategory::Workflow)
+ .with_wait_policy(video_wait),
+ ArtifactKind::Video,
+ workspace_dir.to_path_buf(),
+ files,
+ )
+ .with_blobs(output_blobs),
+ ),
Box::new(MediaListModelsTool { image, video }),
];
tracing::debug!("[media_generation] registered {} media tools", tools.len());
diff --git a/tests/media_generation_e2e.rs b/tests/media_generation_e2e.rs
index 7ce315a4f6..a0475154d6 100644
--- a/tests/media_generation_e2e.rs
+++ b/tests/media_generation_e2e.rs
@@ -217,7 +217,12 @@ async fn media_tools_deliver_images_and_videos_through_the_backend_proxy() {
assert_eq!(image_artifacts.len(), 1, "one filed image: {result:?}");
let image_id = image_artifacts[0]["artifact_id"]
.as_str()
- .expect("image filed as artifact")
+ .unwrap_or_else(|| {
+ panic!(
+ "image was not filed as an artifact: {:?}",
+ image_artifacts[0]
+ )
+ })
.to_owned();
// ── video: must poll through `completed` with no outputs ─────────────
@@ -242,7 +247,12 @@ async fn media_tools_deliver_images_and_videos_through_the_backend_proxy() {
assert_eq!(video_artifacts.len(), 1, "one filed video: {result:?}");
let video_id = video_artifacts[0]["artifact_id"]
.as_str()
- .expect("video filed as artifact")
+ .unwrap_or_else(|| {
+ panic!(
+ "video was not filed as an artifact: {:?}",
+ video_artifacts[0]
+ )
+ })
.to_owned();
assert!(
backend.polls.load(Ordering::SeqCst) >= 4,
@@ -250,12 +260,9 @@ async fn media_tools_deliver_images_and_videos_through_the_backend_proxy() {
);
// ── artifacts are persisted and their visible files resolve ──────────
- assert_eq!(
- std::fs::read_dir(action_dir.join("generated-media"))
- .expect("generated-media staging directory")
- .count(),
- 0,
- "filed media must leave the staging directory"
+ assert!(
+ !action_dir.join("generated-media").exists(),
+ "blob-backed generation must not leave a filesystem staging directory"
);
for (id, kind) in [(&image_id, "image"), (&video_id, "video")] {
let record = openhuman_core::agent::artifacts::ops::ai_get_artifact(&config, id)