Skip to content

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

fix(agent): carry attachment authority explicitly through turns

Steven Enamakel3cca7addaa6e
diff --git a/crates/openhuman-core/src/agent/attachments/legacy.rs b/crates/openhuman-core/src/agent/attachments/legacy.rs
index 434d65c9f5..95f6561f9d 100644
--- a/crates/openhuman-core/src/agent/attachments/legacy.rs
+++ b/crates/openhuman-core/src/agent/attachments/legacy.rs
@@ -5,11 +5,13 @@ use super::*;
pub(crate) async fn migrate_path(
config: &Config,
reference: &str,
+ scope: &AttachmentAccessScope,
) -> anyhow::Result<Option<String>> {
migrate_from(
config,
reference,
&crate::agent::multimodal::attachments_dir(),
+ scope,
)
.await
}
@@ -18,6 +20,7 @@ pub(super) async fn migrate_from(
config: &Config,
reference: &str,
stash: &Path,
+ scope: &AttachmentAccessScope,
) -> anyhow::Result<Option<String>> {
let source = Path::new(reference);
// Rehydration emits direct absolute children from the host's stash index.
@@ -28,10 +31,7 @@ pub(super) async fn migrate_from(
if config.multimodal_files.max_files == 0 || config.multimodal.max_images == 0 {
anyhow::bail!("legacy attachments are disabled");
}
- if matches!(
- crate::agent::turn_origin::current(),
- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
- ) {
+ if scope.external_channel {
anyhow::bail!("legacy attachment reads are disabled for external channel input");
}
let stem = source
@@ -88,7 +88,9 @@ pub(super) async fn migrate_from(
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("image");
- Ok(Some(store_original(config, name, mime, &bytes).await?))
+ Ok(Some(
+ store_original(config, name, mime, &bytes, scope).await?,
+ ))
}
async fn store_original(
@@ -96,6 +98,7 @@ async fn store_original(
name: &str,
mime: &str,
bytes: &[u8],
+ scope: &AttachmentAccessScope,
) -> anyhow::Result<String> {
use sha2::{Digest, Sha256};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -107,7 +110,7 @@ async fn store_original(
.join("legacy-sidecars")
.join(format!("{:x}", hash.finalize()))
.join(filename(name));
- let root = action_root(config);
+ let root = action_root(config, scope);
policy(config, &root)
.validate_parent_path(&root.join(&relative).to_string_lossy())
.await
@@ -162,7 +165,7 @@ async fn store_original(
{
anyhow::bail!("legacy original is not the expected regular file");
}
- let checked = resolve_path(config, &path.to_string_lossy()).await?;
+ let checked = resolve_path(config, &path.to_string_lossy(), scope).await?;
let file = tokio::fs::File::open(checked).await?;
let mut existing = Vec::new();
file.take((bytes.len() + 1) as u64)
diff --git a/crates/openhuman-core/src/agent/attachments/mod.rs b/crates/openhuman-core/src/agent/attachments/mod.rs
index 515b82e3aa..a26e11009a 100644
--- a/crates/openhuman-core/src/agent/attachments/mod.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod.rs
@@ -15,6 +15,53 @@ pub(crate) mod codec;
pub(crate) mod legacy;
pub(crate) mod provider;
+/// Per-model-call attachment authority copied from the live agent context.
+/// The provider wrapper removes its request carrier before forwarding it.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct AttachmentAccessScope {
+ pub(crate) external_channel: bool,
+ pub(crate) workspace: Option<PathBuf>,
+}
+
+const REQUEST_SCOPE_KEY: &str = "__openhuman_attachment_access_scope";
+
+pub(crate) fn attach_request_scope(
+ request: &mut tinyinference_llm::model::ModelRequest,
+ context: &crate::agent::tinyagents::host::OpenHumanRunContext,
+) {
+ let external_channel = matches!(
+ context.origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ );
+ let workspace = context
+ .workspace
+ .as_ref()
+ .map(|workspace| workspace.root.clone());
+ request.metadata[REQUEST_SCOPE_KEY] = serde_json::json!({
+ "external_channel": external_channel,
+ "workspace": workspace,
+ });
+}
+
+pub(crate) fn take_request_scope(metadata: &mut serde_json::Value) -> AttachmentAccessScope {
+ let value = metadata
+ .as_object_mut()
+ .and_then(|metadata| metadata.remove(REQUEST_SCOPE_KEY));
+ let Some(value) = value else {
+ return AttachmentAccessScope::default();
+ };
+ AttachmentAccessScope {
+ external_channel: value
+ .get("external_channel")
+ .and_then(serde_json::Value::as_bool)
+ .unwrap_or(true),
+ workspace: value
+ .get("workspace")
+ .and_then(serde_json::Value::as_str)
+ .map(PathBuf::from),
+ }
+}
+
const PREFIX: &str = "[ATTACHMENT:";
/// Metadata carried by a compact transcript reference. Paths are relative to
@@ -101,8 +148,11 @@ fn safe_relative_path(path: &str) -> bool {
.all(|c| matches!(c, Component::Normal(_)))
}
-pub(crate) fn action_root(config: &Config) -> PathBuf {
- crate::agent::turn_workspace::current().unwrap_or_else(|| config.action_dir.clone())
+pub(crate) fn action_root(config: &Config, scope: &AttachmentAccessScope) -> PathBuf {
+ scope
+ .workspace
+ .clone()
+ .unwrap_or_else(|| config.action_dir.clone())
}
fn policy(config: &Config, root: &Path) -> SecurityPolicy {
@@ -111,8 +161,12 @@ fn policy(config: &Config, root: &Path) -> SecurityPolicy {
/// Resolve a local attachment under the same filesystem policy as acting
/// tools, including symlink checks and the always-forbidden credential floor.
-pub(crate) async fn resolve_path(config: &Config, reference: &str) -> anyhow::Result<PathBuf> {
- let root = action_root(config);
+pub(crate) async fn resolve_path(
+ config: &Config,
+ reference: &str,
+ scope: &AttachmentAccessScope,
+) -> anyhow::Result<PathBuf> {
+ let root = action_root(config, scope);
let policy = policy(config, &root);
if !policy.is_path_string_allowed(reference) {
anyhow::bail!("attachment path is not permitted");
@@ -154,8 +208,9 @@ async fn save(
name: &str,
mime: &str,
bytes: &[u8],
+ scope: &AttachmentAccessScope,
) -> anyhow::Result<Attachment> {
- let root = action_root(config);
+ let root = action_root(config, scope);
// Validate the complete prospective destination before creating even the
// workspace root. This checks existing symlink ancestors as well as the
// credential/internal-state floor.
@@ -234,9 +289,17 @@ async fn save(
/// Stage every original before scanning or persistence. Failure rejects the
/// turn rather than silently discarding an accepted upload.
-pub(crate) async fn stage(message: &str, thread: &str, config: &Config) -> anyhow::Result<String> {
+pub(crate) async fn stage(
+ message: &str,
+ thread: &str,
+ config: &Config,
+ scope: &AttachmentAccessScope,
+) -> anyhow::Result<String> {
let (text, images) = markers::parse_image_markers(message);
let (_, files) = markers::parse_file_markers(&text);
+ if scope.external_channel && (!images.is_empty() || !files.is_empty()) {
+ anyhow::bail!("local attachment reads are disabled for external channel input");
+ }
let (max_images, image_mb) = config.multimodal.effective_limits();
let (max_files, file_mb, max_text) = config.multimodal_files.effective_limits();
if images.len() > max_images
@@ -283,10 +346,10 @@ pub(crate) async fn stage(message: &str, thread: &str, config: &Config) -> anyho
&& !source.starts_with("http://")
&& !source.starts_with("https://")
{
- let local = legacy::migrate_path(config, source)
+ let local = legacy::migrate_path(config, source, scope)
.await?
.unwrap_or_else(|| source.into());
- resolve_path(config, &local)
+ resolve_path(config, &local, scope)
.await?
.to_string_lossy()
.into_owned()
@@ -310,6 +373,7 @@ pub(crate) async fn stage(message: &str, thread: &str, config: &Config) -> anyho
&resolved.name,
&resolved.mime,
&resolved.bytes,
+ scope,
)
.await?;
out.push_str(&attachment.marker());
@@ -325,6 +389,7 @@ pub(crate) async fn delegation_prompt(
prompt: &str,
args: &serde_json::Value,
workspace: Option<&tinytools::WorkspaceDescriptor>,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
) -> anyhow::Result<String> {
let mut prompt = prompt.to_string();
if let Some(value) = args.get("image_paths") {
@@ -343,7 +408,7 @@ pub(crate) async fn delegation_prompt(
return Ok(prompt);
}
if matches!(
- crate::agent::turn_origin::current(),
+ origin,
Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
) {
anyhow::bail!("local attachment reads are disabled for external channel input");
@@ -354,13 +419,18 @@ pub(crate) async fn delegation_prompt(
if let Some(workspace) = workspace {
config.action_dir = workspace.root.clone();
}
- stage(&prompt, "delegation", &config).await
+ let scope = AttachmentAccessScope {
+ external_channel: false,
+ workspace: workspace.map(|workspace| workspace.root.clone()),
+ };
+ stage(&prompt, "delegation", &config, &scope).await
}
/// Validate a vision task's explicit references before constructing inference.
pub(crate) async fn has_resolvable_image(
prompt: &str,
workspace: Option<&tinytools::WorkspaceDescriptor>,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
) -> anyhow::Result<bool> {
let rehydrated = crate::agent::multimodal::rehydrate_image_placeholders(&[
tinyagents_session::transcript::TranscriptMessage::user(prompt),
@@ -378,12 +448,24 @@ pub(crate) async fn has_resolvable_image(
let mut config = crate::config::rpc::load_config_with_timeout()
.await
.map_err(anyhow::Error::msg)?;
+ if matches!(
+ origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ) {
+ anyhow::bail!("local attachment reads are disabled for external channel input");
+ }
if let Some(workspace) = workspace {
config.action_dir = workspace.root.clone();
}
+ let scope = AttachmentAccessScope {
+ external_channel: false,
+ workspace: workspace.map(|workspace| workspace.root.clone()),
+ };
for path in paths {
- let path = legacy::migrate_path(&config, &path).await?.unwrap_or(path);
- let path = resolve_path(&config, &path).await?;
+ let path = legacy::migrate_path(&config, &path, &scope)
+ .await?
+ .unwrap_or(path);
+ let path = resolve_path(&config, &path, &scope).await?;
let metadata = tokio::fs::metadata(path).await?;
if metadata.is_file() && metadata.len() > 0 {
return Ok(true);
@@ -451,6 +533,7 @@ pub(crate) async fn stage_turn(
config: Option<&Config>,
workspace: Option<&tinytools::WorkspaceDescriptor>,
thread: Option<&str>,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
) -> anyhow::Result<String> {
if !message.contains("[IMAGE:") && !message.contains("[FILE:") {
return Ok(message.into());
@@ -459,7 +542,7 @@ pub(crate) async fn stage_turn(
.cloned()
.ok_or_else(|| anyhow::anyhow!("attachment intake requires runtime configuration"))?;
if matches!(
- crate::agent::turn_origin::current(),
+ origin,
Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
) {
config.multimodal_files =
@@ -468,7 +551,14 @@ pub(crate) async fn stage_turn(
if let Some(workspace) = workspace {
config.action_dir = workspace.root.clone();
}
- stage(message, thread.unwrap_or("direct"), &config).await
+ let scope = AttachmentAccessScope {
+ external_channel: matches!(
+ origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ),
+ workspace: workspace.map(|workspace| workspace.root.clone()),
+ };
+ stage(message, thread.unwrap_or("direct"), &config, &scope).await
}
/// The session prelude's typed enrichment hook. Both image forwarding and
diff --git a/crates/openhuman-core/src/agent/attachments/mod_tests.rs b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
index 5d486bab2c..b075d70dda 100644
--- a/crates/openhuman-core/src/agent/attachments/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
@@ -13,24 +13,27 @@ async fn legacy_sidecar_rehydrates_into_an_authorized_acting_original() {
let source = stash.join("legacy.png");
let bytes = b"\x89PNG\r\n\x1a\noriginal";
tokio::fs::write(&source, bytes).await.unwrap();
- assert!(resolve_path(&cfg, source.to_str().unwrap()).await.is_err());
+ let scope = AttachmentAccessScope::default();
+ assert!(resolve_path(&cfg, source.to_str().unwrap(), &scope)
+ .await
+ .is_err());
let index = std::collections::HashMap::from([("legacy".into(), source.clone())]);
let prompt = markers::rehydrate_placeholders_in_text("[Image: old #att:legacy]", &index);
let paths = markers::parse_image_markers(&prompt).1;
assert_eq!(paths, vec![source.to_string_lossy().into_owned()]);
- let migrated = legacy::migrate_from(&cfg, &paths[0], &stash)
+ let migrated = legacy::migrate_from(&cfg, &paths[0], &stash, &scope)
.await
.unwrap()
.unwrap();
assert!(migrated.starts_with("uploads/legacy-sidecars/"));
assert_eq!(
- legacy::migrate_from(&cfg, &paths[0], &stash)
+ legacy::migrate_from(&cfg, &paths[0], &stash, &scope)
.await
.unwrap()
.unwrap(),
migrated
);
- let acting = resolve_path(&cfg, &migrated).await.unwrap();
+ let acting = resolve_path(&cfg, &migrated, &scope).await.unwrap();
assert_eq!(tokio::fs::read(acting).await.unwrap(), bytes);
assert_eq!(tokio::fs::read(&source).await.unwrap(), bytes);
let message =
@@ -45,47 +48,51 @@ async fn legacy_sidecar_rehydrates_into_an_authorized_acting_original() {
async fn legacy_migration_does_not_grant_private_file_or_disabled_image_access() {
let temp = tempfile::tempdir().unwrap();
let mut cfg = config(temp.path());
+ let scope = AttachmentAccessScope::default();
let stash = cfg.workspace_dir.join("attachments");
tokio::fs::create_dir_all(&stash).await.unwrap();
let source = stash.join("legacy.png");
tokio::fs::write(&source, b"\x89PNG\r\n\x1a\noriginal")
.await
.unwrap();
- let origin = crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
- channel: "test".into(),
- sender: None,
- reply_target: "test".into(),
- message_id: "test".into(),
+ let external_scope = AttachmentAccessScope {
+ external_channel: true,
+ workspace: None,
};
- assert!(crate::agent::turn_origin::with_origin(
- origin,
- legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash)
- )
- .await
- .is_err());
+ assert!(
+ legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash, &external_scope)
+ .await
+ .is_err()
+ );
let unrelated = cfg.workspace_dir.join("private.png");
assert!(
- legacy::migrate_from(&cfg, unrelated.to_str().unwrap(), &stash)
+ legacy::migrate_from(&cfg, unrelated.to_str().unwrap(), &stash, &scope)
.await
.unwrap()
.is_none()
);
cfg.multimodal_files.max_files = 0;
- assert!(legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash)
- .await
- .is_err());
+ assert!(
+ legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash, &scope)
+ .await
+ .is_err()
+ );
cfg.multimodal_files.max_files = 4;
cfg.multimodal.max_images = 0;
- assert!(legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash)
- .await
- .is_err());
+ assert!(
+ legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash, &scope)
+ .await
+ .is_err()
+ );
cfg.multimodal.max_images = 4;
tokio::fs::write(&source, b"private text masquerading as a sidecar")
.await
.unwrap();
- assert!(legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash)
- .await
- .is_err());
+ assert!(
+ legacy::migrate_from(&cfg, source.to_str().unwrap(), &stash, &scope)
+ .await
+ .is_err()
+ );
let forbidden = temp.path().join(".ssh").join("attachments");
tokio::fs::create_dir_all(&forbidden).await.unwrap();
let credential = forbidden.join("legacy.png");
@@ -93,7 +100,7 @@ async fn legacy_migration_does_not_grant_private_file_or_disabled_image_access()
.await
.unwrap();
assert!(
- legacy::migrate_from(&cfg, credential.to_str().unwrap(), &forbidden)
+ legacy::migrate_from(&cfg, credential.to_str().unwrap(), &forbidden, &scope)
.await
.is_err()
);
@@ -104,6 +111,7 @@ async fn legacy_migration_does_not_grant_private_file_or_disabled_image_access()
async fn legacy_migration_rejects_symlink_sidecars() {
let temp = tempfile::tempdir().unwrap();
let cfg = config(temp.path());
+ let scope = AttachmentAccessScope::default();
let stash = cfg.workspace_dir.join("attachments");
tokio::fs::create_dir_all(&stash).await.unwrap();
let outside = temp.path().join("outside.png");
@@ -112,9 +120,11 @@ async fn legacy_migration_rejects_symlink_sidecars() {
.unwrap();
let link = stash.join("legacy.png");
std::os::unix::fs::symlink(&outside, &link).unwrap();
- assert!(legacy::migrate_from(&cfg, link.to_str().unwrap(), &stash)
- .await
- .is_err());
+ assert!(
+ legacy::migrate_from(&cfg, link.to_str().unwrap(), &stash, &scope)
+ .await
+ .is_err()
+ );
}
#[test]
@@ -158,9 +168,16 @@ async fn forbidden_acting_root_is_rejected_before_directory_creation() {
let temp = tempfile::tempdir().unwrap();
let mut config = config(temp.path());
config.action_dir = temp.path().join(".ssh").join("new-workspace");
- assert!(save(&config, "thread", "file", "text/plain", b"data")
- .await
- .is_err());
+ assert!(save(
+ &config,
+ "thread",
+ "file",
+ "text/plain",
+ b"data",
+ &AttachmentAccessScope::default()
+ )
+ .await
+ .is_err());
assert!(!temp.path().join(".ssh").exists());
}
@@ -181,7 +198,14 @@ async fn arbitrary_original_is_durable_and_reference_contains_no_payload() {
let input = format!(
"Inspect [FILE:data:application/octet-stream;name=Report%20%CE%B1.zip;base64,{encoded}]"
);
- let staged = stage(&input, "../../unsafe/thread", &config).await.unwrap();
+ let staged = stage(
+ &input,
+ "../../unsafe/thread",
+ &config,
+ &AttachmentAccessScope::default(),
+ )
+ .await
+ .unwrap();
assert!(!staged.contains(&encoded));
let (text, files) = parse(&staged);
assert_eq!(text.trim(), "Inspect");
@@ -195,7 +219,17 @@ async fn arbitrary_original_is_durable_and_reference_contains_no_payload() {
.unwrap(),
bytes
);
- assert_eq!(stage(&staged, "thread", &config).await.unwrap(), staged);
+ assert_eq!(
+ stage(
+ &staged,
+ "thread",
+ &config,
+ &AttachmentAccessScope::default()
+ )
+ .await
+ .unwrap(),
+ staged
+ );
assert_eq!(parse(&files[0].marker()).1, files);
}
@@ -209,6 +243,7 @@ async fn repeated_names_do_not_overwrite_and_escape_names_are_sanitized() {
"../../same.zip",
"application/zip",
b"first",
+ &AttachmentAccessScope::default(),
)
.await
.unwrap();
@@ -218,6 +253,7 @@ async fn repeated_names_do_not_overwrite_and_escape_names_are_sanitized() {
"../../same.zip",
"application/zip",
b"second",
+ &AttachmentAccessScope::default(),
)
.await
.unwrap();
@@ -238,7 +274,9 @@ async fn staging_preserves_interleaved_captions_and_media_order() {
let temp = tempfile::tempdir().unwrap();
let config = config(temp.path());
let source = "first [FILE:data:text/plain;name=one.txt;base64,YQ==] second [IMAGE:data:image/png;name=two.png;base64,iVBORw0KGgo=] third";
- let staged = stage(source, "thread", &config).await.unwrap();
+ let staged = stage(source, "thread", &config, &AttachmentAccessScope::default())
+ .await
+ .unwrap();
let parts = segments(&staged);
assert!(matches!(&parts[0], Segment::Text(text) if text == "first "));
assert!(matches!(&parts[1], Segment::Attachment(file) if file.name == "one.txt"));
@@ -252,8 +290,22 @@ async fn hard_zero_and_count_gate_precede_reads() {
let temp = tempfile::tempdir().unwrap();
let mut config = config(temp.path());
config.multimodal_files.max_files = 0;
- assert!(stage("[FILE:/missing]", "thread", &config).await.is_err());
- assert!(stage("[IMAGE:/missing]", "thread", &config).await.is_err());
+ assert!(stage(
+ "[FILE:/missing]",
+ "thread",
+ &config,
+ &AttachmentAccessScope::default()
+ )
+ .await
+ .is_err());
+ assert!(stage(
+ "[IMAGE:/missing]",
+ "thread",
+ &config,
+ &AttachmentAccessScope::default()
+ )
+ .await
+ .is_err());
assert!(!config.action_dir.exists());
assert!(!safe_relative_path("../escape"));
assert!(!safe_relative_path("/absolute"));
@@ -264,15 +316,19 @@ async fn hard_zero_and_count_gate_precede_reads() {
async fn vision_without_explicit_references_fails_before_configuration_or_inference() {
assert!(!has_resolvable_image(
"Describe a filename mentioned only in prose: picture.png",
+ None,
None
)
.await
.unwrap());
- assert!(
- delegation_prompt("task", &serde_json::json!({ "image_paths": [42] }), None)
- .await
- .is_err()
- );
+ assert!(delegation_prompt(
+ "task",
+ &serde_json::json!({ "image_paths": [42] }),
+ None,
+ None
+ )
+ .await
+ .is_err());
}
#[cfg(unix)]
@@ -289,7 +345,8 @@ async fn upload_symlink_is_rejected_without_writing_outside() {
"thread",
"file",
"application/octet-stream",
- b"original"
+ b"original",
+ &AttachmentAccessScope::default()
)
.await
.is_err());
@@ -297,16 +354,17 @@ async fn upload_symlink_is_rejected_without_writing_outside() {
}
#[tokio::test]
-async fn scoped_workspace_wins_over_ambient_config() {
+async fn explicit_workspace_wins_over_config_action_dir() {
let temp = tempfile::tempdir().unwrap();
let config = config(temp.path());
let scoped = temp.path().join("scoped");
- let attachment = crate::agent::turn_workspace::with_workspace(
- scoped.clone(),
- save(&config, "thread", "file", "text/plain", b"original"),
- )
- .await
- .unwrap();
+ let scope = AttachmentAccessScope {
+ external_channel: false,
+ workspace: Some(scoped.clone()),
+ };
+ let attachment = save(&config, "thread", "file", "text/plain", b"original", &scope)
+ .await
+ .unwrap();
assert!(scoped.join(attachment.path).exists());
assert!(!config.action_dir.exists());
}
diff --git a/crates/openhuman-core/src/agent/attachments/provider.rs b/crates/openhuman-core/src/agent/attachments/provider.rs
index e0d36787ae..86f6b0ff5e 100644
--- a/crates/openhuman-core/src/agent/attachments/provider.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider.rs
@@ -1,4 +1,5 @@
//! Ephemeral provider request preparation for durable workspace attachments.
+use super::AttachmentAccessScope;
use crate::config::Config;
use async_trait::async_trait;
use base64::{engine::general_purpose::STANDARD, Engine};
@@ -106,16 +107,14 @@ impl AttachmentModel {
&self,
path: &str,
modality: InputModality,
+ scope: &AttachmentAccessScope,
) -> tinyinference_llm::Result<Vec<u8>> {
- if matches!(
- crate::agent::turn_origin::current(),
- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
- ) {
+ if scope.external_channel {
return Err(tinyinference_llm::Error::Model(
"local attachment reads are disabled for external channel input".into(),
));
}
- let path = super::resolve_path(&self.config, path)
+ let path = super::resolve_path(&self.config, path, scope)
.await
.map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?;
let (_, file_mb, _) = self.config.multimodal_files.effective_limits();
@@ -155,6 +154,7 @@ impl AttachmentModel {
Ok(bytes)
}
async fn prepare(&self, mut request: ModelRequest) -> tinyinference_llm::Result<ModelRequest> {
+ let scope = super::take_request_scope(&mut request.metadata);
if let Some(Message::User(user)) = request
.messages
.iter()
@@ -194,7 +194,7 @@ impl AttachmentModel {
let mut out = Vec::new();
for block in std::mem::take(&mut user.content) {
let Some((modality, path, mut mime, bytes, recovered)) =
- self.resolve_block(&block).await?
+ self.resolve_block(&block, &scope).await?
else {
out.push(block);
continue;
@@ -256,7 +256,7 @@ impl AttachmentModel {
.cloned();
let cached = match cached {
Some(text) => Some(text),
- None => self.cached_fallback(&path, &key).await,
+ None => self.cached_fallback(&path, &key, &scope).await,
};
let text = match cached {
Some(text) => text,
@@ -264,7 +264,7 @@ impl AttachmentModel {
let (text, cacheable) =
self.fallback(modality, &path, &mime, &bytes).await?;
if cacheable {
- self.save_fallback(&path, &key, &text).await;
+ self.save_fallback(&path, &key, &text, &scope).await;
}
let mut cache = self.fallback_cache.lock().expect("fallback cache");
if cache.len() < 16 {
diff --git a/crates/openhuman-core/src/agent/attachments/provider_cache.rs b/crates/openhuman-core/src/agent/attachments/provider_cache.rs
index e3f69f3711..b9d90d2d2f 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_cache.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_cache.rs
@@ -1,5 +1,6 @@
//! Bounded plain-text derivatives beside durable originals. Originals and
//! transcript references remain unchanged; cache misses never reject uploads.
+use super::AttachmentAccessScope;
use super::*;
use sha2::{Digest, Sha256};
const MAX_CACHE_BYTES: u64 = 1024 * 1024;
@@ -51,9 +52,15 @@ impl AttachmentModel {
hash.update(bytes);
format!("{:x}", hash.finalize())
}
- async fn cache_path(&self, path: &str) -> Option<std::path::PathBuf> {
- let original = super::super::resolve_path(&self.config, path).await.ok()?;
- let root = tokio::fs::canonicalize(super::super::action_root(&self.config))
+ async fn cache_path(
+ &self,
+ path: &str,
+ scope: &AttachmentAccessScope,
+ ) -> Option<std::path::PathBuf> {
+ let original = super::super::resolve_path(&self.config, path, scope)
+ .await
+ .ok()?;
+ let root = tokio::fs::canonicalize(super::super::action_root(&self.config, scope))
.await
.ok()?;
if !original.starts_with(root.join("uploads")) {
@@ -73,8 +80,13 @@ impl AttachmentModel {
}
Some(cache)
}
- pub(super) async fn cached_fallback(&self, path: &str, key: &str) -> Option<String> {
- let cache = self.cache_path(path).await?;
+ pub(super) async fn cached_fallback(
+ &self,
+ path: &str,
+ key: &str,
+ scope: &AttachmentAccessScope,
+ ) -> Option<String> {
+ let cache = self.cache_path(path, scope).await?;
let parent = tokio::fs::symlink_metadata(cache.parent()?).await.ok()?;
if !parent.is_dir() || parent.file_type().is_symlink() {
return None;
@@ -100,15 +112,21 @@ impl AttachmentModel {
let (stored_key, text) = content.split_once('\n')?;
(stored_key == key).then(|| text.to_owned())
}
- pub(super) async fn save_fallback(&self, path: &str, key: &str, text: &str) {
+ pub(super) async fn save_fallback(
+ &self,
+ path: &str,
+ key: &str,
+ text: &str,
+ scope: &AttachmentAccessScope,
+ ) {
if (text.len() + key.len() + 1) as u64 > MAX_CACHE_BYTES {
return;
}
- let Some(cache) = self.cache_path(path).await else {
+ let Some(cache) = self.cache_path(path, scope).await else {
return;
};
let parent = cache.parent().expect("derivative parent");
- let root = super::super::action_root(&self.config);
+ let root = super::super::action_root(&self.config, scope);
let policy = crate::security::SecurityPolicy::from_config(
&self.config.autonomy,
&self.config.workspace_dir,
diff --git a/crates/openhuman-core/src/agent/attachments/provider_fallback.rs b/crates/openhuman-core/src/agent/attachments/provider_fallback.rs
index 91a033ecd4..48e54835f1 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_fallback.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_fallback.rs
@@ -121,7 +121,9 @@ impl AttachmentModel {
}
Err(error) => {
cacheable = false;
- text.push_str(&format!("\nPage {page} readout unavailable: {error}"));
+ text.push_str(&format!(
+ "\nPage {page} readout unavailable: {error}"
+ ));
}
}
}
diff --git a/crates/openhuman-core/src/agent/attachments/provider_source.rs b/crates/openhuman-core/src/agent/attachments/provider_source.rs
index 1e15ac3539..44ef333c7e 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_source.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_source.rs
@@ -1,4 +1,5 @@
//! Resolve every admitted media source on a disposable provider request.
+use super::AttachmentAccessScope;
use super::*;
use sha2::{Digest, Sha256};
use tinyagents_harness::multimodal::{
@@ -9,6 +10,7 @@ impl AttachmentModel {
pub(super) async fn resolve_block(
&self,
block: &ContentBlock,
+ scope: &AttachmentAccessScope,
) -> tinyinference_llm::Result<Option<(InputModality, String, String, Vec<u8>, bool)>> {
let (modality, source, mime, is_local) = match block {
ContentBlock::Image(image) => (
@@ -29,10 +31,7 @@ impl AttachmentModel {
"attachments are disabled for this origin".into(),
));
}
- if matches!(
- crate::agent::turn_origin::current(),
- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
- ) {
+ if scope.external_channel {
return Err(tinyinference_llm::Error::Model(
"attachment resolution is disabled for external channel input".into(),
));
@@ -41,12 +40,12 @@ impl AttachmentModel {
// Old transcripts can point into the private host image stash.
// Publish only its validated managed originals into the acting
// workspace, and retain that stable path for metadata and caches.
- let migrated = super::super::legacy::migrate_path(&self.config, &source)
+ let migrated = super::super::legacy::migrate_path(&self.config, &source, scope)
.await
.map_err(|e| tinyinference_llm::Error::Model(e.to_string()))?;
let recovered = migrated.is_some();
let source = migrated.unwrap_or(source);
- let bytes = self.read(&source, modality).await?;
+ let bytes = self.read(&source, modality, scope).await?;
return Ok(Some((
modality,
source,
@@ -112,7 +111,7 @@ impl AttachmentModel {
resolved.mime
};
let path = self
- .materialize_legacy(&resolved.name, &mime, &resolved.bytes, modality)
+ .materialize_legacy(&resolved.name, &mime, &resolved.bytes, modality, scope)
.await?;
Ok(Some((modality, path, mime, resolved.bytes, true)))
}
@@ -158,6 +157,7 @@ impl AttachmentModel {
mime: &str,
bytes: &[u8],
modality: InputModality,
+ scope: &AttachmentAccessScope,
) -> tinyinference_llm::Result<String> {
let mut hash = Sha256::new();
hash.update((mime.len() as u64).to_le_bytes());
@@ -168,7 +168,7 @@ impl AttachmentModel {
.join("legacy-media")
.join(id)
.join(super::super::filename(name));
- let root = super::super::action_root(&self.config);
+ let root = super::super::action_root(&self.config, scope);
let preliminary = crate::security::SecurityPolicy::from_config(
&self.config.autonomy,
&self.config.workspace_dir,
@@ -236,7 +236,9 @@ impl AttachmentModel {
match linked {
Ok(()) => (),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
- let saved = self.read(&relative.to_string_lossy(), modality).await?;
+ let saved = self
+ .read(&relative.to_string_lossy(), modality, scope)
+ .await?;
if saved != bytes {
return Err(tinyinference_llm::Error::Model(
"legacy upload original has changed".into(),
@@ -246,7 +248,7 @@ impl AttachmentModel {
Err(_) => {
// Some user filesystems cannot hard-link. Preserve bytes using
// the normal collision-free upload store rather than overwrite.
- return super::super::save(&self.config, "legacy-media", name, mime, bytes)
+ return super::super::save(&self.config, "legacy-media", name, mime, bytes, scope)
.await
.map(|a| a.path)
.map_err(|e| tinyinference_llm::Error::Model(e.to_string()));
diff --git a/crates/openhuman-core/src/agent/attachments/provider_tests.rs b/crates/openhuman-core/src/agent/attachments/provider_tests.rs
index 9e2648e118..515d8a8fb3 100644
--- a/crates/openhuman-core/src/agent/attachments/provider_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/provider_tests.rs
@@ -142,7 +142,7 @@ async fn too_many_typed_images_reject_before_read_or_inference() {
#[tokio::test]
async fn external_channel_cannot_rehydrate_a_local_image() {
- use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
+ use crate::agent::turn_origin::AgentTurnOrigin;
let probe = Arc::new(Probe::default());
let wrapper = wrap(
probe.clone(),
@@ -150,7 +150,7 @@ async fn external_channel_cannot_rehydrate_a_local_image() {
"gpt-4o",
"openai",
);
- let request = ModelRequest::new(vec![Message::User(
+ let mut request = ModelRequest::new(vec![Message::User(
tinyinference_llm::message::UserMessage {
content: vec![ContentBlock::Image(ImageRef {
url: "missing.png".into(),
@@ -164,9 +164,10 @@ async fn external_channel_cannot_rehydrate_a_local_image() {
reply_target: "chat".into(),
message_id: "message".into(),
};
- let error = with_origin(origin, wrapper.invoke(&(), request))
- .await
- .unwrap_err();
+ let mut context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ context.origin = Some(origin);
+ super::super::attach_request_scope(&mut request, &context);
+ let error = wrapper.invoke(&(), request).await.unwrap_err();
assert!(error.to_string().contains("external channel"));
assert!(probe.requests.lock().unwrap().is_empty());
}
@@ -217,21 +218,27 @@ async fn derivative_cache_survives_model_recreation_and_invalidates_changed_cont
fallback_cache: Mutex::new(Default::default()),
};
let first = make();
+ let scope = super::super::AttachmentAccessScope::default();
let key = first.fallback_key("uploads/thread/id/original.txt", "text/plain", b"original");
first
- .save_fallback("uploads/thread/id/original.txt", &key, "derived readout")
+ .save_fallback(
+ "uploads/thread/id/original.txt",
+ &key,
+ "derived readout",
+ &scope,
+ )
.await;
let resumed = make();
assert_eq!(
resumed
- .cached_fallback("uploads/thread/id/original.txt", &key)
+ .cached_fallback("uploads/thread/id/original.txt", &key, &scope)
.await
.as_deref(),
Some("derived readout")
);
let changed = first.fallback_key("uploads/thread/id/original.txt", "text/plain", b"modified");
assert!(resumed
- .cached_fallback("uploads/thread/id/original.txt", &changed)
+ .cached_fallback("uploads/thread/id/original.txt", &changed, &scope)
.await
.is_none());
assert_eq!(tokio::fs::read(original).await.unwrap(), b"original");
@@ -258,7 +265,14 @@ async fn cache_is_not_written_beside_unmanaged_local_files() {
profile: ModelProfile::default(),
fallback_cache: Mutex::new(Default::default()),
};
- model.save_fallback("original.txt", "key", "derived").await;
+ model
+ .save_fallback(
+ "original.txt",
+ "key",
+ "derived",
+ &super::super::AttachmentAccessScope::default(),
+ )
+ .await;
assert!(!temp.path().join(".openhuman-intake.txt").exists());
}
@@ -402,9 +416,14 @@ async fn derivative_cache_cannot_overwrite_original_named_like_cache() {
"data:text/plain;name=.openhuman-intake.txt;base64,{}",
STANDARD.encode(b"original")
);
- let staged = super::super::stage(&format!("[FILE:{source}]"), "thread", &config)
- .await
- .unwrap();
+ let staged = super::super::stage(
+ &format!("[FILE:{source}]"),
+ "thread",
+ &config,
+ &super::super::AttachmentAccessScope::default(),
+ )
+ .await
+ .unwrap();
let (_, files) = super::super::parse(&staged);
assert_eq!(files.len(), 1);
assert_eq!(files[0].name, ".openhuman-intake.txt");
@@ -590,6 +609,7 @@ async fn configured_injected_builder_stages_and_resolves_in_explicit_acting_work
Some(&bound),
None,
Some("builder-test"),
+ None,
)
.await
.unwrap();
diff --git a/crates/openhuman-core/src/agent/bus.rs b/crates/openhuman-core/src/agent/bus.rs
index d7c1155e80..49e1014419 100644
--- a/crates/openhuman-core/src/agent/bus.rs
+++ b/crates/openhuman-core/src/agent/bus.rs
@@ -288,6 +288,7 @@ async fn handle_agent_run_turn(req: AgentTurnRequest) -> Result<AgentTurnRespons
channel_name,
target_agent_id.as_deref().unwrap_or("root")
);
+ let graph_origin = origin.clone();
let outcome = turn_origin::with_origin(
origin,
with_file_state_agent_id(
@@ -313,6 +314,7 @@ async fn handle_agent_run_turn(req: AgentTurnRequest) -> Result<AgentTurnRespons
multimodal.clone(),
multimodal_files.clone(),
on_progress,
+ Some(graph_origin),
)
.await
}),
diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rs
index ca2db6e92d..3f93d5e54f 100644
--- a/crates/openhuman-core/src/agent/harness/graph.rs
+++ b/crates/openhuman-core/src/agent/harness/graph.rs
@@ -56,6 +56,7 @@ pub(crate) async fn run_channel_turn_via_graph(
multimodal: MultimodalConfig,
multimodal_files: MultimodalFileConfig,
on_progress: Option<Sender<AgentProgress>>,
+ origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
) -> Result<crate::agent::tinyagents::TinyagentsTurnOutcome> {
let extra_arc = Arc::new(extra_tools);
@@ -90,6 +91,7 @@ pub(crate) async fn run_channel_turn_via_graph(
// Keep originals and durable references in every entry path. Resolution
// into provider bytes belongs to the model decorator, after snapshots.
+ let mut attachment_workspace = None;
for row in history.iter_mut().filter(|row| row.role == "user") {
if row.content.contains("[FILE:") || row.content.contains("[IMAGE:") {
if multimodal_files.max_files == 0 {
@@ -100,8 +102,17 @@ pub(crate) async fn run_channel_turn_via_graph(
.map_err(anyhow::Error::msg)?;
config.multimodal = multimodal.clone();
config.multimodal_files = multimodal_files.clone();
+ let workspace = Some(config.action_dir.clone());
+ attachment_workspace = workspace.clone();
+ let scope = crate::agent::attachments::AttachmentAccessScope {
+ external_channel: matches!(
+ origin.as_ref(),
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ),
+ workspace: workspace.clone(),
+ };
row.content =
- crate::agent::attachments::stage(&row.content, "channel", &config).await?;
+ crate::agent::attachments::stage(&row.content, "channel", &config, &scope).await?;
row.parts = None;
}
}
@@ -118,7 +129,10 @@ pub(crate) async fn run_channel_turn_via_graph(
context_window,
"[channel:graph] routing channel turn through tinyagents harness"
);
+ let turn_origin = origin.clone();
let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ run_context.origin = origin;
+ run_context.workspace = attachment_workspace.map(tinytools::WorkspaceDescriptor::new);
seed_channel_attachments(&mut run_context, &prepared);
// The channel dispatcher owns this explicit sink. It wins over an embedder
// scope exactly as it did before this carrier was introduced.
@@ -160,8 +174,18 @@ pub(crate) async fn run_channel_turn_via_graph(
// NOT emit `TurnCompleted` itself, so let the seam emit the single
// terminal event (legacy-engine parity).
false,
- )
- .await?;
+ );
+ let outcome = match (turn_origin, crate::core::runtime::CoreContext::current()) {
+ (Some(origin), Some(context)) => {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(
+ context,
+ Some(origin),
+ outcome,
+ )
+ .await?
+ }
+ _ => outcome.await?,
+ };
// Append only this turn's typed suffix (assistant tool-calls + tool results +
// final assistant), serialized with the matching dispatcher so a native tool
// round persists as the `{content, tool_calls}` / `{tool_call_id, content}`
diff --git a/crates/openhuman-core/src/agent/harness/graph_tests.rs b/crates/openhuman-core/src/agent/harness/graph_tests.rs
index c93c6d38d8..28edf2b14e 100644
--- a/crates/openhuman-core/src/agent/harness/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/graph_tests.rs
@@ -62,6 +62,7 @@ async fn channel_turn_runs_through_the_graph() {
MultimodalConfig::default(),
MultimodalFileConfig::default(),
None,
+ None,
)
.await
.expect("channel graph turn runs");
@@ -122,6 +123,7 @@ async fn channel_turn_pauses_on_ask_user_clarification() {
MultimodalConfig::default(),
MultimodalFileConfig::default(),
None,
+ None,
)
.await
.expect("channel graph turn runs");
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
index 7e9df34952..6f8374be46 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
@@ -193,6 +193,7 @@ pub(crate) async fn execute_archetype_delegation_with_live_parent(
tool_context
.and_then(|ctx| ctx.workspace())
.or(run_context.workspace.as_ref()),
+ run_context.origin.as_ref(),
)
.await
{
@@ -200,7 +201,7 @@ pub(crate) async fn execute_archetype_delegation_with_live_parent(
Err(error) => {
return Ok(ToolResult::error(format!(
"image forwarding failed: {error}"
- )))
+ )));
}
};
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
index 5d26484edc..20aee7b8e8 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
@@ -369,6 +369,7 @@ pub(crate) async fn execute_collapsed_delegation_with_live_parent(
tool_context
.and_then(|ctx| ctx.workspace())
.or(run_context.workspace.as_ref()),
+ run_context.origin.as_ref(),
)
.await
{
@@ -376,7 +377,7 @@ pub(crate) async fn execute_collapsed_delegation_with_live_parent(
Err(error) => {
return Ok(ToolResult::error(format!(
"image forwarding failed: {error}"
- )))
+ )));
}
};
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
index 5b83ddf6d3..e8e73e413c 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
@@ -248,6 +248,7 @@ pub(crate) async fn dispatch_subagent_with_live_parent(
match crate::agent::attachments::has_resolvable_image(
prompt,
parent_workspace_descriptor.as_ref(),
+ run_context.origin.as_ref(),
)
.await
{
@@ -255,12 +256,12 @@ pub(crate) async fn dispatch_subagent_with_live_parent(
Ok(false) => {
return Ok(ToolResult::error(
"vision_agent requires a resolvable image attachment or image_paths.",
- ))
+ ));
}
Err(error) => {
return Ok(ToolResult::error(format!(
"vision image unavailable: {error}"
- )))
+ )));
}
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
index e97a39ff7b..3640f0d2ea 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_outcomes.rs
@@ -26,7 +26,9 @@ pub(super) fn awaiting_outcome_to_tool_result(
}
pub(super) fn format_subagent_failure(tool_name: &str, message: &str) -> String {
- format!("{tool_name} failed and did not complete — no work was performed and no results were produced. Do NOT treat this as success or fabricate an output; report the failure to the user. Error: {message}")
+ format!(
+ "{tool_name} failed and did not complete — no work was performed and no results were produced. Do NOT treat this as success or fabricate an output; report the failure to the user. Error: {message}"
+ )
}
pub(crate) fn is_unexecuted_tool_call_stub(output: &str) -> bool {
@@ -65,7 +67,9 @@ pub(crate) fn incomplete_envelope(
output: &str,
mode: DispatchMode,
) -> String {
- let envelope = format!("[SUBAGENT_INCOMPLETE] the {tool_name} sub-agent {reason} and did not finish. Below is partial progress only — do NOT report it as done or re-run the identical delegation unchanged.\n\nPartial progress:\n{output}");
+ let envelope = format!(
+ "[SUBAGENT_INCOMPLETE] the {tool_name} sub-agent {reason} and did not finish. Below is partial progress only — do NOT report it as done or re-run the identical delegation unchanged.\n\nPartial progress:\n{output}"
+ );
if mode == DispatchMode::Blocking {
format!("{envelope}{NO_WORKER_NOTE}")
} else {
diff --git a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
index 7369e83a35..1159ae4536 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime/run_loop.rs
@@ -22,6 +22,16 @@ impl OpenHumanSessionHost {
/// It wraps the core `turn` logic with telemetry events (`AgentTurnStarted`,
/// `AgentTurnCompleted`) and error sanitization.
pub async fn run_single(&mut self, message: &str) -> Result<String> {
+ self.run_single_with_origin(message, None).await
+ }
+
+ /// Runs a single turn with authority supplied explicitly by its entry point.
+ pub async fn run_single_with_origin(
+ &mut self,
+ message: &str,
+ origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ ) -> Result<String> {
+ let origin = origin.or_else(crate::core::runtime::CoreContext::current_turn_origin);
let guard = enforce_prompt_input(
message,
PromptEnforcementContext {
@@ -68,7 +78,7 @@ impl OpenHumanSessionHost {
channel: self.event_channel().to_string(),
});
- match self.turn(message).await {
+ match self.turn_with_origin(message, origin.as_ref()).await {
Ok(response) => {
let history = self.history();
let new_entries = Self::new_entries_for_turn(&history_snapshot, &history);
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 7e6e714272..6a81738194 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -5,21 +5,25 @@
//! prefix reconciliation, tool snapshots, resume and persistence remain inside
//! the runtime session.
+#[path = "runtime_session_attachment_input.rs"]
+mod attachment_input;
mod permanent;
mod prompt;
+#[path = "runtime_session_turn.rs"]
+mod turn;
use std::sync::Arc;
use anyhow::Result;
use tinyagents_runtime::{
CommitReceipt, ResumeMode, ResumePreparation, SessionBuilder, SessionTerminal,
- SessionTurnRequest, ToolSnapshot, TranscriptTarget, TurnOptions, TurnPreparation,
+ SessionTurnRequest, ToolSnapshot, TranscriptTarget, TurnPreparation,
};
use tinyagents_session::transcript::TranscriptMeta;
use tinyinference_llm::message::Message;
use crate::agent::{
- message_convert::{user_message_from_text, user_text_with_markers},
+ message_convert::user_text_with_markers,
session_host::{
driver::OpenHumanSessionDriver, OpenHumanSessionHooks, OpenHumanTranscriptCodec,
},
@@ -877,7 +881,9 @@ impl OpenHumanTurnPrelude {
)
.await
{
- log::warn!("[agent_autosave] durable message autosave failed kind={kind} key={key} err={error}");
+ log::warn!(
+ "[agent_autosave] durable message autosave failed kind={kind} key={key} err={error}"
+ );
false
} else {
true
@@ -1209,73 +1215,7 @@ impl OpenHumanSessionHost {
/// Dispatch one public OpenHuman turn through the neutral runtime.
pub async fn turn(&mut self, user_message: &str) -> Result<String> {
- self.ensure_runtime_session()?;
- let staged = crate::agent::attachments::stage_turn(
- user_message,
- self.runtime_config.as_deref(),
- self.workspace_descriptor.as_ref(),
- self.thread_id.as_deref(),
- )
- .await?;
- let user_message = staged.as_str();
-
- let mut context = OpenHumanRunContext::new();
- context.progress = self.on_progress.clone();
- context.thread_id = self.thread_id.clone();
- context.workspace = self.workspace_descriptor.clone();
- let cancellation = context.cancellation.clone();
- let root_config = context.root_run_config("openhuman-session");
- let options = TurnOptions {
- request_id: crate::agent::turn_origin::current_request_id(),
- thread_id: self.thread_id.clone(),
- stream: self.on_progress.is_some(),
- session: self.session.clone(),
- resume: self.turn_resume_mode(),
- cancellation,
- run_context: context.into_tinyagents(root_config),
- };
- // `tinyagents_runtime::Session` owns the restored declaration
- // snapshot. Load a bound, otherwise empty session before its normal
- // lifecycle runs so the host prelude can rebuild only its permitted
- // recorded integration executors for this turn.
- if matches!(options.resume, ResumeMode::Session)
- && self
- .runtime_session
- .as_ref()
- .is_some_and(|session| session.history().is_empty())
- {
- let runtime = self
- .runtime_session
- .as_mut()
- .expect("runtime session initialized");
- let resumed = runtime
- .resume(&options)
- .await
- .map_err(|error| anyhow::anyhow!(error.to_string()))?;
- if resumed.loaded {
- let recorded_tools = runtime.recorded_tools().cloned();
- if let Some(prelude) = self
- .runtime_state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .prelude
- .clone()
- {
- prelude.adopt_recorded_tools(recorded_tools.as_ref());
- }
- }
- }
- let outcome = self
- .runtime_session
- .as_mut()
- .expect("runtime session initialized")
- .turn(
- SessionTurnRequest::new(user_message_from_text(user_message)),
- options,
- )
- .await
- .map_err(|error| anyhow::anyhow!(error.to_string()))?;
- Ok(outcome.output.unwrap_or_default())
+ self.turn_with_origin(user_message, None).await
}
pub(in crate::agent::session_host) fn ensure_runtime_session(&mut self) -> Result<()> {
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_attachment_input.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_attachment_input.rs
new file mode 100644
index 0000000000..a7297bf67f
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_attachment_input.rs
@@ -0,0 +1,19 @@
+use super::OpenHumanSessionHost;
+
+/// Stage direct user input against the exact runtime and workspace bound to
+/// this session. Library callers with no explicit origin retain their existing
+/// authorized attachment behavior.
+pub(super) async fn stage_turn(
+ host: &OpenHumanSessionHost,
+ message: &str,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
+) -> anyhow::Result<String> {
+ crate::agent::attachments::stage_turn(
+ message,
+ host.runtime_config.as_deref(),
+ host.workspace_descriptor.as_ref(),
+ host.thread_id.as_deref(),
+ origin,
+ )
+ .await
+}
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
new file mode 100644
index 0000000000..815847b7fd
--- /dev/null
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs
@@ -0,0 +1,80 @@
+use anyhow::Result;
+use tinyagents_runtime::{ResumeMode, SessionTurnRequest, TurnOptions};
+
+use crate::agent::{
+ message_convert::user_message_from_text, session_host::types::OpenHumanSessionHost,
+ tinyagents::host::OpenHumanRunContext,
+};
+
+impl OpenHumanSessionHost {
+ /// Dispatch a turn with authority supplied by its owning entry point.
+ pub async fn turn_with_origin(
+ &mut self,
+ user_message: &str,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
+ ) -> Result<String> {
+ self.ensure_runtime_session()?;
+ let staged = super::attachment_input::stage_turn(self, user_message, origin).await?;
+ let mut context = OpenHumanRunContext::new();
+ context.origin = origin.cloned();
+ context.progress = self.on_progress.clone();
+ context.thread_id = self.thread_id.clone();
+ context.workspace = self.workspace_descriptor.clone();
+ let cancellation = context.cancellation.clone();
+ let root_config = context.root_run_config("openhuman-session");
+ let options = TurnOptions {
+ request_id: origin.and_then(|origin| match origin {
+ crate::agent::turn_origin::AgentTurnOrigin::WebChat { request_id, .. } => {
+ request_id.clone()
+ }
+ _ => None,
+ }),
+ thread_id: self.thread_id.clone(),
+ stream: self.on_progress.is_some(),
+ session: self.session.clone(),
+ resume: self.turn_resume_mode(),
+ cancellation,
+ run_context: context.into_tinyagents(root_config),
+ };
+ // Load a bound, otherwise empty session before its normal lifecycle so
+ // the host prelude can rebuild its recorded integration executors.
+ if matches!(options.resume, ResumeMode::Session)
+ && self
+ .runtime_session
+ .as_ref()
+ .is_some_and(|session| session.history().is_empty())
+ {
+ let runtime = self
+ .runtime_session
+ .as_mut()
+ .expect("runtime session initialized");
+ let resumed = runtime
+ .resume(&options)
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ if resumed.loaded {
+ let recorded_tools = runtime.recorded_tools().cloned();
+ if let Some(prelude) = self
+ .runtime_state
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+ .prelude
+ .clone()
+ {
+ prelude.adopt_recorded_tools(recorded_tools.as_ref());
+ }
+ }
+ }
+ let outcome = self
+ .runtime_session
+ .as_mut()
+ .expect("runtime session initialized")
+ .turn(
+ SessionTurnRequest::new(user_message_from_text(staged.as_str())),
+ options,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;
+ Ok(outcome.output.unwrap_or_default())
+ }
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 2a9147ef4e..4c1b37069e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -309,6 +309,13 @@ pub struct OpenHumanRunContext {
pub(crate) tool_dialect: tinyagents_harness::config::ToolDispatcher,
}
+/// Minimal immutable authority view exposed to shared tools through the
+/// harness's typed state-view seam.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct HostOperationContext {
+ pub(crate) origin: Option<AgentTurnOrigin>,
+}
+
impl Default for OpenHumanRunContext {
fn default() -> Self {
Self::new()
@@ -473,8 +480,12 @@ impl OpenHumanRunContext {
}
let cancellation = self.cancellation.clone();
let workspace = self.workspace.clone();
+ let host_operations = Arc::new(HostOperationContext {
+ origin: self.origin.clone(),
+ });
let context = tinyagents_harness::context::RunContext::new(config, self)
- .with_cancellation(cancellation);
+ .with_cancellation(cancellation)
+ .with_state_view(host_operations);
match workspace {
Some(workspace) => context.with_workspace(workspace),
None => context,
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
index a2e89c3f5d..3a795510f4 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -377,6 +377,7 @@ impl TurnContextMiddleware {
tool_policies: HashMap<String, TaToolPolicy>,
summary_focus_tools: std::collections::HashSet<String>,
) {
+ harness.push_middleware(Arc::new(AttachmentRequestScopeMiddleware));
// Transcript snapshot (#4466) runs first among before_model hooks so it
// mirrors the *incoming* request transcript (every prior completed round)
// before microcompact/summarization rewrite it — the caller's error path
@@ -417,6 +418,34 @@ impl TurnContextMiddleware {
}
}
+/// Carry attachment authority over the `ChatModel<()>` seam for this request.
+/// The OpenHuman provider wrapper consumes and removes the metadata before the
+/// request reaches any provider or transcript store.
+struct AttachmentRequestScopeMiddleware;
+
+#[async_trait]
+impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
+ for AttachmentRequestScopeMiddleware
+{
+ fn name(&self) -> &str {
+ "attachment_request_scope"
+ }
+
+ fn is_observer(&self) -> bool {
+ true
+ }
+
+ async fn before_model(
+ &self,
+ context: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ crate::agent::attachments::attach_request_scope(request, &context.data);
+ Ok(())
+ }
+}
+
#[cfg(test)]
#[path = "turn_context_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context_tests.rs
index 595694ed39..8a246625ed 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context_tests.rs
@@ -1,6 +1,41 @@
use super::*;
use tinyagents_harness::context::RunConfig;
+#[tokio::test]
+async fn attachment_scope_is_request_local_and_contains_only_typed_authority() {
+ let root = std::path::PathBuf::from("/workspace/project");
+ let mut data = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ data.origin = Some(
+ crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel: "test".into(),
+ sender: None,
+ reply_target: "room".into(),
+ message_id: "message".into(),
+ },
+ );
+ data.workspace = Some(tinytools::WorkspaceDescriptor::new(root.clone()));
+ let mut context = RunContext::new(RunConfig::new("attachment-scope"), data);
+ let mut request = ModelRequest::new(Vec::new());
+ request.metadata["preserved"] = serde_json::json!(true);
+
+ AttachmentRequestScopeMiddleware
+ .before_model(&mut context, &(), &mut request)
+ .await
+ .expect("scope carrier is installed");
+
+ let mut provider_metadata = request.metadata.clone();
+ let scope = crate::agent::attachments::take_request_scope(&mut provider_metadata);
+ assert!(scope.external_channel);
+ assert_eq!(scope.workspace.as_deref(), Some(root.as_path()));
+ assert_eq!(provider_metadata, serde_json::json!({"preserved": true}));
+ assert!(request.messages.is_empty());
+}
+
+#[tokio::test]
+async fn attachment_scope_observes_even_after_an_earlier_middleware_stops() {
+ assert!(AttachmentRequestScopeMiddleware.is_observer());
+}
+
#[tokio::test]
async fn transcript_snapshot_keeps_a_completed_failed_tool_row() {
let sink = Arc::new(std::sync::Mutex::new(TranscriptSnapshot::default()));
diff --git a/crates/openhuman-core/src/agent/tinyagents/tools.rs b/crates/openhuman-core/src/agent/tinyagents/tools.rs
index 3ed9e8482e..6c55353f92 100644
--- a/crates/openhuman-core/src/agent/tinyagents/tools.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/tools.rs
@@ -197,7 +197,28 @@ impl Tool for CanonicalSharedToolAdapter {
// A callable tool's operational failure is input to the agent loop, not
// a failure of the harness itself. Preserve it as an error result so
// the model can recover (or explain the failure) on its next round.
- let result = match tool.execute_with_context(args, options, context).await {
+ let origin = context
+ .and_then(tinytools::ToolRunContext::host_extension)
+ .and_then(|extension| {
+ extension.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>()
+ })
+ .and_then(|context| {
+ context.state::<crate::agent::tinyagents::host::run_context::HostOperationContext>()
+ })
+ .and_then(|context| context.origin.clone());
+ let execution = tool.execute_with_context(args, options, context);
+ let execution = match (origin, crate::core::runtime::CoreContext::current()) {
+ (Some(origin), Some(core_context)) => {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(
+ core_context,
+ Some(origin),
+ execution,
+ )
+ .await
+ }
+ _ => execution.await,
+ };
+ let result = match execution {
Ok(result) => result,
Err(error) => {
tracing::warn!(tool = %self.name, %error, "[tinyagents] shared tool execution failed");
diff --git a/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs
index 124ffdb030..bd5fc12bcf 100644
--- a/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs
@@ -147,6 +147,83 @@ async fn canonical_adapter_preserves_spec_policy_context_and_result() {
);
}
+struct OriginObservingTool(Arc<AtomicBool>);
+
+#[async_trait]
+impl Tool for OriginObservingTool {
+ fn name(&self) -> &str {
+ "origin_observer"
+ }
+ fn description(&self) -> &str {
+ "Observes the per-turn core authority."
+ }
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type":"object"})
+ }
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("executed"))
+ }
+ async fn execute_with_context(
+ &self,
+ _args: serde_json::Value,
+ _options: ToolCallOptions,
+ _context: Option<&dyn ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ self.0.store(
+ matches!(
+ crate::core::runtime::CoreContext::current_turn_origin(),
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ),
+ Ordering::SeqCst,
+ );
+ Ok(ToolResult::success("executed"))
+ }
+}
+
+#[tokio::test]
+async fn canonical_adapter_scopes_tool_execution_to_the_run_origin() {
+ use tinyagents_harness::context::RunConfig;
+
+ let context = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ None,
+ None,
+ );
+ let observed = Arc::new(AtomicBool::new(false));
+ let tools: Vec<Arc<Vec<Box<dyn Tool>>>> = vec![Arc::new(vec![Box::new(OriginObservingTool(
+ observed.clone(),
+ ))])];
+ let adapter = CanonicalSharedToolAdapter::for_name(tools, "origin_observer").unwrap();
+ let mut host = crate::agent::tinyagents::host::OpenHumanRunContext::new();
+ host.origin = Some(
+ crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel: "test".into(),
+ sender: None,
+ reply_target: "room".into(),
+ message_id: "message".into(),
+ },
+ );
+ let run = host.into_tinyagents(RunConfig::new("origin-observer"));
+ let tool_context = tinyagents_harness::tool::ToolExecutionContext::from_run_context(
+ &run,
+ tinyagents_harness::ids::CallId::new("call"),
+ );
+
+ crate::core::runtime::CoreContext::scope(context, async {
+ adapter
+ .execute_with_context(
+ serde_json::json!({}),
+ ToolCallOptions::default(),
+ Some(&tool_context),
+ )
+ .await
+ .expect("tool execution succeeds");
+ assert!(observed.load(Ordering::SeqCst));
+ assert!(crate::core::runtime::CoreContext::current_turn_origin().is_none());
+ })
+ .await;
+}
+
#[tokio::test]
async fn canonical_adapter_fails_closed_when_the_registered_tool_is_gone() {
let adapter = CanonicalSharedToolAdapter {
diff --git a/crates/openhuman-core/src/agent/turn_origin.rs b/crates/openhuman-core/src/agent/turn_origin.rs
index 52666fec26..a283aacd62 100644
--- a/crates/openhuman-core/src/agent/turn_origin.rs
+++ b/crates/openhuman-core/src/agent/turn_origin.rs
@@ -191,6 +191,18 @@ tokio::task_local! {
/// covers every caller (web channel, channel runtime, cron, background
/// jobs, CLI).
pub async fn with_origin<F: std::future::Future>(origin: AgentTurnOrigin, fut: F) -> F::Output {
+ let scoped = scope_origin(origin.clone(), fut);
+ let context = crate::core::runtime::CoreContext::current()
+ .or_else(crate::core::runtime::CoreContext::default_context);
+ if let Some(context) = context {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(context, Some(origin), scoped)
+ .await
+ } else {
+ scoped.await
+ }
+}
+
+async fn scope_origin<F: std::future::Future>(origin: AgentTurnOrigin, fut: F) -> F::Output {
AGENT_TURN_ORIGIN.scope(origin, Box::pin(fut)).await
}
diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rs
index 0900593897..d593968558 100644
--- a/crates/openhuman-core/src/core/runtime/context.rs
+++ b/crates/openhuman-core/src/core/runtime/context.rs
@@ -104,6 +104,8 @@ pub struct CoreContext {
/// Inherited unchanged by every context derived through
/// [`CoreContext::derive_with`].
backend_transport: Option<Arc<dyn crate::backend::transport::BackendTransport>>,
+ /// Explicit authority on this derived turn context.
+ turn_origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
}
/// Per-agent overrides layered onto a booted context by
@@ -357,6 +359,7 @@ impl CoreContext {
embedder_config,
user_skill_roots: true,
backend_transport,
+ turn_origin: None,
});
// Register the process default context (first build wins). Dispatch
@@ -472,6 +475,7 @@ impl CoreContext {
embedder_config: Some(overlay.config),
user_skill_roots: overlay.user_skill_roots,
backend_transport: self.backend_transport.clone(),
+ turn_origin: self.turn_origin.clone(),
})
}
@@ -621,19 +625,6 @@ impl CoreContext {
Self::current().and_then(|ctx| ctx.embedder_config.clone())
}
- pub fn current() -> Option<Arc<CoreContext>> {
- CURRENT_CONTEXT
- .try_with(|ctx| ctx.clone())
- .ok()
- .or_else(|| DEFAULT_CONTEXT.get().cloned())
- }
-
- /// The process default context (first built), independent of any active
- /// scope. Used by the dispatch chokepoint to establish the ambient scope.
- pub fn default_context() -> Option<Arc<CoreContext>> {
- DEFAULT_CONTEXT.get().cloned()
- }
-
/// Rebind the process default context to the current active user's
/// workspace **and** that user's `[subsystems.memory]` config. Desktop
/// login, logout, and pending-session revalidation can switch the active
@@ -783,6 +774,7 @@ impl CoreContext {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
})
}
@@ -812,6 +804,7 @@ impl CoreContext {
embedder_config: Some(config),
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
})
}
}
@@ -1019,6 +1012,9 @@ pub async fn init_stores(cfg: &crate::config::Config, domains: crate::core::runt
}
}
+#[path = "context_turn_origin.rs"]
+mod turn_origin_scope;
+
#[cfg(test)]
#[path = "context_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rs
index 39d74b006b..fee1ad2002 100644
--- a/crates/openhuman-core/src/core/runtime/context_tests.rs
+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs
@@ -13,6 +13,7 @@ fn ctx(dir: &str) -> Arc<CoreContext> {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
})
}
@@ -43,6 +44,7 @@ fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {
embedder_config: Some(config),
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
})
}
@@ -355,6 +357,7 @@ fn degraded_context_rejects_workspace_bound_stores() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
// `workspace_dir()` is the gate every workspace-bound store goes
@@ -406,6 +409,7 @@ fn memory_binding_is_isolated_per_context_workspace() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
});
let b = Arc::new(CoreContext {
host_kind: HostKind::Cli,
@@ -418,6 +422,7 @@ fn memory_binding_is_isolated_per_context_workspace() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
});
let bind_a = a.memory_binding().expect("bind workspace A");
@@ -446,6 +451,7 @@ fn rebind_workspace_updates_context_memory_binding() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
let bind_a = ctx.memory_binding().expect("bind workspace A");
@@ -475,6 +481,7 @@ fn rebind_workspace_refreshes_memory_subsystem_config() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
let bind_a = ctx.memory_binding().expect("bind workspace A");
@@ -517,6 +524,7 @@ fn failed_bind_never_returns_previous_workspace_binding() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
let b = CoreContext {
host_kind: HostKind::Cli,
@@ -529,6 +537,7 @@ fn failed_bind_never_returns_previous_workspace_binding() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
let bind_a = a.memory_binding().expect("bind workspace A");
@@ -561,6 +570,7 @@ fn memory_capabilities_defaults_open_without_a_workspace() {
embedder_config: None,
user_skill_roots: true,
backend_transport: None,
+ turn_origin: None,
};
assert!(ctx.memory_binding().is_err(), "no workspace ⇒ no binding");
assert_eq!(
@@ -718,3 +728,7 @@ fn a_parent_workspace_rebind_does_not_move_a_derived_context() {
"tinycortex"
);
}
+
+#[cfg(test)]
+#[path = "context_turn_origin_tests.rs"]
+mod turn_origin_tests;
diff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
new file mode 100644
index 0000000000..bae5e254d5
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs
@@ -0,0 +1,48 @@
+use super::*;
+
+impl CoreContext {
+ pub fn current() -> Option<Arc<CoreContext>> {
+ CURRENT_CONTEXT
+ .try_with(|ctx| ctx.clone())
+ .ok()
+ .or_else(|| DEFAULT_CONTEXT.get().cloned())
+ }
+
+ /// The process default context (first built), independent of any active
+ /// scope. Used by the dispatch chokepoint to establish the ambient scope.
+ pub fn default_context() -> Option<Arc<CoreContext>> {
+ DEFAULT_CONTEXT.get().cloned()
+ }
+
+ /// Typed origin bound to this immutable per-turn context, if supplied by
+ /// its entrypoint. Missing authority retains library/CLI behavior.
+ pub fn current_turn_origin() -> Option<crate::agent::turn_origin::AgentTurnOrigin> {
+ Self::current().and_then(|ctx| ctx.turn_origin.clone())
+ }
+
+ /// Run a turn under a derived immutable context carrying its explicit
+ /// entrypoint authority. The shared parent and other concurrent turns are
+ /// untouched.
+ pub async fn scope_with_turn_origin<F: Future>(
+ ctx: Arc<CoreContext>,
+ origin: Option<crate::agent::turn_origin::AgentTurnOrigin>,
+ fut: F,
+ ) -> F::Output {
+ let context = Arc::new(CoreContext {
+ host_kind: ctx.host_kind,
+ workspace_binding: RwLock::new(
+ ctx.workspace_binding
+ .read()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone(),
+ ),
+ domains: ctx.domains,
+ tool_groups: ctx.tool_groups.clone(),
+ embedder_config: ctx.embedder_config.clone(),
+ user_skill_roots: ctx.user_skill_roots,
+ backend_transport: ctx.backend_transport.clone(),
+ turn_origin: origin.or_else(|| ctx.turn_origin.clone()),
+ });
+ CURRENT_CONTEXT.scope(context, fut).await
+ }
+}
diff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs
new file mode 100644
index 0000000000..9049da5c1b
--- /dev/null
+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin_tests.rs
@@ -0,0 +1,82 @@
+use super::*;
+
+#[tokio::test]
+async fn dispatch_scope_uses_explicit_origin_without_mutating_shared_context() {
+ let ctx = ctx("/tmp/origin-scope");
+ let origin = crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel: "test".into(),
+ sender: Some("sender".into()),
+ reply_target: "room".into(),
+ message_id: "message".into(),
+ };
+ CoreContext::scope_with_turn_origin(ctx.clone(), Some(origin), async {
+ assert!(matches!(
+ CoreContext::current_turn_origin(),
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ));
+ })
+ .await;
+ assert!(CoreContext::current_turn_origin().is_none());
+ assert!(ctx.embedder_config().is_none());
+}
+
+#[tokio::test]
+async fn missing_child_origin_inherits_bound_external_authority() {
+ let ctx = ctx("/tmp/origin-inheritance");
+ let external = crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel: "test".into(),
+ sender: None,
+ reply_target: "room".into(),
+ message_id: "message".into(),
+ };
+ CoreContext::scope_with_turn_origin(ctx, Some(external), async {
+ let parent = CoreContext::current().expect("parent context");
+ CoreContext::scope_with_turn_origin(parent, None, async {
+ assert!(matches!(
+ CoreContext::current_turn_origin(),
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ));
+ })
+ .await;
+ })
+ .await;
+}
+
+#[tokio::test]
+async fn explicit_origin_scope_bridges_legacy_and_core_context_without_cross_talk() {
+ use crate::agent::turn_origin::{self, AgentTurnOrigin};
+
+ let run = |workspace: &'static str, channel: &'static str| async move {
+ let context = ctx(workspace);
+ let origin = AgentTurnOrigin::ExternalChannel {
+ channel: channel.into(),
+ sender: Some(format!("{channel}-sender")),
+ reply_target: format!("{channel}-room"),
+ message_id: format!("{channel}-message"),
+ };
+ CoreContext::scope(context, async {
+ turn_origin::with_origin(origin, async {
+ assert!(matches!(
+ turn_origin::current(),
+ Some(AgentTurnOrigin::ExternalChannel { channel: current, .. })
+ if current == channel
+ ));
+ assert!(matches!(
+ CoreContext::current_turn_origin(),
+ Some(AgentTurnOrigin::ExternalChannel { channel: current, .. })
+ if current == channel
+ ));
+ })
+ .await;
+
+ assert!(turn_origin::current().is_none());
+ assert!(CoreContext::current_turn_origin().is_none());
+ })
+ .await;
+ };
+
+ tokio::join!(
+ run("/tmp/origin-a", "channel-a"),
+ run("/tmp/origin-b", "channel-b")
+ );
+}
diff --git a/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs b/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs
index 94107fdd9d..a77bb87501 100644
--- a/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs
+++ b/crates/openhuman-core/src/skills/e2e_plumbing_tests.rs
@@ -208,6 +208,7 @@ async fn mock_llm_orchestrator_lists_and_runs_workflows_through_the_loop() {
MultimodalConfig::default(),
MultimodalFileConfig::default(),
None,
+ None,
)
.await
.expect("tool loop should run to completion");
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index df5ce3f0b5..43506a91d2 100644
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@ -151,15 +151,17 @@ pub async fn transcript_search(
pub async fn message_append(
request: AppendConversationMessageRequest,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
+ let origin = crate::core::runtime::CoreContext::current_turn_origin();
let config = crate::config::Config::load_or_init()
.await
.map_err(|error| ThreadsError::Message(format!("load config: {error}")))?;
- message_append_with_config(request, &config).await
+ message_append_with_config(request, &config, origin.as_ref()).await
}
async fn message_append_with_config(
mut request: AppendConversationMessageRequest,
config: &crate::config::Config,
+ origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
if request.message.sender == "user" {
let raw_upload = request.message.content.contains("[IMAGE:")
@@ -184,7 +186,7 @@ async fn message_append_with_config(
|| durable_files.len() - image_count + raw_files.len() > max_files
|| (image_count > 0 && config.multimodal.max_images == 0)
|| matches!(
- crate::agent::turn_origin::current(),
+ origin,
Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
)
{
@@ -193,7 +195,14 @@ async fn message_append_with_config(
));
}
for file in &durable_files {
- let path = crate::agent::attachments::resolve_path(config, &file.path)
+ let scope = crate::agent::attachments::AttachmentAccessScope {
+ external_channel: matches!(
+ origin,
+ Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel { .. })
+ ),
+ workspace: Some(config.action_dir.clone()),
+ };
+ let path = crate::agent::attachments::resolve_path(config, &file.path, &scope)
.await
.map_err(|error| {
ThreadsError::Message(format!("validate user attachment: {error}"))
@@ -240,6 +249,7 @@ async fn message_append_with_config(
Some(config),
None,
Some(&request.thread_id),
+ origin,
)
.await
.map_err(|error| ThreadsError::Message(format!("stage user attachments: {error}")))?;
diff --git a/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs b/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
index 9c41cbdfbb..11356a3f46 100644
--- a/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
+++ b/crates/openhuman-core/src/threads/ops/crud_message_append_tests.rs
@@ -49,6 +49,7 @@ async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_con
"user",
),
&config,
+ None,
)
.await
.unwrap()
@@ -73,7 +74,7 @@ async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_con
);
assert_eq!(first.extra_metadata["attachmentKinds"], json!(["image"]));
assert_eq!(first.extra_metadata["other"], "kept");
- let second = message_append_with_config(request("two", &first.content, "user"), &config)
+ let second = message_append_with_config(request("two", &first.content, "user"), &config, None)
.await
.unwrap()
.value
@@ -85,6 +86,7 @@ async fn user_append_stages_original_strips_upload_bytes_and_reuses_returned_con
Some(&config),
None,
Some("uploads"),
+ None,
)
.await
.unwrap();
@@ -109,19 +111,21 @@ async fn rejected_upload_never_appends_a_message() {
"[IMAGE:data:image/png;base64,iVBORw0KGgo=]",
"user"
),
- &config
+ &config,
+ None,
)
.await
.is_err());
config.multimodal_files.max_files = 3;
assert!(message_append_with_config(
request("bad", "[FILE:data:application/zip;base64,!]", "user"),
- &config
+ &config,
+ None,
)
.await
.is_err());
assert!(
- message_append_with_config(request("missing", "image.png", "user"), &config)
+ message_append_with_config(request("missing", "image.png", "user"), &config, None)
.await
.is_err()
);
@@ -133,12 +137,45 @@ async fn rejected_upload_never_appends_a_message() {
);
}
+#[tokio::test]
+async fn external_origin_cannot_reuse_an_existing_attachment_marker() {
+ let (_temp, config) = setup().await;
+ let staged = crate::agent::attachments::stage_turn(
+ "[IMAGE:data:image/png;base64,iVBORw0KGgo=]",
+ Some(&config),
+ None,
+ Some("uploads"),
+ None,
+ )
+ .await
+ .unwrap();
+ let origin = crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
+ channel: "test".into(),
+ sender: None,
+ reply_target: "room".into(),
+ message_id: "message".into(),
+ };
+ assert!(message_append_with_config(
+ request("external", &staged, "user"),
+ &config,
+ Some(&origin)
+ )
+ .await
+ .is_err());
+ assert!(
+ conversations::blocking::get_messages(config.workspace_dir, "uploads".into())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
#[tokio::test]
async fn ordinary_user_text_and_agent_images_are_preserved() {
let (_temp, config) = setup().await;
let mut user = request("text", "ordinary text", "user");
user.message.extra_metadata = json!({"other":"kept"});
- let stored = message_append_with_config(user, &config)
+ let stored = message_append_with_config(user, &config, None)
.await
.unwrap()
.value
@@ -152,7 +189,7 @@ async fn ordinary_user_text_and_agent_images_are_preserved() {
"assistant",
);
let expected = serde_json::to_value(&assistant.message).unwrap();
- let stored = message_append_with_config(assistant, &config)
+ let stored = message_append_with_config(assistant, &config, None)
.await
.unwrap()
.value
@@ -169,7 +206,9 @@ async fn poster_only_user_metadata_is_rejected_before_persistence() {
"attachmentNames": ["video.mp4"],
"attachmentPosters": ["data:image/png;base64,iVBORw0KGgo="]
});
- assert!(message_append_with_config(upload, &config).await.is_err());
+ assert!(message_append_with_config(upload, &config, None)
+ .await
+ .is_err());
assert!(
conversations::blocking::get_messages(config.workspace_dir.clone(), "uploads".into())
.await
diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
index 2b0143948a..7cf6f74c11 100644
--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
@@ -61,7 +61,7 @@ pub(crate) async fn spawn_parallel_turn(
};
let result = run_turn_under_cancel_and_deadline(
task_cancel_token,
- origin,
+ origin.clone(),
approval_ctx,
run_chat_task(
&client_id_task,
@@ -73,6 +73,7 @@ pub(crate) async fn spawn_parallel_turn(
locale,
run_queue,
metadata,
+ origin.clone(),
/* fork */ true,
),
)
diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
index 90d0cdf7ea..b082978eea 100644
--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs
+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs
@@ -163,9 +163,17 @@ pub async fn start_chat(
.map_err(|error| {
StartChatError::Other(format!("upload configuration unavailable: {error}"))
})?;
- crate::agent::attachments::stage(&message, &thread_id, &config)
- .await
- .map_err(|error| StartChatError::Other(format!("upload could not be saved: {error}")))?
+ crate::agent::attachments::stage(
+ &message,
+ &thread_id,
+ &config,
+ &crate::agent::attachments::AttachmentAccessScope {
+ external_channel: false,
+ workspace: Some(config.action_dir.clone()),
+ },
+ )
+ .await
+ .map_err(|error| StartChatError::Other(format!("upload could not be saved: {error}")))?
} else {
message
};
@@ -459,7 +467,7 @@ pub async fn start_chat(
// user-facing `chat_error`, so we just unwind quietly here.
let result = run_turn_under_cancel_and_deadline(
task_cancel_token,
- origin,
+ origin.clone(),
approval_ctx,
run_chat_task(
&client_id_task,
@@ -471,6 +479,7 @@ pub async fn start_chat(
locale,
turn_run_queue_task,
metadata,
+ origin.clone(),
/* fork */ false,
),
)
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 1cf713a9f1..a0561c2eff 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -36,6 +36,7 @@ pub(crate) async fn run_chat_task(
locale: Option<String>,
run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,
metadata: ChatRequestMetadata,
+ origin: crate::agent::turn_origin::AgentTurnOrigin,
// When true, run as an isolated fork: build a fresh agent seeded from the
// thread's history-at-start and never touch the shared `THREAD_SESSIONS`
// cache, so a concurrent same-thread (parallel) turn cannot clobber — or be
@@ -154,7 +155,7 @@ pub(crate) async fn run_chat_task(
// wrappers below hold a pointer rather than inlining the whole future into
// this already-large `run_chat_task` frame (which otherwise overflows the
// default test-thread stack — see the channels web-turn coverage tests).
- let turn = Box::pin(agent.run_single(message));
+ let turn = Box::pin(agent.run_single_with_origin(message, Some(origin)));
let mut result = match turn.await {
Ok(response) => {
// A successful turn proves the thread's balance is usable, so drop
diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.json
index 62344b80cc..3743801f53 100644
--- a/scripts/ci/agent-runtime-boundary-baseline.json
+++ b/scripts/ci/agent-runtime-boundary-baseline.json
@@ -440,13 +440,6 @@
"text": "workspace_descriptor: crate::agent::harness::current_parent()",
"occurrence": 1
},
- {
- "rule": "openhuman-task-local",
- "path": "crates/openhuman-core/src/agent/session_host/runtime_session.rs",
- "line": 1272,
- "text": "request_id: crate::agent::turn_origin::current_request_id(),",
- "occurrence": 1
- },
{
"rule": "openhuman-task-local",
"path": "crates/openhuman-core/src/agent/session_host/turn/graph.rs",
diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjs
index 4fdf68abda..9bf0e0d005 100644
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@ -38,7 +38,7 @@ 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", 1875],
+ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1815],
// 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
@@ -60,7 +60,7 @@ const LEGACY_LIMIT_ENTRIES = [
["crates/openhuman-core/src/core/events_tests.rs", 1062],
["crates/openhuman-core/src/core/observability.rs", 3631],
["crates/openhuman-core/src/core/runtime/builder.rs", 825],
- ["crates/openhuman-core/src/core/runtime/context.rs", 1024],
+ ["crates/openhuman-core/src/core/runtime/context.rs", 1020],
];
const LEGACY_LIMITS = new Map(LEGACY_LIMIT_ENTRIES);