Skip to content

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

fix: optimize reusable media artifact lookup

Steven Enamakel97ae7230a60c
diff --git a/crates/openhuman-core/src/agent/artifacts/files.rs b/crates/openhuman-core/src/agent/artifacts/files.rs
index 4d4038204a..0b7183560a 100644
--- a/crates/openhuman-core/src/agent/artifacts/files.rs
+++ b/crates/openhuman-core/src/agent/artifacts/files.rs
@@ -84,6 +84,16 @@ impl FileRoots {
let root = canon(root);
self.trusted.iter().any(|t| canon(t) == root)
}
+
+ /// Whether an existing path is beneath any folder this host trusts for
+ /// artifact resolution, including prior Files-folder locations.
+ pub(crate) fn contains_path(&self, path: &Path) -> bool {
+ let canonical_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
+ self.trusted.iter().any(|root| {
+ let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
+ path.starts_with(root) || canonical_path.starts_with(&canonical_root)
+ })
+ }
}
impl From<PathBuf> for FileRoots {
@@ -256,15 +266,26 @@ pub async fn resolve_ready_file(
artifact_id: &str,
) -> Result<PathBuf, String> {
let meta = get_artifact(workspace_dir, artifact_id).await?;
- if !matches!(meta.status, ArtifactStatus::Ready) {
+ resolve_ready_file_meta(workspace_dir, roots, &meta).await
+}
+
+/// Resolve an already-loaded `Ready` artifact record to its existing file.
+/// Callers that list many records can reuse each row instead of loading it a
+/// second time by id.
+pub(crate) async fn resolve_ready_file_meta(
+ workspace_dir: &Path,
+ roots: &FileRoots,
+ meta: &ArtifactMeta,
+) -> Result<PathBuf, String> {
+ if !matches!(&meta.status, ArtifactStatus::Ready) {
return Err(format!(
- "[artifacts] artifact id={artifact_id} is not ready (status={:?})",
- meta.status
+ "[artifacts] artifact id={} is not ready (status={:?})",
+ meta.id, meta.status
));
}
- let path = resolve_file(workspace_dir, &meta, roots).await?;
+ let path = resolve_file(workspace_dir, meta, roots).await?;
if !tokio::fs::try_exists(&path).await.unwrap_or(false) {
- return Err(missing_file_error(artifact_id, &path));
+ return Err(missing_file_error(&meta.id, &path));
}
Ok(path)
}
diff --git a/crates/openhuman-core/src/agent/artifacts/mod.rs b/crates/openhuman-core/src/agent/artifacts/mod.rs
index faa254f38a..51b699390a 100644
--- a/crates/openhuman-core/src/agent/artifacts/mod.rs
+++ b/crates/openhuman-core/src/agent/artifacts/mod.rs
@@ -7,6 +7,7 @@ mod store_documents;
pub mod tools;
pub mod types;
+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 --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
index 597232f9ac..ad766f77a5 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
@@ -8,7 +8,6 @@ fn cx() -> crate::core::runtime::DispatchCtx {
use crate::agent::orchestration::background_completions::{
forget_workspace_for_test, pending_for, record_completion, router_for_workspace, TestWorkspace,
};
-use crate::core::runtime::DispatchCtx;
use std::path::Path;
use std::sync::atomic::{AtomicU32, Ordering};
use tinyagents_tasks::DEFAULT_MAX_ATTEMPTS;
diff --git a/crates/openhuman-core/src/agent/plan_review/tool.rs b/crates/openhuman-core/src/agent/plan_review/tool.rs
index d196803145..e3bab947b2 100644
--- a/crates/openhuman-core/src/agent/plan_review/tool.rs
+++ b/crates/openhuman-core/src/agent/plan_review/tool.rs
@@ -11,7 +11,7 @@
use async_trait::async_trait;
use serde_json::json;
-use crate::agent::turn_origin::{self, AgentTurnOrigin};
+use crate::agent::turn_origin::AgentTurnOrigin;
use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext, ToolTimeout};
use super::gate;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
index cbb1404a99..cde64e18aa 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_adapter_tests.rs
@@ -13,9 +13,10 @@ use tinyinference_llm::message::Message;
use super::announcement_notes::{
integration_announcement_note, mcp_announcement_note, skill_announcement_note,
};
+use super::runtime_session::tool_surface::reconcile_synthesized_visibility;
use super::runtime_session::{
account_committed_turn_against_goal, begin_turn_resume, holistic_last_turn_usage,
- reconcile_synthesized_visibility, OpenHumanSessionState,
+ OpenHumanSessionState,
};
use super::{OpenHumanSessionFactory, OpenHumanSessionHooks, OpenHumanTranscriptCodec};
use crate::agent::tinyagents::host::OpenHumanRunContext;
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index f90393734e..6282ffc4cf 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -535,23 +535,6 @@ impl OpenHumanTurnPrelude {
}
}
-/// Reconcile visible delegate names without reopening a caller's explicit
-/// restriction. Revoked names disappear; a newly connected name is admitted
-/// only for the wildcard belt.
-pub(super) fn reconcile_synthesized_visibility(
- visible: &mut std::collections::HashSet<String>,
- previous: &std::collections::HashSet<String>,
- next: &std::collections::HashSet<String>,
- auto_include_new: bool,
-) {
- for name in previous.difference(next) {
- visible.remove(name);
- }
- if auto_include_new {
- visible.extend(next.iter().cloned());
- }
-}
-
#[path = "runtime_session_usage.rs"]
mod usage;
pub(super) use usage::{account_committed_turn_against_goal, holistic_last_turn_usage};
@@ -1067,7 +1050,7 @@ impl OpenHumanSessionHost {
}
#[path = "runtime_session_tool_surface.rs"]
-mod tool_surface;
+pub(super) mod tool_surface;
#[cfg(test)]
#[path = "runtime_session_juice_tests.rs"]
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs
index b3379e9ecd..fd2ab651c6 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tool_surface.rs
@@ -2,6 +2,23 @@
use super::*;
+/// Reconcile visible delegate names without reopening a caller's explicit
+/// restriction. Revoked names disappear; a newly connected name is admitted
+/// only for the wildcard belt.
+pub(in crate::agent::session_host) fn reconcile_synthesized_visibility(
+ visible: &mut std::collections::HashSet<String>,
+ previous: &std::collections::HashSet<String>,
+ next: &std::collections::HashSet<String>,
+ auto_include_new: bool,
+) {
+ for name in previous.difference(next) {
+ visible.remove(name);
+ }
+ if auto_include_new {
+ visible.extend(next.iter().cloned());
+ }
+}
+
impl OpenHumanTurnPrelude {
/// Rebuild every delegation-dependent tool view from the current cached
/// integration set, replacing rather than appending. A revoked delegate is
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 41f3a1e4e6..3df4e33b30 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -29,6 +29,8 @@ use tinyinference_llm::{
};
use tokio::sync::{Mutex as AsyncMutex, Notify};
+use checkpoint::absolute_checkpoint_dir;
+
use super::{
SubagentRunError, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus, SubagentUsage,
};
@@ -210,18 +212,6 @@ pub(super) fn host_in_flight(ctx: &crate::core::runtime::DispatchCtx) -> Arc<Hos
crate::core::runtime::slot_for(ctx)
}
-fn absolute_checkpoint_dir(path: PathBuf) -> PathBuf {
- std::fs::canonicalize(&path).unwrap_or_else(|_| {
- if path.is_absolute() {
- path
- } else {
- std::env::current_dir()
- .map(|cwd| cwd.join(&path))
- .unwrap_or(path)
- }
- })
-}
-
impl OpenHumanSubagentHost {
pub fn new(
definition: crate::agent::harness::host_definition::AgentDefinition,
@@ -294,8 +284,9 @@ impl OpenHumanSubagentHost {
checkpoint_dir: checkpoint_dir.clone(),
task_key: task_key.clone(),
};
+ let dispatch_ctx = parent.data.dispatch_ctx();
let (entry, is_leader) = {
- let mut entries = host_in_flight(&parent.data.dispatch_ctx()).lock_owned().await;
+ let mut entries = host_in_flight(&dispatch_ctx).lock_owned().await;
match entries.get(&lifecycle_key) {
Some(entry) => (entry.clone(), false),
None => {
@@ -333,7 +324,7 @@ impl OpenHumanSubagentHost {
))
.await;
entry.complete(result.as_ref().ok().cloned()).await;
- let mut entries = host_in_flight(&parent.data.dispatch_ctx()).lock_owned().await;
+ let mut entries = host_in_flight(&dispatch_ctx).lock_owned().await;
if entries
.get(&lifecycle_key)
.is_some_and(|current| Arc::ptr_eq(current, &entry))
@@ -1239,3 +1230,6 @@ fn cost_source_of(charged: Option<&ChargedAmount>) -> tinyagents_harness::cost::
None => tinyagents_harness::cost::CostSource::Unknown,
}
}
+
+#[path = "lifecycle_checkpoint.rs"]
+mod checkpoint;
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle_checkpoint.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle_checkpoint.rs
new file mode 100644
index 0000000000..ac9d068be3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle_checkpoint.rs
@@ -0,0 +1,15 @@
+//! Canonicalize subagent checkpoint paths before reserving a lifecycle.
+
+use std::path::PathBuf;
+
+pub(super) fn absolute_checkpoint_dir(path: PathBuf) -> PathBuf {
+ std::fs::canonicalize(&path).unwrap_or_else(|_| {
+ if path.is_absolute() {
+ path
+ } else {
+ std::env::current_dir()
+ .map(|cwd| cwd.join(&path))
+ .unwrap_or(path)
+ }
+ })
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs
index add492d3c8..985a3f69bb 100644
--- a/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs
@@ -6,8 +6,11 @@ use super::*;
#[test]
fn crate_native_turn_source_retains_only_role_and_config() {
- let source =
- TurnModelSource::new_crate_native(&crate::core::runtime::DispatchCtx::ambient(), "chat", Arc::new(crate::config::Config::default()));
+ let source = TurnModelSource::new_crate_native(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ Arc::new(crate::config::Config::default()),
+ );
assert!(source.direct_model.is_none());
assert!(source.crate_native.is_some());
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
index de280aa91a..26d5a79cf1 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs
@@ -3,8 +3,8 @@
use std::sync::Arc;
-use crate::core::runtime::DispatchCtx;
pub(crate) use super::turn_model_resolver::TurnModelResolver;
+use crate::core::runtime::DispatchCtx;
use crate::agent::tinyagents::model::{BuiltTurnModels, TierRoutes, TurnChatModel};
use tinyinference_llm::model::ProfileOverrideModel;
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
index 8dede88376..670957371a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models_tests.rs
@@ -28,9 +28,13 @@ async fn role_pins_apply_when_the_primary_uses_config_routing() {
.host_overrides(Arc::new(overrides)),
);
CoreContext::scope(context, async {
- let models = TurnModelSource::new_crate_native(&crate::core::runtime::DispatchCtx::ambient(), "chat", Arc::new(config))
- .build("hint:chat", 0.0, None, None)
- .expect("config-routed models");
+ let models = TurnModelSource::new_crate_native(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ Arc::new(config),
+ )
+ .build("hint:chat", 0.0, None, None)
+ .expect("config-routed models");
let coding = models
.routes
.iter()
diff --git a/crates/openhuman-core/src/core/runtime/dispatch_ctx_tests.rs b/crates/openhuman-core/src/core/runtime/dispatch_ctx_tests.rs
index 1c9a399fdf..356fd8ca7b 100644
--- a/crates/openhuman-core/src/core/runtime/dispatch_ctx_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/dispatch_ctx_tests.rs
@@ -63,7 +63,9 @@ async fn explicit_turn_origin_wins_over_the_scoped_one_and_does_not_cross() {
assert_eq!(thread_of(&explicit), "b");
assert_eq!(explicit.turn_origin_or_scoped().map(|_| ()), Some(()));
let moved = explicit.clone();
- let from_task = tokio::spawn(async move { thread_of(&moved) }).await.unwrap();
+ let from_task = tokio::spawn(async move { thread_of(&moved) })
+ .await
+ .unwrap();
assert_eq!(from_task, "b");
assert_eq!(thread_of(&DispatchCtx::new(Arc::clone(&a))), "a");
})
diff --git a/crates/openhuman-core/src/cron/origin_tests.rs b/crates/openhuman-core/src/cron/origin_tests.rs
index 293c046587..3b3e2a6c8f 100644
--- a/crates/openhuman-core/src/cron/origin_tests.rs
+++ b/crates/openhuman-core/src/cron/origin_tests.rs
@@ -71,8 +71,14 @@ fn other_origins_have_no_job_origin() {
#[tokio::test]
async fn current_job_origin_reads_the_scoped_turn() {
- assert_eq!(current_job_origin(crate::agent::turn_origin::current().as_ref()), None);
- let got = with_origin(web_turn("t-9"), async { current_job_origin(crate::agent::turn_origin::current().as_ref()) }).await;
+ assert_eq!(
+ current_job_origin(crate::agent::turn_origin::current().as_ref()),
+ None
+ );
+ let got = with_origin(web_turn("t-9"), async {
+ current_job_origin(crate::agent::turn_origin::current().as_ref())
+ })
+ .await;
assert!(matches!(got, Some(JobOrigin::Web { thread_id, .. }) if thread_id == "t-9"));
}
diff --git a/crates/openhuman-core/src/flows/memory_tools.rs b/crates/openhuman-core/src/flows/memory_tools.rs
index 8ffd79e339..b609c01990 100644
--- a/crates/openhuman-core/src/flows/memory_tools.rs
+++ b/crates/openhuman-core/src/flows/memory_tools.rs
@@ -33,7 +33,7 @@ use tinymemory_api::{
};
use tinytools::{PermissionLevel, Tool, ToolResult};
-use crate::agent::turn_origin::{self, AgentTurnOrigin, TrustedAutomationSource};
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
use crate::memory::types::{LearnParams, RecallParams};
use crate::memory::{MemoryError, MemoryResult};
diff --git a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
index fd50ee8258..26386cb25d 100644
--- a/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/memory_adapter.rs
@@ -38,7 +38,9 @@ use serde_json::{json, Value};
use tinyflows::caps::MemoryProvider;
use tinyflows::error::{EngineError, Result};
-use crate::agent::turn_origin::{self, AgentTurnOrigin, TrustedAutomationSource};
+#[cfg(test)]
+use crate::agent::turn_origin;
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
use crate::flows::{
cross_flow_filter, flow_filter, flow_key_of, flow_key_tag, forget_matching, remember_keyed,
diff --git a/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs b/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
index 4bee1c5fed..55819e80f8 100644
--- a/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/factory_crate_native_tests.rs
@@ -191,15 +191,28 @@ async fn one_shot_chat_models_preserve_factory_temperature_as_request_default()
.await
.expect("explicit-temperature invoke");
- let turn_model = create_turn_chat_model(&crate::core::runtime::DispatchCtx::ambient(), "chat", &config, "hint:chat", 0.2).expect("turn model");
+ let turn_model = create_turn_chat_model(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ &config,
+ "hint:chat",
+ 0.2,
+ )
+ .expect("turn model");
turn_model
.invoke(&(), ModelRequest::new(vec![Message::user("turn default")]))
.await
.expect("turn default-temperature invoke");
- let explicit_turn_model =
- create_turn_chat_model_from_string(&crate::core::runtime::DispatchCtx::ambient(), "chat", "openhuman", &config, "hint:chat", 0.4)
- .expect("explicit turn model");
+ let explicit_turn_model = create_turn_chat_model_from_string(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ "openhuman",
+ &config,
+ "hint:chat",
+ 0.4,
+ )
+ .expect("explicit turn model");
explicit_turn_model
.invoke(
&(),
@@ -527,8 +540,14 @@ async fn native_claude_turn_routes_disclose_pinned_models() {
let pinned_sdk = "egress-sdk-pinned-marker";
let mut sdk_config = Config::default();
sdk_config.chat_provider = Some(format!("claude_agent_sdk:{configured_sdk}"));
- create_turn_chat_model(&crate::core::runtime::DispatchCtx::ambient(), "chat", &sdk_config, pinned_sdk, 0.0)
- .expect("Claude Agent SDK turn model should build");
+ create_turn_chat_model(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ &sdk_config,
+ pinned_sdk,
+ 0.0,
+ )
+ .expect("Claude Agent SDK turn model should build");
let configured_code = "egress-code-configured-marker";
let pinned_code = "egress-code-pinned-marker";
@@ -537,7 +556,13 @@ async fn native_claude_turn_routes_disclose_pinned_models() {
// Egress is disclosed once the effective model is selected, before the
// environment probe. The test therefore remains valid on hosts without the
// Claude Code CLI.
- let _ = create_turn_chat_model(&crate::core::runtime::DispatchCtx::ambient(), "chat", &code_config, pinned_code, 0.0);
+ let _ = create_turn_chat_model(
+ &crate::core::runtime::DispatchCtx::ambient(),
+ "chat",
+ &code_config,
+ pinned_code,
+ 0.0,
+ );
let sentinel = "egress-native-claude-sentinel-end";
BUS.publish(DomainEvent::ExternalTransferPending {
diff --git a/crates/openhuman-core/src/media/generation/artifact_tool.rs b/crates/openhuman-core/src/media/generation/artifact_tool.rs
index 6755bf295a..dd74e33d4d 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool.rs
@@ -47,6 +47,41 @@ use tinyagents_harness::tinyinference_video::ProgressFn;
use super::progress::{video_status_observer, JobStateSlot};
+const FILE_REFERENCE_FIELDS: [&str; 8] = [
+ "references",
+ "reference_images",
+ "input_images",
+ "inputImages",
+ "first_frame",
+ "inputImage",
+ "input_image",
+ "last_frame",
+];
+
+/// Whether a media call references an absolute path under a trusted Files root.
+/// Only these requests need a durable-artifact refresh before tool execution.
+fn has_reusable_files_reference(args: &Value, files: &crate::agent::artifacts::FileRoots) -> bool {
+ for field in FILE_REFERENCE_FIELDS {
+ let Some(value) = args.get(field) else {
+ continue;
+ };
+ let candidates = value.as_str().into_iter().chain(
+ value
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str),
+ );
+ if candidates.into_iter().any(|candidate| {
+ let path = Path::new(candidate);
+ path.is_absolute() && files.contains_path(path)
+ }) {
+ return true;
+ }
+ }
+ false
+}
+
/// Maximum characters of the prompt kept in a generated artifact's title.
const TITLE_PROMPT_CHARS: usize = 60;
@@ -333,49 +368,40 @@ impl<T: Tool> MediaArtifactTool<T> {
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
- let mut offset = 0usize;
- loop {
- let (artifacts, total) = match crate::agent::artifacts::store::list_artifacts(
+ 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;
+ }
+ };
+
+ 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,
- offset,
- 200,
- None,
+ &self.files_dir,
+ meta,
)
.await
- {
- Ok(page) => page,
- Err(error) => {
- tracing::warn!(
- target: "media_generation",
- %error,
- "[media_generation] could not refresh reusable artifact paths"
- );
- return;
- }
+ else {
+ continue;
};
-
- 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(
- &self.workspace_dir,
- &self.files_dir,
- &meta.id,
- )
- .await
- else {
- continue;
- };
- if let Ok(path) = tokio::fs::canonicalize(path).await {
- recovered.insert(path);
- }
- }
-
- let page_len = artifacts.len();
- offset = offset.saturating_add(page_len);
- if page_len == 0 || offset >= total {
- break;
+ if let Ok(path) = tokio::fs::canonicalize(path).await {
+ recovered.insert(path);
}
}
@@ -535,7 +561,9 @@ impl<T: Tool> Tool for MediaArtifactTool<T> {
options: ToolCallOptions,
context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- self.refresh_allowed_references().await;
+ if has_reusable_files_reference(&args, &self.files_dir) {
+ self.refresh_allowed_references().await;
+ }
// Generation blocks for minutes; report a heartbeat (with the video
// job's polled state) so the wait is visible on the call.
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 e85cc17401..1b42f8ee0a 100644
--- a/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
+++ b/crates/openhuman-core/src/media/generation/artifact_tool_tests.rs
@@ -6,8 +6,35 @@ use tinyagents_harness::media::MediaOutput;
use tinystoragedrivers::BlobStore;
use tinytools::{PermissionLevel, Tool, ToolCategory, ToolContent, ToolResult};
-use super::{copy_blob_to_file, MediaArtifactTool};
-use crate::agent::artifacts::{ArtifactKind, ArtifactStatus};
+use super::{copy_blob_to_file, has_reusable_files_reference, MediaArtifactTool};
+use crate::agent::artifacts::{ArtifactKind, ArtifactStatus, FileRoots};
+
+#[test]
+fn artifact_history_is_refreshed_only_for_absolute_paths_in_files_roots() {
+ let root = tempfile::tempdir().unwrap();
+ let files = root.path().join("Files");
+ std::fs::create_dir_all(&files).unwrap();
+ let roots = FileRoots::new(&files);
+ let filed = files.join("generated.png");
+ let outside = root.path().join("action/generated.png");
+
+ assert!(has_reusable_files_reference(
+ &json!({ "references": [filed.to_string_lossy()] }),
+ &roots
+ ));
+ assert!(!has_reusable_files_reference(
+ &json!({ "references": ["https://example.test/image.png"] }),
+ &roots
+ ));
+ assert!(!has_reusable_files_reference(
+ &json!({ "first_frame": outside.to_string_lossy() }),
+ &roots
+ ));
+ assert!(!has_reusable_files_reference(
+ &json!({ "references": ["generated.png"] }),
+ &roots
+ ));
+}
struct PartialThenFail(bool);
diff --git a/crates/openhuman-core/src/media/generation/mod.rs b/crates/openhuman-core/src/media/generation/mod.rs
index 48b723677c..e2d0229444 100644
--- a/crates/openhuman-core/src/media/generation/mod.rs
+++ b/crates/openhuman-core/src/media/generation/mod.rs
@@ -21,6 +21,7 @@ pub mod tools;
pub use artifact_tool::MediaArtifactTool;
pub use provider::{managed_generators, MediaGenerators, OPENROUTER_PROXY_PATH};
+pub(crate) use tools::build_media_tools_with_allowlist;
pub use tools::{
build_media_tools, media_tools_from, MediaListModelsTool, IMAGE_TOOL_NAME,
LIST_MODELS_TOOL_NAME, VIDEO_TOOL_NAME,
diff --git a/crates/openhuman-core/src/media/generation/tools.rs b/crates/openhuman-core/src/media/generation/tools.rs
index f4850cf4b6..78d14e8ef4 100644
--- a/crates/openhuman-core/src/media/generation/tools.rs
+++ b/crates/openhuman-core/src/media/generation/tools.rs
@@ -52,10 +52,22 @@ const VIDEO_DESCRIPTION: &str = "Generate a short video clip via OpenRouter (def
/// Registers the media tools, or nothing when no backend is reachable.
pub fn build_media_tools(root_config: &Config, action_dir: &Path) -> Vec<Box<dyn Tool>> {
+ build_media_tools_with_allowlist(
+ root_config,
+ action_dir,
+ Arc::new(Mutex::new(HashSet::new())),
+ )
+}
+
+pub(crate) fn build_media_tools_with_allowlist(
+ root_config: &Config,
+ action_dir: &Path,
+ allowed_references: MediaReferenceAllowlist,
+) -> Vec<Box<dyn Tool>> {
let Some(generators) = managed_generators(root_config) else {
return Vec::new();
};
- media_tools_from(
+ media_tools_from_with_allowlist(
generators,
action_dir,
&root_config.workspace_dir,
@@ -64,6 +76,7 @@ pub fn build_media_tools(root_config: &Config, action_dir: &Path) -> Vec<Box<dyn
// (`super::progress`, wired per call by `MediaArtifactTool`), so a
// multi-minute wait is not silent.
WaitPolicy::new(VIDEO_POLL_INTERVAL, VIDEO_WAIT_BUDGET),
+ allowed_references,
)
}
@@ -76,10 +89,27 @@ pub fn media_tools_from(
workspace_dir: &Path,
files_dir: impl Into<crate::agent::artifacts::FileRoots>,
video_wait: WaitPolicy,
+) -> Vec<Box<dyn Tool>> {
+ media_tools_from_with_allowlist(
+ generators,
+ action_dir,
+ workspace_dir,
+ files_dir,
+ video_wait,
+ Arc::new(Mutex::new(HashSet::new())),
+ )
+}
+
+fn media_tools_from_with_allowlist(
+ generators: MediaGenerators,
+ action_dir: &Path,
+ workspace_dir: &Path,
+ files_dir: impl Into<crate::agent::artifacts::FileRoots>,
+ video_wait: WaitPolicy,
+ allowed_artifacts: MediaReferenceAllowlist,
) -> Vec<Box<dyn Tool>> {
let files = files_dir.into();
let generators = Arc::new(generators);
- let allowed_artifacts = Arc::new(Mutex::new(HashSet::new()));
let output = MediaOutput::new(action_dir).with_reference_policy(reference_policy(
action_dir,
workspace_dir,
@@ -187,8 +217,8 @@ pub(crate) fn reference_policy(
}
let is_filed_artifact = allowed_artifacts
.lock()
- .map(|paths| paths.contains(path))
- .unwrap_or(false);
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains(path);
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",
diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rs
index 992a872cd6..7b40a6ff7b 100644
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@ -5,7 +5,6 @@ fn ambient() -> DispatchCtx {
}
use crate::memory::scope::MemoryIdentity;
use crate::memory::test_fixtures::{bind_reference, config_in, stored};
-use std::collections::HashSet;
use std::path::{Path, PathBuf};
use tinymemory_api::{ItemKind, MetaFilter, Namespace};
diff --git a/crates/openhuman-core/src/security/approval/gate.rs b/crates/openhuman-core/src/security/approval/gate.rs
index 288d2bf4cb..013b206ba1 100644
--- a/crates/openhuman-core/src/security/approval/gate.rs
+++ b/crates/openhuman-core/src/security/approval/gate.rs
@@ -37,7 +37,9 @@ use std::time::Duration;
use parking_lot::Mutex;
use tokio::sync::oneshot;
-use crate::agent::turn_origin::{self, AgentTurnOrigin, TrustedAutomationSource};
+#[cfg(test)]
+use crate::agent::turn_origin;
+use crate::agent::turn_origin::{AgentTurnOrigin, TrustedAutomationSource};
use crate::config::Config;
use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
diff --git a/crates/openhuman-core/src/security/policy/enforcement.rs b/crates/openhuman-core/src/security/policy/enforcement.rs
index 3e5f307670..183905d966 100644
--- a/crates/openhuman-core/src/security/policy/enforcement.rs
+++ b/crates/openhuman-core/src/security/policy/enforcement.rs
@@ -267,6 +267,8 @@ impl SecurityPolicy {
require_approval_for_medium_risk: autonomy_config.require_approval_for_medium_risk,
block_high_risk_commands: autonomy_config.block_high_risk_commands,
trusted_roots,
+ media_artifact_paths: Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
+ media_files_roots: Arc::new(std::sync::Mutex::new(None)),
allow_tool_install: autonomy_config.allow_tool_install,
auto_approve: autonomy_config.auto_approve.clone(),
auto_approve_all: autonomy_config.auto_approve_all,
diff --git a/crates/openhuman-core/src/security/policy/mod.rs b/crates/openhuman-core/src/security/policy/mod.rs
index 5ef37682cc..aaac97ec15 100644
--- a/crates/openhuman-core/src/security/policy/mod.rs
+++ b/crates/openhuman-core/src/security/policy/mod.rs
@@ -32,3 +32,7 @@ mod policy_disabled_tests;
#[cfg(test)]
mod proptest_tests;
+
+#[cfg(test)]
+#[path = "policy_media_artifact_tests.rs"]
+mod policy_media_artifact_tests;
diff --git a/crates/openhuman-core/src/security/policy/path_checks.rs b/crates/openhuman-core/src/security/policy/path_checks.rs
index 2bc8da8d58..aae84e7110 100644
--- a/crates/openhuman-core/src/security/policy/path_checks.rs
+++ b/crates/openhuman-core/src/security/policy/path_checks.rs
@@ -96,6 +96,21 @@ impl SecurityPolicy {
return false;
}
+ // Media outputs live in the configured Files folder, which can be
+ // outside the action/workspace roots. Let those candidates reach the
+ // asynchronous Ready-artifact check in `validate_path`; a Files-root
+ // match alone never grants the read.
+ if self.is_media_artifact_path_cached(expanded_path)
+ || self
+ .media_files_roots
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .as_ref()
+ .is_some_and(|roots| roots.contains_path(expanded_path))
+ {
+ return true;
+ }
+
// With the policy disabled, containment (`workspace_only`,
// `forbidden_paths`, trusted roots, the workspace-internal boundary) is
// inert; the host's container/jail is what bounds the agent. The
@@ -327,7 +342,9 @@ impl SecurityPolicy {
let resolved = tokio::fs::canonicalize(&full_path)
.await
.map_err(|e| format!("Failed to resolve path '{path}': {e}"))?;
- if !self.is_resolved_path_allowed_for(&resolved, false) {
+ if !self.is_resolved_path_allowed_for(&resolved, false)
+ && !self.authorize_ready_media_artifact_path(&resolved).await
+ {
return Err(format!(
"{POLICY_BLOCKED_MARKER} Resolved path escapes workspace: {}",
resolved.display()
@@ -556,6 +573,9 @@ impl SecurityPolicy {
if !self.enabled {
return true;
}
+ if !require_write && self.is_media_artifact_path_cached(resolved) {
+ return true;
+ }
let workspace_root = self.workspace_root_sync();
resolved.starts_with(&workspace_root)
|| self.is_within_trusted_root(resolved, require_write)
@@ -587,6 +607,9 @@ impl SecurityPolicy {
resolved.display()
));
}
+ if self.is_media_artifact_path_cached(resolved) {
+ return Ok(());
+ }
// A trusted-root grant takes precedence over forbidden_paths for its subtree.
if self.is_within_trusted_root(resolved, false) {
return Ok(());
@@ -610,4 +633,76 @@ impl SecurityPolicy {
}
Ok(())
}
+
+ fn is_media_artifact_path_cached(&self, path: &Path) -> bool {
+ self.media_artifact_paths
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .contains(path)
+ }
+
+ /// Resolve a candidate outside the normal tool roots through the durable
+ /// artifact store. Only Ready image/video files in configured Files roots
+ /// are cached for the read-only file inspection tools.
+ async fn authorize_ready_media_artifact_path(&self, path: &Path) -> bool {
+ if Self::is_always_forbidden(path) || self.is_workspace_internal_path(path) {
+ return false;
+ }
+ let Some(roots) = self
+ .media_files_roots
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone()
+ else {
+ return false;
+ };
+ if !roots.contains_path(path) {
+ return false;
+ }
+
+ 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: "security",
+ %error,
+ "[security] could not resolve a media artifact read"
+ );
+ return false;
+ }
+ };
+
+ for meta in artifacts.iter().filter(|meta| {
+ matches!(
+ &meta.kind,
+ crate::agent::artifacts::ArtifactKind::Image
+ | crate::agent::artifacts::ArtifactKind::Video
+ ) && matches!(&meta.status, crate::agent::artifacts::ArtifactStatus::Ready)
+ }) {
+ let Ok(ready_path) =
+ crate::agent::artifacts::resolve_ready_file_meta(&self.workspace_dir, &roots, meta)
+ .await
+ else {
+ continue;
+ };
+ let Ok(ready_path) = tokio::fs::canonicalize(ready_path).await else {
+ continue;
+ };
+ if ready_path == path {
+ self.media_artifact_paths
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(ready_path);
+ return true;
+ }
+ }
+ false
+ }
}
diff --git a/crates/openhuman-core/src/security/policy/policy_media_artifact_tests.rs b/crates/openhuman-core/src/security/policy/policy_media_artifact_tests.rs
new file mode 100644
index 0000000000..60541eb982
--- /dev/null
+++ b/crates/openhuman-core/src/security/policy/policy_media_artifact_tests.rs
@@ -0,0 +1,79 @@
+use super::*;
+use crate::agent::artifacts::{create_artifact, finalize_artifact, ArtifactKind, FileRoots};
+use std::sync::Arc;
+use tempfile::TempDir;
+
+#[tokio::test]
+async fn ready_media_artifacts_are_readable_but_other_files_are_not() {
+ let tmp = TempDir::new().unwrap();
+ let workspace = tmp.path().join("workspace");
+ let files = tmp.path().join("Files");
+ tokio::fs::create_dir_all(&workspace).await.unwrap();
+ tokio::fs::create_dir_all(&files).await.unwrap();
+
+ let (image, image_path) = create_artifact(
+ &workspace,
+ &files,
+ ArtifactKind::Image,
+ "Generated image",
+ "png",
+ None,
+ )
+ .await
+ .unwrap();
+ tokio::fs::write(&image_path, b"image bytes").await.unwrap();
+ finalize_artifact(&workspace, &image.id, 11, None)
+ .await
+ .unwrap();
+
+ let (document, document_path) = create_artifact(
+ &workspace,
+ &files,
+ ArtifactKind::Document,
+ "Other file",
+ "txt",
+ None,
+ )
+ .await
+ .unwrap();
+ tokio::fs::write(&document_path, b"document bytes")
+ .await
+ .unwrap();
+ finalize_artifact(&workspace, &document.id, 14, None)
+ .await
+ .unwrap();
+
+ let (_pending_video, pending_path) = create_artifact(
+ &workspace,
+ &files,
+ ArtifactKind::Video,
+ "Pending video",
+ "mp4",
+ None,
+ )
+ .await
+ .unwrap();
+ tokio::fs::write(&pending_path, b"pending bytes")
+ .await
+ .unwrap();
+
+ let policy = SecurityPolicy {
+ workspace_dir: workspace,
+ action_dir: tmp.path().join("action"),
+ media_files_roots: Arc::new(std::sync::Mutex::new(Some(FileRoots::new(files)))),
+ ..SecurityPolicy::default()
+ };
+
+ assert!(policy
+ .validate_path(&image_path.to_string_lossy())
+ .await
+ .is_ok());
+ assert!(policy
+ .validate_path(&document_path.to_string_lossy())
+ .await
+ .is_err());
+ assert!(policy
+ .validate_path(&pending_path.to_string_lossy())
+ .await
+ .is_err());
+}
diff --git a/crates/openhuman-core/src/security/policy/types.rs b/crates/openhuman-core/src/security/policy/types.rs
index f7c7cf4d50..c2f36c2ec0 100644
--- a/crates/openhuman-core/src/security/policy/types.rs
+++ b/crates/openhuman-core/src/security/policy/types.rs
@@ -2,6 +2,7 @@ use crate::config::PrivacyMode;
use parking_lot::Mutex;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
@@ -259,6 +260,15 @@ pub struct SecurityPolicy {
pub block_high_risk_commands: bool,
/// Directories outside the workspace the agent may access (read or read-write).
pub trusted_roots: Vec<TrustedRoot>,
+ /// Exact, finalized media artifact files admitted for read-only inspection.
+ /// Shared with the media tools so file_read and image_info follow the same
+ /// per-artifact grant without trusting the whole Files directory.
+ #[doc(hidden)]
+ pub media_artifact_paths: Arc<std::sync::Mutex<HashSet<PathBuf>>>,
+ /// Configured Files roots used to resolve Ready artifact records after a
+ /// session is rebuilt.
+ #[doc(hidden)]
+ pub media_files_roots: Arc<std::sync::Mutex<Option<crate::agent::artifacts::FileRoots>>>,
/// Whether the agent may install OS packages via the `install_tool` tool.
pub allow_tool_install: bool,
/// Tool names the user has pre-approved ("Always allow"). The `ApprovalGate`
@@ -409,6 +419,8 @@ impl Default for SecurityPolicy {
require_approval_for_medium_risk: true,
block_high_risk_commands: true,
trusted_roots: Vec::new(),
+ media_artifact_paths: Arc::new(std::sync::Mutex::new(HashSet::new())),
+ media_files_roots: Arc::new(std::sync::Mutex::new(None)),
allow_tool_install: false,
auto_approve: Vec::new(),
auto_approve_all: false,
diff --git a/crates/openhuman-core/src/threads/store/bus.rs b/crates/openhuman-core/src/threads/store/bus.rs
index 40b95f9c94..8038030836 100644
--- a/crates/openhuman-core/src/threads/store/bus.rs
+++ b/crates/openhuman-core/src/threads/store/bus.rs
@@ -351,7 +351,7 @@ struct ChannelTurnDescriptor<'a> {
}
async fn persist_channel_turn(
- ctx: &DispatchCtx,
+ _ctx: &DispatchCtx,
workspace_dir: &Path,
descriptor: ChannelTurnDescriptor<'_>,
) -> Result<(), String> {
@@ -360,7 +360,7 @@ async fn persist_channel_turn(
let client = crate::channels::module_fixture::client().await;
#[cfg(not(all(test, feature = "channels", feature = "modules")))]
let client = {
- let config = ctx.load_config().await?;
+ let config = _ctx.load_config().await?;
if config.workspace_dir != workspace_dir {
return Err("channel workspace changed".into());
}
diff --git a/crates/openhuman-core/src/threads/store/mod.rs b/crates/openhuman-core/src/threads/store/mod.rs
index d63aec580d..5cd48bfb50 100644
--- a/crates/openhuman-core/src/threads/store/mod.rs
+++ b/crates/openhuman-core/src/threads/store/mod.rs
@@ -33,10 +33,10 @@ pub mod blocking;
mod bus;
mod legacy_import;
-mod transcript_key;
#[cfg(test)]
#[path = "legacy_import_tests.rs"]
mod legacy_import_tests;
+mod transcript_key;
use backend as store;
use tinyagents_session::threads as types;
@@ -66,12 +66,12 @@ impl From<types::ConversationPurgeStats> for ConversationPurgeStats {
#[cfg(feature = "channels")]
pub(crate) use bus::claim_channel_turn;
pub use bus::register_conversation_persistence_subscriber;
-pub(crate) use transcript_key::bind_transcript_key;
pub use store::{
append_message, delete_messages_from, delete_thread, ensure_thread, get_messages, list_threads,
purge_threads, update_message, update_thread_labels, update_thread_title,
update_thread_working_dir, ConversationStore,
};
+pub(crate) use transcript_key::bind_transcript_key;
pub use types::{
is_deterministic_message_id, reply_run_id, run_reply_message_id, ConversationThread,
CreateConversationThread, CrossThreadHit, ThreadMessage as ConversationMessage,
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index e401d02a00..4f20244a56 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -405,10 +405,18 @@ pub fn all_tools_with_runtime(
// Gated by the `media` compile-time feature (#4804); absent from slim
// builds. Runtime `DomainSet::media` (#4796) still gates it when compiled.
#[cfg(feature = "media")]
- tools.extend(crate::media::generation::build_media_tools(
- root_config,
- action_dir,
- ));
+ {
+ *security
+ .media_files_roots
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) =
+ Some(crate::agent::artifacts::FileRoots::from_config(root_config));
+ tools.extend(crate::media::generation::build_media_tools_with_allowlist(
+ root_config,
+ action_dir,
+ Arc::clone(&security.media_artifact_paths),
+ ));
+ }
// Managed cloud file storage (S3 via the backend). Skipped when no
// integration client is configured; downloads land under `action_dir`.
diff --git a/crates/openhuman-core/src/util/mod.rs b/crates/openhuman-core/src/util/mod.rs
index 4164758baa..74079955d7 100644
--- a/crates/openhuman-core/src/util/mod.rs
+++ b/crates/openhuman-core/src/util/mod.rs
@@ -40,7 +40,7 @@ pub use text::{
};
pub use types::MaybeSet;
-#[cfg(test)]
-pub(crate) mod module_test_process;
#[cfg(test)]
pub(crate) mod classic_transcript_fixture;
+#[cfg(test)]
+pub(crate) mod module_test_process;
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index e26efe9df0..dc4a9a6aaf 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -351,6 +351,8 @@ pub(crate) fn spawn_progress_bridge(
// real beat lands one full interval after the turn begins.
heartbeat.tick().await;
let mut turn_active = false;
+ let bridge_ctx =
+ BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
loop {
let event = tokio::select! {
@@ -685,10 +687,8 @@ pub(crate) fn spawn_progress_bridge(
parent_call_id,
..
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_spawned(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
&mut subagent_parent_call_ids,
round,
@@ -715,10 +715,8 @@ pub(crate) fn spawn_progress_bridge(
dirty_status,
..
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_completed(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
&mut subagent_parent_call_ids,
&child_tool_counts,
@@ -740,10 +738,8 @@ pub(crate) fn spawn_progress_bridge(
task_id,
error,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_failed(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
&mut subagent_parent_call_ids,
&child_tool_counts,
@@ -760,10 +756,8 @@ pub(crate) fn spawn_progress_bridge(
worker_thread_id,
checkpoint_path,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_awaiting_user(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
&subagent_parent_call_ids,
round,
@@ -781,10 +775,8 @@ pub(crate) fn spawn_progress_bridge(
max_iterations,
extended_policy,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_iteration_started(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
round,
agent_id,
@@ -804,10 +796,8 @@ pub(crate) fn spawn_progress_bridge(
display_label,
display_detail,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_tool_call_started(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
&mut child_tool_counts,
round,
@@ -837,10 +827,8 @@ pub(crate) fn spawn_progress_bridge(
display_detail,
structured,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_tool_call_completed(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
round,
agent_id,
@@ -865,10 +853,8 @@ pub(crate) fn spawn_progress_bridge(
delta,
iteration,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_text_delta(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
round,
agent_id,
@@ -883,10 +869,8 @@ pub(crate) fn spawn_progress_bridge(
delta,
iteration,
} => {
- let ctx =
- BridgeCtx::new(&client_id, &thread_id, &request_id, &config, &dispatch_ctx);
subagent_events::on_subagent_thinking_delta(
- &ctx,
+ &bridge_ctx,
&mut emit_seq,
round,
agent_id,
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_subagent_tests.rs b/crates/openhuman-core/src/web_chat/progress_bridge_subagent_tests.rs
new file mode 100644
index 0000000000..304daa3a9e
--- /dev/null
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_subagent_tests.rs
@@ -0,0 +1,112 @@
+use super::*;
+
+#[tokio::test]
+async fn subagent_spawned_forwards_parent_call_id() {
+ let mut events = super::super::super::event_bus::subscribe_web_channel_events();
+ let thread_id = "thread-c1-spawned";
+ let tx = spawn_test_bridge(thread_id, "req-c1-spawned");
+
+ tx.send(AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-c1".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: Some("call-parent-1".into()),
+ })
+ .await
+ .unwrap();
+
+ let ev = recv_for_thread(&mut events, thread_id).await;
+ assert_eq!(ev.event, "subagent_spawned");
+ let subagent = ev.subagent.expect("subagent detail present");
+ assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-1"));
+}
+
+/// Terminal sub-agent events (`_completed`/`_failed`/`_awaiting_user`) must
+/// keep carrying the same `parent_call_id` the spawn recorded, even though
+/// those `AgentProgress` variants don't repeat it — the bridge remembers it
+/// per `task_id` (#C1).
+#[tokio::test]
+async fn subagent_completed_carries_parent_call_id_and_capped_output() {
+ let mut events = super::super::super::event_bus::subscribe_web_channel_events();
+ let thread_id = "thread-c1-completed";
+ let tx = spawn_test_bridge(thread_id, "req-c1-completed");
+
+ tx.send(AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-c1-done".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: Some("call-parent-2".into()),
+ })
+ .await
+ .unwrap();
+ let spawned = recv_for_thread(&mut events, thread_id).await;
+ assert_eq!(spawned.event, "subagent_spawned");
+
+ tx.send(AgentProgress::SubagentCompleted {
+ agent_id: "researcher".into(),
+ task_id: "sub-c1-done".into(),
+ elapsed_ms: 10,
+ iterations: 1,
+ output_chars: 5,
+ usage: None,
+ output: "final answer".into(),
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ stop: None,
+ })
+ .await
+ .unwrap();
+
+ let completed = recv_for_thread(&mut events, thread_id).await;
+ assert_eq!(completed.event, "subagent_completed");
+ let subagent = completed.subagent.expect("subagent detail present");
+ assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-2"));
+ assert_eq!(subagent.output.as_deref(), Some("final answer"));
+}
+
+#[tokio::test]
+async fn subagent_failed_carries_parent_call_id() {
+ let mut events = super::super::super::event_bus::subscribe_web_channel_events();
+ let thread_id = "thread-c1-failed";
+ let tx = spawn_test_bridge(thread_id, "req-c1-failed");
+
+ tx.send(AgentProgress::SubagentSpawned {
+ agent_id: "researcher".into(),
+ task_id: "sub-c1-failed".into(),
+ mode: "typed".into(),
+ dedicated_thread: false,
+ prompt_chars: 4,
+ prompt: "help".into(),
+ worker_thread_id: None,
+ display_name: None,
+ parent_call_id: Some("call-parent-3".into()),
+ })
+ .await
+ .unwrap();
+ let spawned = recv_for_thread(&mut events, thread_id).await;
+ assert_eq!(spawned.event, "subagent_spawned");
+
+ tx.send(AgentProgress::SubagentFailed {
+ agent_id: "researcher".into(),
+ task_id: "sub-c1-failed".into(),
+ error: "boom".into(),
+ })
+ .await
+ .unwrap();
+
+ let failed = recv_for_thread(&mut events, thread_id).await;
+ assert_eq!(failed.event, "subagent_failed");
+ let subagent = failed.subagent.expect("subagent detail present");
+ assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-3"));
+}
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
index 531b57c308..670a07ceab 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
@@ -568,119 +568,6 @@ fn cap_wire_args_truncates_oversized_payload_to_a_marker_string() {
/// on `subagent_spawned`) so the frontend can key the delegation row to the
/// spawning tool call (#C1).
#[tokio::test]
-async fn subagent_spawned_forwards_parent_call_id() {
- let mut events = super::super::event_bus::subscribe_web_channel_events();
- let thread_id = "thread-c1-spawned";
- let tx = spawn_test_bridge(thread_id, "req-c1-spawned");
-
- tx.send(AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-c1".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: Some("call-parent-1".into()),
- })
- .await
- .unwrap();
-
- let ev = recv_for_thread(&mut events, thread_id).await;
- assert_eq!(ev.event, "subagent_spawned");
- let subagent = ev.subagent.expect("subagent detail present");
- assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-1"));
-}
-
-/// Terminal sub-agent events (`_completed`/`_failed`/`_awaiting_user`) must
-/// keep carrying the same `parent_call_id` the spawn recorded, even though
-/// those `AgentProgress` variants don't repeat it — the bridge remembers it
-/// per `task_id` (#C1).
-#[tokio::test]
-async fn subagent_completed_carries_parent_call_id_and_capped_output() {
- let mut events = super::super::event_bus::subscribe_web_channel_events();
- let thread_id = "thread-c1-completed";
- let tx = spawn_test_bridge(thread_id, "req-c1-completed");
-
- tx.send(AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-c1-done".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: Some("call-parent-2".into()),
- })
- .await
- .unwrap();
- let spawned = recv_for_thread(&mut events, thread_id).await;
- assert_eq!(spawned.event, "subagent_spawned");
-
- tx.send(AgentProgress::SubagentCompleted {
- agent_id: "researcher".into(),
- task_id: "sub-c1-done".into(),
- elapsed_ms: 10,
- iterations: 1,
- output_chars: 5,
- usage: None,
- output: "final answer".into(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- stop: None,
- })
- .await
- .unwrap();
-
- let completed = recv_for_thread(&mut events, thread_id).await;
- assert_eq!(completed.event, "subagent_completed");
- let subagent = completed.subagent.expect("subagent detail present");
- assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-2"));
- assert_eq!(subagent.output.as_deref(), Some("final answer"));
-}
-
-#[tokio::test]
-async fn subagent_failed_carries_parent_call_id() {
- let mut events = super::super::event_bus::subscribe_web_channel_events();
- let thread_id = "thread-c1-failed";
- let tx = spawn_test_bridge(thread_id, "req-c1-failed");
-
- tx.send(AgentProgress::SubagentSpawned {
- agent_id: "researcher".into(),
- task_id: "sub-c1-failed".into(),
- mode: "typed".into(),
- dedicated_thread: false,
- prompt_chars: 4,
- prompt: "help".into(),
- worker_thread_id: None,
- display_name: None,
- parent_call_id: Some("call-parent-3".into()),
- })
- .await
- .unwrap();
- let spawned = recv_for_thread(&mut events, thread_id).await;
- assert_eq!(spawned.event, "subagent_spawned");
-
- tx.send(AgentProgress::SubagentFailed {
- agent_id: "researcher".into(),
- task_id: "sub-c1-failed".into(),
- error: "boom".into(),
- })
- .await
- .unwrap();
-
- let failed = recv_for_thread(&mut events, thread_id).await;
- assert_eq!(failed.event, "subagent_failed");
- let subagent = failed.subagent.expect("subagent detail present");
- assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-3"));
-}
-
-/// A held turn (TinyMemes treatment arm) must not stream the answer text, but
-/// narration before a tool call still surfaces as an interim bubble.
-#[tokio::test]
async fn hold_text_stream_suppresses_text_delta_but_keeps_interim() {
use crate::agent::progress::AgentProgress;
let tmp = tempfile::TempDir::new().unwrap();
@@ -754,3 +641,6 @@ async fn hold_text_stream_suppresses_text_delta_but_keeps_interim() {
}
#[path = "progress_bridge_tool_progress_tests.rs"]
mod tool_progress_tests;
+
+#[path = "progress_bridge_subagent_tests.rs"]
+mod subagent_tests;
diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rs
index 644f6a4859..2900bf3fb1 100644
--- a/crates/openhuman-rpc/src/server/socketio.rs
+++ b/crates/openhuman-rpc/src/server/socketio.rs
@@ -406,7 +406,11 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {
if let Some(run_mode) = payload.run_mode.as_deref() {
match crate::core_host::agent::tinyagents::run_mode::parse_mode_label(run_mode) {
Some(mode) => {
- crate::core_host::agent::tinyagents::run_mode::set_mode(&DispatchCtx::host_default(), &thread_id, mode);
+ crate::core_host::agent::tinyagents::run_mode::set_mode(
+ &crate::core_host::core::runtime::DispatchCtx::host_default(),
+ &thread_id,
+ mode,
+ );
}
None => log::warn!(
"[socketio] chat:start thread_id={thread_id} ignoring unrecognized run_mode={run_mode}"
diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjs
index 81efd7e981..426d3248a8 100644
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@ -27,15 +27,15 @@ const LEGACY_LIMIT_ENTRIES = [
// under the general 750 limit, so it needs no exception at all.
// The session-todo integration added transcript metadata construction to
// this already-exempt composition seam. Keep its allowance exact.
- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1080],
+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1065],
// Session-host factory still assembles the product's deliberately coupled
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 974],
- ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1241],
+ ["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1235],
["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1045],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1173],
+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1171],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its
diff --git a/scripts/ci/check-storage-bypass.mjs b/scripts/ci/check-storage-bypass.mjs
index 1d392b1dfb..36ac80d668 100755
--- a/scripts/ci/check-storage-bypass.mjs
+++ b/scripts/ci/check-storage-bypass.mjs
@@ -150,6 +150,12 @@ 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",
],
+ [
+ "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 }]);
diff --git a/scripts/ci/ignored-test-baseline.json b/scripts/ci/ignored-test-baseline.json
index b5d93c4f55..1629c5fd78 100644
--- a/scripts/ci/ignored-test-baseline.json
+++ b/scripts/ci/ignored-test-baseline.json
@@ -1,7 +1,7 @@
{
"openhuman-app": 5,
"openhuman-cli": 0,
- "openhuman-core": 12,
+ "openhuman-core": 10,
"openhuman-embed": 0,
"openhuman-modules-linked": 0,
"openhuman-rpc": 0,
diff --git a/scripts/ci/module-boundaries.json b/scripts/ci/module-boundaries.json
index cac3a1fd04..366bda825e 100644
--- a/scripts/ci/module-boundaries.json
+++ b/scripts/ci/module-boundaries.json
@@ -133,6 +133,16 @@
"scope": "tinychannels-bus",
"package": "tokio",
"reason": "tinychannels-bus (vendor/tinychannels) still carries a provider trait with async-trait/anyhow/tokio::sync; the contract needs to be split upstream in tinyhumansai/tinychannels before this edge can go (tracked under #7523)."
+ },
+ {
+ "scope": "tinyconnectors-bus",
+ "package": "hmac",
+ "reason": "TinyConnectors #72 adds optional pure Composio webhook verification helpers to the bus contract for hosts that own the endpoint; this edge is enabled only by its opt-in webhook feature and is recorded for contract-boundary review."
+ },
+ {
+ "scope": "tinyconnectors-bus",
+ "package": "sha2",
+ "reason": "TinyConnectors #72 adds optional pure Composio webhook verification helpers to the bus contract for hosts that own the endpoint; this edge is enabled only by its opt-in webhook feature and is recorded for contract-boundary review."
}
],
"excludedSubsystems": [