Skip to content

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

fix: keep generated media paths usable

Steven Enamakelcce73000f897
diff --git a/crates/openhuman-core/src/media/README.md b/crates/openhuman-core/src/media/README.md
index 6fdac8db1d..b061cf60f7 100644
--- a/crates/openhuman-core/src/media/README.md
+++ b/crates/openhuman-core/src/media/README.md
@@ -40,10 +40,10 @@ When the agent calls `media_generate_image`, the TinyAgents tool parses the
arguments and calls the guarded generator. The guard checks the privacy
policy and announces the external transfer, checks the managed-credit budget,
then hands the request to TinyInference, which talks to OpenRouter through the
-backend proxy. The image is written under `<action_dir>/generated-media/`.
-`MediaArtifactTool` then moves each saved file into the visible files folder,
-records it as an artifact (metadata under the workspace's `artifacts/<id>/`),
-and adds an `artifact_id` to that file's entry in the result so the chat UI
+backend proxy. TinyAgents stores generated bytes in its media blob store.
+`MediaArtifactTool` copies each blob into the visible files folder, records it
+as an artifact (metadata under the workspace's `artifacts/<id>/`), and updates
+the JSON and Markdown result paths plus `artifact_id` so the chat UI
can show a card. Video works the same way, except the generator submits a job
and polls it (every 5 s, for up to 600 s) before downloading the clip. A
timed-out video can be resumed with `resume_job_id` instead of paying for a
@@ -89,7 +89,7 @@ Inside `generation/`:
| Tool | Permission | Effect |
| --- | --- | --- |
-| `media_generate_image` | Execute | Generates or edits images from a prompt, optionally with reference images (URLs or workspace paths). Billed per call. |
+| `media_generate_image` | Execute | Generates or edits images from a prompt, optionally with reference images (URLs or allowed local paths). Billed per call. |
| `media_generate_video` | Execute | Generates a short clip, optionally from a first or last frame. Blocks until ready. Billed per call. |
| `media_list_models` | ReadOnly | Lists image and/or video models with an optional substring filter. |
diff --git a/crates/openhuman-core/src/media/generation/README.md b/crates/openhuman-core/src/media/generation/README.md
index 0ec98e541b..26d711c86f 100644
--- a/crates/openhuman-core/src/media/generation/README.md
+++ b/crates/openhuman-core/src/media/generation/README.md
@@ -39,10 +39,12 @@ split across three layers, each with a different owner:
`build_media_tools` is called from wherever the tool registry assembles the
agent's tool list; it returns an empty list rather than erroring when no
backend transport is installed, so a library host with no TinyHumans
-connection simply has no media tools rather than a broken one. Generated
-files land under `<action_dir>/generated-media/`, and `MediaArtifactTool`
-moves each one into the visible files folder (`~/OpenHuman/projects/Files`, metadata in the workspace's `artifacts/<id>/`) so it shows up
-as a card in the chat UI. Billing and margin stay backend-side: this module
+connection simply has no media tools rather than a broken one. TinyAgents
+stores generated bytes in its media blob store, and `MediaArtifactTool` copies
+each one into the visible files folder (`~/OpenHuman/projects/Files`, metadata
+in the workspace's `artifacts/<id>/`). JSON and Markdown results point at the
+filed path so it can be reused as a later media reference and shown as a card
+in the chat UI. Billing and margin stay backend-side: this module
never charges directly, it only refuses to submit when
`crate::integrations::client::budget_gate` reports the account's managed
credits are exhausted.
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs
index abfab4b02c..e33f6d40a5 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@ -59,6 +59,7 @@ pub struct MediaArtifactTool<T: Tool> {
/// Visible folder each generated file is moved into (#5505).
files_dir: crate::agent::artifacts::FileRoots,
blobs: Option<Arc<dyn tinystoragedrivers::BlobStore>>,
+ allowed_references: Option<super::tools::MediaReferenceAllowlist>,
/// Builds the inner tool for one call around that call's poll observer.
/// Set for the video tool, whose `WaitPolicy::progress` hook is fixed at
/// construction: a tool per call lets the observer record into the call's
@@ -86,6 +87,7 @@ impl<T: Tool> MediaArtifactTool<T> {
workspace_dir: workspace_dir.into(),
files_dir: files_dir.into(),
blobs: None,
+ allowed_references: None,
per_call: None,
}
}
@@ -99,6 +101,16 @@ impl<T: Tool> MediaArtifactTool<T> {
self
}
+ /// Allows later media calls to use only the exact files this wrapper filed.
+ #[must_use]
+ pub(crate) fn with_reference_allowlist(
+ mut self,
+ allowed_references: super::tools::MediaReferenceAllowlist,
+ ) -> Self {
+ self.allowed_references = Some(allowed_references);
+ self
+ }
+
/// Run each call on a tool built by `build` around that call's poll
/// observer and chat routing, so a long job's polled state reaches that
/// call's heartbeat and its egress disclosures reach that call's chat.
@@ -153,21 +165,31 @@ impl<T: Tool> MediaArtifactTool<T> {
return result;
};
let total = artifacts.len();
+ let mut filed_paths = Vec::new();
for (index, entry) in artifacts.iter_mut().enumerate() {
let Some(src_path) = entry.get("path").and_then(Value::as_str).map(PathBuf::from)
else {
continue;
};
- self.file_one(
- entry,
- &src_path,
- args,
- index,
- total,
- call_id.as_deref(),
- chat,
- )
- .await;
+ if let Some(filed_path) = self
+ .file_one(
+ entry,
+ &src_path,
+ args,
+ index,
+ total,
+ call_id.as_deref(),
+ chat,
+ )
+ .await
+ {
+ filed_paths.push((src_path.to_string_lossy().into_owned(), filed_path));
+ }
+ }
+ if let Some(markdown) = result.markdown_formatted.as_mut() {
+ for (source, destination) in filed_paths {
+ *markdown = markdown.replace(&source, &destination);
+ }
}
result
}
@@ -181,7 +203,7 @@ impl<T: Tool> MediaArtifactTool<T> {
total: usize,
call_id: Option<&str>,
chat: Option<&ApprovalChatContext>,
- ) {
+ ) -> Option<String> {
let ext = src
.extension()
.and_then(|e| e.to_str())
@@ -207,7 +229,7 @@ impl<T: Tool> MediaArtifactTool<T> {
"[media_generation] create_artifact failed; generated file left unfiled"
);
set_artifact_error(entry, &err);
- return;
+ return None;
}
};
let stored = if src.is_absolute() {
@@ -217,11 +239,25 @@ impl<T: Tool> MediaArtifactTool<T> {
};
match stored {
Ok(size_bytes) => {
- match finalize_artifact(&self.workspace_dir, &meta.id, size_bytes, chat).await {
+ let filed_path = dest.display().to_string();
+ if let Some(obj) = entry.as_object_mut() {
+ obj.insert("path".into(), json!(filed_path));
+ }
+ if let Some(allowed) = &self.allowed_references {
+ if let Ok(canonical) = dest.canonicalize() {
+ allowed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(canonical);
+ }
+ }
+ match self
+ .finalize_and_discard_blob(&meta.id, size_bytes, chat, src)
+ .await
+ {
Ok(updated) => {
if let Some(obj) = entry.as_object_mut() {
obj.insert("artifact_id".into(), json!(updated.id));
- obj.insert("path".into(), json!(dest.display().to_string()));
}
}
Err(err) => {
@@ -236,6 +272,7 @@ impl<T: Tool> MediaArtifactTool<T> {
set_artifact_error(entry, &err);
}
}
+ Some(filed_path)
}
Err(err) => {
let _ =
@@ -247,10 +284,41 @@ impl<T: Tool> MediaArtifactTool<T> {
"[media_generation] failed to file generated media as an artifact"
);
set_artifact_error(entry, &err);
+ None
}
}
}
+ async fn delete_blob_after_finalize(&self, src: &Path) {
+ if src.is_absolute() {
+ return;
+ }
+ let (Some(blobs), Some(key)) = (self.blobs.as_ref(), src.to_str()) else {
+ return;
+ };
+ if let Err(error) = blobs.delete(key).await {
+ tracing::warn!(
+ target: "media_generation",
+ %error,
+ blob_key = key,
+ "[media_generation] finalized media but could not discard its source blob"
+ );
+ }
+ }
+
+ async fn finalize_and_discard_blob(
+ &self,
+ artifact_id: &str,
+ size_bytes: u64,
+ chat: Option<&ApprovalChatContext>,
+ src: &Path,
+ ) -> Result<crate::agent::artifacts::ArtifactMeta, String> {
+ let finalized =
+ finalize_artifact(&self.workspace_dir, artifact_id, size_bytes, chat).await?;
+ self.delete_blob_after_finalize(src).await;
+ Ok(finalized)
+ }
+
async fn file_blob(&self, key: &Path, dest: &Path) -> Result<u64, String> {
let key = key
.to_str()
@@ -263,16 +331,7 @@ impl<T: Tool> MediaArtifactTool<T> {
.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 size = copy_blob_to_file(&mut *blob.reader, dest, key).await?;
- 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)
+ copy_blob_to_file(&mut *blob.reader, dest, key).await
}
}
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 8dfd12a8c1..65d087282a 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,6 @@
use async_trait::async_trait;
use serde_json::{json, Value};
+use std::path::Path;
use std::sync::Arc;
use tinyagents_harness::media::MediaOutput;
use tinystoragedrivers::BlobStore;
@@ -109,7 +110,7 @@ impl Tool for BlobBackedMediaTool {
"bytes": 16
}]
}),
- "generated blob-backed media",
+ "Saved image at generated-media/stub-0.png\nCost: $0.01",
))
}
}
@@ -153,6 +154,10 @@ async fn files_a_blob_backed_generated_artifact() {
.expect("artifact record");
let file = record.file.expect("visible file");
assert_eq!(artifact["path"].as_str(), Some(file.as_str()));
+ assert_eq!(
+ result.markdown_formatted.as_deref(),
+ Some(format!("Saved image at {file}\nCost: $0.01").as_str())
+ );
assert_eq!(std::fs::read(file).unwrap(), b"blob-media-bytes");
assert!(blobs
.get("generated-media/stub-0.png")
@@ -179,6 +184,36 @@ async fn removes_partial_destination_when_blob_read_fails() {
assert!(!dest.exists());
}
+#[tokio::test]
+async fn keeps_source_blob_when_artifact_finalization_fails() {
+ let root = tempfile::tempdir().unwrap();
+ let workspace = root.path().join("workspace");
+ let blobs = MediaOutput::new(root.path()).blobs.clone();
+ let key = "generated-media/finalize-failure.png";
+ blobs
+ .put(key, b"media bytes".to_vec(), Some("image/png"))
+ .await
+ .unwrap();
+ let tool = MediaArtifactTool::new(
+ StubMediaTool {
+ file_count: 0,
+ fail: false,
+ },
+ ArtifactKind::Image,
+ workspace,
+ root.path().join("Files"),
+ )
+ .with_blobs(Arc::clone(&blobs));
+
+ let error = tool
+ .finalize_and_discard_blob("missing-artifact", 11, None, Path::new(key))
+ .await
+ .unwrap_err();
+
+ assert!(error.contains("artifact"));
+ assert!(blobs.get(key).await.unwrap().is_some());
+}
+
#[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 8006f23e3e..f4850cf4b6 100644
--- a/crates/openhuman-core/src/media/generation/tools.rs
+++ b/crates/openhuman-core/src/media/generation/tools.rs
@@ -6,8 +6,9 @@
//! and the image/video agents' allowlists already use. `media_list_models`
//! lists what the generators can run.
+use std::collections::HashSet;
use std::path::{Component, Path, PathBuf};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use std::time::Duration;
use async_trait::async_trait;
@@ -33,15 +34,19 @@ pub const LIST_MODELS_TOOL_NAME: &str = "media_list_models";
const VIDEO_POLL_INTERVAL: Duration = Duration::from_secs(5);
const VIDEO_WAIT_BUDGET: Duration = Duration::from_secs(600);
+pub(crate) type MediaReferenceAllowlist = Arc<Mutex<HashSet<PathBuf>>>;
+
const IMAGE_DESCRIPTION: &str = "Generate or edit images from a text prompt via OpenRouter \
- (default model: Seedream 5.0 Lite). Pass `references` (https URLs or workspace file paths) \
+ (default model: Seedream 5.0 Lite). Pass `references` (https URLs, workspace paths, or \
+ paths returned by earlier media calls) \
to edit, restyle, or keep a subject consistent. Saves each image in the Files folder and \
returns its local file path. Billed per call: after an error that \
says the call was billed, do not call again — report it to the user.";
const VIDEO_DESCRIPTION: &str = "Generate a short video clip via OpenRouter (default model: \
Seedance 2.0 Mini, 4–15 s, 480p/720p, optional audio). Optionally start from \
- `first_frame` or end on `last_frame` (URL or workspace path). Blocks until the clip is \
+ `first_frame` or end on `last_frame` (URL, workspace path, or path returned by an earlier \
+ media call). Blocks until the clip is \
ready (minutes) and saves it in the Files folder. Billed per call: if it times out, \
call again with `resume_job_id` instead of submitting a new job.";
@@ -74,8 +79,12 @@ pub fn media_tools_from(
) -> Vec<Box<dyn Tool>> {
let files = files_dir.into();
let generators = Arc::new(generators);
- let output = MediaOutput::new(action_dir)
- .with_reference_policy(reference_policy(action_dir, workspace_dir));
+ let allowed_artifacts = Arc::new(Mutex::new(HashSet::new()));
+ let output = MediaOutput::new(action_dir).with_reference_policy(reference_policy(
+ action_dir,
+ workspace_dir,
+ Arc::clone(&allowed_artifacts),
+ ));
let output_blobs = Arc::clone(&output.blobs);
let image_tool = |image: &Arc<dyn ImageGenerator>| {
GenerateImageTool::new(Arc::clone(image), output.clone())
@@ -93,6 +102,7 @@ pub fn media_tools_from(
files.clone(),
)
.with_blobs(Arc::clone(&output_blobs))
+ .with_reference_allowlist(Arc::clone(&allowed_artifacts))
// A tool per call, around generators that disclose to that call's
// chat.
.with_per_call_inner({
@@ -116,6 +126,7 @@ pub fn media_tools_from(
files,
)
.with_blobs(output_blobs)
+ .with_reference_allowlist(Arc::clone(&allowed_artifacts))
.with_per_call_inner({
let generators = Arc::clone(&generators);
let output = output.clone();
@@ -158,6 +169,7 @@ fn video_tool(
pub(crate) fn reference_policy(
action_dir: &Path,
workspace_dir: &Path,
+ allowed_artifacts: MediaReferenceAllowlist,
) -> tinyagents_harness::media::ReferencePathPolicy {
let roots: Vec<PathBuf> = vec![action_dir.to_path_buf(), workspace_dir.to_path_buf()];
Arc::new(move |path: &Path| {
@@ -173,7 +185,11 @@ pub(crate) fn reference_policy(
path.display()
));
}
- if !roots.iter().any(|root| path.starts_with(root)) {
+ let is_filed_artifact = allowed_artifacts
+ .lock()
+ .map(|paths| paths.contains(path))
+ .unwrap_or(false);
+ if !is_filed_artifact && !roots.iter().any(|root| path.starts_with(root)) {
return Err(format!(
"reference path {} is outside the workspace; use a URL or a file inside the workspace",
path.display()
diff --git a/crates/openhuman-core/src/media/generation/tools_tests.rs b/crates/openhuman-core/src/media/generation/tools_tests.rs
index 8fbc65598c..998dab33e7 100644
--- a/crates/openhuman-core/src/media/generation/tools_tests.rs
+++ b/crates/openhuman-core/src/media/generation/tools_tests.rs
@@ -1,5 +1,6 @@
+use std::collections::HashSet;
use std::path::Path;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use serde_json::json;
use tinyagents_harness::tinyinference_image::MockImageGenerator;
@@ -129,13 +130,21 @@ async fn list_models_reports_both_catalogs_and_defaults() {
fn reference_policy_admits_workspace_files_only() {
let action = Path::new("/home/user/OpenHuman/projects");
let workspace = Path::new("/home/user/.openhuman/users/u/workspace");
- let policy = reference_policy(action, workspace);
+ let allowed_artifacts = Arc::new(Mutex::new(HashSet::new()));
+ let policy = reference_policy(action, workspace, Arc::clone(&allowed_artifacts));
assert!(policy(&action.join("art/ref.png")).is_ok());
assert!(policy(&workspace.join("attachments/photo.jpg")).is_ok());
assert!(policy(&action.join("../secret.png")).is_err());
assert!(policy(Path::new("/etc/passwd")).is_err());
assert!(policy(Path::new("/home/user/Documents/private.png")).is_err());
+ let files = tempfile::tempdir().unwrap();
+ let filed = files.path().join("generated.png");
+ std::fs::write(&filed, b"generated image").unwrap();
+ let filed = filed.canonicalize().unwrap();
+ allowed_artifacts.lock().unwrap().insert(filed.clone());
+ assert!(policy(&filed).is_ok());
+ assert!(policy(&files.path().join("unrelated.png")).is_err());
assert!(
policy(&action.join(".ssh/id_rsa")).is_err(),
"credential stores stay forbidden"
diff --git a/docs/gitbooks/en/features/native-tools/media-generation.md b/docs/gitbooks/en/features/native-tools/media-generation.md
index 48b9f66329..38043a4745 100644
--- a/docs/gitbooks/en/features/native-tools/media-generation.md
+++ b/docs/gitbooks/en/features/native-tools/media-generation.md
@@ -19,7 +19,7 @@ OpenHuman can make media, not just read it. Ask for "an image of…", "edit this
The `media_generation` domain (`crates/openhuman-core/src/media/generation/`) gives the agent three tools: generate image, generate video and list models. They use the OpenHuman backend's media-generation provider. The backend owns the provider keys, billing and rate limiting, and your subscription covers it like any other model call.
-The tools submit a job and then poll every 4 seconds, for up to 180 seconds for images and 420 seconds for video. You and the agent see live progress instead of a hung call. Finished files are downloaded into the `generated-media/` folder of your workspace and returned as local file paths, ready to attach, post or edit further.
+The tools submit a job and then poll every 4 seconds, for up to 180 seconds for images and 420 seconds for video. You and the agent see live progress instead of a hung call. Finished files are filed in the Files folder and returned as local file paths, ready to attach, post or edit further.
## Privacy
diff --git a/tests/x402_twit_sh_live.rs b/tests/x402_twit_sh_live.rs
index b4a96f5a3d..dc8fc1fc08 100644
--- a/tests/x402_twit_sh_live.rs
+++ b/tests/x402_twit_sh_live.rs
@@ -26,8 +26,13 @@ async fn x402_pay_twit_sh_for_hal_finney_tweet() {
action_dir: tmp.path().to_path_buf(),
..SecurityPolicy::default()
});
- let tool =
- openhuman_core::tools::http_request_tool(security, vec!["x402.twit.sh".into()], 0, 0);
+ let tool = openhuman_core::tools::http_request_tool(
+ &openhuman_core::core::runtime::DispatchCtx::ambient(),
+ security,
+ vec!["x402.twit.sh".into()],
+ 0,
+ 0,
+ );
let result = tool
.execute(json!({
"url": "https://x402.twit.sh/tweets/by/id?id=1110302988",