Skip to content

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

Merge upstream/main into feat/tiny-artifacts-service

Sanil9badfb605253
diff --cc crates/openhuman-core/src/agent/artifacts/mod.rs
index b107865778,51b699390a..4da9b385a8
--- a/crates/openhuman-core/src/agent/artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs
@@@ -6,10 -4,10 +6,11 @@@ pub mod production
pub mod schemas;
pub mod store;
mod store_documents;
-pub mod tools;
+pub mod tiny_store;
pub mod types;
+pub mod version_documents;
+ pub(crate) use files::resolve_ready_file_meta;
pub use files::{resolve_ready_file, FileRoots};
pub use migrate::{migrate_legacy_artifacts, MigrationReport};
pub use schemas::{
diff --cc crates/openhuman-core/src/media/generation/README.md
index 0ec98e541b,6ce6646b4f..9e46a77545
--- a/crates/openhuman-core/src/media/generation/README.md
+++ b/crates/openhuman-core/src/media/generation/README.md
@@@ -22,7 -22,7 +22,7 @@@ split across three layers, each with a
| --- | --- |
| [`provider.rs`](./provider.rs) | `managed_generators`: builds `MediaGenerators { image, video }` against the managed backend, or returns `None` when no backend transport is installed. Wraps each generator in a `Guard` that enforces local-only privacy mode and the egress disclosure before a request leaves the device, and the managed-credit budget gate before a billed submit. |
| [`tools.rs`](./tools.rs) | `build_media_tools`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over the generators from `provider.rs`. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory. |
--| [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, following the same `create_artifact` / `finalize_artifact` pattern the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. |
++| [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, through the same `Production` flow (reserve, write, complete) the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. |
| [`progress.rs`](./progress.rs) | Progress for a long generation call: a heartbeat every 15s through `ToolRunContext::report_progress` while the inner tool runs, carrying the video job state the `WaitPolicy::progress` observer records on each poll. The harness emits these as `AgentEvent::ToolProgressDetail`, which the host publishes on the web channel as `tool_progress`; the chat UI does not render it yet. |
| [`mod.rs`](./mod.rs) | Re-exports: `MediaArtifactTool`, `managed_generators`, `MediaGenerators`, `OPENROUTER_PROXY_PATH`, `build_media_tools`, `media_tools_from`, `MediaListModelsTool`, and the three tool-name constants. |
diff --cc crates/openhuman-core/src/media/generation/artifact_tool.rs
index a3798d08c0,f69527ca03..e5b068c927
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@@ -1,18 -1,20 +1,18 @@@
//! [`MediaArtifactTool`] — wraps a media-generation [`Tool`] (TinyAgents'
//! `GenerateImageTool` / `GenerateVideoTool`, boxed in `super::tools`) so
-//! every file the inner tool saves is also tracked as an OpenHuman artifact,
-//! following the pattern `tools/impl/document/mod.rs` and
-//! `tools/impl/presentation/mod.rs` use for their own producers
-//! (`create_artifact` → write bytes → `finalize_artifact`/`fail_artifact`).
+//! every file the inner tool saves is also filed as a versioned OpenHuman
+//! artifact, through the same [`Production`] flow the document and
+//! presentation producers use.
//!
- //! 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:
- //! starts a [`Production`] (recording the provider-assigned tool-call id so the
- //! card correlates with the tool-call bubble, #C5), moves the file into the
- //! artifact's reserved path, and completes it — or fails just that one
+ //! `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
-//! artifact's reserved path, and finalizes it — or fails just that one
++//! tool unchanged, then for every reported output: starts a [`Production`]
++//! (recording the provider-assigned tool-call id so the card correlates with
++//! the tool-call bubble, #C5), stores the blob or file into the artifact's
++//! reserved path, and completes it — or fails just that one
//! artifact and annotates its entry with `artifact_error`, without
//! disturbing the others (`n > 1` generations are common for images). On
//! success each entry gains an `artifact_id` field so the model (and the
@@@ -33,9 -36,11 +34,10 @@@ 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,
-};
+use crate::agent::artifacts::production::Production;
+use crate::agent::artifacts::ArtifactKind;
use crate::security::approval::ApprovalChatContext;
use crate::tools::host_extensions::tool_call_id;
use tinyagents_harness::tinyinference_video::ProgressFn;
@@@ -196,34 -261,213 +266,198 @@@ impl<T: Tool> MediaArtifactTool<T>
tracing::warn!(
target: "media_generation",
err = %err,
- "[media_generation] create_artifact failed; generated file left unfiled"
+ "[media_generation] could not open the artifact; generated file left unfiled"
);
set_artifact_error(entry, &err);
- return;
+ return None;
}
};
- if let Err(err) = move_or_copy(src, production.path()).await {
++ let dest = production.path().to_path_buf();
+ let stored = if src.is_absolute() {
+ move_or_copy(src, &dest).await
+ } else {
+ self.file_blob(src, &dest).await
+ };
- match stored {
- Ok(size_bytes) => {
- let canonical = dest.canonicalize().ok();
- let filed_path = canonical.as_deref().unwrap_or(&dest).display().to_string();
- if let Some(obj) = entry.as_object_mut() {
- obj.insert("path".into(), json!(filed_path));
++ if let Err(err) = stored {
+ production.fail(&err).await;
+ tracing::warn!(
+ target: "media_generation",
+ err = %err,
+ artifact_id = %production.id(),
+ "[media_generation] failed to file generated media as an artifact"
+ );
+ set_artifact_error(entry, &err);
- return;
++ return None;
+ }
- // The moved file becomes the artifact's first version; the card turns
++ let canonical = dest.canonicalize().ok();
++ let filed_path = canonical.as_deref().unwrap_or(&dest).display().to_string();
++ if let Some(obj) = entry.as_object_mut() {
++ obj.insert("path".into(), json!(filed_path));
++ }
++ // The stored file becomes the artifact's first version; the card turns
+ // ready from that record.
- match production.complete().await {
++ match self.complete_and_discard_blob(&production, src).await {
+ Ok(_) => {
++ if let (Some(allowed), Some(canonical)) = (&self.allowed_references, canonical) {
++ 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(allowed), Some(canonical)) =
- (&self.allowed_references, canonical)
- {
- allowed
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(canonical);
- }
- if let Some(obj) = entry.as_object_mut() {
- obj.insert("artifact_id".into(), json!(updated.id));
- }
- }
- Err(err) => {
- let _ = fail_artifact(
- &self.workspace_dir,
- &self.files_dir,
- &meta.id,
- &err,
- chat,
- )
- .await;
- set_artifact_error(entry, &err);
- }
+ if let Some(obj) = entry.as_object_mut() {
+ obj.insert("artifact_id".into(), json!(production.id()));
}
+ Some(filed_path)
+ }
+ Err(err) => {
- let _ =
- fail_artifact(&self.workspace_dir, &self.files_dir, &meta.id, &err, chat).await;
- tracing::warn!(
- target: "media_generation",
- err = %err,
- artifact_id = %meta.id,
- "[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(
++ /// Complete `production` and only then discard its source blob, so a
++ /// failed completion leaves the blob for a retry.
++ async fn complete_and_discard_blob(
+ &self,
- artifact_id: &str,
- size_bytes: u64,
- chat: Option<&ApprovalChatContext>,
++ production: &Production,
+ src: &Path,
- ) -> Result<crate::agent::artifacts::ArtifactMeta, String> {
- let finalized =
- finalize_artifact(&self.workspace_dir, artifact_id, size_bytes, chat).await?;
++ ) -> Result<u64, String> {
++ let size = production.complete().await?;
+ self.delete_blob_after_finalize(src).await;
- Ok(finalized)
++ Ok(size)
+ }
+
+ /// Rehydrates finalized media paths after a session rebuild. Only Ready
+ /// image/video artifacts whose files still resolve through the configured
+ /// trusted roots enter the exact-path allowlist.
+ async fn refresh_allowed_references(&self) -> Result<(), String> {
+ let Some(allowed) = &self.allowed_references else {
+ return Ok(());
+ };
+
+ let mut recovered = std::collections::HashSet::new();
+ let previously_allowed = allowed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ let artifacts = match crate::agent::artifacts::store::list_artifacts(
+ &self.workspace_dir,
+ 0,
+ usize::MAX,
+ None,
+ )
+ .await
+ {
+ Ok((artifacts, _)) => artifacts,
+ Err(error) => {
+ tracing::warn!(
+ target: "media_generation",
+ %error,
+ "[media_generation] could not refresh reusable artifact paths"
+ );
+ return Err(
+ "could not validate previously generated media references; retry the media call"
+ .to_string(),
+ );
}
- Err(err) => set_artifact_error(entry, &err),
+ };
+
+ for meta in artifacts.iter().filter(|meta| {
+ matches!(&meta.kind, ArtifactKind::Image | ArtifactKind::Video)
+ && matches!(&meta.status, crate::agent::artifacts::ArtifactStatus::Ready)
+ }) {
+ let Ok(path) = crate::agent::artifacts::resolve_ready_file_meta(
+ &self.workspace_dir,
+ &self.files_dir,
+ meta,
+ )
+ .await
+ else {
+ continue;
+ };
+ if let Ok(path) = tokio::fs::canonicalize(path).await {
+ recovered.insert(path);
+ }
+ }
+
+ // Prune paths that were allowed before this scan but are no longer
+ // Ready. Paths added concurrently after the snapshot are preserved.
+ let mut allowed = allowed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ allowed.retain(|path| !previously_allowed.contains(path) || recovered.contains(path));
+ allowed.extend(recovered);
+ Ok(())
+ }
+
+ 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"))?;
+ copy_blob_to_file(&mut *blob.reader, dest, key).await
+ }
+ }
+
+ async fn copy_blob_to_file<R>(reader: &mut R, dest: &Path, key: &str) -> Result<u64, String>
+ where
+ R: tokio::io::AsyncRead + Unpin + ?Sized,
+ {
+ 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 = match tokio::io::copy(reader, &mut file).await {
+ Ok(size) => size,
+ Err(error) => {
+ drop(file);
+ let _ = tokio::fs::remove_file(dest).await;
+ return Err(format!(
+ "failed to copy generated media blob {key:?}: {error}"
+ ));
}
+ };
+ if let Err(error) = file.flush().await {
+ drop(file);
+ let _ = tokio::fs::remove_file(dest).await;
+ return Err(format!(
+ "failed to flush artifact destination {}: {error}",
+ dest.display()
+ ));
}
+ Ok(size)
}
fn set_artifact_error(entry: &mut Value, message: &str) {
diff --cc crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
index a37f7edbb7,11ccb59a0d..f26e5e565d
--- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
@@@ -66,6 -185,167 +185,181 @@@ fn json_payload(result: &ToolResult) -
.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");
+ let canonical_file = std::path::Path::new(&file).canonicalize().unwrap();
+ assert_eq!(
+ artifact["path"].as_str(),
+ Some(canonical_file.to_str().unwrap())
+ );
+ assert_eq!(
+ result.markdown_formatted.as_deref(),
+ Some(format!("Saved image at {}\nCost: $0.01", canonical_file.display()).as_str())
+ );
+ assert_eq!(std::fs::read(&file).unwrap(), b"blob-media-bytes");
+ assert!(blobs
+ .get("generated-media/stub-0.png")
+ .await
+ .unwrap()
+ .is_none());
+
+ let (_, failed_file) = crate::agent::artifacts::create_artifact_for_call(
+ &workspace,
+ files_dir.clone(),
+ ArtifactKind::Video,
+ "Failed generated clip",
+ "mp4",
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ std::fs::write(&failed_file, b"failed output").unwrap();
+ let failed = crate::agent::artifacts::store::list_artifacts(&workspace, 0, 10, None)
+ .await
+ .unwrap()
+ .0
+ .into_iter()
+ .find(|meta| meta.title == "Failed generated clip")
+ .expect("failed artifact record");
+ crate::agent::artifacts::fail_artifact(
+ &workspace,
+ files_dir.clone(),
+ &failed.id,
+ "test finalization failure",
+ None,
+ )
+ .await
+ .unwrap();
+
+ let fresh = MediaArtifactTool::new(
+ StubMediaTool {
+ file_count: 0,
+ fail: false,
+ },
+ ArtifactKind::Image,
+ workspace.clone(),
+ files_dir,
+ )
+ .with_blobs(blobs)
+ .with_reference_allowlist(Arc::new(std::sync::Mutex::new(Default::default())));
+ fresh.refresh_allowed_references().await.unwrap();
+ {
+ let allowed = fresh.allowed_references.as_ref().unwrap().lock().unwrap();
+ assert!(allowed.contains(&canonical_file));
+ assert!(!allowed.contains(&failed_file.canonicalize().unwrap()));
+ }
+
+ crate::agent::artifacts::fail_artifact(
+ &workspace,
+ fresh.files_dir.clone(),
+ artifact_id,
+ "revoked for the refresh test",
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(
+ canonical_file.exists(),
+ "failed regeneration retains the previous non-empty file"
+ );
+ fresh.refresh_allowed_references().await.unwrap();
+ assert!(!fresh
+ .allowed_references
+ .as_ref()
+ .unwrap()
+ .lock()
+ .unwrap()
+ .contains(&canonical_file));
+ }
+
+ #[tokio::test]
+ async fn removes_partial_destination_when_blob_read_fails() {
+ let root = tempfile::tempdir().unwrap();
+ let dest = root.path().join("partial.png");
+ std::fs::write(&dest, b"reserved placeholder").unwrap();
+
+ let error = copy_blob_to_file(
+ &mut PartialThenFail(false),
+ &dest,
+ "generated-media/fail.png",
+ )
+ .await
+ .unwrap_err();
+
+ assert!(error.contains("failed to copy generated media blob"));
+ 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));
+
++ // An artifact whose file is gone cannot be completed.
++ let production = crate::agent::artifacts::production::Production::start(
++ &tool.workspace_dir,
++ tool.files_dir.clone(),
++ tiny_artifacts::ArtifactKind::Image,
++ "Finalize failure",
++ "png",
++ None,
++ None,
++ None,
++ )
++ .await
++ .unwrap();
++ let _ = std::fs::remove_file(production.path());
+ let error = tool
- .finalize_and_discard_blob("missing-artifact", 11, None, Path::new(key))
++ .complete_and_discard_blob(&production, 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 --cc scripts/ci/check-storage-bypass.mjs
index 66267f1355,36ac80d668..f12f2fd079
--- a/scripts/ci/check-storage-bypass.mjs
+++ b/scripts/ci/check-storage-bypass.mjs
@@@ -150,12 -150,12 +150,18 @@@ export const ALLOW = new Map
"match tokio::fs::OpenOptions::new()",
"reserves the artifact's content file in the user-visible files folder; the bytes stay a file on every backend (the port has no blob store), only the records moved",
],
+ [
+ "agent/artifacts/tiny_store.rs",
+ "json-write",
+ "tokio::fs::write(&dest, latest.body.as_bytes()).await?;",
+ "writes a text artifact's newest version into its file in the user-visible files folder; the deliverable is a user file on every backend, the versioned record itself goes through the artifact store",
+ ],
+ [
+ "media/generation/artifact_tool.rs",
+ "json-write",
+ "let mut file = tokio::fs::OpenOptions::new()",
+ "copies a generated media blob into the artifact's reserved user-visible file; the finalized file remains the artifact bytes on every backend because the storage port has no blob store",
+ ],
].reduce((map, [path, rule, site, reason]) => {
const key = `${SRC}${path}`;
map.set(key, [...(map.get(key) ?? []), { rule, site, reason }]);