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
fix(agent): dispatch all delegation tools with parent context
Steven Enamakel941ccbf83ba8
diff --git a/crates/openhuman-core/src/agent/orchestration/README.md b/crates/openhuman-core/src/agent/orchestration/README.mdindex 98aa64de13..dcdf040fee 100644--- a/crates/openhuman-core/src/agent/orchestration/README.md+++ b/crates/openhuman-core/src/agent/orchestration/README.md@@ -131,7 +131,10 @@ OpenHumanRunContext>` wrappers and fork the parent carrier for every child,so cancellation, origin, progress, dispatch state, thread, and workspace stayattached. `delegate_to` retains its concrete enum-to-agent routing table inits schema metadata at registration; it never broadens a call by rebuilding-targets from the global agent registry. Execution itself routes through+targets from the global agent registry. `delegate_graph` has a dedicated typed+registration for its durable plan→execute→review loop, while the optional+config-driven `delegate` registration preserves the configured executor and+races it against the inherited cancellation token. Execution itself routes through`agent::harness::run_subagent`.## Persistencediff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsindex c01fa0ed76..a4f918db28 100644--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs@@ -28,7 +28,6 @@ use tinyagents_graph::delegation::{DelegationConfig, DelegationStage, DelegationStageOutput, DelegationState,};use tinyagents_graph::SqliteCheckpointer;-use tinyagents_harness::CancellationToken;use tinytools::WorkspaceDescriptor;const LOG_TARGET: &str = "agent_orchestration::delegation";@@ -50,12 +49,44 @@ pub(crate) async fn run_subagent_delegation(task_prompt: String,max_revisions: usize,parent_workspace_descriptor: Option<WorkspaceDescriptor>,+) -> Result<DelegationState, String> {+ // 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();+ run_context.parent = current_parent();+ run_subagent_delegation_with_parent_context(+ config,+ definition,+ task_prompt,+ max_revisions,+ parent_workspace_descriptor,+ run_context,+ )+ .await+}++/// Typed live entrypoint for the durable delegation graph.+///+/// The graph does create a durable graph id for its checkpoints, but each+/// stage retains the caller's cancellation, origin, dispatch, progress,+/// conversation thread, and workspace through the supplied carrier.+pub(crate) async fn run_subagent_delegation_with_parent_context(+ config: Arc<Config>,+ definition: AgentDefinition,+ task_prompt: String,+ max_revisions: usize,+ parent_workspace_descriptor: Option<WorkspaceDescriptor>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> Result<DelegationState, String> {let thread_id = format!("delegrun-{}", uuid::Uuid::new_v4());// The graph and every stage share this cancellation token. A stage gets an// owned host carrier before it enters `run_subagent`, rather than making a// fresh context after the graph has spawned work.- let cancellation = CancellationToken::new();+ let parent_context = run_context.parent.clone();+ let stage_context = run_context.clone();+ let graph_cancellation = run_context.cancellation.clone();// Durable graph checkpoints ride the crate's `SqliteCheckpointer` (issue// #4249, 04.3) at a dedicated `graph_checkpoints.db` under the workspace —// a separate SQLite file from OpenHuman's session-db pool, so the crate's@@ -93,18 +124,15 @@ pub(crate) async fn run_subagent_delegation(// Re-entrant per-stage worker: clones its captures each call so the graph// node handler stays `Fn` while each stage dispatches a fresh sub-agent.let parent_workspace_descriptor = parent_workspace_descriptor.clone();- let cancellation = cancellation.clone();- let stage_cancellation = cancellation.clone();+ let stage_cancellation = graph_cancellation.clone();let run_stage = move |stage: DelegationStage, state: DelegationState| {let definition = definition.clone();let task = task_prompt.clone();let workspace_descriptor = parent_workspace_descriptor.clone();let cancellation = stage_cancellation.clone();+ let mut run_context = stage_context.child();async move {let prompt = build_stage_prompt(stage, &task, &state);- let mut run_context =- crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes();- run_context.parent = current_parent();run_context.workspace = workspace_descriptor.clone().or(run_context.workspace);run_context.cancellation = cancellation;match run_subagent(@@ -135,7 +163,7 @@ pub(crate) async fn run_subagent_delegation(max_revisions,checkpointer: Some(checkpointer),thread_id: Some(thread_id),- cancel: cancellation,+ cancel: graph_cancellation,// Automated (non-human-gated) delegation: the reviewer stage decides// approve/revise on its own. The durable human-approval interrupt// (see `tinyagents_graph::delegation::run_delegation_durable`) is opt-in and@@ -150,8 +178,8 @@ pub(crate) async fn run_subagent_delegation(.map(|outcome| outcome.state)};- if current_parent().is_some() {- run.await+ if let Some(parent) = parent_context {+ with_parent_context(parent, run).await} else {let parent = build_root_parent(&config, "delegation_engine", "delegation", "delegation").awaitdiff --git a/crates/openhuman-core/src/agent/orchestration/tools.rs b/crates/openhuman-core/src/agent/orchestration/tools.rsindex bd3f58e40c..63eee9d59d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs@@ -72,6 +72,7 @@ pub use close_subagent::CloseSubagentTool;pub use collapsed_delegation::{CollapsedDelegationTool, DelegateTarget, DELEGATE_TO_TOOL_NAME};pub(crate) use continue_subagent::ContinueSubagentDispatch;pub use continue_subagent::ContinueSubagentTool;+pub(crate) use delegate_graph::DelegateGraphDispatch;pub use delegate_graph::DelegateGraphTool;pub use list_subagents::ListSubagentsTool;pub use skill_delegation::{SkillDelegationTool, INTEGRATIONS_DELEGATE_TOOL_NAME};diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rsindex 49e76c84c4..ed16b48526 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs@@ -11,11 +11,13 @@//! loop; use `spawn_subagent` for a single focused hand-off.use crate::agent::harness::definition::AgentDefinitionRegistry;-use crate::agent::orchestration::delegation::run_subagent_delegation;+use crate::agent::orchestration::delegation::run_subagent_delegation_with_parent_context;use crate::config::Config;use async_trait::async_trait;use serde_json::json;use std::sync::Arc;+use tinyagents_harness::context::RunContext;+use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};use tinytools::ToolRunContext;use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};@@ -27,6 +29,41 @@ const MAX_MAX_REVISIONS: usize = 5;/// Runs the durable multi-stage delegation graph for a chosen sub-agent.pub struct DelegateGraphTool;+/// Typed harness dispatch for the durable graph delegation tool. This must be+/// registered before the synthesized `delegate_*` family: `delegate_graph`+/// has its own plan→execute→review semantics and is not an archetype target.+pub(crate) struct DelegateGraphDispatch {+ tool: Arc<dyn Tool>,+}++impl DelegateGraphDispatch {+ pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {+ Self { tool }+ }+}++#[async_trait]+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>+ for DelegateGraphDispatch+{+ fn tool(&self) -> Arc<dyn Tool> {+ self.tool.clone()+ }++ async fn execute(+ &self,+ _state: &(),+ arguments: serde_json::Value,+ _options: ToolCallOptions,+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let context = ToolExecutionContext::from_run_context(parent);+ DelegateGraphTool::new()+ .execute_with_parent_context(arguments, Some(&context), parent.data.child())+ .await+ }+}+impl Default for DelegateGraphTool {fn default() -> Self {Self::new()@@ -109,6 +146,23 @@ impl Tool for DelegateGraphTool {args: serde_json::Value,_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+ }+}++impl DelegateGraphTool {+ /// Execute the concrete durable graph with an explicit child carrier.+ pub(crate) async fn execute_with_parent_context(+ &self,+ args: serde_json::Value,+ tool_context: Option<&dyn ToolRunContext>,+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,) -> anyhow::Result<ToolResult> {let agent_id = match args.get("agent_id").and_then(|v| v.as_str()) {Some(s) if !s.trim().is_empty() => s.trim().to_string(),@@ -150,12 +204,15 @@ impl Tool for DelegateGraphTool {}};- match run_subagent_delegation(+ match run_subagent_delegation_with_parent_context(config,definition,task,max_revisions,- tool_context.and_then(|ctx| ctx.workspace().cloned()),+ tool_context+ .and_then(|ctx| ctx.workspace().cloned())+ .or_else(|| run_context.workspace.clone()),+ run_context,).await{diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rsindex 6e6ff6ef3f..97b0bb092d 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs@@ -52,7 +52,22 @@ impl DelegationDispatch {.collect();DelegationDispatchKind::Integrations { connected_toolkits }}- name if name.starts_with("delegate_") => DelegationDispatchKind::Archetype,+ // Only synthesized archetype delegate names enter this path.+ // `delegate_graph` is a concrete durable graph tool with its own+ // typed dispatcher, and arbitrary `delegate_*` tools must not be+ // mistaken for an agent target merely because of their spelling.+ name if AgentDefinitionRegistry::global().is_some_and(|registry| {+ registry.list().into_iter().any(|definition| {+ definition+ .delegate_name+ .clone()+ .unwrap_or_else(|| format!("delegate_{}", definition.id))+ == name+ })+ }) =>+ {+ DelegationDispatchKind::Archetype+ }_ => return None,};Some(Self { tool, kind })diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rsindex 6488b1e898..b8fe76b9e0 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs@@ -6,7 +6,10 @@ use tinytools::Tool;use super::super::collapsed_delegation::{dispatch_targets_from_schema, CollapsedDelegationTool, DelegateTarget,};-use crate::agent::tools::AskClarificationTool;+use super::super::delegate_graph::DelegateGraphDispatch;+use crate::agent::tools::{AskClarificationTool, DelegateToolDispatch};+use tinyagents_harness::context::RunConfig;+use tinyagents_harness::tool::ToolDispatch;struct DelegationRegistrationTool {name: &'static str,@@ -34,6 +37,7 @@ impl Tool for DelegationRegistrationTool {#[test]fn typed_dispatch_registration_recognises_every_synthesised_delegate_surface() {+ let _ = crate::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins();let collapsed: Arc<dyn Tool> = Arc::new(CollapsedDelegationTool::for_targets(vec![DelegateTarget {tool_name: "research".to_string(),@@ -63,6 +67,71 @@ fn typed_dispatch_registration_recognises_every_synthesised_delegate_surface() {}}+#[test]+fn delegate_graph_is_not_misclassified_as_an_archetype_delegate() {+ let graph: Arc<dyn Tool> = Arc::new(DelegationRegistrationTool {+ name: "delegate_graph",+ parameters: serde_json::json!({}),+ });+ assert!(+ DelegationDispatch::for_tool(graph).is_none(),+ "delegate_graph must retain its dedicated durable-graph dispatcher"+ );+}++#[tokio::test]+async fn delegate_graph_dispatch_uses_its_durable_graph_argument_path() {+ let tool: Arc<dyn Tool> = Arc::new(DelegationRegistrationTool {+ name: "delegate_graph",+ parameters: serde_json::json!({}),+ });+ let dispatch = DelegateGraphDispatch::new(tool);+ let parent = crate::agent::tinyagents::host::OpenHumanRunContext::new()+ .into_tinyagents(RunConfig::new("delegate-graph-parent"));++ let result = dispatch+ .execute(+ &(),+ serde_json::json!({"task": "review this change"}),+ tinytools::ToolCallOptions::default(),+ &parent,+ )+ .await+ .expect("dedicated dispatcher returns a tool result");+ assert!(result.is_error);+ assert!(+ result.output().contains("`agent_id` is required"),+ "delegate_graph must execute its concrete graph validation, not an archetype lookup: {}",+ result.output()+ );+}++#[tokio::test]+async fn config_delegate_dispatch_honours_the_parent_cancellation_token() {+ let tool: Arc<dyn Tool> = Arc::new(DelegationRegistrationTool {+ name: "delegate",+ parameters: serde_json::json!({}),+ });+ let dispatch = DelegateToolDispatch::new(tool);+ let cancellation = tinyagents_harness::CancellationToken::new();+ let parent = crate::agent::tinyagents::host::OpenHumanRunContext::new()+ .with_cancellation(cancellation.clone())+ .into_tinyagents(RunConfig::new("config-delegate-parent").with_thread("thread-parent"));+ cancellation.cancel();++ let result = dispatch+ .execute(+ &(),+ serde_json::json!({"agent": "configured", "prompt": "work"}),+ tinytools::ToolCallOptions::default(),+ &parent,+ )+ .await+ .expect("cancellation is reported as a tool result");+ assert!(result.is_error);+ assert!(result.output().contains("cancelled"), "{}", result.output());+}+#[test]fn collapsed_dispatch_mapping_has_exact_advertised_vocabulary_and_rejects_drift() {let tool = CollapsedDelegationTool::for_targets(vec![diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rsindex 40b6263744..1d3173dd66 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs@@ -12,14 +12,14 @@ use tinyagents_registry::{};use crate::agent::orchestration::tools::{- AgentPrepareContextDispatch, ContinueSubagentDispatch, DelegationDispatch,- SpawnAsyncSubagentDispatch, SpawnParallelAgentsDispatch, SpawnSubagentDispatch,- SpawnWorkerThreadDispatch,+ AgentPrepareContextDispatch, ContinueSubagentDispatch, DelegateGraphDispatch,+ DelegationDispatch, SpawnAsyncSubagentDispatch, SpawnParallelAgentsDispatch,+ SpawnSubagentDispatch, SpawnWorkerThreadDispatch,};use crate::agent::tinyagents::host::OpenHumanRunContext;use crate::agent::tinyagents::tools::{CanonicalSharedToolAdapter, EarlyExitHook};use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;-use crate::agent::tools::DelegateToPersonalityDispatch;+use crate::agent::tools::{DelegateToPersonalityDispatch, DelegateToolDispatch};/// Register every admitted tool from `tool_sets` onto `harness` (and its/// `capability_registry` projection), project the visible agent set as@@ -120,6 +120,10 @@ pub(super) fn register_turn_tools_and_agents(harness.register_tool_dispatch(Arc::new(DelegateToPersonalityDispatch::new(adapter,)));+ } else if name == "delegate_graph" {+ harness.register_tool_dispatch(Arc::new(DelegateGraphDispatch::new(adapter)));+ } else if name == "delegate" {+ harness.register_tool_dispatch(Arc::new(DelegateToolDispatch::new(adapter)));} else if let Some(dispatch) = DelegationDispatch::for_tool(adapter.clone()) {harness.register_tool_dispatch(Arc::new(dispatch));} else {diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rsindex 061e68ee7e..e7b7ff8c47 100644--- a/crates/openhuman-core/src/agent/tools.rs+++ b/crates/openhuman-core/src/agent/tools.rs@@ -44,6 +44,7 @@ mod update_task;pub use ask_clarification::AskClarificationTool;pub use delegate::DelegateTool;+pub(crate) use delegate::DelegateToolDispatch;pub(crate) use delegate_to_personality::DelegateToPersonalityDispatch;pub use delegate_to_personality::DelegateToPersonalityTool;pub use plan_exit::{PlanExitTool, PLAN_EXIT_MARKER};diff --git a/crates/openhuman-core/src/agent/tools/delegate.rs b/crates/openhuman-core/src/agent/tools/delegate.rsindex 0fdef961ab..4ab35df98a 100644--- a/crates/openhuman-core/src/agent/tools/delegate.rs+++ b/crates/openhuman-core/src/agent/tools/delegate.rs@@ -10,9 +10,11 @@ use serde_json::json;use std::collections::HashMap;use std::sync::Arc;use std::time::Duration;+use tinyagents_harness::context::RunContext;+use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};use tinyinference_llm::message::Message;use tinyinference_llm::model::{ChatModel, ModelRequest};-use tinytools::{Tool, ToolResult};+use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};/// Tool that delegates a subtask to a named agent with a different/// provider/model configuration. Enables multi-agent workflows where@@ -27,6 +29,48 @@ pub struct DelegateTool {depth: u32,}+/// Typed harness dispatch for the config-defined `delegate` tool.+///+/// The configured tool remains the canonical executor (and therefore retains+/// its configured agents, model routing, and security policy); this wrapper+/// supplies the live thread/workspace context and makes cancellation explicit+/// instead of relying on a task-local carrier.+pub(crate) struct DelegateToolDispatch {+ tool: Arc<dyn Tool>,+}++impl DelegateToolDispatch {+ pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {+ Self { tool }+ }+}++#[async_trait]+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>+ for DelegateToolDispatch+{+ fn tool(&self) -> Arc<dyn Tool> {+ self.tool.clone()+ }++ async fn execute(+ &self,+ _state: &(),+ arguments: serde_json::Value,+ options: ToolCallOptions,+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ ) -> anyhow::Result<ToolResult> {+ let context = ToolExecutionContext::from_run_context(parent);+ let child = parent.data.child();+ tokio::select! {+ _ = child.cancellation.cancelled() => Ok(ToolResult::error(+ "delegate: cancelled before the configured agent completed"+ )),+ result = self.tool.execute_with_context(arguments, options, Some(&context)) => result,+ }+ }+}+impl DelegateTool {pub fn new(agents: HashMap<String, DelegateAgentConfig>,@@ -119,6 +163,25 @@ impl Tool for DelegateTool {}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ self.execute_inner(args, None).await+ }++ async fn execute_with_context(+ &self,+ args: serde_json::Value,+ _options: ToolCallOptions,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ self.execute_inner(args, tool_context).await+ }+}++impl DelegateTool {+ async fn execute_inner(+ &self,+ args: serde_json::Value,+ tool_context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {let agent_name = args.get("agent").and_then(|v| v.as_str())@@ -196,22 +259,29 @@ impl Tool for DelegateTool {let delegate_timeout_secs = tool_execution_timeout_secs();// Wrap the provider call in a timeout to prevent indefinite blocking+ let mut request = ModelRequest::new(+ agent_config+ .system_prompt+ .as_deref()+ .map(Message::system)+ .into_iter()+ .chain(std::iter::once(Message::user(full_prompt)))+ .collect(),+ )+ .with_model(agent_config.model.clone())+ .with_temperature(temperature);+ request.metadata = json!({+ "openhuman": {+ "thread_id": tool_context.and_then(ToolRunContext::thread_id),+ "workspace_root": tool_context+ .and_then(ToolRunContext::workspace)+ .map(|workspace| workspace.root.display().to_string()),+ }+ });+let result = tokio::time::timeout(Duration::from_secs(delegate_timeout_secs),- model.invoke(- &(),- ModelRequest::new(- agent_config- .system_prompt- .as_deref()- .map(Message::system)- .into_iter()- .chain(std::iter::once(Message::user(full_prompt)))- .collect(),- )- .with_model(agent_config.model.clone())- .with_temperature(temperature),- ),+ model.invoke(&(), request),).await;diff --git a/scripts/ci/agent-runtime-boundary-baseline.json b/scripts/ci/agent-runtime-boundary-baseline.jsonindex 8a6b428d2d..6983e90780 100644--- a/scripts/ci/agent-runtime-boundary-baseline.json+++ b/scripts/ci/agent-runtime-boundary-baseline.json@@ -723,21 +723,21 @@{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/delegation.rs",- "line": 107,+ "line": 58,"text": "run_context.parent = current_parent();","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/delegation.rs",- "line": 153,- "text": "if current_parent().is_some() {",+ "line": 182,+ "text": "with_parent_context(parent, run).await","occurrence": 1},{"rule": "openhuman-task-local","path": "crates/openhuman-core/src/agent/orchestration/delegation.rs",- "line": 159,+ "line": 187,"text": "with_parent_context(parent, run).await","occurrence": 1},