The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge remote-tracking branch 'upstream/main' into pr/6949
Steven Enamakel8954bd2c58cd
diff --cc crates/openhuman-core/src/agent/attachments/provider_tests.rsindex 0000000000,955be008b4..c9d70b070emode 000000,100644..100644--- a/crates/openhuman-core/src/agent/attachments/provider_tests.rs+++ b/crates/openhuman-core/src/agent/attachments/provider_tests.rs@@@ -1,0 -1,656 +1,654 @@@+ use super::*;+ use std::sync::Mutex;+ #[derive(Default)]+ pub(super) struct Probe {+ pub(super) requests: Mutex<Vec<ModelRequest>>,+ profile: ModelProfile,+ }+ #[async_trait]+ impl ChatModel<()> for Probe {+ fn profile(&self) -> Option<&ModelProfile> {+ Some(&self.profile)+ }+ fn supports_input(&self, m: InputModality, t: &str, s: InputSource) -> bool {+ m == InputModality::Image+ && matches!(t, "image/png" | "image/jpeg")+ && s == InputSource::Base64+ }+ async fn invoke(+ &self,+ _: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ self.requests.lock().unwrap().push(request);+ Err(tinyinference_llm::Error::Model("probe".into()))+ }+ }+ #[tokio::test]+ async fn local_native_resolution_changes_only_ephemeral_request() {+ let temp = tempfile::tempdir().unwrap();+ tokio::fs::write(temp.path().join("sample.png"), b"original-png")+ .await+ .unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ config.workspace_dir = temp.path().join("internal");+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: "sample.png".into(),+ mime_type: Some("image/png".into()),+ })],+ },+ )]);+ let durable = request.clone();+ assert!(wrapper.invoke(&(), request).await.is_err());+ assert!(serde_json::to_string(&durable)+ .unwrap()+ .contains("sample.png"));+ let captured = probe.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ assert!(serde_json::to_string(&captured[0])+ .unwrap()+ .contains("data:image/png;base64,"));+ assert_eq!(+ tokio::fs::read(temp.path().join("sample.png"))+ .await+ .unwrap(),+ b"original-png"+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn blocked_attachment_fails_before_model_call() {+ let mut config = Config::default();+ config.multimodal_files.max_files = 0;+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: "../secret.png".into(),+ mime_type: Some("image/png".into()),+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ assert!(probe.requests.lock().unwrap().is_empty());+ }+ #[test]+ fn unknown_model_does_not_inherit_transport_vision() {+ let model = wrap(+ Arc::new(Probe::default()),+ Arc::new(Config::default()),+ "unknown-model",+ "cloud",+ );+ assert!(!model.profile().unwrap().modalities.image_in);+ }++ #[tokio::test]+ async fn persisted_image_without_mime_uses_magic_over_extension() {+ let temp = tempfile::tempdir().unwrap();+ tokio::fs::write(temp.path().join("renamed.png"), [0xff, 0xd8, 0xff, 0xe0])+ .await+ .unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: "renamed.png".into(),+ mime_type: None,+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ let captured = probe.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ assert!(serde_json::to_string(&captured[0])+ .unwrap()+ .contains("data:image/jpeg;base64,"));+ }++ #[tokio::test]+ async fn too_many_typed_images_reject_before_read_or_inference() {+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(+ probe.clone(),+ Arc::new(Config::default()),+ "gpt-4o",+ "openai",+ );+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: (0..5)+ .map(|_| {+ ContentBlock::Image(ImageRef {+ url: "missing.png".into(),+ mime_type: None,+ })+ })+ .collect(),+ },+ )]);+ let error = wrapper.invoke(&(), request).await.unwrap_err();+ assert!(error.to_string().contains("attachment count"));+ assert!(probe.requests.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn external_channel_cannot_rehydrate_a_local_image() {+ use crate::agent::turn_origin::AgentTurnOrigin;+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(+ probe.clone(),+ Arc::new(Config::default()),+ "gpt-4o",+ "openai",+ );+ let mut request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: "missing.png".into(),+ mime_type: None,+ })],+ },+ )]);+ let origin = AgentTurnOrigin::ExternalChannel {+ channel: "telegram".into(),+ sender: None,+ reply_target: "chat".into(),+ message_id: "message".into(),+ };+ 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());+ }++ #[tokio::test]+ async fn unknown_video_retains_path_as_metadata_without_specialist() {+ let temp = tempfile::tempdir().unwrap();+ tokio::fs::write(temp.path().join("clip.mp4"), b"video-original")+ .await+ .unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config), "unknown", "custom");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Video(MediaRef::Path {+ path: "clip.mp4".into(),+ media_type: Some("video/mp4".into()),+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ let captured = probe.requests.lock().unwrap().clone();+ let text = captured[0].messages[0].text();+ assert!(text.contains("clip.mp4"));+ assert!(text.contains("14 bytes"));+ assert!(!serde_json::to_string(&captured[0])+ .unwrap()+ .contains("base64"));+ }++ #[tokio::test]+ async fn derivative_cache_survives_model_recreation_and_invalidates_changed_content() {+ let temp = tempfile::tempdir().unwrap();+ let original = temp.path().join("uploads/thread/id/original.txt");+ tokio::fs::create_dir_all(original.parent().unwrap())+ .await+ .unwrap();+ tokio::fs::write(&original, b"original").await.unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let config = Arc::new(config);+ let make = || AttachmentModel {+ inner: Arc::new(Probe::default()),+ config: config.clone(),+ profile: ModelProfile::default(),+ 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",+ &scope,+ )+ .await;+ let resumed = make();+ assert_eq!(+ resumed+ .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, &scope)+ .await+ .is_none());+ assert_eq!(tokio::fs::read(original).await.unwrap(), b"original");+ assert!(tokio::fs::read_dir(temp.path().join("uploads/thread/id"))+ .await+ .unwrap()+ .next_entry()+ .await+ .unwrap()+ .is_some());+ }++ #[tokio::test]+ async fn cache_is_not_written_beside_unmanaged_local_files() {+ let temp = tempfile::tempdir().unwrap();+ tokio::fs::write(temp.path().join("original.txt"), b"original")+ .await+ .unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let model = AttachmentModel {+ inner: Arc::new(Probe::default()),+ config: Arc::new(config),+ profile: ModelProfile::default(),+ fallback_cache: Mutex::new(Default::default()),+ };+ model+ .save_fallback(+ "original.txt",+ "key",+ "derived",+ &super::super::AttachmentAccessScope::default(),+ )+ .await;+ assert!(!temp.path().join(".openhuman-intake.txt").exists());+ }++ #[test]+ fn endpoint_discovery_denial_overrides_offline_vision_facts() {+ use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};+ use tinyinference_llm::model::discover::{model_limits_cache, LimitSource, ModelLimits};+ let temp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.config_path = temp.path().join("config.toml");+ config.workspace_dir = temp.path().join("workspace");+ config.cloud_providers = vec![CloudProviderCreds {+ id: "p_attachment_probe".into(),+ slug: "attachment-probe".into(),+ label: "test".into(),+ endpoint: "http://127.0.0.1:19991/v1".into(),+ auth_style: AuthStyle::None,+ ..Default::default()+ }];+ let request = crate::inference::provider::factory::model_limits_request(+ "chat",+ "attachment-probe:gpt-4o",+ "gpt-4o",+ &config,+ )+ .unwrap();+ model_limits_cache().insert_discovered_variant(+ &request.endpoint,+ &request.model,+ &request.cache_variant(),+ Some(ModelLimits {+ context_window: None,+ max_output_tokens: None,+ input_modalities: Some(vec!["text".into()]),+ source: LimitSource::ProviderListing,+ }),+ );+ let model = wrap(+ Arc::new(Probe::default()),+ Arc::new(config),+ "gpt-4o",+ "attachment-probe",+ );+ assert!(!model.profile().unwrap().modalities.image_in);+ }++ #[tokio::test]+ async fn legacy_inline_source_is_bounded_and_malformed_base64_rejects_before_primary() {+ let probe = Arc::new(Probe::default());+ let mut config = Config::default();+ config.multimodal.max_image_size_mb = 1;+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");+ for source in [+ "data:image/png;base64,%%%".to_owned(),+ format!("data:image/png;base64,{}", "A".repeat(2 * 1024 * 1024)),+ ] {+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: source,+ mime_type: Some("image/png".into()),+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ }+ assert!(probe.requests.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn disabled_remote_replay_is_rejected_before_inference() {+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(+ probe.clone(),+ Arc::new(Config::default()),+ "unknown",+ "custom",+ );+ for block in [+ ContentBlock::Image(ImageRef {+ url: "https://example.invalid/image.png".into(),+ mime_type: Some("image/png".into()),+ }),+ ContentBlock::Document(MediaRef::Url {+ url: "https://example.invalid/file.pdf".into(),+ media_type: Some("application/pdf".into()),+ }),+ ] {+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![block],+ },+ )]);+ let error = wrapper.invoke(&(), request).await.unwrap_err();+ assert!(error+ .to_string()+ .contains("remote attachment fetch is disabled"));+ }+ assert!(probe.requests.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn inline_native_replay_materializes_original_and_keeps_durable_message_unchanged() {+ let temp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config), "gpt-4o", "openai");+ let bytes = b"\x89PNG\r\n\x1a\noriginal";+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: format!("data:image/png;base64,{}", STANDARD.encode(bytes)),+ mime_type: None,+ })],+ },+ )]);+ let durable = request.clone();+ assert!(wrapper.invoke(&(), request).await.is_err());+ let captured = probe.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ let text = captured[0].messages[0].text();+ let path = text+ .split("workspace path: ")+ .nth(1)+ .unwrap()+ .trim_end_matches(']');+ assert_eq!(+ tokio::fs::read(temp.path().join(path)).await.unwrap(),+ bytes+ );+ assert_eq!(durable.messages[0].text(), "");+ }++ #[tokio::test]+ async fn derivative_cache_cannot_overwrite_original_named_like_cache() {+ let temp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let source = format!(+ "data:text/plain;name=.openhuman-intake.txt;base64,{}",+ STANDARD.encode(b"original")+ );+ 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");+ let probe = Arc::new(Probe::default());+ let wrapper = wrap(probe.clone(), Arc::new(config.clone()), "unknown", "custom");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Document(MediaRef::Path {+ path: files[0].path.clone(),+ media_type: Some("text/plain".into()),+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ assert_eq!(+ tokio::fs::read(temp.path().join(&files[0].path))+ .await+ .unwrap(),+ b"original"+ );+ }++ struct InlineVision {+ profile: ModelProfile,+ calls: std::sync::atomic::AtomicUsize,+ }+ #[async_trait]+ impl ChatModel<()> for InlineVision {+ fn profile(&self) -> Option<&ModelProfile> {+ Some(&self.profile)+ }+ fn supports_input(&self, m: InputModality, mime: &str, source: InputSource) -> bool {+ m == InputModality::Image && mime == "image/png" && source == InputSource::Base64+ }+ async fn invoke(+ &self,+ _: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ assert!(+ matches!(&request.messages[0],Message::User(user) if user.content.iter().any(|b|matches!(b,ContentBlock::Image(_))))+ );+ self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(ModelResponse::assistant("specialist image readout"))+ }+ }++ #[tokio::test]+ async fn unknown_model_legacy_inline_replay_uses_specialist_once_across_model_recreation() {+ let temp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let config = Arc::new(config);+ let mut profile = ModelProfile::default();+ profile.provider = Some("injected".into());+ profile.modalities.image_in = true;+ let specialist = Arc::new(InlineVision {+ profile,+ calls: std::sync::atomic::AtomicUsize::new(0),+ });+ let _guard = crate::inference::provider::factory::test_provider_override::install_model(+ specialist.clone(),+ );+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: format!(+ "data:image/png;base64,{}",+ STANDARD.encode(b"\x89PNG\r\n\x1a\noriginal")+ ),+ mime_type: None,+ })],+ },+ )]);+ for _ in 0..2 {+ let main = Arc::new(Probe::default());+ let wrapper = wrap(main.clone(), config.clone(), "unknown-model", "custom");+ assert!(wrapper.invoke(&(), request.clone()).await.is_err());+ let captured = main.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ assert!(captured[0].messages[0]+ .text()+ .contains("specialist image readout"));+ assert!(!serde_json::to_string(&captured[0])+ .unwrap()+ .contains("base64"));+ }+ assert_eq!(+ specialist.calls.load(std::sync::atomic::Ordering::SeqCst),+ 1+ );+ }++ #[tokio::test]+ async fn legacy_audio_base64_unsupported_transport_becomes_workspace_reference() {+ let temp = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let main = Arc::new(Probe::default());+ let wrapper = wrap(main.clone(), Arc::new(config), "unknown", "custom");+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Audio(MediaRef::Base64 {+ data: STANDARD.encode(b"original-audio"),+ media_type: "audio/wav".into(),+ })],+ },+ )]);+ assert!(wrapper.invoke(&(), request).await.is_err());+ let captured = main.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ let text = captured[0].messages[0].text();+ assert!(text.contains("audio/wav"));+ assert!(text.contains("workspace path: uploads/legacy-media/"));+ assert!(!serde_json::to_string(&captured[0])+ .unwrap()+ .contains("base64"));+ }++ #[tokio::test]+ async fn injected_turn_source_uses_bound_workspace_and_explicit_model_facts() {+ let temp = tempfile::tempdir().unwrap();+ tokio::fs::write(+ temp.path().join("injected.png"),+ b"\x89PNG\r\n\x1a\noriginal",+ )+ .await+ .unwrap();+ let mut config = Config::default();+ config.action_dir = temp.path().into();+ let mut probe = Probe::default();+ probe.profile.provider = Some("injected".into());+ probe.profile.modalities.image_in = true;+ let probe = Arc::new(probe);+ let source = crate::agent::tinyagents::TurnModelSource::from_model(probe.clone())+ .with_attachment_config(Arc::new(config));+ let models = source+ .build("explicit-injected-model", 0.0, None, None)+ .unwrap();+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: "injected.png".into(),+ mime_type: None,+ })],+ },+ )]);+ assert!(models.primary.invoke(&(), request).await.is_err());+ let captured = probe.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ assert!(serde_json::to_string(&captured[0])+ .unwrap()+ .contains("data:image/png;base64,"));+ }++ #[tokio::test]+ async fn configured_injected_builder_stages_and_resolves_in_explicit_acting_workspace() {+ let temp = tempfile::tempdir().unwrap();+ let acting = temp.path().join("override-action");+ let mut config = Config::default();+ config.workspace_dir = temp.path().join("internal");+ config.action_dir = temp.path().join("configured-action");+ config.config_path = temp.path().join("config.toml");+ let mut probe = Probe::default();+ probe.profile.provider = Some("injected".into());+ probe.profile.modalities.image_in = true;+ let probe = Arc::new(probe);+ let agent = crate::agent::SessionHostBuilder::new()+ .chat_model_with_config(probe.clone(), Arc::new(config.clone()))+ .action_dir(acting.clone())+ .tools(Vec::new())- .memory(crate::memory::test_support::noop_memory())+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))+ .build()+ .unwrap();+ let bound = agent.runtime_config().unwrap();+ assert_eq!(bound.action_dir, acting);+ assert_eq!(bound.workspace_dir, config.workspace_dir);+ assert_eq!(bound.config_path, config.config_path);+ let bytes = b"\x89PNG\r\n\x1a\noriginal";+ let staged = super::super::stage_turn(+ &format!("[IMAGE:data:image/png;base64,{}]", STANDARD.encode(bytes)),+ Some(&bound),+ None,+ Some("builder-test"),+ None,+ )+ .await+ .unwrap();+ let (_, attachments) = super::super::parse(&staged);+ assert_eq!(attachments.len(), 1);+ assert_eq!(+ tokio::fs::read(acting.join(&attachments[0].path))+ .await+ .unwrap(),+ bytes+ );+ let models = agent+ .turn_model_source()+ .build("explicit-injected", 0.0, None, None)+ .unwrap();+ let request = ModelRequest::new(vec![Message::User(+ tinyinference_llm::message::UserMessage {+ content: vec![ContentBlock::Image(ImageRef {+ url: attachments[0].path.clone(),+ mime_type: None,+ })],+ },+ )]);+ assert!(models.primary.invoke(&(), request).await.is_err());+ let captured = probe.requests.lock().unwrap().clone();+ assert_eq!(captured.len(), 1);+ assert!(serde_json::to_string(&captured[0])+ .unwrap()+ .contains("data:image/png;base64,"));+ }++ #[test]+ fn bare_injected_builder_does_not_load_operator_config() {+ let agent = crate::agent::SessionHostBuilder::new()+ .chat_model(Arc::new(Probe::default()))+ .tools(Vec::new())- .memory(crate::memory::test_support::noop_memory())+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))+ .build()+ .unwrap();+ assert!(agent.runtime_config().is_none());+ }diff --cc crates/openhuman-core/src/agent/bus.rsindex ed4c46bbff,49e1014419..5e876fae8d--- a/crates/openhuman-core/src/agent/bus.rs+++ b/crates/openhuman-core/src/agent/bus.rs@@@ -288,40 -288,36 +288,42 @@@ async fn handle_agent_run_turn(req: Agechannel_name,target_agent_id.as_deref().unwrap_or("root"));+ // Memory acts as the target agent (the root when none is named) for+ // the whole channel turn.+ let memory_agent = target_agent_id.clone().unwrap_or_default();+ let graph_origin = origin.clone();let outcome = turn_origin::with_origin(origin,- with_file_state_agent_id(- file_state_id,- with_current_sandbox_mode(sandbox_mode, async {- // Channel/CLI turns run through the tinyagents harness- // (issue #4249); the legacy `run_tool_call_loop` is removed.- // `on_progress` mirrors the harness event stream (tool- // timeline, text deltas, cost footer) — production channel- // dispatch always supplies it and now expects it live.- // `on_delta` (raw Sender<String>) is superseded by- // `on_progress` text deltas, so it's intentionally unused.- let _ = (&provider_name, silent, &channel_name, on_delta);- run_channel_turn_via_graph(- turn_model_source.clone(),- &mut history,- tools_registry.clone(),- extra_tools,- visible_tool_names.as_ref(),- &model,- temperature,- max_tool_iterations,- multimodal.clone(),- multimodal_files.clone(),- on_progress,- Some(graph_origin),- )- .await- }),+ crate::memory::scope::within_agent(+ &memory_agent,+ with_file_state_agent_id(+ file_state_id,+ with_current_sandbox_mode(sandbox_mode, async {+ // Channel/CLI turns run through the tinyagents harness+ // (issue #4249); the legacy `run_tool_call_loop` is removed.+ // `on_progress` mirrors the harness event stream (tool+ // timeline, text deltas, cost footer) — production channel+ // dispatch always supplies it and now expects it live.+ // `on_delta` (raw Sender<String>) is superseded by+ // `on_progress` text deltas, so it's intentionally unused.+ let _ = (&provider_name, silent, &channel_name, on_delta);+ run_channel_turn_via_graph(+ turn_model_source.clone(),+ &mut history,+ tools_registry.clone(),+ extra_tools,+ visible_tool_names.as_ref(),+ &model,+ temperature,+ max_tool_iterations,+ multimodal.clone(),+ multimodal_files.clone(),+ on_progress,++ Some(graph_origin),+ )+ .await+ }),+ ),),).awaitdiff --cc crates/openhuman-core/src/agent/session_host/builder/builder_build.rsindex 8fcc96c0fc,fbd57e3caf..12fd5e8ac7--- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs@@@ -318,13 -318,34 +318,30 @@@ impl SessionHostBuilder// Live history reduction moved to the tinyagents graph// (`ContextCompressionMiddleware` + `MessageTrimMiddleware`, issue// #4249), so the session no longer constructs an in-turn summarizer- // here. The archivist hook still drives durable segment recaps on its- // own post-turn path; it is no longer coupled to context compaction.+ // here.let context = ContextManager::new(&context_config, prompt_builder);- let workspace_dir = self- .workspace_dir- .unwrap_or_else(|| std::path::PathBuf::from("."));- let action_dir = self.action_dir.unwrap_or_else(|| workspace_dir.clone());+ let workspace_dir = self.workspace_dir.unwrap_or_else(|| {+ self.runtime_config+ .as_ref()- .map(|c| c.workspace_dir.clone())++ .map(|config| config.workspace_dir.clone())+ .unwrap_or_else(|| std::path::PathBuf::from("."))+ });+ let action_dir = self.action_dir.unwrap_or_else(|| {+ self.runtime_config+ .as_ref()- .map(|c| c.action_dir.clone())++ .map(|config| config.action_dir.clone())+ .unwrap_or_else(|| workspace_dir.clone())+ });+ let runtime_config = self.runtime_config.map(|config| {+ let mut config = (*config).clone();+ config.workspace_dir = workspace_dir.clone();+ config.action_dir = action_dir.clone();+ Arc::new(config)+ });+ if let Some(config) = &runtime_config {+ turn_model_source = turn_model_source.with_attachment_config(config.clone());+ }- let memory = self- .memory- .ok_or_else(|| anyhow::anyhow!("memory is required"))?;// Direct builder callers (notably unit fixtures) do not pass through// `build_session_agent_inner`, which normally creates the durable host@@@ -456,11 -483,16 +473,11 @@@run_queue: None,connected_integrations: Vec::new(),connected_integrations_initialized: false,- runtime_config: None,+ runtime_config,hosted_base,definition: None,- // Default to `true` (omit) so legacy / custom agents built- // without a definition stay lean. Opt-in agents thread their- // `omit_profile = false` through the builder.- omit_profile: self.omit_profile.unwrap_or(true),- omit_memory_md: self.omit_memory_md.unwrap_or(true),+ omit_memory_context: self.omit_memory_context.unwrap_or(false),payload_summarizer: self.payload_summarizer,- trigger_memory_agent: self.trigger_memory_agent.unwrap_or_default(),tokenjuice_compression: self.tokenjuice_compression,tool_policy: self.tool_policydiff --cc crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 3f250ec9dd,6a81738194..8facec2398--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@@ -5,8 -5,12 +5,12 @@@//! prefix reconciliation, tool snapshots, resume and persistence remain inside//! the runtime session.+mod memory_ingest;+mod permanent;+ #[path = "runtime_session_attachment_input.rs"]+ mod attachment_input;-mod permanent;-mod prompt;+ #[path = "runtime_session_turn.rs"]+ mod turn;use std::sync::Arc;diff --cc crates/openhuman-core/src/agent/session_host/runtime_session_turn.rsindex 0000000000,815847b7fd..e10160b71bmode 000000,100644..100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_turn.rs@@@ -1,0 -1,80 +1,82 @@@+ 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++ let agent_id = self.agent_definition_id.clone();++ let turn = self+ .runtime_session+ .as_mut()+ .expect("runtime session initialized")+ .turn(+ SessionTurnRequest::new(user_message_from_text(staged.as_str())),+ options,- )++ );++ let outcome = crate::memory::scope::within_agent(&agent_id, Box::pin(turn))+ .await+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ Ok(outcome.output.unwrap_or_default())+ }+ }diff --cc crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rsindex e7f323fbb6,2d96799764..0908aea1b8--- a/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/typed_transcript_compat_tests.rs@@@ -30,6 -30,70 +30,69 @@@ use super::transcript_compat_tests::/// multi-file and the compaction record is not a plain row list).const TYPED_SCENARIOS: &[&str] = &["plain", "native_tools", "image_user", "xml_tools"];+ /// Native-image transport support for live fixtures, independent of the+ /// selected-model facts supplied to the scripted response model.+ struct LiveImageModel(std::sync::Arc<tinyagents_harness::testkit::ScriptedModel>);++ #[async_trait::async_trait]+ impl tinyinference_llm::model::ChatModel<()> for LiveImageModel {+ fn profile(&self) -> Option<&tinyinference_llm::model::ModelProfile> {+ tinyinference_llm::model::ChatModel::<()>::profile(self.0.as_ref())+ }+ fn supports_input(+ &self,+ modality: tinyinference_llm::model::InputModality,+ mime: &str,+ source: tinyinference_llm::model::InputSource,+ ) -> bool {+ modality == tinyinference_llm::model::InputModality::Image+ && mime == "image/png"+ && source == tinyinference_llm::model::InputSource::Base64+ }+ async fn invoke(+ &self,+ state: &(),+ request: tinyinference_llm::model::ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ tinyinference_llm::model::ChatModel::invoke(self.0.as_ref(), state, request).await+ }+ }++ fn live_image_model(reply: &str) -> std::sync::Arc<LiveImageModel> {+ use tinyinference_llm::model::{Modalities, ModelProfile};+ std::sync::Arc::new(LiveImageModel(std::sync::Arc::new(+ tinyagents_harness::testkit::ScriptedModel::new(vec![ModelResponse::assistant(reply)])+ .with_profile(ModelProfile {+ tool_calling: true,+ modalities: Modalities {+ image_in: true,+ ..Default::default()+ },+ ..Default::default()+ }),+ )))+ }++ fn build_live_image_host(+ root: &std::path::Path,+ model: std::sync::Arc<LiveImageModel>,+ thread: &str,+ ) -> crate::agent::OpenHumanSessionHost {+ let mut config = crate::config::Config::default();+ config.workspace_dir = root.join("workspace");+ config.action_dir = root.to_path_buf();+ config.config_path = root.join("config.toml");+ config.modules.enabled = false;+ let mut host = crate::agent::SessionHostBuilder::new()+ .chat_model_with_config(model, std::sync::Arc::new(config))+ .tools(Vec::new())- .memory(crate::memory::test_support::noop_memory())+ .tool_dispatcher(Box::new(tinytools_agent::dialect::NativeDialect))+ .build()+ .expect("configured image session");+ host.set_thread_id(Some(thread));+ host+ }+fn scenario(name: &str) -> &'static Scenario {SCENARIOS.iter()diff --cc crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rsindex 124ffdb030,bd5fc12bcf..244926d6b5--- 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 +147,82 @@@ async fn canonical_adapter_preserves_sp);}+ 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 --cc crates/openhuman-core/src/core/runtime/context.rsindex deef1c7403,d593968558..4ec83a3d25--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@@ -463,26 -625,19 +467,13 @@@ impl CoreContextSelf::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- /// workspace after boot without rebuilding the core; every call site- /// already holds the target `Config`, so passing the config here keeps the- /// bound driver (and its hooks / trust settings) from silently carrying- /// over from the previous user. Scoped multi-tenant dispatch is unaffected- /// because tenant contexts are passed to [`CoreContext::scope`] explicitly- /// and are not the process default.- pub fn rebind_default_workspace(- workspace_dir: &std::path::Path,- memory_subsystem: crate::config::schema::MemorySubsystemConfig,- ) -> Result<(), String> {+ /// workspace. Desktop login, logout, and pending-session revalidation can+ /// switch the active workspace after boot without rebuilding the core.+ /// Scoped multi-tenant dispatch is unaffected because tenant contexts are+ /// passed to [`CoreContext::scope`] explicitly and are not the process+ /// default.+ pub fn rebind_default_workspace(workspace_dir: &std::path::Path) -> Result<(), String> {let Some(ctx) = DEFAULT_CONTEXT.get() else {log::debug!("[core-context] default context not initialized; skipped workspace rebind to {}",diff --cc scripts/ci/check-dep-sim-calibration.shindex 159dcd24b6,a802a5b6c9..d7f387f484--- a/scripts/ci/check-dep-sim-calibration.sh+++ b/scripts/ci/check-dep-sim-calibration.sh@@@ -88,6 -95,6 +95,6 @@@ set -euo pipefaicd "$(dirname "$0")/../.."- EXPECTED_NAMES=302-EXPECTED_NAMES=318++EXPECTED_NAMES=316exec python3 scripts/dep-sim.py --cut-nothing --expect-names "${EXPECTED_NAMES}"diff --cc scripts/ci/check-openhuman-rust-layout.mjsindex 437036f80d,9bf0e0d005..e8c8bea3ee--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@@ -38,7 -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", 1551],- ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1815],++ ["crates/openhuman-core/src/agent/session_host/runtime_session.rs", 1495],// 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 indiff --cc scripts/kernel-floor.limitsindex 5094056975,b36c660e8a..7c368f598f--- a/scripts/kernel-floor.limits+++ b/scripts/kernel-floor.limits@@@ -13,9 -13,13 +13,16 @@@# Simulate with: scripts/dep-sim.py --cut <crates>## History- # 323/302/2 2026-10-03 The updated TinyAgents and TinyMemory pins resolve- # 323 packages / 302 names / 2 native builds in the- # flows profile. Ratchet to the measured graph.++# 337/316/3 2026-10-04 Merge upstream/main file-intake and module updates.++# The merged flows profile measures 337 packages / 316++# names / 3 native builds (including libdeflate-sys).+ # 339/318/3 2026-10-04 Workspace attachment intake adds lossless PNG+ # optimization through oxipng (11 packages/names, including+ # libdeflate-sys C compilation). The merged TinyBox jail+ # enables Landlock by default (3 packages/names). Removing+ # both closures in the simulator exactly recovers 325/304;+ # this is dependency growth, not a shedding claim. Native+ # accounting now includes libdeflate-sys in both tools.# 325/304/2 2026-10-02 Merge upstream/main at 708f677cca. CI measures the# refreshed flows graph at 325 packages / 304 names / 2# native builds. This release merge adds no Cargo or@@@ -641,4 -645,4 +648,4 @@@# into the required host runtime. The migration adds five# resolved packages and four unique crate names; it does# not add a native build dependency.- flows:323:302:2-flows:339:318:3++flows:337:316:3