Skip to content

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

refactor(orchestration): route delegation through the delegate_graph tool

Steven Enamakel76b7b83a9978
diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rs
index ee3ff81777..04fc906761 100644
--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs
@@ -18,7 +18,7 @@
use std::sync::Arc;
use crate::agent::subagent_host::{
- run_subagent_with_parent, SubagentRunOptions, SubagentRunStatus,
+ run_subagent_via_driver_tool, SubagentRunOptions, SubagentRunStatus,
};
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent_registry::host_definition::AgentDefinition;
@@ -29,7 +29,11 @@ use tinyagents_graph::delegation::{
DelegationConfig, DelegationStage, DelegationStageOutput, DelegationState,
};
use tinyagents_harness::context::{RunConfig, RunContext};
-use tinytools::WorkspaceDescriptor;
+use tinyagents_harness::tool::ToolDispatch;
+use tinytools::{
+ PermissionLevel, ToolCallOptions, ToolCategory, ToolResult, ToolScope, ToolTimeout,
+ WorkspaceDescriptor,
+};
const LOG_TARGET: &str = "agent_orchestration::delegation";
@@ -64,12 +68,11 @@ pub(crate) async fn run_subagent_delegation_with_parent_context(
max_revisions: usize,
parent_workspace_descriptor: Option<WorkspaceDescriptor>,
live_parent: Arc<RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,
-) -> Result<DelegationState, String> {
+) -> Result<ToolResult, 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 graph_cancellation = live_parent.cancellation.clone();
// Durable graph checkpoints live in the storage backend, in the acting
// agent's scope (`DriverCheckpointer`).
let checkpointer = open_delegation_checkpointer(&config)?;
@@ -92,22 +95,22 @@ pub(crate) async fn run_subagent_delegation_with_parent_context(
);
}
- let run = async move {
- // 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 stage_parent = live_parent.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 stage_parent = stage_parent.clone();
- async move {
+ let invocation_agent_id = definition.id.clone();
+ let invocation_task_prompt = task_prompt.clone();
+ let stage_parent = live_parent.clone();
+ let run_stage = move |_stage_args: serde_json::Value,
+ stage: DelegationStage,
+ state: DelegationState| {
+ let definition = definition.clone();
+ let task = task_prompt.clone();
+ let workspace_descriptor = parent_workspace_descriptor.clone();
+ let stage_parent = stage_parent.clone();
+ async move {
let prompt = build_stage_prompt(stage, &task, &state);
let (stage_parent, stage_context) =
stage_run_contexts(&stage_parent, workspace_descriptor.clone())
.map_err(|error| format!("delegation stage context: {error}"))?;
- match run_subagent_with_parent(
+ match run_subagent_via_driver_tool(
&stage_parent,
definition,
prompt.clone(),
@@ -115,7 +118,7 @@ pub(crate) async fn run_subagent_delegation_with_parent_context(
)
.await
{
- Ok(outcome) => {
+ Ok((outcome, _public_job_id)) => {
let should_emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
match outcome.status {
SubagentRunStatus::Completed => {}
@@ -190,32 +193,97 @@ pub(crate) async fn run_subagent_delegation_with_parent_context(
}
Err(e) => Err(format!("delegation stage {stage:?} failed: {e}")),
}
- }
- };
-
+ }
+ };
+ let config_checkpointer = Arc::clone(&checkpointer);
+ let config_thread_id = thread_id.clone();
+ let config_factory = move |_state: &(), parent: &RunContext<OpenHumanRunContext>, _args: &serde_json::Value| {
let mut delegation_config = DelegationConfig {
max_revisions,
- checkpointer: Some(checkpointer),
- thread_id: Some(thread_id),
- 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
- // stays off here until a human-review delegation surface wires it.
+ checkpointer: Some(Arc::clone(&config_checkpointer)),
+ thread_id: Some(config_thread_id.clone()),
+ cancel: parent.cancellation.clone(),
+ // Automated delegation: preserve the host's existing worker-output
+ // review policy while the generic tool owns graph lifecycle mechanics.
..DelegationConfig::default()
};
- delegation_config.event_sink = Some(Arc::new(tinyagents_graph::GraphTracingSink::new(
- "delegation:graph",
- )));
- // Resume-aware entry (#3884): with today's fresh-per-run `thread_id` this
- // is always a fresh run; reusing a stable `thread_id` resumes from the
- // last checkpoint boundary instead of restarting.
- tinyagents_graph::delegation::run_or_resume_delegation(delegation_config, run_stage)
- .await
- .map(|outcome| outcome.state)
+ delegation_config.event_sink = Some(Arc::new(
+ tinyagents_graph::GraphTracingSink::new("delegation:graph"),
+ ));
+ delegation_config
};
+ let result_agent_id = invocation_agent_id.clone();
+ let tool = tinyagents_orchestration::subagent::DelegationTool::new(
+ config_factory,
+ run_stage,
+ )
+ .with_tool_name("delegate_graph")
+ .with_description("Durable plan, execute, review, and finalize delegation.")
+ .with_parameters(serde_json::json!({
+ "type": "object",
+ "required": ["task"],
+ "properties": {"task": {"type": "string"}}
+ }))
+ .with_resumable_execution()
+ .with_review_approval_policy(
+ tinyagents_orchestration::subagent::ReviewApprovalPolicy::WorkerOutput,
+ )
+ .with_metadata(
+ PermissionLevel::Execute,
+ ToolScope::All,
+ ToolCategory::System,
+ ToolTimeout::Unbounded,
+ )
+ .with_result_projection(move |result| match result {
+ Ok(outcome) if outcome.pending.is_some() => {
+ let pending = outcome.pending.expect("checked above");
+ ToolResult::json(serde_json::json!({
+ "status": "pending",
+ "state": outcome.state,
+ "pending": {
+ "interrupt_id": pending.interrupt_id,
+ "node": pending.node,
+ "payload": pending.payload,
+ "thread_id": pending.thread_id,
+ }
+ }))
+ }
+ Ok(outcome) if outcome.state.cancelled => ToolResult::error(format!(
+ "delegate_graph cancelled for '{result_agent_id}'."
+ )),
+ Ok(outcome) => {
+ let state = outcome.state;
+ let final_output = state
+ .final_output
+ .unwrap_or_else(|| "(delegation produced no final output)".to_string());
+ let note = if state.revisions > 0 {
+ " (after revision)"
+ } else {
+ ""
+ };
+ ToolResult::success(format!(
+ "[Delegated to {result_agent_id}{note}, {} review pass(es)]\n{final_output}",
+ state.reviews.len()
+ ))
+ }
+ Err(error) => ToolResult::error(format!(
+ "delegate_graph failed for '{result_agent_id}': {error}"
+ )),
+ });
- run.await
+ tool.execute(
+ &(),
+ tinyagents_harness::CallId::new(format!("delegation-{thread_id}")),
+ serde_json::json!({
+ "agent_id": invocation_agent_id,
+ "task": invocation_task_prompt,
+ "max_revisions": max_revisions
+ }),
+ ToolCallOptions::default(),
+ &live_parent,
+ )
+ .await
+ .map_err(|error| format!("delegate_graph failed: {error}"))
}
/// Per-stage prompt builder: each stage sees the task plus the accumulated state
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs
index 61a88862e7..9ed87bab3a 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs
@@ -257,25 +257,7 @@ impl DelegateGraphTool {
)
.await
{
- Ok(state) => {
- if state.cancelled {
- return Ok(ToolResult::error(format!(
- "delegate_graph cancelled for '{agent_id}'."
- )));
- }
- let final_output = state
- .final_output
- .unwrap_or_else(|| "(delegation produced no final output)".to_string());
- let note = if state.revisions > 0 {
- " (after revision)"
- } else {
- ""
- };
- Ok(ToolResult::success(format!(
- "[Delegated to {agent_id}{note}, {} review pass(es)]\n{final_output}",
- state.reviews.len()
- )))
- }
+ Ok(result) => Ok(result),
Err(e) => Ok(ToolResult::error(format!(
"delegate_graph failed for '{agent_id}': {e}"
))),