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: propagate tool thread context explicitly
Steven Enamakelfa8ae05af29b
diff --git a/crates/openhuman-core/src/agent/goals/tools.rs b/crates/openhuman-core/src/agent/goals/tools.rsindex 1133944643..2a0e74f27c 100644--- a/crates/openhuman-core/src/agent/goals/tools.rs+++ b/crates/openhuman-core/src/agent/goals/tools.rs@@ -6,9 +6,7 @@//! mark it complete (`goal_complete`). Pause / resume / budget-limit are//! system-driven and have no model tool.//!-//! The target thread is resolved from the ambient-//! [`current_thread_id`](crate::agent::tinyagents::thread_context::current_thread_id)-//! task-local set by the chat channel — tools never take a `thread_id` arg, so+//! The target thread is resolved from the TinyAgents run context — tools never take a `thread_id` arg, so//! the model can't address another thread's goal. Each tool is sandboxed to a//! single `workspace_dir` captured at construction.@@ -19,8 +17,7 @@ use serde_json::json;use super::store;use super::ThreadGoal;-use crate::agent::tinyagents::thread_context::current_thread_id;-use tinytools::{PermissionLevel, Tool, ToolResult};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};/// Render a goal as a compact, model-readable block.fn render_goal(goal: &ThreadGoal) -> String {@@ -35,13 +32,12 @@ fn render_goal(goal: &ThreadGoal) -> String {)}-/// Resolve the ambient thread id or return a uniform tool error.-fn require_thread_id() -> Result<String, ToolResult> {- current_thread_id().ok_or_else(|| {- ToolResult::error(- "thread goal tools require an active chat thread (no ambient thread_id in this context)",- )- })+/// Resolve the caller thread id or return a uniform tool error.+fn require_thread_id(context: Option<&dyn ToolRunContext>) -> Result<String, ToolResult> {+ context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned)+ .ok_or_else(|| ToolResult::error("thread goal tools require an active chat thread"))}/// `goal_get` — read the current thread goal.@@ -75,8 +71,18 @@ impl Tool for GoalGetTool {PermissionLevel::ReadOnly}- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id() {+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ _args: serde_json::Value,+ _options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let thread_id = match require_thread_id(context) {Ok(id) => id,Err(e) => return Ok(e),};@@ -137,7 +143,17 @@ impl Tool for GoalSetTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id() {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let thread_id = match require_thread_id(context) {Ok(id) => id,Err(e) => return Ok(e),};@@ -197,8 +213,18 @@ impl Tool for GoalCompleteTool {PermissionLevel::Write}- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id() {+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ _args: serde_json::Value,+ _options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let thread_id = match require_thread_id(context) {Ok(id) => id,Err(e) => return Ok(e),};diff --git a/crates/openhuman-core/src/agent/goals/tools_tests.rs b/crates/openhuman-core/src/agent/goals/tools_tests.rsindex 4a02220aa3..680ffc7a0b 100644--- a/crates/openhuman-core/src/agent/goals/tools_tests.rs+++ b/crates/openhuman-core/src/agent/goals/tools_tests.rs@@ -1,28 +1,44 @@use super::*;-use crate::agent::tinyagents::thread_context::with_thread_id;+use tinytools::{ToolCallOptions, ToolRunContext};++struct ThreadContext(&'static str);++impl ToolRunContext for ThreadContext {+ fn thread_id(&self) -> Option<&str> {+ Some(self.0)+ }+}#[tokio::test]async fn set_get_complete_via_tools_in_thread_scope() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- with_thread_id("thread-tools", async {- let set = GoalSetTool::new(dir.clone());- let res = set- .execute(json!({ "objective": "land the PR", "token_budget": 5000 }))- .await- .unwrap();- assert!(!res.is_error, "{}", res.text());- assert!(res.text().contains("land the PR"));+ let context = ThreadContext("thread-tools");+ let set = GoalSetTool::new(dir.clone());+ let res = set+ .execute_with_context(+ json!({ "objective": "land the PR", "token_budget": 5000 }),+ ToolCallOptions::default(),+ Some(&context),+ )+ .await+ .unwrap();+ assert!(!res.is_error, "{}", res.text());+ assert!(res.text().contains("land the PR"));- let get = GoalGetTool::new(dir.clone());- let res = get.execute(json!({})).await.unwrap();- assert!(res.text().contains("status: active"));+ let get = GoalGetTool::new(dir.clone());+ let res = get+ .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))+ .await+ .unwrap();+ assert!(res.text().contains("status: active"));- let done = GoalCompleteTool::new(dir.clone());- let res = done.execute(json!({})).await.unwrap();- assert!(res.text().contains("status: complete"));- })- .await;+ let done = GoalCompleteTool::new(dir.clone());+ let res = done+ .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))+ .await+ .unwrap();+ assert!(res.text().contains("status: complete"));}#[tokio::test]@@ -39,10 +55,11 @@ async fn tools_error_without_thread_scope() {async fn get_reports_absent_goal() {let tmp = tempfile::tempdir().unwrap();let dir = tmp.path().to_path_buf();- with_thread_id("empty-thread", async {- let get = GoalGetTool::new(dir.clone());- let res = get.execute(json!({})).await.unwrap();- assert!(res.text().contains("no goal set"));- })- .await;+ let context = ThreadContext("empty-thread");+ let get = GoalGetTool::new(dir.clone());+ let res = get+ .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))+ .await+ .unwrap();+ assert!(res.text().contains("no goal set"));}diff --git a/crates/openhuman-core/src/agent/harness/agent_graph.rs b/crates/openhuman-core/src/agent/harness/agent_graph.rsindex 9844a7bdd7..af68dba3d8 100644--- a/crates/openhuman-core/src/agent/harness/agent_graph.rs+++ b/crates/openhuman-core/src/agent/harness/agent_graph.rs@@ -56,6 +56,8 @@ pub struct AgentTurnRequest {pub agent_id: String,pub task_id: String,pub extended_policy: bool,+ /// Explicit caller/worker thread propagated from the originating tool.+ pub thread_id: Option<String>,pub worker_thread_id: Option<String>,pub workspace_dir: PathBuf,pub workspace_descriptor: Option<WorkspaceDescriptor>,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 e9f27a85ec..3d3c41cf1a 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@@ -50,6 +50,8 @@ pub(crate) async fn run_agent_turn_request_via_default_graph(agent_id,task_id,extended_policy,+ thread_id,+ run_context,worker_thread_id,workspace_dir,workspace_descriptor,@@ -78,6 +80,8 @@ pub(crate) async fn run_agent_turn_request_via_default_graph(&agent_id,&task_id,extended_policy,+ thread_id,+ run_context,worker_thread_id,workspace_dir,workspace_descriptor,@@ -127,6 +131,8 @@ pub(in super::super) async fn run_subagent_via_graph(agent_id: &str,task_id: &str,extended_policy: bool,+ thread_id: Option<String>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,worker_thread_id: Option<String>,workspace_dir: std::path::PathBuf,workspace_descriptor: Option<WorkspaceDescriptor>,@@ -263,8 +269,8 @@ pub(in super::super) async fn run_subagent_via_graph(// that owned carrier and fork it so cancellation, origin, thread, progress,// workspace grants, and dispatch state follow the child while its route and// subagent-usage slots remain isolated.- let mut child_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes().child();+ let mut child_context = run_context.child();+ child_context.thread_id = thread_id.clone();child_context.progress = on_progress.clone().or(child_context.progress);child_context.workspace = workspace_descriptor.clone().or(child_context.workspace);let run_result = Box::pin(run_turn_via_tinyagents_shared(@@ -381,6 +387,7 @@ pub(in super::super) async fn run_subagent_via_graph(model,&recovered,&recovered_usage,+ thread_id.as_deref(),unanswered_steps.as_deref(),completed_rounds,context_window.unwrap_or(0),@@ -524,6 +531,7 @@ pub(in super::super) async fn run_subagent_via_graph(model,history_for_transcript,&usage,+ thread_id.as_deref(),context_window.unwrap_or(0),// Match the dispatcher the history was actually serialized with (text-mode// integrations turns write XML), and the real iteration count.diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rsindex 26b6cf6660..3beb31a4ae 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs@@ -49,6 +49,7 @@ pub(super) fn persist_subagent_transcript(model: &str,history: &[ChatMessage],usage: &AggregatedUsage,+ thread_id: Option<&str>,context_window: u64,dispatcher: &str,iteration: u32,@@ -96,7 +97,7 @@ pub(super) fn persist_subagent_transcript(output_tokens: usage.output_tokens,cached_input_tokens: usage.cached_input_tokens,charged_amount_usd: usage.charged_amount_usd,- thread_id: crate::agent::tinyagents::thread_context::current_thread_id(),+ thread_id: thread_id.map(str::to_owned),task_id: Some(task_id.to_string()),};if let Err(err) = transcript::write_transcript(&path, history, &meta, Some(&turn_usage)) {@@ -127,6 +128,7 @@ pub(super) fn persist_failed_run(model: &str,recovered: &[ChatMessage],usage: &AggregatedUsage,+ thread_id: Option<&str>,unanswered_steps: Option<&str>,completed_rounds: u32,context_window: u64,@@ -150,6 +152,7 @@ pub(super) fn persist_failed_run(model,&history,usage,+ thread_id,context_window,dispatcher,completed_rounds,diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rsindex 97e0143601..df8827801d 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner.rs@@ -1579,6 +1579,8 @@ async fn run_typed_mode(&definition.id,task_id,definition.iteration_policy == IterationPolicy::Extended,+ options.thread_id.clone(),+ options.run_context.clone(),options.worker_thread_id.clone(),parent.workspace_dir.clone(),workspace_descriptor.clone(),@@ -1620,6 +1622,8 @@ async fn run_typed_mode(agent_id: definition.id.clone(),task_id: task_id.to_string(),extended_policy: definition.iteration_policy == IterationPolicy::Extended,+ thread_id: options.thread_id.clone(),+ run_context: options.run_context.clone(),worker_thread_id: options.worker_thread_id.clone(),workspace_dir: parent.workspace_dir.clone(),workspace_descriptor: workspace_descriptor.clone(),diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rsindex 838b084c55..e316ce849b 100644--- a/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/types.rs@@ -14,7 +14,7 @@ use crate::agent::messages::ChatMessage;/// Per-spawn options that override or augment what the/// [`AgentDefinition`] specifies. Built by `SpawnSubagentTool::execute`/// from the parent model's call arguments.-#[derive(Debug, Clone, Default)]+#[derive(Clone, Default)]pub struct SubagentRunOptions {/// Optional skill-id override (e.g. `"notion"`). When set, the/// resolved tool list is further restricted to tools whose name@@ -42,6 +42,15 @@ pub struct SubagentRunOptions {/// Stable id for tracing / DomainEvents (defaults to a UUID).pub task_id: Option<String>,+ /// Explicit thread identity for the child run. Tool callers copy this from+ /// their `ToolRunContext`; detached workers set the durable worker affinity+ /// before crossing `tokio::spawn`. This is never recovered from a task-local.+ pub thread_id: Option<String>,++ /// Explicit host carrier for the child run. Recursive execution must use+ /// this value rather than snapshotting task-local scopes after a spawn.+ pub run_context: crate::agent::tinyagents::host::OpenHumanRunContext,+/// Optional thread ID for persistent worker threads. When set,/// every assistant message and tool result in the inner loop is/// appended to this thread in the global ConversationStore.diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsindex 5ffca1dd27..81972f1a71 100644--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs@@ -205,6 +205,8 @@ fn delegation_subagent_options(context: None,model_override: None,task_id: None,+ thread_id: None,+ run_context: Default::default(),worker_thread_id: None,initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/orchestration/ops.rs b/crates/openhuman-core/src/agent/orchestration/ops.rsindex 5405b4d651..54412c5a39 100644--- a/crates/openhuman-core/src/agent/orchestration/ops.rs+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs@@ -375,6 +375,8 @@ impl AgentOrchestrationSession {context: request.context,model_override: request.model,task_id: Some(orchestration_id.clone()),+ thread_id: None,+ run_context: Default::default(),worker_thread_id: None,initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rsindex f91b54c947..ed717b51a3 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/graph.rs@@ -148,6 +148,7 @@ pub(crate) async fn run_spawn_parallel_execution_graph(action_root: Option<PathBuf>,cancel: CancellationToken,parent_workspace_descriptor: Option<WorkspaceDescriptor>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> Result<SpawnParallelGraphOutcome, String> {let phases = SPAWN_PARALLEL_PHASES;let label = format!("spawn_parallel_agents:{parent_session}");@@ -164,6 +165,7 @@ pub(crate) async fn run_spawn_parallel_execution_graph(let cancel_for_worker = cancel.clone();let cancel_for_collect = cancel.clone();let cancel_for_finalize = cancel.clone();+ let run_context_for_worker = run_context.clone();let graph = GraphBuilder::<SpawnParallelState, SpawnParallelUpdate>::new().set_reducer(ClosureStateReducer::new(|mut state: SpawnParallelState, update: SpawnParallelUpdate| {@@ -262,6 +264,7 @@ pub(crate) async fn run_spawn_parallel_execution_graph(phases[2],move |state: SpawnParallelState, _ctx: NodeContext| {let cancel = cancel_for_worker.clone();+ let run_context = run_context_for_worker.clone();async move {if state.cancelled_phase.is_some() || state.rejection.is_some() {return Ok(NodeResult::Update(SpawnParallelUpdate::PhaseEntered(@@ -275,22 +278,26 @@ pub(crate) async fn run_spawn_parallel_execution_graph();return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled("worker")));}- let fanned =- match run_spawn_parallel_workers(state.prepared, state.action_root, cancel)- .await- {- Ok(fanned) => fanned,- Err(TinyAgentsError::Cancelled) => {- tracing::debug!(- phase = "worker",- "[spawn_parallel_agents] fanout_cancelled"- );- return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(- "worker",- )));- }- Err(err) => return Err(err),- };+ let fanned = match run_spawn_parallel_workers(+ state.prepared,+ state.action_root,+ cancel,+ run_context,+ )+ .await+ {+ Ok(fanned) => fanned,+ Err(TinyAgentsError::Cancelled) => {+ tracing::debug!(+ phase = "worker",+ "[spawn_parallel_agents] fanout_cancelled"+ );+ return Ok(NodeResult::Update(SpawnParallelUpdate::Cancelled(+ "worker",+ )));+ }+ Err(err) => return Err(err),+ };Ok(NodeResult::Update(SpawnParallelUpdate::Fanned(fanned)))}},diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rsindex fe05cdc7cd..cdf3cf573d 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/run.rs@@ -29,6 +29,7 @@ pub(crate) async fn run_spawn_parallel_graph_with_workspace(args,CancellationToken::new(),parent_workspace_descriptor,+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),).await}@@ -37,13 +38,20 @@ pub(crate) async fn run_spawn_parallel_graph_with_cancellation(args: serde_json::Value,cancel: CancellationToken,) -> Result<SpawnParallelGraphOutcome, String> {- run_spawn_parallel_graph_with_cancellation_and_workspace(args, cancel, None).await+ run_spawn_parallel_graph_with_cancellation_and_workspace(+ args,+ cancel,+ None,+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),+ )+ .await}pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(args: serde_json::Value,cancel: CancellationToken,parent_workspace_descriptor: Option<WorkspaceDescriptor>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> Result<SpawnParallelGraphOutcome, String> {let tasks = match validate_spawn_parallel_tool_request(&args, None) {Ok(tasks) => tasks,@@ -92,6 +100,7 @@ pub(crate) async fn run_spawn_parallel_graph_with_cancellation_and_workspace(action_root,cancel,parent_workspace_descriptor,+ run_context,).await?;match &outcome {diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rsindex 11fdf0c925..61cd710c1c 100644--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/workers.rs@@ -16,6 +16,7 @@ pub(crate) async fn run_spawn_parallel_workers(prepared: Vec<SpawnParallelWorker>,action_root: Option<PathBuf>,cancel: CancellationToken,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> tinyagents_harness::Result<Vec<ParallelAgentResult>> {let n = prepared.len();let serial_write_count = prepared@@ -43,13 +44,16 @@ pub(crate) async fn run_spawn_parallel_workers();return Err(TinyAgentsError::Cancelled);}- results.push(run_one_parallel_task(worker, action_root.clone()).await);+ results.push(+ run_one_parallel_task(worker, action_root.clone(), run_context.child()).await,+ );}return Ok(results);}let max_concurrency = prepared.len().max(1);let action_root_for_workers = action_root.clone();+ let run_context_for_workers = run_context.clone();tracing::debug!(target: "orchestration",workers = n,@@ -62,7 +66,8 @@ pub(crate) async fn run_spawn_parallel_workers(.with_cancellation(cancel);let outcome = map_reduce(prepared, options, move |_i, worker| {let repo_root = action_root_for_workers.clone();- async move { Ok(run_one_parallel_task(worker, repo_root).await) }+ let run_context = run_context_for_workers.child();+ async move { Ok(run_one_parallel_task(worker, repo_root, run_context).await) }}).await?;@@ -90,6 +95,7 @@ pub(crate) async fn run_spawn_parallel_workers(async fn run_one_parallel_task(worker: SpawnParallelWorker,repo_root: Option<PathBuf>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> ParallelAgentResult {let SpawnParallelWorker {definition,@@ -122,6 +128,8 @@ async fn run_one_parallel_task(context: task.context.clone(),model_override: None,task_id: Some(task_id.clone()),+ thread_id: None,+ run_context,worker_thread_id: None,initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rsindex c37756a314..a9e7f4a0f5 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/scout_run.rs@@ -8,7 +8,6 @@ use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunError, SubagentRunOptions, SubagentRunStatus,};use crate::agent::progress::AgentProgress;-use crate::agent::tinyagents::thread_context::current_thread_id;use crate::core::bus::BUS;use crate::core::events::DomainEvent;use tinytools::ToolResult;@@ -128,7 +127,7 @@ pub async fn run_context_scout_with_catalog(focus: Option<&str>,tool_catalog: &str,) -> anyhow::Result<ToolResult> {- run_context_scout_with_catalog_and_workspace(question, focus, tool_catalog, None).await+ run_context_scout_with_catalog_and_workspace(question, focus, tool_catalog, None, None).await}/// The text [`log_scout_failure`] classifies: a failed run flattened into one@@ -209,6 +208,7 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace(focus: Option<&str>,tool_catalog: &str,parent_workspace_descriptor: Option<WorkspaceDescriptor>,+ thread_id: Option<String>,) -> anyhow::Result<ToolResult> {let question = question.trim().to_string();let focus = focus.map(|s| s.to_string());@@ -300,6 +300,8 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace(}let options = SubagentRunOptions {task_id: Some(task_id.clone()),+ thread_id: thread_id.clone(),+ run_context: Default::default(),worktree_action_dir,workspace_descriptor: parent_workspace_descriptor,..Default::default()@@ -393,7 +395,7 @@ pub(super) async fn run_context_scout_with_catalog_and_workspace(// context-gathering path just seeds a goal on the first scout of// a fresh chat so the harness has something to steer toward.// Best-effort — never fails the call.- if let (Some(parent), Some(thread_id)) = (current_parent(), current_thread_id()) {+ if let (Some(parent), Some(thread_id)) = (current_parent(), thread_id) {if let Some(objective) = AgentPrepareContextTool::parse_proposed_goal(&bundle) {match crate::agent::goals::store::set_if_absent(&parent.workspace_dir,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rsindex 80e4ec4b05..206c0827ab 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/agent_prepare_context/tool.rs@@ -214,6 +214,9 @@ impl Tool for AgentPrepareContextTool {focus,&tool_catalog,tool_context.and_then(|ctx| ctx.workspace().cloned()),+ tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned),).await}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rsindex 6d8933b667..8b6bd75a29 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs@@ -5,7 +5,7 @@ use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;use crate::agent::orchestration::{running_subagents, subagent_sessions};use async_trait::async_trait;use serde_json::json;-use tinytools::{PermissionLevel, Tool, ToolResult};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};pub struct CloseSubagentTool;@@ -50,6 +50,16 @@ impl Tool for CloseSubagentTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {let subagent_session_id = args.get("subagent_session_id").and_then(|v| v.as_str())@@ -70,11 +80,11 @@ impl Tool for CloseSubagentTool {}};let store = SubagentSessionStore::new(parent.workspace_dir.clone());- let parent_thread_id = crate::agent::tinyagents::thread_context::current_thread_id();+ let parent_thread_id = tool_context.and_then(ToolRunContext::thread_id);let owned = match subagent_sessions::list_for_parent(&store,&parent.session_id,- parent_thread_id.as_deref(),+ parent_thread_id,) {Ok(sessions) => sessions.iter()@@ -89,7 +99,7 @@ impl Tool for CloseSubagentTool {log::warn!("[subagent_reuse] close rejected parent_session={} parent_thread_id={} subagent_session_id={}",parent.session_id,- parent_thread_id.as_deref().unwrap_or("none"),+ parent_thread_id.unwrap_or("none"),subagent_session_id);return Ok(ToolResult::error(diff --git a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rsindex cb3971d335..fa4bb558c9 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent.rs@@ -368,6 +368,10 @@ impl Tool for ContinueSubagentTool {context: None,model_override: checkpoint.model_override,task_id: Some(task_id.clone()),+ thread_id: tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned),+ run_context: Default::default(),worker_thread_id: checkpoint.worker_thread_id.clone(),initial_history: Some(history),checkpoint_dir: Some(checkpoint_dir.clone()),diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rsindex 11635cda50..68227a357d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs@@ -118,8 +118,7 @@ pub(crate) async fn dispatch_subagent(// stateless builder (the "day 0 context" bug).if mode == DispatchMode::PreferAsync {let has_parent_turn = parent_ctx.is_some();- let has_delivery_thread =- crate::agent::tinyagents::thread_context::current_thread_id().is_some();+ let has_delivery_thread = tool_context.and_then(ToolRunContext::thread_id).is_some();if has_parent_turn && has_delivery_thread {let mut async_args = serde_json::json!({"agent_id": definition.id.clone(),@@ -239,6 +238,10 @@ pub(crate) async fn dispatch_subagent(context: None,model_override: model_override.map(str::to_string),task_id: Some(task_id.clone()),+ thread_id: tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned),+ run_context: Default::default(),worker_thread_id: None,initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs b/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rsindex d23f53286c..0ee2b51fe3 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs@@ -10,7 +10,7 @@ use crate::agent::orchestration::{use async_trait::async_trait;use serde_json::json;use tinyagents_graph::orchestration::{OrchestrationTaskRecord, OrchestrationTaskStatus};-use tinytools::{PermissionLevel, Tool, ToolResult};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};pub struct ListSubagentsTool;@@ -49,6 +49,16 @@ impl Tool for ListSubagentsTool {}async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(_args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ _args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {let parent = match current_parent() {Some(parent) => parent,None => {@@ -57,13 +67,9 @@ impl Tool for ListSubagentsTool {));}};- let parent_thread_id = crate::agent::tinyagents::thread_context::current_thread_id();+ let parent_thread_id = tool_context.and_then(ToolRunContext::thread_id);let store = SubagentSessionStore::new(parent.workspace_dir.clone());- match subagent_sessions::list_for_parent(- &store,- &parent.session_id,- parent_thread_id.as_deref(),- ) {+ match subagent_sessions::list_for_parent(&store, &parent.session_id, parent_thread_id) {Ok(sessions) => {let summaries: Vec<DurableSubagentSessionSummary> = sessions.iter()@@ -79,7 +85,7 @@ impl Tool for ListSubagentsTool {.collect();log::debug!("[subagent_reuse] list parent_thread_id={} parent_session={} count={}",- parent_thread_id.as_deref().unwrap_or("none"),+ parent_thread_id.unwrap_or("none"),parent.session_id,summaries.len());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 54ffb28993..5c37fef3e0 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@@ -102,8 +102,9 @@ impl SpawnAsyncSubagentTool {let parent_session = parent.session_id.clone();let progress_sink = parent.on_progress.clone();- let parent_thread_id =- crate::agent::tinyagents::thread_context::current_thread_id();+ let parent_thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned);// Async delivery is thread-addressed: the finished result is inserted// back into the parent chat thread as a follow-up turn@@ -392,7 +393,7 @@ impl SpawnAsyncSubagentTool {let background_worktree_action_dir = background_workspace_descriptor.as_ref().map(|descriptor| descriptor.root.clone());- let background_thread_affinity_id = background_worker_thread_id+ let background_thread_id = background_worker_thread_id.clone().unwrap_or_else(|| background_subagent_session_id.clone());let background_initial_history = initial_history;@@ -412,13 +413,11 @@ impl SpawnAsyncSubagentTool {register_parent_thread_id.as_deref().unwrap_or("none"));let background_prompt = add_background_contract(&prompt);- // The detached child starts on a fresh task, and a `tokio::task_local`- // does not cross `tokio::spawn`. The parent's execution context and- // chat thread are already re-installed inside the task for exactly that- // reason; the turn's origin label and its workspace root are the other- // two that have to travel, and they are captured **here**, on the- // spawning task, rather than inside the closure where they would- // already be gone. Without the origin every external-effect tool the+ // The detached child starts on a fresh task. Capture its durable thread+ // identity now and carry it in `SubagentRunOptions`; task-local scope+ // does not cross `tokio::spawn`. The turn's origin label and workspace+ // root are the other values that must travel, and they are captured+ // **here**, on the spawning task. Without the origin every external-effect tool the// child calls reaches the approval gate unlabelled and is refused,// which is the whole of why a delegated coding task could not run a// shell.@@ -430,6 +429,8 @@ impl SpawnAsyncSubagentTool {context,model_override,task_id: Some(background_task_id.clone()),+ thread_id: Some(background_thread_id),+ run_context: Default::default(),worker_thread_id: background_worker_thread_id.clone(),initial_history: background_initial_history,checkpoint_dir: None,@@ -439,13 +440,7 @@ impl SpawnAsyncSubagentTool {};let result = with_parent_context(background_parent, async move {- crate::agent::tinyagents::thread_context::with_thread_id(- background_thread_affinity_id,- async move {- run_subagent(&background_definition, &background_prompt, options).await- },- )- .await+ run_subagent(&background_definition, &background_prompt, options).await}).await;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rsindex f15926946f..a533e8ebf5 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_tool_impl.rs@@ -374,8 +374,10 @@ impl Tool for SpawnSubagentTool {// that both executes it and returns its output. Mirrors the// `has_delivery_thread` fallback the `delegate_*` tools already do in// `dispatch.rs::dispatch_subagent`.- let has_delivery_thread =- crate::agent::tinyagents::thread_context::current_thread_id().is_some();+ let parent_thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned);+ let has_delivery_thread = parent_thread_id.is_some();if !blocking && !has_delivery_thread {log::info!("[spawn_subagent] async delegation requested for '{}' but no delivery thread \@@ -420,8 +422,7 @@ impl Tool for SpawnSubagentTool {// uses. Best-effort: with no parent context or thread store the run// still proceeds live-only (`worker_thread_id: None`).let worker_thread_id = current_parent().and_then(|p| {- let parent_thread_id =- crate::agent::tinyagents::thread_context::current_thread_id()?;+ let parent_thread_id = parent_thread_id.as_ref()?;let title: String = prompt.chars().take(60).collect();super::worker_thread::create_worker_thread(p.workspace_dir.clone(),@@ -481,6 +482,8 @@ impl Tool for SpawnSubagentTool {context,model_override,task_id: Some(task_id.clone()),+ thread_id: parent_thread_id,+ run_context: Default::default(),worker_thread_id: worker_thread_id.clone(),initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rsindex c63811b0cf..c180afe857 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_worker_thread.rs@@ -153,8 +153,10 @@ impl Tool for SpawnWorkerThreadTool {// ── Depth Guard ────────────────────────────────────────────────// Check if the current thread is already a worker thread.- let current_thread_id = crate::agent::tinyagents::thread_context::current_thread_id()- .unwrap_or_else(|| "unknown".to_string());+ let current_thread_id = tool_context+ .and_then(ToolRunContext::thread_id)+ .unwrap_or("unknown")+ .to_string();tracing::info!(agent_id = %agent_id,@@ -247,6 +249,10 @@ impl Tool for SpawnWorkerThreadTool {context,model_override,task_id: None,+ thread_id: tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned),+ run_context: Default::default(),worker_thread_id: Some(worker_thread_id.clone()),initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/tinyagents/host/agent_memory.rs b/crates/openhuman-core/src/agent/tinyagents/host/agent_memory.rsindex dfb50fa330..a0ca7b282e 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/agent_memory.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/agent_memory.rs@@ -356,21 +356,15 @@ impl AgentMemory for OpenHumanAgentMemory {async fn recall(&self, req: RecallRequest) -> TaResult<Vec<MemoryItem>> {let limit = self.effective_limit(req.limit);let session = req.thread_id.as_ref().map(|t| t.as_str());- // Bound outside the `RecallOpts` literal: the struct borrows it.- let current_thread_id_ref = crate::agent::tinyagents::thread_context::current_thread_id();let opts = RecallOpts {namespace: Some(self.namespace.as_str()),category: None,session_id: session,min_score: Some(self.min_score),- // The self-echo exclusion, passed explicitly rather than left to the- // engine's `thread_context` task-local. That task-local is only- // visible to an in-process engine; once memory is reached through- // the loadable module it reads as absent on the far side, and- // absent means "exclude nothing" — the agent gets handed back what- // it just said. Resolving it here keeps the behaviour identical on- // both paths.+ // The self-echo exclusion is the request's explicit thread hint,+ // rather than an engine task-local. This adapter can run through a+ // loadable module, where ambient task-local state is absent.//// It does not fight `session_id` above. The engine filters only// document-kind hits by this field, while `session_id` and@@ -378,14 +372,7 @@ impl AgentMemory for OpenHumanAgentMemory {// to a session and excluding it is not a contradiction, and a// thread hint still narrows *to* that session.//- // Ambient first, the request's thread as fallback — not either- // alone. Inside a turn the task-local names the thread whose- // trigger was auto-saved, and when both are set they agree. But a- // recall reaching this adapter *outside* a turn (an RPC-driven- // recall carrying a thread hint) has no ambient value, and its- // hint names exactly the thread whose saved trigger would echo- // back. Dropping the fallback reintroduces the echo on that path.- exclude_session_id: current_thread_id_ref.as_deref().or(session),+ exclude_session_id: session,// Widening past the requested session is a wiring decision, never a// runtime hint.cross_session: self.cross_session,diff --git a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rsindex e20973d05e..4054bcd5dc 100644--- a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs+++ b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs@@ -238,6 +238,10 @@ impl Tool for DelegateToPersonalityTool {toolkit_override: None,skill_filter_override: None,task_id: None,+ thread_id: tool_context+ .and_then(ToolRunContext::thread_id)+ .map(str::to_owned),+ run_context: Default::default(),worker_thread_id: None,initial_history: None,checkpoint_dir: None,diff --git a/crates/openhuman-core/src/agent/tools/todo.rs b/crates/openhuman-core/src/agent/tools/todo.rsindex 0223559e44..cb145bc648 100644--- a/crates/openhuman-core/src/agent/tools/todo.rs+++ b/crates/openhuman-core/src/agent/tools/todo.rs@@ -3,16 +3,15 @@//! Dispatches on the `op` field so a single tool exposes//! `add` / `edit` / `update_status` / `remove` / `replace` / `clear` ///! `list`. The board is persisted to the active thread (when there is-//! one) via [`crate::agent::todos::ops`]; without a thread context the+//! one) via [`crate::agent::todos::ops`]; without a caller thread the//! tool falls back to a process-global scratch list. Returns a markdown//! rendering so transcripts read cleanly.-use crate::agent::tinyagents::thread_context;use crate::agent::todos::ops::{self, BoardLocation, CardPatch};use crate::agent::todos::types::{TaskApprovalMode, TaskBoardCard, TaskCardStatus};use async_trait::async_trait;use serde_json::json;-use tinytools::{PermissionLevel, Tool, ToolResult};+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};pub struct TodoTool;@@ -99,6 +98,16 @@ impl Tool for TodoTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {let op = args.get("op").and_then(|v| v.as_str())@@ -106,7 +115,7 @@ impl Tool for TodoTool {.trim().to_string();- let location = current_location();+ let location = current_location(tool_context);tracing::debug!(op = %op, thread_id = ?location.thread_id(), "[tool][todo] dispatch");let result = match op.as_str() {@@ -197,7 +206,7 @@ async fn default_task_approval_mode() -> Option<TaskApprovalMode> {}}-fn current_location() -> BoardLocation {+fn current_location(tool_context: Option<&dyn ToolRunContext>) -> BoardLocation {let Some(parent) = crate::agent::harness::fork_context::current_parent() else {return BoardLocation::Scratch;};@@ -210,12 +219,12 @@ fn current_location() -> BoardLocation {thread_id: ops::ORCHESTRATOR_TASKS_THREAD_ID.to_string(),};}- let Some(thread_id) = thread_context::current_thread_id() else {+ let Some(thread_id) = tool_context.and_then(ToolRunContext::thread_id) else {return BoardLocation::Scratch;};BoardLocation::Thread {workspace_dir: parent.workspace_dir.clone(),- thread_id,+ thread_id: thread_id.to_owned(),}}diff --git a/crates/openhuman-core/src/memory/tools/search/hybrid_search.rs b/crates/openhuman-core/src/memory/tools/search/hybrid_search.rsindex 623c97926d..4c5667ef10 100644--- a/crates/openhuman-core/src/memory/tools/search/hybrid_search.rs+++ b/crates/openhuman-core/src/memory/tools/search/hybrid_search.rs@@ -12,7 +12,7 @@ use std::fmt::Write;use crate::memory::api::provider::MemoryProvider;use crate::memory::api::types::MemoryItemKind;use crate::memory::ops::guard::active_memory_guard;-use tinytools::{Tool, ToolExposure, ToolResult};+use tinytools::{Tool, ToolCallOptions, ToolExposure, ToolResult, ToolRunContext};pub struct MemoryHybridSearchTool;@@ -206,6 +206,16 @@ impl Tool for MemoryHybridSearchTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_with_context(args, ToolCallOptions::default(), None)+ .await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {let parsed: Args = serde_json::from_value(args).map_err(|e| anyhow::anyhow!("invalid arguments for memory_hybrid_search: {e}"))?;@@ -254,11 +264,10 @@ impl Tool for MemoryHybridSearchTool {})?;// Self-echo guard (agent-agnostic, mirrors `UnifiedMemory::recall`):- // exclude documents auto-saved for the ambient chat thread (set by- // the web channel around the turn) so a search issued mid-turn+ // exclude documents auto-saved for the caller chat thread so a search issued mid-turn// never retrieves the very request that triggered it. `None`// outside a chat turn — unchanged behavior for cron/CLI/tests.- let exclude_session_id = crate::agent::tinyagents::thread_context::current_thread_id();+ let exclude_session_id = tool_context.and_then(ToolRunContext::thread_id);if let Some(ref excluded) = exclude_session_id {log::debug!("[tool][memory_hybrid_search] applying same-session exclusion exclude_session_id={excluded}"@@ -269,7 +278,7 @@ impl Tool for MemoryHybridSearchTool {&parsed.namespace,&parsed.query,limit as usize,- exclude_session_id.as_deref(),+ exclude_session_id,).await.map_err(|e| anyhow::anyhow!("memory_hybrid_search: query failed: {e}"))?;diff --git a/docs/specs/agent-runtime-upstream-boundary.md b/docs/specs/agent-runtime-upstream-boundary.mdindex 24ae7f1745..214641af7c 100644--- a/docs/specs/agent-runtime-upstream-boundary.md+++ b/docs/specs/agent-runtime-upstream-boundary.md@@ -160,6 +160,12 @@ canonical call. OpenHuman tools implement `tinytools::Tool` directly; the`SharedToolAdapter`, `ToolAdapter`, `spec_to_schema`, and`execute_openhuman_tool` bridge disappear.+Thread ownership follows the same boundary: a tool reads its caller thread+only from `ToolRunContext::thread_id()`. Recursive and detached sub-agent+launches copy that explicit value into their owned run options before spawning;+they do not re-scope a thread task-local. Memory recall receives its session+and exclusion identity from TinyAgents' `RecallRequest`.+All users import parsing APIs from `tinytools_agent::{...}` or`tinytools_agent::dialect::{...}`. Delete`tinyagents_harness::tool_calling`, the former OpenHuman `agent::dispatcher`