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
refactor: carry agent threads explicitly
Steven Enamakele0d8c1928bb8
diff --git a/crates/openhuman-core/src/agent/goals/continuation.rs b/crates/openhuman-core/src/agent/goals/continuation.rsindex eaec06fad0..0cb4d7d29f 100644--- a/crates/openhuman-core/src/agent/goals/continuation.rs+++ b/crates/openhuman-core/src/agent/goals/continuation.rs@@ -29,7 +29,6 @@ use tokio::sync::Semaphore;use super::store;use super::{ThreadGoal, ThreadGoalStatus};-use crate::agent::tinyagents::thread_context::with_thread_id;use crate::agent::turn_origin::{with_origin, AgentTurnOrigin, TrustedAutomationSource};use crate::agent::Agent;use crate::config::Config;@@ -193,14 +192,10 @@ async fn dispatch_continuation(config: &Config, goal: &ThreadGoal) -> bool {source: TrustedAutomationSource::GoalContinuation,};- // Scope the ambient thread id (so the goal tools + per-turn injection target- // this thread) and the trusted-automation origin (so the approval gate parks- // unattended external actions). `run_single` resumes the thread transcript.- let result = with_thread_id(- thread_id.clone(),- with_origin(origin, agent.run_single(&prompt)),- )- .await;+ // The continuation owns its thread directly; child runs inherit it through+ // `OpenHumanRunContext::child`.+ agent.set_thread_id(Some(thread_id.as_str()));+ let result = with_origin(origin, agent.run_single(&prompt)).await;match result {Ok(text) => tracing::info!(diff --git a/crates/openhuman-core/src/agent/goals/runtime.rs b/crates/openhuman-core/src/agent/goals/runtime.rsindex ffd9990e87..a1ccaa3c94 100644--- a/crates/openhuman-core/src/agent/goals/runtime.rs+++ b/crates/openhuman-core/src/agent/goals/runtime.rs@@ -27,14 +27,12 @@ use tinyagents_graph::goals::{BudgetVerdict, GoalBudgetGuard};use super::store::{self, goals_store};use super::{ThreadGoal, ThreadGoalStatus};use crate::agent::stop_hooks::{StopDecision, StopHook, TurnState};-use crate::agent::tinyagents::thread_context::current_thread_id;use crate::core::bus::BUS;use crate::core::events::DomainEvent;-/// Load the goal for the ambient chat thread, if any. Returns `None` outside a-/// thread scope (CLI / background paths) or when the thread has no goal.-pub async fn load_for_current_thread(workspace_dir: &Path) -> Option<ThreadGoal> {- let thread_id = current_thread_id()?;+/// Load the goal for an explicitly supplied chat thread.+pub async fn load_for_thread(workspace_dir: &Path, thread_id: Option<&str>) -> Option<ThreadGoal> {+ let thread_id = normalized_thread(thread_id)?;match store::get(workspace_dir, &thread_id).await {Ok(goal) => goal,Err(e) => {@@ -44,11 +42,13 @@ pub async fn load_for_current_thread(workspace_dir: &Path) -> Option<ThreadGoal>}}-/// Reactivate a paused goal for the ambient thread (thread-resume semantics).-/// Returns the updated goal, or `None` outside a thread scope / when absent.+/// Reactivate a paused goal for an explicit thread (thread-resume semantics)./// Best-effort: a failure is logged and surfaced as `Ok(None)`-style `None`.-pub async fn resume_for_current_thread(workspace_dir: &Path) -> Option<Option<ThreadGoal>> {- let thread_id = current_thread_id()?;+pub async fn resume_for_thread(+ workspace_dir: &Path,+ thread_id: Option<&str>,+) -> Option<Option<ThreadGoal>> {+ let thread_id = normalized_thread(thread_id)?;match store::resume(workspace_dir, &thread_id).await {Ok(goal) => {if goal.status.is_active() {@@ -69,8 +69,8 @@ pub async fn resume_for_current_thread(workspace_dir: &Path) -> Option<Option<Th/// Pause the active goal for the ambient thread (interrupt/abort semantics)./// Best-effort; safe to call when there is no goal or no thread scope.-pub async fn pause_for_current_thread(workspace_dir: &Path) {- let Some(thread_id) = current_thread_id() else {+pub async fn pause_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {+ let Some(thread_id) = normalized_thread(thread_id) else {return;};match store::pause(workspace_dir, &thread_id).await {@@ -98,8 +98,8 @@ pub async fn pause_for_current_thread(workspace_dir: &Path) {/// re-injected as an `[active_goal]` block on every later turn — including/// unrelated chat (#1725). A caller that owns a task's lifecycle calls this/// when the task reaches a terminal, satisfied state so the goal can't linger.-pub async fn complete_for_current_thread(workspace_dir: &Path) {- let Some(thread_id) = current_thread_id() else {+pub async fn complete_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {+ let Some(thread_id) = normalized_thread(thread_id) else {return;};match store::complete(workspace_dir, &thread_id).await {@@ -125,8 +125,8 @@ pub async fn complete_for_current_thread(workspace_dir: &Path) {/// Clearing removes the row rather than moving it to a terminal status, so a/// later turn loads `None` and injects no `[active_goal]` block at all — the/// strongest guarantee that a stale objective cannot leak forward (#1725).-pub async fn clear_for_current_thread(workspace_dir: &Path) {- let Some(thread_id) = current_thread_id() else {+pub async fn clear_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {+ let Some(thread_id) = normalized_thread(thread_id) else {return;};match store::clear(workspace_dir, &thread_id).await {@@ -171,8 +171,14 @@ fn is_goal_continuation_turn() -> bool {/// emitting `ThreadGoalUpdated` when the status changes (e.g. →/// `budget_limited`) so the UI chip refreshes. Best-effort throughout: a/// failure is logged and swallowed so accounting never fails a user turn.-pub async fn account_turn_against_goal(workspace_dir: &Path, input: u64, output: u64, secs: u64) {- let Some(thread_id) = current_thread_id() else {+pub async fn account_turn_against_goal(+ workspace_dir: &Path,+ thread_id: Option<&str>,+ input: u64,+ output: u64,+ secs: u64,+) {+ let Some(thread_id) = normalized_thread(thread_id) else {return;};let prev_status = match store::get(workspace_dir, &thread_id).await {@@ -212,6 +218,13 @@ pub async fn account_turn_against_goal(workspace_dir: &Path, input: u64, output:}}+fn normalized_thread(thread_id: Option<&str>) -> Option<String> {+ thread_id+ .map(str::trim)+ .filter(|thread_id| !thread_id.is_empty())+ .map(ToOwned::to_owned)+}+/// Mid-turn stop hook that halts an in-flight turn once an **active** goal's/// running usage (already-accounted tokens from prior turns + this turn's/// tokens so far) would meet or exceed its budget.diff --git a/crates/openhuman-core/src/agent/goals/runtime_tests.rs b/crates/openhuman-core/src/agent/goals/runtime_tests.rsindex 0d5eaf59f8..47419a8325 100644--- a/crates/openhuman-core/src/agent/goals/runtime_tests.rs+++ b/crates/openhuman-core/src/agent/goals/runtime_tests.rs@@ -19,75 +19,63 @@ fn cost_with_tokens(input: u64, output: u64) -> TurnCost {async fn account_turn_charges_active_goal_and_trips_budget() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-acct", async {- store::set(&dir, "t-acct", "obj", Some(100)).await.unwrap();- account_turn_against_goal(&dir, 80, 40, 3).await; // 120 >= 100- let g = store::get(&dir, "t-acct").await.unwrap().unwrap();- assert_eq!(g.tokens_used, 120);- assert_eq!(g.status, ThreadGoalStatus::BudgetLimited);- })- .await;+ store::set(&dir, "t-acct", "obj", Some(100)).await.unwrap();+ account_turn_against_goal(&dir, Some("t-acct"), 80, 40, 3).await; // 120 >= 100+ let g = store::get(&dir, "t-acct").await.unwrap().unwrap();+ assert_eq!(g.tokens_used, 120);+ assert_eq!(g.status, ThreadGoalStatus::BudgetLimited);}#[tokio::test]async fn account_turn_skips_non_active_goal() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-paused", async {- store::set(&dir, "t-paused", "obj", Some(1000))- .await- .unwrap();- store::pause(&dir, "t-paused").await.unwrap();- account_turn_against_goal(&dir, 500, 500, 1).await;- let g = store::get(&dir, "t-paused").await.unwrap().unwrap();- assert_eq!(g.tokens_used, 0, "paused goal must not accrue usage");- })- .await;+ store::set(&dir, "t-paused", "obj", Some(1000))+ .await+ .unwrap();+ store::pause(&dir, "t-paused").await.unwrap();+ account_turn_against_goal(&dir, Some("t-paused"), 500, 500, 1).await;+ let g = store::get(&dir, "t-paused").await.unwrap().unwrap();+ assert_eq!(g.tokens_used, 0, "paused goal must not accrue usage");}#[tokio::test]-async fn complete_for_current_thread_settles_active_goal() {+async fn complete_for_thread_settles_active_goal() {// A goal an originating task left behind is settled to `Complete` so a// later turn stops re-injecting its `[active_goal]` block (#1725).let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-complete", async {- store::set(&dir, "t-complete", "obj", Some(1000))- .await- .unwrap();- complete_for_current_thread(&dir).await;- let g = store::get(&dir, "t-complete").await.unwrap().unwrap();- assert_eq!(- g.status,- ThreadGoalStatus::Complete,- "an originating task's settle must mark the goal Complete, not leave it Active"- );- assert!(- !g.status.is_active(),- "a completed goal must not stay active (it would keep steering unrelated turns)"- );- })- .await;+ store::set(&dir, "t-complete", "obj", Some(1000))+ .await+ .unwrap();+ complete_for_thread(&dir, Some("t-complete")).await;+ let g = store::get(&dir, "t-complete").await.unwrap().unwrap();+ assert_eq!(+ g.status,+ ThreadGoalStatus::Complete,+ "an originating task's settle must mark the goal Complete, not leave it Active"+ );+ assert!(+ !g.status.is_active(),+ "a completed goal must not stay active (it would keep steering unrelated turns)"+ );}#[tokio::test]-async fn clear_for_current_thread_removes_the_goal_row() {+async fn clear_for_thread_removes_the_goal_row() {// Clearing deletes the row entirely, so a later turn loads `None` and// injects no goal block at all — the strongest anti-leak guarantee.let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-clear", async {- store::set(&dir, "t-clear", "obj", Some(1000))- .await- .unwrap();- clear_for_current_thread(&dir).await;- let g = store::get(&dir, "t-clear").await.unwrap();- assert!(- g.is_none(),- "clearing must delete the goal row so no [active_goal] can leak forward"- );- })- .await;+ store::set(&dir, "t-clear", "obj", Some(1000))+ .await+ .unwrap();+ clear_for_thread(&dir, Some("t-clear")).await;+ let g = store::get(&dir, "t-clear").await.unwrap();+ assert!(+ g.is_none(),+ "clearing must delete the goal row so no [active_goal] can leak forward"+ );}#[tokio::test]@@ -96,38 +84,32 @@ async fn complete_and_clear_are_safe_without_a_goal_or_thread() {// goal for the thread, and when called outside any thread scope.let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-empty", async {- complete_for_current_thread(&dir).await;- clear_for_current_thread(&dir).await;- assert!(store::get(&dir, "t-empty").await.unwrap().is_none());- })- .await;+ complete_for_thread(&dir, Some("t-empty")).await;+ clear_for_thread(&dir, Some("t-empty")).await;+ assert!(store::get(&dir, "t-empty").await.unwrap().is_none());// No ambient thread scope at all.- complete_for_current_thread(&dir).await;- clear_for_current_thread(&dir).await;+ complete_for_thread(&dir, None).await;+ clear_for_thread(&dir, None).await;}#[tokio::test]async fn account_turn_clears_suppression_without_losing_usage() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- crate::agent::tinyagents::thread_context::with_thread_id("t-suppressed", async {- let goal = store::set(&dir, "t-suppressed", "obj", Some(1000))- .await- .unwrap();- store::set_continuation_suppressed_if(&dir, "t-suppressed", &goal.goal_id, true)- .await- .unwrap();+ let goal = store::set(&dir, "t-suppressed", "obj", Some(1000))+ .await+ .unwrap();+ store::set_continuation_suppressed_if(&dir, "t-suppressed", &goal.goal_id, true)+ .await+ .unwrap();- account_turn_against_goal(&dir, 80, 40, 3).await;+ account_turn_against_goal(&dir, Some("t-suppressed"), 80, 40, 3).await;- let updated = store::get(&dir, "t-suppressed").await.unwrap().unwrap();- assert_eq!(updated.goal_id, goal.goal_id);- assert!(!updated.continuation_suppressed);- assert_eq!(updated.tokens_used, 120);- assert_eq!(updated.time_used_seconds, 3);- })- .await;+ let updated = store::get(&dir, "t-suppressed").await.unwrap().unwrap();+ assert_eq!(updated.goal_id, goal.goal_id);+ assert!(!updated.continuation_suppressed);+ assert_eq!(updated.tokens_used, 120);+ assert_eq!(updated.time_used_seconds, 3);}#[tokio::test]diff --git a/crates/openhuman-core/src/agent/harness/graph.rs b/crates/openhuman-core/src/agent/harness/graph.rsindex c7b08ce0d0..cb3eb3fe2c 100644--- a/crates/openhuman-core/src/agent/harness/graph.rs+++ b/crates/openhuman-core/src/agent/harness/graph.rs@@ -80,7 +80,7 @@ pub(crate) async fn run_channel_turn_via_graph(// Phase 3 / Motion A): the harness graph names crate model types only, and// reads native-tool / vision capability + telemetry id off the built bundle.let context_window = source.effective_context_window(model).await;- let turn_models = source.build(model, temperature, context_window)?;+ let turn_models = source.build(model, temperature, context_window, None)?;// Native-tool support drives the durable history-suffix dispatcher (native// envelope vs prompt-guided text) at the end of this turn; capture it before@@ -115,8 +115,7 @@ pub(crate) async fn run_channel_turn_via_graph(context_window,"[channel:graph] routing channel turn through tinyagents harness");- let mut run_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();// The channel dispatcher owns this explicit sink. It wins over an embedder// scope exactly as it did before this carrier was introduced.run_context.progress = on_progress.clone().or(run_context.progress);diff --git a/crates/openhuman-core/src/agent/harness/memory_context.rs b/crates/openhuman-core/src/agent/harness/memory_context.rsindex 8bc748b6d8..e5b714f856 100644--- a/crates/openhuman-core/src/agent/harness/memory_context.rs+++ b/crates/openhuman-core/src/agent/harness/memory_context.rs@@ -38,6 +38,17 @@ pub(crate) async fn build_context(mem: &dyn Memory,user_msg: &str,min_relevance_score: f64,+) -> String {+ build_context_for_thread(mem, user_msg, min_relevance_score, None).await+}++/// Build context while explicitly excluding the current conversation from+/// cross-session recall. Root/session callers pass their owned thread id.+pub(crate) async fn build_context_for_thread(+ mem: &dyn Memory,+ user_msg: &str,+ min_relevance_score: f64,+ thread_id: Option<&str>,) -> String {let mut context = String::new();let mut seen_keys = HashSet::new();@@ -119,9 +130,12 @@ pub(crate) async fn build_context(// enforced at the SQLite layer (one DB per workspace == one user);// the current chat is excluded by passing `session_id` so the block// never duplicates the same-chat history.- let current_thread_id = crate::agent::tinyagents::thread_context::current_thread_id();+ let thread_id = thread_id+ .map(str::trim)+ .filter(|thread_id| !thread_id.is_empty())+ .map(ToOwned::to_owned);let cross_session_opts = crate::memory::RecallOpts {- session_id: current_thread_id.as_deref(),+ session_id: thread_id.as_deref(),cross_session: true,min_score: Some(min_relevance_score),..Default::default()@@ -149,7 +163,7 @@ pub(crate) async fn build_context("[memory-context] cross-chat recall returned {} entries, {} after filtering (exclude={:?})",entries.len(),cross.len(),- current_thread_id+ thread_id);if !cross.is_empty() {diff --git a/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs b/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rsindex fa84621b11..1713f80384 100644--- a/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs+++ b/crates/openhuman-core/src/agent/harness/session/builder/builder_build.rs@@ -284,6 +284,7 @@ impl AgentBuilder {explicit_preferences_enabled: self.explicit_preferences_enabled,event_session_id,event_channel,+ thread_id: None,agent_definition_name: agent_definition_name.clone(),// Canonical registry id — captured here at build time// before any caller can call `set_agent_definition_name`diff --git a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rsindex 53c1947c5e..20ae14a000 100644--- a/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs+++ b/crates/openhuman-core/src/agent/harness/session/runtime/accessors.rs@@ -306,6 +306,19 @@ impl Agent {self.rebuild_tool_policy_session();}+ /// Bind the OpenHuman conversation thread for the next and subsequent+ /// turns. Empty input intentionally clears the binding.+ pub fn set_thread_id(&mut self, thread_id: Option<impl AsRef<str>>) {+ self.thread_id = thread_id.and_then(|thread_id| {+ let thread_id = thread_id.as_ref().trim();+ (!thread_id.is_empty()).then(|| thread_id.to_owned())+ });+ }++ pub(crate) fn thread_id(&self) -> Option<&str> {+ self.thread_id.as_deref()+ }+/// Override the agent definition name used for session transcript/// file paths. Callers (e.g. the web channel) use this to scope/// transcripts per thread so each conversation thread gets its owndiff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rsindex 46a28705ce..24f4480abd 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs@@ -81,9 +81,12 @@ impl Agent {.turn_model_source.effective_context_window(effective_model).await;- let turn_models =- self.turn_model_source- .build(effective_model, temperature, context_window)?;+ let turn_models = self.turn_model_source.build(+ effective_model,+ temperature,+ context_window,+ self.thread_id(),+ )?;// Honor custom/BYOK vision models too: they can set `model_vision` even// when the provider capability bit is false, and must still rehydrate@@ -206,6 +209,7 @@ impl Agent {.resolved_definition().map(|definition| definition.sandbox_mode).unwrap_or(crate::agent::harness::definition::SandboxMode::None),+ thread_id: self.thread_id.clone(),}),),);@@ -525,6 +529,7 @@ impl Agent {// — a no-op when there is no active goal for the ambient thread.crate::agent::goals::runtime::account_turn_against_goal(&self.workspace_dir,+ self.thread_id(),input_tokens,output_tokens,turn_started.elapsed().as_secs(),diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rsindex 1850d51d15..78fe1fc275 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/core_turn.rs@@ -275,17 +275,14 @@ impl Agent {let user_msg = user_message.to_string();let autosave_key = format!("user_msg:{}", uuid::Uuid::new_v4());let chars = user_msg.chars().count();- // Captured *before* `tokio::spawn` — the ambient thread id is a- // `tokio::task_local` (see `tinyagents::thread_context`)- // and does not propagate into a spawned task, so it must be read- // on this (still-scoped) task and moved in explicitly. Tagging+ // Captured before `tokio::spawn` from this owned session carrier.+ // Tagging// this document with the live chat thread id is what lets the// same-session exclusion filter (`UnifiedMemory::recall` /// `memory_hybrid_search`) recognize and drop it later this same// turn, so the agent's own on-demand memory search doesn't echo// its own triggering request back as a "relevant" result.- let session_id_for_autosave =- crate::agent::tinyagents::thread_context::current_thread_id();+ let session_id_for_autosave = self.thread_id.clone();log::debug!("[agent_autosave] enqueue user-message store key={autosave_key} chars={chars} \session_id={}",@@ -395,8 +392,8 @@ impl Agent {);None} else {- let loaded = crate::agent::goals::runtime::load_for_current_thread(- &self.workspace_dir,+ let loaded = crate::agent::goals::runtime::load_for_thread(+ &self.workspace_dir, self.thread_id(),).await;// Thread-resume semantics: the user re-engaging a thread reactivates a@@ -409,8 +406,8 @@ impl Agent {crate::agent::goals::ThreadGoalStatus::Paused) =>{- crate::agent::goals::runtime::resume_for_current_thread(- &self.workspace_dir,+ crate::agent::goals::runtime::resume_for_thread(+ &self.workspace_dir, self.thread_id(),).await.unwrap_or(Some(goal))diff --git a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs b/crates/openhuman-core/src/agent/harness/session/turn/graph.rsindex 41e0a3c435..1b71160c10 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/graph.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/graph.rs@@ -90,6 +90,8 @@ pub(crate) struct ChatTurnGraph {/// Declared sandbox mode for the top-level agent. The chat path scopes it/// around the shared harness so acting tools see the same mode as workers.pub sandbox_mode: SandboxMode,+ /// Explicit backend/persistence thread for this root turn.+ pub thread_id: Option<String>,}/// Drive the chat turn graph: a thin wrapper over the shared tinyagents seam@@ -112,11 +114,11 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen// on the bundle.let provider_id = graph.turn_models.provider_id().to_string();with_current_sandbox_mode(graph.sandbox_mode, async {- let mut run_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();run_context.progress = graph.on_progress.clone().or(run_context.progress);run_context.workspace = graph.workspace_descriptor.clone().or(run_context.workspace);run_context.sandbox_mode = Some(graph.sandbox_mode);+ run_context.thread_id = graph.thread_id;run_turn_via_tinyagents_shared(run_context,graph.turn_models,diff --git a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rsindex eb6417a945..dc52316e3d 100644--- a/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs+++ b/crates/openhuman-core/src/agent/harness/session/turn/session_io/transcript_persist.rs@@ -53,7 +53,7 @@ impl Agent {output_tokens,cached_input_tokens,charged_amount_usd,- thread_id: crate::agent::tinyagents::thread_context::current_thread_id(),+ thread_id: self.thread_id.clone(),task_id: None,};diff --git a/crates/openhuman-core/src/agent/harness/session/types.rs b/crates/openhuman-core/src/agent/harness/session/types.rsindex 2be7cb0eb0..5826c563f6 100644--- a/crates/openhuman-core/src/agent/harness/session/types.rs+++ b/crates/openhuman-core/src/agent/harness/session/types.rs@@ -226,6 +226,10 @@ pub struct Agent {pub(super) explicit_preferences_enabled: bool,pub(super) event_session_id: String,pub(super) event_channel: String,+ /// Backend/session thread explicitly owned by this agent run. It is kept+ /// separate from event identity: CLI and worker event sessions are not+ /// necessarily user conversation threads.+ pub(super) thread_id: Option<String>,/// Human-readable agent definition name (e.g. `"main"`,/// `"code_executor"`). Used as the `{agent}` component in session/// transcript paths: `sessions/DDMMYYYY/{agent}_{index}.md`.diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rsindex 1c23801ef6..09d5778108 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs@@ -217,7 +217,12 @@ pub(in super::super) async fn run_subagent_via_graph(// Build the child turn's crate `ChatModel` set from the source; capability// reads (vision/native-tools) + telemetry id now come off the built bundle,// so the sub-agent path names crate model types only.- let turn_models = source.build(model, temperature, context_window)?;+ let turn_models = source.build(+ model,+ temperature,+ context_window,+ run_context.thread_id.as_deref(),+ )?;// Vision forwarding (parity with the legacy `run_inner_loop`): rehydrate// `[IMAGE:…]` placeholders in the sub-agent's history when either the modeldiff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsindex a4f918db28..69d32d0a81 100644--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs@@ -53,8 +53,7 @@ pub(crate) async fn run_subagent_delegation(// This legacy/direct entrypoint is a genuine root boundary. Live harness// tools call `run_subagent_delegation_with_parent_context` below with the// owned parent carrier instead.- let mut run_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();run_context.parent = current_parent();run_subagent_delegation_with_parent_context(config,diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rsindex 0ce1b90a90..3c6fd957a4 100644--- a/crates/openhuman-core/src/agent/orchestration/ops.rs+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs@@ -365,8 +365,7 @@ impl AgentOrchestrationSession {// only its route/usage observations are isolated by `child()` in the// subagent runner.let cancellation = CancellationToken::new();- let mut run_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();run_context.parent = Some(parent.clone());run_context.progress = parent.on_progress.clone().or(run_context.progress);run_context.workspace = parent_workspace_descriptordiff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rsindex e844f4f4fe..f75ae8e9ef 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs@@ -155,12 +155,16 @@ impl Tool for ArchetypeDelegationTool {_options: ToolCallOptions,tool_context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ run_context.thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(ToOwned::to_owned);execute_archetype_delegation(&self.agent_id.0,&self.tool_name,args,tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),+ run_context,).await}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rsindex 27f23ba99a..91aaddd9d7 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs@@ -21,14 +21,9 @@ async fn rejects_session_from_different_parent_thread() {let session = seed_session(&store, "thread-b");let res = with_parent_context(parent_context(workspace.path()), async {- crate::agent::tinyagents::thread_context::with_thread_id("thread-a", async {- CloseSubagentTool::new()- .execute(json!({- "subagent_session_id": session.subagent_session_id,- }))- .await- })- .await+ CloseSubagentTool::new()+ .execute(json!({ "subagent_session_id": session.subagent_session_id }))+ .await}).await.unwrap();@@ -49,14 +44,9 @@ async fn closes_session_owned_by_current_parent_thread() {let session = seed_session(&store, "thread-a");let res = with_parent_context(parent_context(workspace.path()), async {- crate::agent::tinyagents::thread_context::with_thread_id("thread-a", async {- CloseSubagentTool::new()- .execute(json!({- "subagent_session_id": session.subagent_session_id,- }))- .await- })- .await+ CloseSubagentTool::new()+ .execute(json!({ "subagent_session_id": session.subagent_session_id }))+ .await}).await.unwrap();diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rsindex 491055d53c..bebb139eb9 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs@@ -252,13 +252,11 @@ impl Tool for CollapsedDelegationTool {_options: ToolCallOptions,tool_context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {- execute_collapsed_delegation(- &self.targets,- args,- tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),- )- .await+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ run_context.thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(ToOwned::to_owned);+ execute_collapsed_delegation(&self.targets, args, tool_context, run_context).await}}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rsindex ed16b48526..6686e1d7eb 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs@@ -147,12 +147,12 @@ impl Tool for DelegateGraphTool {_options: ToolCallOptions,tool_context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {- self.execute_with_parent_context(- args,- tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),- )- .await+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ run_context.thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(ToOwned::to_owned);+ self.execute_with_parent_context(args, tool_context, run_context)+ .await}}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rsindex f4c0144e87..108bebc23f 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs@@ -202,12 +202,16 @@ impl Tool for SkillDelegationTool {_options: ToolCallOptions,tool_context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ run_context.thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(ToOwned::to_owned);execute_skill_delegation(&self.tool_name,&self.connected_toolkits,args,tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),+ run_context,).await}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rsindex e5426f24b6..0d5b5c93b2 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_execute.rs@@ -111,7 +111,7 @@ impl SpawnAsyncSubagentTool {// Async delivery is thread-addressed: the finished result is inserted// back into the parent chat thread as a follow-up turn// (`background_delivery`). Outside a chat turn (flow `agent` nodes,- // CLI, cron) there is no `current_thread_id()` to deliver into, so+ // CLI and cron runs intentionally have no parent thread to deliver into, so// `background_delivery::deliver_batch` logs "dropping headless batch"// and the (possibly real, completed) work is silently discarded — the// caller sees "Accepted" and never learns the result never arrived.diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rsindex 309c00f522..3a0728e42d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs@@ -261,7 +261,7 @@ async fn missing_prompt_returns_error() {/// `background_delivery`'s "headless batch" path. Sets up a real parent/// turn context (so the call gets past the `current_parent()` //// allowlist / registry checks) but deliberately does NOT wrap the call-/// in `with_thread_id`, so `current_thread_id()` is None — the exact+/// without an explicit parent thread, so the child has no thread — the exact/// condition that used to sail through to `tokio::spawn` and lose the/// result.#[tokio::test]diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread_tests.rsindex 697a97f4eb..8871e207a9 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread_tests.rs@@ -105,25 +105,22 @@ async fn rejects_if_already_worker_thread() {).unwrap();- crate::agent::tinyagents::thread_context::with_thread_id(thread_id.to_string(), async {- let parent = test_parent_ctx(temp.path().to_path_buf());- with_parent_context(parent, async {- let tool = SpawnWorkerThreadTool::new();- let result = tool- .execute(json!({- "agent_id": "researcher",- "prompt": "do it",- "task_title": "Task"- }))- .await- .unwrap();+ let parent = test_parent_ctx(temp.path().to_path_buf());+ with_parent_context(parent, async {+ let tool = SpawnWorkerThreadTool::new();+ let result = tool+ .execute(json!({+ "agent_id": "researcher",+ "prompt": "do it",+ "task_title": "Task"+ }))+ .await+ .unwrap();- assert!(result.is_error);- assert!(result- .output()- .contains("cannot spawn other worker threads"));- })- .await;+ assert!(result.is_error);+ assert!(result+ .output()+ .contains("cannot spawn other worker threads"));}).await;}@@ -145,25 +142,22 @@ async fn rejects_if_has_parent_thread_id() {).unwrap();- crate::agent::tinyagents::thread_context::with_thread_id(thread_id.to_string(), async {- let parent = test_parent_ctx(temp.path().to_path_buf());- with_parent_context(parent, async {- let tool = SpawnWorkerThreadTool::new();- let result = tool- .execute(json!({- "agent_id": "researcher",- "prompt": "do it",- "task_title": "Task"- }))- .await- .unwrap();+ let parent = test_parent_ctx(temp.path().to_path_buf());+ with_parent_context(parent, async {+ let tool = SpawnWorkerThreadTool::new();+ let result = tool+ .execute(json!({+ "agent_id": "researcher",+ "prompt": "do it",+ "task_title": "Task"+ }))+ .await+ .unwrap();- assert!(result.is_error);- assert!(result- .output()- .contains("cannot spawn other worker threads"));- })- .await;+ assert!(result.is_error);+ assert!(result+ .output()+ .contains("cannot spawn other worker threads"));}).await;}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rsindex f93545f5b6..432d309165 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs@@ -120,13 +120,10 @@ async fn archetype_delegation_defaults_to_async_with_durable_session_e2e() {let mut ctx = parent_context(workspace.path(), provider.clone(), vec![]);ctx.session_id = "tools-e2e-async-session".into();let result = with_parent_context(ctx, async {- crate::agent::tinyagents::thread_context::with_thread_id("thread-async-parent", async {- tool.execute(json!({- "prompt": format!("Research {ARCHETYPE_DELEGATION_CANARY} in the background"),- "model": "test-model"- }))- .await- })+ tool.execute(json!({+ "prompt": format!("Research {ARCHETYPE_DELEGATION_CANARY} in the background"),+ "model": "test-model"+ })).await}).await@@ -252,16 +249,13 @@ async fn continue_subagent_resumes_idle_durable_session_e2e() {ctx.session_id = "tools-e2e-continue-session".into();let session_id = session.subagent_session_id.clone();let result = with_parent_context(ctx, async {- crate::agent::tinyagents::thread_context::with_thread_id("thread-continue-parent", async {- ContinueSubagentTool::new()- .execute(json!({- "task_id": session_id,- "agent_id": "researcher",- "message": "looks good — proceed with continue-durable-canary"- }))- .await- })- .await+ ContinueSubagentTool::new()+ .execute(json!({+ "task_id": session_id,+ "agent_id": "researcher",+ "message": "looks good — proceed with continue-durable-canary"+ }))+ .await}).await.expect("tool execution");diff --git a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs b/crates/openhuman-core/src/agent/task_dispatcher/executor.rsindex 53db960827..609c17cc4d 100644--- a/crates/openhuman-core/src/agent/task_dispatcher/executor.rs+++ b/crates/openhuman-core/src/agent/task_dispatcher/executor.rs@@ -222,6 +222,7 @@ pub(super) async fn run_autonomous(.profile.as_ref().and_then(|p| p.memory_sources.clone());+ agent.set_thread_id(session_thread_id.as_deref());let run = crate::memory::source_scope::with_source_scope(memory_scope,crate::agent::turn_origin::with_origin(@@ -229,14 +230,7 @@ pub(super) async fn run_autonomous(with_autonomous_iter_cap(TASK_RUN_MAX_ITERATIONS, agent.run_single(prompt)),),);- let result = match session_thread_id.as_deref() {- Some(thread_id) => {- crate::agent::tinyagents::thread_context::with_thread_id(thread_id.to_string(), run)- .await- }- None => run.await,- }- .map_err(|e| format!("{e:#}"));+ let result = run.await.map_err(|e| format!("{e:#}"));// Close the run in its thread. Order matters (#5933): persist the closing// message FIRST, announce the terminal event SECOND. A client viewing thediff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.mdindex 237979b3fb..44f840f68c 100644--- a/crates/openhuman-core/src/agent/tinyagents/README.md+++ b/crates/openhuman-core/src/agent/tinyagents/README.md@@ -47,7 +47,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../| `summarize.rs` | `ModelSummarizer` / `FaultTolerantCachingSummarizer` plus a context-window-aware `SummarizationPolicy` driving the crate's `ContextCompressionMiddleware`. || `embeddings.rs` | `ProviderEmbeddingModel`: adapts `crate::inference::embedding_host::EmbeddingProvider` onto the crate's `EmbeddingModel` trait. || `retriever.rs` | `recall_through_facade` / `build_retriever`: wraps `Memory::recall`, projects onto the crate's `ScoredDoc`, applies the `path_scope` dedupe rule, emits `MemoryLoaded`. |-| `thread_context.rs` | Task-local ambient `thread_id` (`with_thread_id`, `current_thread_id`) read by the OpenAI-compatible provider when serialising request bodies. |+| `host/run_context.rs` | Explicit run-owned `thread_id` inherited by children and supplied to managed backend construction. || `todos.rs` | `todos_store` / `scratch_todos_store` (the crate `Store` behind per-thread agent todos, `tinyagents_graph::todos`). || `config.rs` | Maps OpenHuman's `Config` (including model pins) onto `tinyagents_harness::config` structs. || `*_tests.rs` | Sibling test suites for each file/part group above. |@@ -59,7 +59,7 @@ Most of the module is `pub(crate)` or private. The `pub` items, per `mod.rs`:- `config::*`: the host half of the generic-harness config seam.- `payload_summarizer::*`: `pub` since issue #6014 so an embedder can pass its own `Arc<dyn PayloadSummarizer>` to `AgentBuilder::payload_summarizer` (the default dispatches a sub-agent, which some embedders cannot do).- `routes::ResolvedRouteMiddleware`: records canonical response metadata in the explicit run context; `TinyagentsTurnOutcome` carries it to the bus.-- `thread_context::*`, `todos::*`, `host::*` (all ten `OpenHuman*` adapter structs), and `TurnModelSource`.+- `todos::*`, `host::*` (all ten `OpenHuman*` adapter structs), and `TurnModelSource`.Within the crate the entry point is `run_turn_via_tinyagents_shared` (`pub(crate)`); `run_turn_via_tinyagents` is `#[cfg(test)]` only.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex 94bd506f49..b62b0addbc 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -80,25 +80,6 @@ impl Default for OpenHumanRunContext {}impl OpenHumanRunContext {- /// Snapshot the values already scoped by a live legacy entrypoint.- ///- /// This is the transition boundary: roots construct one owned carrier from- /// their current scopes, then recursive paths pass [`Self::child`] instead- /// of depending on task-local inheritance. Explicit root inputs overwrite- /// these snapshots only when they intentionally own the same value.- pub(crate) fn from_current_scopes() -> Self {- let mut context = Self::new();- context.origin = crate::agent::turn_origin::current();- context.progress = crate::agent::progress_sink::current_progress_sink();- context.stop_hooks = crate::agent::stop_hooks::current_stop_hooks();- context.dispatch = crate::agent::harness::turn_dispatch_guard::current();- context.thread_id = crate::agent::tinyagents::thread_context::current_thread_id();- context.workspace = crate::agent::turn_workspace::current()- .filter(|root| root.is_dir())- .map(|root| tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"));- context- }-/// Builds an unbound context. Entry points set only the values their turn/// actually owns; `None` is an explicit absence, not an ambient fallback.pub fn new() -> Self {diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsindex ecf97b7a2b..6cf7f05b8a 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -49,59 +49,9 @@ fn child_inherits_tree_handles_but_isolates_observations_and_usage() {assert!(child.cancellation.is_cancelled());}-#[tokio::test]-async fn snapshots_scoped_stop_hooks_into_the_explicit_carrier() {- let hooks: Vec<std::sync::Arc<dyn crate::agent::stop_hooks::StopHook>> =- vec![std::sync::Arc::new(- crate::agent::stop_hooks::MaxIterationsStopHook::new(3),- )];-- crate::agent::stop_hooks::with_stop_hooks(hooks, async {- let captured = OpenHumanRunContext::from_current_scopes();- assert_eq!(captured.stop_hooks.len(), 1);- assert_eq!(captured.stop_hooks[0].name(), "max_iterations");- })- .await;-}--#[tokio::test]-async fn snapshots_live_root_scopes_before_child_dispatch() {- let root = tempfile::tempdir().expect("workspace");- let (progress, _rx) = tokio::sync::mpsc::channel(1);-- crate::agent::turn_origin::with_origin(- crate::agent::turn_origin::AgentTurnOrigin::Cli,- crate::agent::turn_workspace::with_workspace(- root.path().to_path_buf(),- crate::agent::progress_sink::with_progress_sink(- progress.clone(),- crate::agent::tinyagents::thread_context::with_thread_id(- "thread-a",- crate::agent::harness::turn_dispatch_guard::with_dispatch_guard(None, async {- let expected_dispatch =- crate::agent::harness::turn_dispatch_guard::current()- .expect("dispatch scope");- let captured = OpenHumanRunContext::from_current_scopes();- assert!(matches!(- captured.origin,- Some(crate::agent::turn_origin::AgentTurnOrigin::Cli)- ));- assert!(captured.progress.is_some());- assert_eq!(captured.thread_id.as_deref(), Some("thread-a"));- assert_eq!(captured.workspace.expect("workspace").root, root.path());- assert!(std::sync::Arc::ptr_eq(- captured.dispatch.as_ref().expect("dispatch"),- &expected_dispatch,- ));- assert!(captured- .resolved_route- .lock()- .expect("route lock")- .is_none());- }),- ),- ),- ),- )- .await;+#[test]+fn root_context_is_owned_and_children_inherit_thread() {+ let mut root = OpenHumanRunContext::new();+ root.thread_id = Some("thread-a".to_owned());+ assert_eq!(root.child().thread_id.as_deref(), Some("thread-a"));}diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex 999829b0bb..df1ea03e36 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -52,7 +52,6 @@ mod routes;mod steering_forwarder;pub(crate) mod stop_hooks;mod summarize;-pub mod thread_context;pub mod todos;pub(crate) mod tools;mod topology;diff --git a/crates/openhuman-core/src/agent/tinyagents/thread_context.rs b/crates/openhuman-core/src/agent/tinyagents/thread_context.rsdeleted file mode 100644index 18fb57e414..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/thread_context.rs+++ /dev/null@@ -1,96 +0,0 @@-//! Ambient chat-thread id for the current async scope.-//!-//! The web channel keys runtime sessions by `(client_id, thread_id)` and the-//! backend's `/openai/v1/chat/completions` endpoint accepts an optional-//! `thread_id` field so it can group inference logs and align KV-cache keys-//! with the same logical chat the user sees on screen.-//!-//! Threading the identifier through every layer (`Agent` → tool loop →-//! sub-agent runner → `Provider` impl) would touch dozens of call sites and-//! tests. Instead the channel sets a [`tokio::task_local`] before invoking the-//! agent loop, and the OpenAI-compatible provider reads it when serialising the-//! request body. Other call paths see `None` and omit the field — backward-//! compatible with backends that do not accept it.-//!-//! ```ignore-//! use crate::agent::tinyagents::thread_context::{current_thread_id, with_thread_id};-//!-//! with_thread_id("abc123", async {-//! // any provider.chat() call inside this future sees thread_id=Some("abc123")-//! assert_eq!(current_thread_id().as_deref(), Some("abc123"));-//! }).await;-//! ```-//!-//! # Why the definition is here again (#5560)-//!-//! It was `pub use tinymemory_core::thread_context::{…}` — the task-local was-//! defined in the memory engine because the engine's own recall read it, and-//! two `tokio::task_local!` invocations are two distinct keys. The previous-//! revision of these docs said the move back "comes with the engine's removal,-//! in the same commit — not before it", because leaving the engine's key unset-//! would make its self-echo exclusion fail **open**: recall would start echoing-//! the caller's own thread back at it, with no error anywhere.-//!-//! That condition is met, and by a stronger route than the docs anticipated.-//! The engine reads this task-local in exactly one place —-//! `store::recall_policy::current_self_echo_exclusion`, reached only from-//! `impl Memory for UnifiedMemory`'s `recall`, and only as the fallback when-//! the caller passed no `RecallOpts::exclude_session_id`. Nothing in this-//! binary constructs a `UnifiedMemory` any more: `memory::binding` refuses-//! `DriverClass::Embedded` outright, `memory::mod`'s alias list dropped-//! `MemoryClient` / `UnifiedMemory` for want of consumers, and-//! `tinymemory_core::global::init` survives in `memory::ops::test_support`-//! alone. So the engine-side read is already unreachable in a production build-//! — and where it *is* reachable, from a test that boots an in-process client,-//! that test names the engine crate directly and gets the engine's own key.-//!-//! The host's own call sites are unaffected either way: every one of them-//! reaches this path (`agent::tinyagents::thread_context`) for both `with_` and-//! `current_`, so the scope they set is the scope they read. A caller that-//! needs the exclusion applied by the *module* driver must still pass-//! `RecallOpts::exclude_session_id` explicitly — a task-local set in this-//! process is invisible inside a separately compiled `cdylib`, which is why-//! `agent::tinyagents::host::agent_memory` and `agent::harness::memory_context`-//! already do.--use std::future::Future;--tokio::task_local! {- static THREAD_ID: Option<String>;-}--/// Run `fut` with the given `thread_id` available to any descendant task that-/// calls [`current_thread_id`]. Empty / whitespace-only ids are normalised to-/// `None` so callers can pass user input through without guarding for it.-pub async fn with_thread_id<F, T>(thread_id: impl Into<String>, fut: F) -> T-where- F: Future<Output = T>,-{- let id = thread_id.into();- let trimmed = id.trim();- let value = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };- log::debug!(- "[thread-context] entering scope has_thread_id={}",- value.is_some()- );- THREAD_ID.scope(value, fut).await-}--/// Return the ambient `thread_id` set by an enclosing [`with_thread_id`] scope,-/// or `None` when called outside one (tests, CLI, sub-systems that do not-/// participate in chat sessions).-pub fn current_thread_id() -> Option<String> {- THREAD_ID- .try_with(|v| v.clone())- .ok()- .flatten()- .filter(|s| !s.is_empty())-}--#[cfg(test)]-#[path = "thread_context_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/thread_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/thread_context_tests.rsdeleted file mode 100644index b46f9daeec..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/thread_context_tests.rs+++ /dev/null@@ -1,69 +0,0 @@-//! Tests for the surrounding module.-//!-//! The task-local came home in #5560, so its normalisation and scoping rules-//! are this crate's to pin: an unset scope must read as `None` (the provider-//! then omits the field rather than sending an empty one), whitespace-only ids-//! must normalise to `None` rather than reaching the wire, and a nested scope-//! must shadow its parent for the duration and no longer.--use super::{current_thread_id, with_thread_id};--#[tokio::test]-async fn reads_the_id_set_by_the_enclosing_scope() {- with_thread_id("abc123", async {- assert_eq!(current_thread_id().as_deref(), Some("abc123"));- })- .await;-}--#[tokio::test]-async fn outside_any_scope_there_is_no_ambient_id() {- assert_eq!(current_thread_id(), None);-}--#[tokio::test]-async fn blank_ids_normalise_to_none() {- with_thread_id(" ", async {- assert_eq!(current_thread_id(), None);- })- .await;- with_thread_id("", async {- assert_eq!(current_thread_id(), None);- })- .await;-}--#[tokio::test]-async fn surrounding_whitespace_is_trimmed() {- with_thread_id(" t-42\n", async {- assert_eq!(current_thread_id().as_deref(), Some("t-42"));- })- .await;-}--#[tokio::test]-async fn a_nested_scope_shadows_its_parent_and_then_restores_it() {- with_thread_id("outer", async {- assert_eq!(current_thread_id().as_deref(), Some("outer"));- with_thread_id("inner", async {- assert_eq!(current_thread_id().as_deref(), Some("inner"));- })- .await;- assert_eq!(current_thread_id().as_deref(), Some("outer"));- })- .await;-}--/// A spawned task does not inherit the parent's task-local, which is why the-/// orchestrator's async sub-agent path re-enters `with_thread_id` explicitly-/// rather than relying on the scope it was spawned from.-#[tokio::test]-async fn a_spawned_task_does_not_inherit_the_scope() {- with_thread_id("parent", async {- let inherited = tokio::spawn(async { current_thread_id() })- .await- .expect("spawned task panicked");- assert_eq!(inherited, None);- })- .await;-}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs b/crates/openhuman-core/src/agent/tinyagents/turn_models.rsindex d84539269f..1f044752cc 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_models.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_models.rs@@ -109,12 +109,32 @@ fn build_turn_models_crate(native_tools: bool,supports_vision: bool,force_text_mode: bool,+ thread_id: Option<&str>,) -> anyhow::Result<TurnModels> {use crate::inference::provider::factory;// The primary honours an explicit provider-string override when the producer's// effective provider differs from `provider_for_role(role)` (triage #1257).let build_primary = |m: &str| -> anyhow::Result<TurnChatModel> {+ let managed = primary_override+ .map(|provider| {+ let provider = provider.trim();+ provider.is_empty() || provider == "cloud" || provider == "openhuman"+ })+ .unwrap_or_else(|| factory::resolves_to_managed_backend(role, config));+ if managed {+ let (backend, _) = factory::make_openhuman_backend_model_for_thread(+ role,+ config,+ m,+ !force_text_mode,+ thread_id,+ )?;+ return Ok(Arc::new(RouteRecordingModel::new(+ backend,+ ResolvedModelRoute::new("openhuman", m, m),+ )));+ }let (model, provider, resolved_model) = match primary_override {Some(ps) => factory::create_turn_chat_model_from_string_with_native_tools_and_route(role,@@ -157,13 +177,25 @@ fn build_turn_models_crate(continue;}let tier_role = factory::role_for_model_tier(tier);- match factory::create_turn_chat_model_with_native_tools_and_route(- tier_role,- config,- tier,- temperature,- !force_text_mode,- ) {+ let route = if factory::resolves_to_managed_backend(tier_role, config) {+ factory::make_openhuman_backend_model_for_thread(+ tier_role,+ config,+ tier,+ !force_text_mode,+ thread_id,+ )+ .map(|(backend, _)| (backend, "openhuman".to_string(), tier.to_string()))+ } else {+ factory::create_turn_chat_model_with_native_tools_and_route(+ tier_role,+ config,+ tier,+ temperature,+ !force_text_mode,+ )+ };+ match route {Ok((route_model, provider, resolved_model)) => routes.push((tier.to_string(),Arc::new(RouteRecordingModel::new(@@ -363,6 +395,7 @@ impl TurnModelSource {model: &str,temperature: f64,context_window: Option<u64>,+ thread_id: Option<&str>,) -> anyhow::Result<TurnModels> {if let Some(direct) = &self.direct_model {let mut profile = direct.profile().cloned().unwrap_or_default();@@ -424,6 +457,7 @@ impl TurnModelSource {!is_local,!is_local,cn.force_text_mode,+ thread_id,);}Err(anyhow::anyhow!("turn model source is missing a model"))diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex 21b6f025a4..f4fbfd1fc0 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -578,40 +578,31 @@ pub(crate) async fn run_turn_via_tinyagents_shared(// nested inside its parent's drive future — leaving it inline on the stack// overflows when the parent + child drives compose. Boxing keeps only a// pointer on the stack at each level.- // The legacy thread scope remains for APIs outside the typed TinyAgents- // surface. Cancellation is carried solely by the canonical run context and- // reaches recursive tools through typed parent dispatch. Route metadata is- // likewise carried by the typed run context and canonical model response.- let run_thread_id = run_context.thread_id.clone().unwrap_or_default();let resolved_route_slot = run_context.resolved_route.clone();- let run_result =- crate::agent::tinyagents::thread_context::with_thread_id(run_thread_id, async move {- if streaming {- let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));- let mut terminal = None;- while let Some(item) = stream.next().await {- match item {- AgentStreamItem::Event(_) => {}- AgentStreamItem::Completed(run) => {- terminal = Some(Ok(*run));- break;- }- AgentStreamItem::Failed { error, .. } => {- terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));- break;- }- }+ let run_result = if streaming {+ let mut stream = Box::pin(harness.invoke_stream_in_context(&(), ctx, input));+ let mut terminal = None;+ while let Some(item) = stream.next().await {+ match item {+ AgentStreamItem::Event(_) => {}+ AgentStreamItem::Completed(run) => {+ terminal = Some(Ok(*run));+ break;+ }+ AgentStreamItem::Failed { error, .. } => {+ terminal = Some(Err(tinyagents_harness::TinyAgentsError::Model(error)));+ break;}- terminal.unwrap_or_else(|| {- Err(tinyagents_harness::TinyAgentsError::Model(- "tinyagents stream ended without terminal run".to_string(),- ))- })- } else {- Box::pin(harness.invoke_in_context(&(), ctx, input)).await}+ }+ terminal.unwrap_or_else(|| {+ Err(tinyagents_harness::TinyAgentsError::Model(+ "tinyagents stream ended without terminal run".to_string(),+ ))})- .await;+ } else {+ Box::pin(harness.invoke_in_context(&(), ctx, input)).await+ };// Drive future returned: run cleanup now (abort poll task + deregister +// requeue residual steers) rather than deferring to end-of-scope so the poll// loop cannot deliver into the no-longer-drained handle during post-rundiff --git a/crates/openhuman-core/src/agent/tools/delegate.rs b/crates/openhuman-core/src/agent/tools/delegate.rsindex 4ab35df98a..6dbf9b5a84 100644--- a/crates/openhuman-core/src/agent/tools/delegate.rs+++ b/crates/openhuman-core/src/agent/tools/delegate.rs@@ -246,7 +246,11 @@ impl DelegateTool {None,&self.provider_runtime_options,agent_config.model.clone(),- );+ )+ // `metadata` below is diagnostic only; the managed model owns the+ // actual backend wire extension so configured delegates cannot lose+ // their parent's thread between typed dispatch and provider invoke.+ .with_thread_id(tool_context.and_then(ToolRunContext::thread_id));// Build the messagelet full_prompt = if context.is_empty() {diff --git a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rsindex 01529e142f..b713843231 100644--- a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs+++ b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs@@ -106,12 +106,11 @@ impl Tool for DelegateToPersonalityTool {_options: ToolCallOptions,tool_context: Option<&dyn ToolRunContext>,) -> anyhow::Result<ToolResult> {- execute_delegate_to_personality(- args,- tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),- )- .await+ let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new();+ run_context.thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(ToOwned::to_owned);+ execute_delegate_to_personality(args, tool_context, run_context).await}}diff --git a/crates/openhuman-core/src/agent/turn_origin.rs b/crates/openhuman-core/src/agent/turn_origin.rsindex 9c2101e39b..e2cc199f2a 100644--- a/crates/openhuman-core/src/agent/turn_origin.rs+++ b/crates/openhuman-core/src/agent/turn_origin.rs@@ -277,7 +277,7 @@ pub async fn with_inherited_origin<F: std::future::Future>(/// refused — even though the parent turn that delegated the work was properly/// labelled. That is the same failure mode/// [`fork_context::with_parent_context`](crate::agent::harness::fork_context)-/// and [`thread_context::with_thread_id`](crate::agent::tinyagents::thread_context)+/// and an explicit [`OpenHumanRunContext`](crate::agent::tinyagents::host::OpenHumanRunContext)/// already re-install explicitly at those spawn sites; the origin is the third/// thing that has to travel with them.///diff --git a/crates/openhuman-core/src/flows/README.md b/crates/openhuman-core/src/flows/README.mdindex 97e96013d2..74dba61532 100644--- a/crates/openhuman-core/src/flows/README.md+++ b/crates/openhuman-core/src/flows/README.md@@ -54,7 +54,7 @@ from always-compiled code.## Calls into- `vendor/tinyflows/` — the actual workflow model, validation, compilation, and run engine; this domain never re-implements it.-- `crates/openhuman-core/src/agent/tinyagents/` — message/tool-call/usage conversions used by the `llm` and `prompt` capabilities, and `thread_context::with_thread_id` around a run; `agent` nodes run a nested harness turn through the `agent` capability (`tinyflows/caps/agent.rs`).+- `crates/openhuman-core/src/agent/tinyagents/` — message/tool-call/usage conversions used by the `llm` and `prompt` capabilities; `agent` nodes pass an explicit run context into nested harness turns through the `agent` capability (`tinyflows/caps/agent.rs`).- `crates/openhuman-core/src/cron/` — `add_flow_schedule_job` arms a schedule-triggered flow as a `JobType::Flow` cron job; the scheduler fires it by publishing `DomainEvent::FlowScheduleTick`, which `bus::FlowTriggerSubscriber` picks up.- `crates/openhuman-core/src/platform/socket/medulla/workflows.rs` — `WorkflowBridge` trait implemented by `medulla_bridge`.- `crates/openhuman-core/src/skills/` — the `Workflow` / `WorkflowScope` catalogue types used by `catalogue.rs`, and the native `BundledSkill` mechanism that exposes the portable `tinyflows-copilot` authoring manual.diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rsindex 3b96c852d9..2dac26311f 100644--- a/crates/openhuman-core/src/flows/ops/builder.rs+++ b/crates/openhuman-core/src/flows/ops/builder.rs@@ -172,6 +172,7 @@ pub(crate) async fn flows_build_with_extra_hidden_tools(// a copilot pane the user may have already navigated away from// shouldn't idle that long. Main-chat turns never scope this, so// they are unaffected.+ agent.set_thread_id(Some(target.thread_id.as_str()));let run = with_origin(origin,APPROVAL_CHAT_CONTEXT.scope(@@ -181,10 +182,6 @@ pub(crate) async fn flows_build_with_extra_hidden_tools();let run =tokio::time::timeout(std::time::Duration::from_secs(FLOW_BUILD_TIMEOUT_SECS), run);- let run = crate::agent::tinyagents::thread_context::with_thread_id(- target.thread_id.clone(),- run,- );// Register this turn's cancellation token BEFORE racing the run,// so a `flows_build_cancel` call landing the instant this turndiff --git a/crates/openhuman-core/src/flows/ops/discovery.rs b/crates/openhuman-core/src/flows/ops/discovery.rsindex 68c2422642..083bd1dfd7 100644--- a/crates/openhuman-core/src/flows/ops/discovery.rs+++ b/crates/openhuman-core/src/flows/ops/discovery.rs@@ -63,6 +63,7 @@ pub async fn flows_discover(// the run stays headless, exactly as before.if let Some(target) = &stream {attach_flow_progress_bridge(&mut agent, target, "flows_discover", config);+ agent.set_thread_id(Some(target.thread_id.as_str()));}// Run to completion under a CLI origin (an internal, user-initiated action —@@ -75,13 +76,7 @@ pub async fn flows_discover(std::time::Duration::from_secs(FLOW_DISCOVER_TIMEOUT_SECS),run,);- let timed = match &stream {- Some(target) => {- crate::agent::tinyagents::thread_context::with_thread_id(target.thread_id.clone(), run)- .await- }- None => run.await,- };+ let timed = run.await;// Reduce the (timeout, run) result to a single `Result<summary, error>` so// the terminal chat event can be emitted uniformly for the streamed case.let outcome: Result<String, String> = match timed {diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rsindex 400504f539..5766e0f9d5 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs@@ -474,7 +474,7 @@ impl OpenHumanAgentRunner {/// dropped to the default chat model once routed through the harness.////// **Synchronous only (B40 / Gap 4).** A flow `agent` node runs here with- /// no chat thread bound via `thread_context::current_thread_id()`. If the+ /// no explicit chat thread on its run context. If the/// agent it runs is a delegating agent (orchestrator/subconscious) and/// calls `spawn_async_subagent` directly, the tool now refuses (see the/// `parent_thread_id.is_none()` guard indiff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rsindex d9fda95890..827e082ae0 100644--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs@@ -187,6 +187,7 @@ pub async fn agent_chat_for(.map(str::trim).filter(|id| !id.is_empty()){+ agent.set_thread_id(Some(id));// Scoped to this call's agent identity, when it has one: a library// host can hand the same caller-supplied thread_id to several// independently configured runtime agents, and unscoped matching@@ -229,17 +230,7 @@ pub async fn agent_chat_for(effective_agent_chat_origin(),agent.run_single(message),);- let response = match thread_id.as_deref() {- Some(id) if !id.trim().is_empty() => {- log::debug!("[inference] agent_chat routing with thread_id={id}");- crate::agent::tinyagents::thread_context::with_thread_id(id, run).await- }- _ => {- log::debug!("[inference] agent_chat routing without thread_id");- run.await- }- }- .map_err(|e| e.to_string())?;+ let response = run.await.map_err(|e| e.to_string())?;Ok(RpcOutcome::single_log(response, "agent chat completed"))}@@ -267,12 +258,28 @@ pub async fn agent_chat_simple(.clone().unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string());- let (model, resolved_model) = providers::create_chat_model_with_model_id(- "chat",- &effective,- effective.default_temperature,- )- .map_err(|e| e.to_string())?;+ let (model, resolved_model): (+ std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,+ String,+ ) = if providers::factory::resolves_to_managed_backend("chat", &effective) {+ let (backend, resolved_model) =+ providers::factory::make_openhuman_backend_model_for_thread(+ "chat",+ &effective,+ &default_model,+ true,+ thread_id.as_deref(),+ )+ .map_err(|e| e.to_string())?;+ (backend, resolved_model)+ } else {+ providers::create_chat_model_with_model_id(+ "chat",+ &effective,+ effective.default_temperature,+ )+ .map_err(|e| e.to_string())?+ };tracing::debug!(requested_model = %default_model,resolved_model = %resolved_model,@@ -287,18 +294,7 @@ pub async fn agent_chat_simple(.with_model(default_model.clone()).with_temperature(effective.default_temperature),);- let response = match thread_id.as_deref() {- Some(id) if !id.trim().is_empty() => {- log::debug!("[inference] agent_chat_simple routing with thread_id={id}");- crate::agent::tinyagents::thread_context::with_thread_id(id, run).await- }- _ => {- log::debug!("[inference] agent_chat_simple routing without thread_id");- run.await- }- }- .map_err(|e| e.to_string())?- .text();+ let response = run.await.map_err(|e| e.to_string())?.text();Ok(RpcOutcome::single_log(response,diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.mdindex d85a7efe3b..22eb754378 100644--- a/crates/openhuman-core/src/inference/provider/README.md+++ b/crates/openhuman-core/src/inference/provider/README.md@@ -45,7 +45,7 @@ domain.`Config::claude_agent_sdk`, abstract tier model constants.- `crate::security::credentials` — auth-profile store for BYOK keys and OAuthtokens.-- `crate::agent::tinyagents::{routes, thread_context}` — workload routing and+- `crate::agent::tinyagents::{routes, host}` — workload routing and explicit runambient thread-context plumbing consumed while building a model.- `crate::security::live_policy` + `crate::security::egress` — Privacy-Mode`LocalOnly` refusal and `EgressDescriptor` emission at the factory chokepointdiff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rsindex e2d2bf5be4..2b399cbc17 100644--- a/crates/openhuman-core/src/inference/provider/factory.rs+++ b/crates/openhuman-core/src/inference/provider/factory.rs@@ -84,6 +84,7 @@ use local_runtime::{try_create_local_runtime_chat_model, try_create_local_runtime_chat_model_from_string,OptionalChatModelResult,};+pub(crate) use managed_backend::make_openhuman_backend_model_for_thread;use managed_backend::{resolve_managed_backend, resolve_managed_backend_with_model_override};use primary_cloud::{legacy_inference_slug, resolve_primary_cloud_provider_string};use routing::split_model_and_temperature;diff --git a/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rsindex eb24074be9..8d41945193 100644--- a/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs+++ b/crates/openhuman-core/src/inference/provider/factory/managed_backend.rs@@ -105,6 +105,30 @@ pub(super) fn resolve_managed_backend(resolve_managed_backend_with_model_override(role, config, None)}+/// Construct a managed turn model with the explicit OpenHuman thread attached.+/// This intentionally exposes no generic backend resolver outside the factory.+pub(crate) fn make_openhuman_backend_model_for_thread(+ role: &str,+ config: &Config,+ model: &str,+ native_tool_calling: bool,+ thread_id: Option<&str>,+) -> anyhow::Result<(+ std::sync::Arc<dyn tinyinference_llm::model::ChatModel<()>>,+ String,+)> {+ let (backend, resolved_model) = resolve_managed_backend(role, config)?;+ Ok((+ std::sync::Arc::new(+ backend+ .with_default_model(model)+ .with_native_tool_calling(native_tool_calling)+ .with_thread_id(thread_id),+ ),+ resolved_model,+ ))+}+pub(super) fn resolve_managed_backend_with_model_override(role: &str,config: &Config,diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rsindex dc6634aae3..680f6be43b 100644--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model.rs@@ -36,7 +36,6 @@ use tinyinference_llm::providers::openai::OpenAiModel;use tinyinference_llm::Error as TiError;use super::ProviderRuntimeOptions;-use crate::agent::tinyagents::thread_context;use crate::api::config::effective_api_url;use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER};@@ -80,6 +79,10 @@ pub struct OpenHumanBackendModel {default_model: String,native_tool_calling: bool,profile: ModelProfile,+ /// Normalized OpenHuman conversation thread. This is deliberately owned by+ /// the managed backend model: BYOK and third-party models must never see+ /// this backend-only extension.+ thread_id: Option<String>,}impl OpenHumanBackendModel {@@ -108,9 +111,21 @@ impl OpenHumanBackendModel {streaming_tool_chunks: true,..ModelProfile::default()},+ thread_id: None,}}+ /// Attach the explicit run thread used by OpenHuman's managed inference+ /// endpoint. Blank values mean no backend thread rather than an empty wire+ /// field.+ pub fn with_thread_id(mut self, thread_id: Option<impl AsRef<str>>) -> Self {+ self.thread_id = thread_id.and_then(|thread_id| {+ let thread_id = thread_id.as_ref().trim();+ (!thread_id.is_empty()).then(|| thread_id.to_owned())+ });+ self+ }+pub fn with_default_model(mut self, model: impl Into<String>) -> Self {self.default_model = resolve_model(&model.into());self@@ -445,8 +460,8 @@ fn project_managed_usage(mut response: ModelResponse) -> ModelResponse {/// have not yet migrated to the explicit run carrier still establish this/// scope; the shared-runner cutover preserves that boundary until those routes/// pass `OpenHumanRunContext.thread_id` end-to-end.-fn with_thread_id(request: ModelRequest) -> ModelRequest {- let Some(thread_id) = thread_context::current_thread_id() else {+fn with_thread_id(request: ModelRequest, thread_id: Option<&str>) -> ModelRequest {+ let Some(thread_id) = thread_id else {return request;};let mut options = request.provider_options.clone();@@ -555,7 +570,10 @@ impl ChatModel<()> for OpenHumanBackendModel {request: ModelRequest,) -> tinyinference_llm::Result<ModelResponse> {let model = self.build_wire_model()?;- let response = match model.invoke(state, with_thread_id(request)).await {+ let response = match model+ .invoke(state, with_thread_id(request, self.thread_id.as_deref()))+ .await+ {Ok(response) => response,Err(e) => {log_managed_dispatch_error(&e, "invoke");@@ -579,7 +597,10 @@ impl ChatModel<()> for OpenHumanBackendModel {// survive via `UsageDelta`). The authoritative charged amount is recovered// on the non-streaming `invoke` path above. Restoring it for streaming// needs the crate to preserve the final chunk's raw JSON (tracked upstream).- match model.stream(state, with_thread_id(request)).await {+ match model+ .stream(state, with_thread_id(request, self.thread_id.as_deref()))+ .await+ {Ok(stream) => Ok(stream),Err(e) => {log_managed_dispatch_error(&e, "stream");diff --git a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rsindex d6ec531ccb..2f84fa42ac 100644--- a/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs+++ b/crates/openhuman-core/src/inference/provider/openhuman_backend_model_tests.rs@@ -10,26 +10,29 @@ fn backend() -> OpenHumanBackendModel {)}-#[tokio::test]-async fn with_thread_id_injects_when_ambient_thread_present() {- thread_context::with_thread_id("thread-42", async {- let request = ModelRequest::new(vec![Message::user("hi")]);- let updated = with_thread_id(request);- assert_eq!(- updated.provider_options["thread_id"],- serde_json::json!("thread-42")- );- })- .await;+#[test]+fn with_thread_id_injects_explicit_thread() {+ let request = ModelRequest::new(vec![Message::user("hi")]);+ let updated = with_thread_id(request, Some("thread-42"));+ assert_eq!(+ updated.provider_options["thread_id"],+ serde_json::json!("thread-42")+ );}#[test]-fn with_thread_id_is_noop_without_ambient_thread() {+fn with_thread_id_is_noop_without_explicit_thread() {let request = ModelRequest::new(vec![Message::user("hi")]);- let updated = with_thread_id(request);+ let updated = with_thread_id(request, None);assert!(updated.provider_options.get("thread_id").is_none());}+#[test]+fn managed_model_keeps_its_explicit_thread_without_an_ambient_scope() {+ let model = backend().with_thread_id(Some(" delegate-thread "));+ assert_eq!(model.thread_id.as_deref(), Some("delegate-thread"));+}+#[test]fn managed_model_advertises_tool_and_vision_capabilities() {let model = backend();diff --git a/crates/openhuman-core/src/voice/realtime_harness/agent.rs b/crates/openhuman-core/src/voice/realtime_harness/agent.rsindex 32b0e1c0d6..2687958114 100644--- a/crates/openhuman-core/src/voice/realtime_harness/agent.rs+++ b/crates/openhuman-core/src/voice/realtime_harness/agent.rs@@ -146,7 +146,7 @@ async fn run_single_with_timeout(prompt: &str,) -> Result<String, String> {// Scope the turn with the SAME chat context the web-chat path installs- // (`APPROVAL_CHAT_CONTEXT` + `with_thread_id`), so approval-surfaced tools+ // (`APPROVAL_CHAT_CONTEXT` plus an explicit agent thread), so approval-surfaced tools// behave identically on voice. Without it `composio_connect` fails closed// for lack of a routable surface, which the model paraphrases to the user as// a confabulated "reconnect your Gmail" mid email-summary (#5399). See@@ -156,10 +156,8 @@ async fn run_single_with_timeout(thread_id: VOICE_CHAT_THREAD_ID.to_string(),client_id: VOICE_CHAT_CLIENT_ID.to_string(),};- let scoped_run = crate::agent::tinyagents::thread_context::with_thread_id(- VOICE_CHAT_THREAD_ID,- agent.run_single(prompt),- );+ agent.set_thread_id(Some(VOICE_CHAT_THREAD_ID));+ let scoped_run = agent.run_single(prompt);let fut = with_origin(AgentTurnOrigin::ExternalChannel {channel: "voice".to_string(),diff --git a/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rsindex df7c20291e..a48fb61e43 100644--- a/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs+++ b/crates/openhuman-core/src/voice/realtime_harness/chat_delivery.rs@@ -9,7 +9,7 @@ use crate::platform::socket::manager::global_socket_manager;/// Chat thread + client id the voice turn scopes as its approval / routing/// surface, mirroring `deliver_voice_result_to_chat`. Setting these around the-/// turn (via `APPROVAL_CHAT_CONTEXT` + `with_thread_id`) is what makes the voice+/// turn (via `APPROVAL_CHAT_CONTEXT` plus the explicit agent thread) is what makes the voice/// orchestrator behave like the chat path for tools that need a *routable*/// approval surface:///@@ -24,7 +24,7 @@ use crate::platform::socket::manager::global_socket_manager;/// - external_effect tool approvals raised on the `ExternalChannel` turn now/// have a thread card to route to (the same `proactive:voice` thread where/// deferred voice answers land) rather than silently TTL-denying.-/// - `with_thread_id` gives async delegation (`spawn_async_subagent`) the+/// - The explicit run context gives async delegation (`spawn_async_subagent`) the/// `parent_thread_id` it requires and aligns inference logs / KV-cache with/// the voice thread.pub(super) const VOICE_CHAT_THREAD_ID: &str = "proactive:voice";diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsindex cc63c440c1..3b18bdab18 100644--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ b/crates/openhuman-core/src/web_chat/run_task.rs@@ -238,6 +238,7 @@ pub(crate) async fn run_chat_task(let (progress_tx, progress_rx) = tokio::sync::mpsc::channel(256);agent.set_on_progress(Some(progress_tx));agent.set_run_queue(Some(run_queue));+ agent.set_thread_id(Some(thread_id));let turn_state_store = TurnStateStore::new(config.workspace_dir.clone());// Stamp the resolved agent onto the bridge metadata so the trace exporter// can attribute the run (`agent.id` attr / `agent.turn:<id>` trace name).@@ -262,9 +263,9 @@ pub(crate) async fn run_chat_task(// 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 result = match crate::agent::tinyagents::thread_context::with_thread_id(- thread_id.to_string(),- crate::memory::source_scope::with_source_scope(profile.memory_sources.clone(), turn),+ let result = match crate::memory::source_scope::with_source_scope(+ profile.memory_sources.clone(),+ turn,).await{diff --git a/tests/agent_turn_overrides_e2e.rs b/tests/agent_turn_overrides_e2e.rsindex f8a6cdd97a..a06a6694de 100644--- a/tests/agent_turn_overrides_e2e.rs+++ b/tests/agent_turn_overrides_e2e.rs@@ -36,7 +36,6 @@ use tempfile::TempDir;use openhuman_core::agent::goals::{runtime as goal_runtime, store as goal_store};use openhuman_core::agent::harness::session::TurnOverrides;-use openhuman_core::agent::tinyagents::thread_context::with_thread_id;use openhuman_core::agent::Agent;use openhuman_core::config::{AgentConfig, ContextConfig};use tinyinference_llm::message::Message;@@ -292,7 +291,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {const THREAD: &str = "thread-suppress-active-goal";const OBJECTIVE: &str = "turn-overrides objective that must not leak into small talk";- with_thread_id(THREAD, async {+ {// CONTROL — without the override the goal reaches the prompt.let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)@@ -305,6 +304,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {control_workspace.clone(),Box::new(XmlDialect),);+ control.set_thread_id(Some(THREAD));control.turn("where are we on the task?").await@@ -329,6 +329,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {workspace_path.clone(),Box::new(XmlDialect),);+ agent.set_thread_id(Some(THREAD));agent.set_next_turn_overrides(TurnOverrides {suppress_active_goal: true,..Default::default()@@ -345,8 +346,7 @@ async fn suppress_active_goal_keeps_the_thread_goal_out_of_the_prompt_inner() {!prompt.contains("[thread goal]"),"suppress_active_goal must not inject the [thread goal] block; prompt was: {prompt}");- })- .await;+ }}// ─── suppress_transcript_autoload ───────────────────────────────────────────@@ -377,7 +377,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript//// These scopes do not steer the lookup, and are not meant to. Autoload is// `session_io_impl_01_part_01.rs:45` — `latest_for_agent(&self.agent_definition_name)`- // — which never reads `thread_context::current_thread_id()`; that+ // — which never read a conversation-thread carrier; that// agent-name-only resolution IS the defect the override exists to work// around. They are here so the control states the stronger fact (the prior// transcript is replayed *even under a different thread id*), and so that a@@ -387,7 +387,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcriptconst LATER_THREAD: &str = "turn-overrides-autoload-thread-b";// A first conversation persists a transcript under this agent name.- with_thread_id(PRIOR_THREAD, async {+ {let first_model = ScriptedModel::new(vec![text("first thread reply")]);let mut first = agent_with(first_model.clone(),@@ -395,15 +395,15 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcriptworkspace_path.clone(),Box::new(XmlDialect),);+ first.set_thread_id(Some(PRIOR_THREAD));first.turn(PRIOR_MARKER).await.expect("first thread turn should succeed");- })- .await;+ }// Everything below is the *later* chat the host has re-bound to.- with_thread_id(LATER_THREAD, async {+ {// CONTROL — a fresh agent with an empty history DOES pick that transcript// up, across the thread change.let control_model = ScriptedModel::new(vec![text("control reply")]);@@ -413,6 +413,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcriptworkspace_path.clone(),Box::new(XmlDialect),);+ control.set_thread_id(Some(LATER_THREAD));control.turn("an unrelated question").await@@ -432,6 +433,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcriptworkspace_path.clone(),Box::new(XmlDialect),);+ agent.set_thread_id(Some(LATER_THREAD));agent.set_next_turn_overrides(TurnOverrides {suppress_transcript_autoload: true,..Default::default()@@ -447,8 +449,7 @@ async fn suppress_transcript_autoload_does_not_replay_a_prior_threads_transcript"suppress_transcript_autoload must not replay another conversation's transcript \into the prompt; found the prior thread's marker in: {prompt}");- })- .await;+ }}// ─── one-shot semantics ─────────────────────────────────────────────────────@@ -539,7 +540,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innerconst THREAD: &str = "thread-goal-terminal";const OBJECTIVE: &str = "turn-overrides objective a finished task must stop replaying";- with_thread_id(THREAD, async {+ {// CONTROL — an Active goal reaches a turn.let control_guard = EnvGuard::set_path("OPENHUMAN_WORKSPACE", &control_workspace);goal_store::set(&control_workspace, THREAD, OBJECTIVE, None)@@ -552,6 +553,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innercontrol_workspace.clone(),Box::new(XmlDialect),);+ control.set_thread_id(Some(THREAD));control.turn("status?").await.expect("pre-completion turn");assert!(control_model.all_prompt_text().contains(OBJECTIVE),@@ -566,7 +568,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innergoal_store::set(&workspace_path, THREAD, OBJECTIVE, None).await.expect("seed an active thread goal for the measured agent");- let seeded = goal_runtime::load_for_current_thread(&workspace_path)+ let seeded = goal_runtime::load_for_thread(&workspace_path, Some(THREAD)).await.expect("the seeded goal must load before completion");assert_eq!(@@ -574,7 +576,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner"control: the goal must be loadable before completing it");- goal_runtime::complete_for_current_thread(&workspace_path).await;+ goal_runtime::complete_for_thread(&workspace_path, Some(THREAD)).await;// A completed goal renders no context block, so a later turn is clean// with no per-turn override set at all.@@ -585,6 +587,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innerworkspace_path.clone(),Box::new(XmlDialect),);+ agent.set_thread_id(Some(THREAD));agent.turn("something unrelated").await@@ -596,9 +599,9 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innerlater turns; found it in: {prompt}");- goal_runtime::clear_for_current_thread(&workspace_path).await;+ goal_runtime::clear_for_thread(&workspace_path, Some(THREAD)).await;assert!(- goal_runtime::load_for_current_thread(&workspace_path)+ goal_runtime::load_for_thread(&workspace_path, Some(THREAD)).await.is_none(),"clear_for_current_thread must remove the goal row outright"@@ -613,7 +616,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innergoal_store::set(&workspace_path, THREAD, ACTIVE_OBJECTIVE, None).await.expect("seed a second, still-active thread goal");- let active = goal_runtime::load_for_current_thread(&workspace_path)+ let active = goal_runtime::load_for_thread(&workspace_path, Some(THREAD)).await.expect("the second goal must load while it is still active");assert_eq!(@@ -622,9 +625,9 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innerproves nothing");- goal_runtime::clear_for_current_thread(&workspace_path).await;+ goal_runtime::clear_for_thread(&workspace_path, Some(THREAD)).await;assert!(- goal_runtime::load_for_current_thread(&workspace_path)+ goal_runtime::load_for_thread(&workspace_path, Some(THREAD)).await.is_none(),"clear_for_current_thread must remove an ACTIVE goal, not only a completed one"@@ -639,6 +642,7 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_innerworkspace_path.clone(),Box::new(XmlDialect),);+ post_clear.set_thread_id(Some(THREAD));post_clear.turn("something else entirely").await@@ -649,6 +653,5 @@ async fn thread_goal_complete_and_clear_stop_the_goal_reaching_later_turns_inner"an active goal cleared via clear_for_current_thread must stop being injected \into later turns; found it in: {post_clear_prompt}");- })- .await;+ }}diff --git a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rsindex a85ce0f3f1..70d270ee8a 100644--- a/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs+++ b/tests/raw_coverage/inference_agent_raw_coverage_e2e.rs@@ -168,7 +168,6 @@ use openhuman_core::agent::profiles::{AgentProfile, AgentProfileStore, AgentProfilesState, DEFAULT_PROFILE_ID,};use openhuman_core::security::SecurityPolicy;-use openhuman_core::agent::tinyagents::thread_context::{current_thread_id, with_thread_id};use openhuman_core::agent::todos::ops::BoardLocation;use openhuman_core::inference::tokenjuice::AgentTokenjuiceCompression;use tinytools::{Tool, ToolResult, ToolSpec};@@ -1672,15 +1671,6 @@ async fn inference_public_helpers_cover_context_windows_and_sentiment_fallbacks(assert_eq!(empty.valence, "neutral");assert_eq!(empty.confidence, 1.0);- assert!(current_thread_id().is_none());- let scoped = with_thread_id(" thread-coverage ", async {- assert_eq!(current_thread_id().as_deref(), Some("thread-coverage"));- with_thread_id(" ", async { current_thread_id() }).await- })- .await;- assert!(scoped.is_none());- assert!(current_thread_id().is_none());-let mut cleanup_config = Config::default();assert_eq!(cleanup_transcription(&cleanup_config, "", None).await, "");cleanup_config.local_ai.voice_llm_cleanup_enabled = false;