Skip to content

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

feat(agent): dispatch delegation through typed parent context

Steven Enamakela71daa648f34
diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rs
index 81972f1a71..c01fa0ed76 100644
--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs
@@ -52,6 +52,10 @@ pub(crate) async fn run_subagent_delegation(
parent_workspace_descriptor: Option<WorkspaceDescriptor>,
) -> 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();
// 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
@@ -89,16 +93,24 @@ 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 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();
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(
&definition,
&prompt,
- delegation_subagent_options(workspace_descriptor),
+ delegation_subagent_options(workspace_descriptor, run_context),
)
.await
{
@@ -123,7 +135,7 @@ pub(crate) async fn run_subagent_delegation(
max_revisions,
checkpointer: Some(checkpointer),
thread_id: Some(thread_id),
- cancel: CancellationToken::new(),
+ cancel: 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
@@ -195,6 +207,7 @@ fn review_approves(output: &str) -> bool {
/// call (so retries/revisions don't collide), everything else inherited.
fn delegation_subagent_options(
workspace_descriptor: Option<WorkspaceDescriptor>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> SubagentRunOptions {
let worktree_action_dir = workspace_descriptor
.as_ref()
@@ -205,8 +218,8 @@ fn delegation_subagent_options(
context: None,
model_override: None,
task_id: None,
- thread_id: None,
- run_context: Default::default(),
+ thread_id: run_context.thread_id.clone(),
+ run_context,
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.rs
index 54412c5a39..0ce1b90a90 100644
--- a/crates/openhuman-core/src/agent/orchestration/ops.rs
+++ b/crates/openhuman-core/src/agent/orchestration/ops.rs
@@ -359,6 +359,20 @@ impl AgentOrchestrationSession {
let parent_worktree_action_dir = parent_workspace_descriptor
.as_ref()
.map(|descriptor| descriptor.root.clone());
+ // This control-plane API crosses a `tokio::spawn` boundary, so retain
+ // the live parent carrier before that boundary. The detached child must
+ // share cancellation, origin, dispatch and progress with its caller;
+ // 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();
+ run_context.parent = Some(parent.clone());
+ run_context.progress = parent.on_progress.clone().or(run_context.progress);
+ run_context.workspace = parent_workspace_descriptor
+ .clone()
+ .or(run_context.workspace);
+ run_context.cancellation = cancellation.clone();
if let Some(descriptor) = parent_workspace_descriptor.as_ref() {
tracing::debug!(
orchestration_id = %orchestration_id,
@@ -376,7 +390,7 @@ impl AgentOrchestrationSession {
model_override: request.model,
task_id: Some(orchestration_id.clone()),
thread_id: None,
- run_context: Default::default(),
+ run_context,
worker_thread_id: None,
initial_history: None,
checkpoint_dir: None,
@@ -425,7 +439,7 @@ impl AgentOrchestrationSession {
self.session_id.clone(),
metadata,
status_rx,
- CancellationToken::new(),
+ cancellation,
handle.abort_handle(),
)
.map_err(|err| {
diff --git a/crates/openhuman-core/src/agent/orchestration/tools.rs b/crates/openhuman-core/src/agent/orchestration/tools.rs
index 31e6a44bd0..bd3f58e40c 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools.rs
@@ -61,7 +61,7 @@ mod wait_subagent;
#[path = "tools/worker_thread.rs"]
mod worker_thread;
-pub(crate) use dispatch::dispatch_subagent;
+pub(crate) use dispatch::{dispatch_subagent, DelegationDispatch};
pub(crate) use agent_prepare_context::AgentPrepareContextDispatch;
pub use agent_prepare_context::{
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
index a5d5e7a1bb..e844f4f4fe 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs
@@ -155,55 +155,74 @@ impl Tool for ArchetypeDelegationTool {
_options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- let raw_prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- if raw_prompt.is_empty() {
- return Ok(ToolResult::error(format!(
- "{}: `prompt` is required",
- self.tool_name
- )));
- }
- let prompt = render_structured_handoff(&raw_prompt, &args);
-
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty());
-
- // Async by default: the delegated specialist runs as a durable,
- // resumable worker and its result comes back as a new chat turn.
- // `blocking: true` is the opt-in for results that must gate this
- // reply. (`dispatch_subagent` itself falls back to blocking when
- // there is no chat thread to deliver an async result into.)
- let blocking = args
- .get("blocking")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- let mode = if blocking {
- super::dispatch::DispatchMode::Blocking
- } else {
- super::dispatch::DispatchMode::PreferAsync
- };
-
- super::dispatch_subagent(
+ execute_archetype_delegation(
&self.agent_id.0,
&self.tool_name,
- &prompt,
- None,
- model_override,
+ args,
tool_context,
- mode,
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),
)
.await
}
}
+/// Execute an archetype hand-off with an explicit child run carrier.
+pub(crate) async fn execute_archetype_delegation(
+ agent_id: &str,
+ tool_name: &str,
+ args: serde_json::Value,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+) -> anyhow::Result<ToolResult> {
+ let raw_prompt = args
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+
+ if raw_prompt.is_empty() {
+ return Ok(ToolResult::error(format!(
+ "{}: `prompt` is required",
+ tool_name
+ )));
+ }
+ let prompt = render_structured_handoff(&raw_prompt, &args);
+
+ let model_override = args
+ .get("model")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+
+ // Async by default: the delegated specialist runs as a durable,
+ // resumable worker and its result comes back as a new chat turn.
+ // `blocking: true` is the opt-in for results that must gate this
+ // reply. (`dispatch_subagent` itself falls back to blocking when
+ // there is no chat thread to deliver an async result into.)
+ let blocking = args
+ .get("blocking")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+ let mode = if blocking {
+ super::dispatch::DispatchMode::Blocking
+ } else {
+ super::dispatch::DispatchMode::PreferAsync
+ };
+
+ super::dispatch_subagent(
+ agent_id,
+ tool_name,
+ &prompt,
+ None,
+ model_override,
+ tool_context,
+ mode,
+ run_context,
+ )
+ .await
+}
+
pub(super) fn render_structured_handoff(prompt: &str, args: &Value) -> String {
let mut out = String::new();
out.push_str("Task:\n");
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
index 4cce3958c2..42d311afec 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation.rs
@@ -229,69 +229,92 @@ impl Tool for CollapsedDelegationTool {
_options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- let requested = args.get("agent").and_then(Value::as_str).map(str::trim);
- let Some(target) = requested.and_then(|agent| self.resolve(agent)) else {
- return Ok(ToolResult::error(format!(
- "`agent` must be one of: {}. Got: {}",
- self.agent_enum().join(", "),
- requested.filter(|s| !s.is_empty()).unwrap_or("(missing)")
- )));
- };
-
- let raw_prompt = args
- .get("prompt")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim()
- .to_string();
- if raw_prompt.is_empty() {
- return Ok(ToolResult::error(format!(
- "{DELEGATE_TO_TOOL_NAME}: `prompt` is required"
- )));
- }
- let prompt = render_structured_handoff(&raw_prompt, &args);
-
- let model_override = args
- .get("model")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
-
- // Async by default, exactly as the member tools were: the specialist
- // runs as a durable, resumable worker and its result arrives as a new
- // chat turn. `blocking: true` is the opt-in for a result that must gate
- // this reply.
- let blocking = args
- .get("blocking")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let mode = if blocking {
- super::dispatch::DispatchMode::Blocking
- } else {
- super::dispatch::DispatchMode::PreferAsync
- };
-
- tracing::debug!(
- agent = %target.agent_id,
- via = %target.tool_name,
- "[delegate] dispatch"
- );
- // `target.tool_name`, not `DELEGATE_TO_TOOL_NAME`: the dispatch name rides
- // into run records and the UI, and reporting every hand-off as
- // `delegate` would erase which specialist was chosen from every trace.
- super::dispatch_subagent(
- &target.agent_id,
- &target.tool_name,
- &prompt,
- None,
- model_override,
+ execute_collapsed_delegation(
+ &self.targets,
+ args,
tool_context,
- mode,
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),
)
.await
}
}
+/// Execute a collapsed hand-off with an explicit child run carrier.
+pub(crate) async fn execute_collapsed_delegation(
+ targets: &[DelegateTarget],
+ args: Value,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+) -> anyhow::Result<ToolResult> {
+ let requested = args.get("agent").and_then(Value::as_str).map(str::trim);
+ let Some(target) =
+ requested.and_then(|agent| targets.iter().find(|target| target.tool_name == agent))
+ else {
+ return Ok(ToolResult::error(format!(
+ "`agent` must be one of: {}. Got: {}",
+ targets
+ .iter()
+ .map(|target| target.tool_name.as_str())
+ .collect::<Vec<_>>()
+ .join(", "),
+ requested.filter(|s| !s.is_empty()).unwrap_or("(missing)")
+ )));
+ };
+
+ let raw_prompt = args
+ .get("prompt")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ if raw_prompt.is_empty() {
+ return Ok(ToolResult::error(format!(
+ "{DELEGATE_TO_TOOL_NAME}: `prompt` is required"
+ )));
+ }
+ let prompt = render_structured_handoff(&raw_prompt, &args);
+
+ let model_override = args
+ .get("model")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+
+ // Async by default, exactly as the member tools were: the specialist
+ // runs as a durable, resumable worker and its result arrives as a new
+ // chat turn. `blocking: true` is the opt-in for a result that must gate
+ // this reply.
+ let blocking = args
+ .get("blocking")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ let mode = if blocking {
+ super::dispatch::DispatchMode::Blocking
+ } else {
+ super::dispatch::DispatchMode::PreferAsync
+ };
+
+ tracing::debug!(
+ agent = %target.agent_id,
+ via = %target.tool_name,
+ "[delegate] dispatch"
+ );
+ // `target.tool_name`, not `DELEGATE_TO_TOOL_NAME`: the dispatch name rides
+ // into run records and the UI, and reporting every hand-off as
+ // `delegate` would erase which specialist was chosen from every trace.
+ super::dispatch_subagent(
+ &target.agent_id,
+ &target.tool_name,
+ &prompt,
+ None,
+ model_override,
+ tool_context,
+ mode,
+ run_context,
+ )
+ .await
+}
+
#[cfg(test)]
#[path = "collapsed_delegation_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
index 68227a357d..ef94b3bd93 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch.rs
@@ -1,11 +1,138 @@
//! Subagent dispatch logic shared by all agent delegation tools.
use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::fork_context::current_parent;
use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions, SubagentRunStatus};
use crate::agent::progress::AgentProgress;
+use async_trait::async_trait;
+use std::sync::Arc;
+use tinyagents_harness::context::RunContext;
+use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
use tinytools::ToolRunContext;
-use tinytools::{Tool as _, ToolCallOptions, ToolResult};
+use tinytools::{ToolCallOptions, ToolResult};
+
+/// Typed dispatch for the delegation tools synthesised from the active agent.
+///
+/// These tools are dynamic, so their common registration resolves the admitted
+/// target from its name and passes the live parent carrier explicitly. This is
+/// the recursive boundary: it never reconstructs product state from a task
+/// local or a downcast.
+pub(crate) struct DelegationDispatch {
+ tool: Arc<dyn tinytools::Tool>,
+ kind: DelegationDispatchKind,
+}
+
+enum DelegationDispatchKind {
+ Collapsed,
+ Integrations { connected_toolkits: Vec<String> },
+ Archetype,
+}
+
+impl DelegationDispatch {
+ pub(crate) fn for_tool(tool: Arc<dyn tinytools::Tool>) -> Option<Self> {
+ let kind = match tool.name() {
+ super::collapsed_delegation::DELEGATE_TO_TOOL_NAME => DelegationDispatchKind::Collapsed,
+ super::skill_delegation::INTEGRATIONS_DELEGATE_TOOL_NAME => {
+ let connected_toolkits = tool
+ .parameters_schema()
+ .pointer("/properties/toolkit/enum")
+ .and_then(serde_json::Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|value| value.as_str().map(str::to_owned))
+ .collect();
+ DelegationDispatchKind::Integrations { connected_toolkits }
+ }
+ name if name.starts_with("delegate_") => DelegationDispatchKind::Archetype,
+ _ => return None,
+ };
+ Some(Self { tool, kind })
+ }
+}
+
+#[async_trait]
+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for DelegationDispatch {
+ fn tool(&self) -> Arc<dyn tinytools::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 tool_context = ToolExecutionContext::from_run_context(parent);
+ let child = parent.data.child();
+ match &self.kind {
+ DelegationDispatchKind::Collapsed => {
+ let targets: Vec<super::collapsed_delegation::DelegateTarget> =
+ AgentDefinitionRegistry::global()
+ .map(|registry| {
+ registry
+ .list()
+ .into_iter()
+ .map(|definition| super::collapsed_delegation::DelegateTarget {
+ tool_name: definition
+ .delegate_name
+ .clone()
+ .unwrap_or_else(|| format!("delegate_{}", definition.id)),
+ agent_id: definition.id.clone(),
+ description: definition.when_to_use.clone(),
+ })
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ super::collapsed_delegation::execute_collapsed_delegation(
+ &targets,
+ arguments,
+ Some(&tool_context),
+ child,
+ )
+ .await
+ }
+ DelegationDispatchKind::Integrations { connected_toolkits } => {
+ let connected_toolkits: Vec<(String, String)> = connected_toolkits
+ .iter()
+ .cloned()
+ .map(|slug| (slug, String::new()))
+ .collect();
+ super::skill_delegation::execute_skill_delegation(
+ self.tool.name(),
+ &connected_toolkits,
+ arguments,
+ Some(&tool_context),
+ child,
+ )
+ .await
+ }
+ DelegationDispatchKind::Archetype => {
+ let Some(agent_id) = AgentDefinitionRegistry::global().and_then(|registry| {
+ registry.list().into_iter().find_map(|definition| {
+ let name = definition
+ .delegate_name
+ .clone()
+ .unwrap_or_else(|| format!("delegate_{}", definition.id));
+ (name == self.tool.name()).then_some(definition.id.clone())
+ })
+ }) else {
+ return Ok(ToolResult::error(format!(
+ "{}: delegation target is not registered",
+ self.tool.name()
+ )));
+ };
+ super::archetype_delegation::execute_archetype_delegation(
+ &agent_id,
+ self.tool.name(),
+ arguments,
+ Some(&tool_context),
+ child,
+ )
+ .await
+ }
+ }
+ }
+}
/// How a delegated sub-agent run should be scheduled relative to the parent
/// turn.
@@ -32,8 +159,11 @@ pub(crate) async fn dispatch_subagent(
model_override: Option<&str>,
tool_context: Option<&dyn ToolRunContext>,
mode: DispatchMode,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
) -> anyhow::Result<ToolResult> {
- let parent_workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
+ let parent_workspace_descriptor = tool_context
+ .and_then(|ctx| ctx.workspace().cloned())
+ .or_else(|| run_context.workspace.clone());
let registry = match AgentDefinitionRegistry::global() {
Some(reg) => reg,
None => {
@@ -54,7 +184,7 @@ pub(crate) async fn dispatch_subagent(
}
};
- let parent_ctx = current_parent();
+ let parent_ctx = run_context.parent.clone();
if let Some(ctx) = &parent_ctx {
if !ctx.allowed_subagent_ids.contains(&definition.id) {
log::warn!(
@@ -79,8 +209,7 @@ pub(crate) async fn dispatch_subagent(
// prompt so its own turn rehydrates the image from the on-disk sidecar.
let forwarded_prompt;
let prompt: &str = {
- let images =
- crate::agent::harness::turn_attachments_context::current_turn_image_placeholders();
+ let images = &run_context.attachment_placeholders;
let subagent_model = match model_override {
Some(m) => m.to_string(),
None => {
@@ -118,7 +247,10 @@ 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 = tool_context.and_then(ToolRunContext::thread_id).is_some();
+ let has_delivery_thread = tool_context
+ .and_then(ToolRunContext::thread_id)
+ .or(run_context.thread_id.as_deref())
+ .is_some();
if has_parent_turn && has_delivery_thread {
let mut async_args = serde_json::json!({
"agent_id": definition.id.clone(),
@@ -152,7 +284,7 @@ pub(crate) async fn dispatch_subagent(
// parallel-delegation flows.
return Box::pin(async move {
super::spawn_async_subagent::SpawnAsyncSubagentTool::new()
- .execute_with_context(async_args, ToolCallOptions::default(), tool_context)
+ .execute_with_parent_context(async_args, tool_context, run_context)
.await
})
.await;
@@ -187,7 +319,7 @@ pub(crate) async fn dispatch_subagent(
// Also send to the per-request progress sink so the web channel bridge
// emits `subagent_spawned` to the frontend (same pattern as spawn_subagent.rs).
- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
+ if let Some(progress) = run_context.progress.clone() {
let _ = progress
.send(AgentProgress::SubagentSpawned {
agent_id: definition.id.clone(),
@@ -240,8 +372,9 @@ pub(crate) async fn dispatch_subagent(
task_id: Some(task_id.clone()),
thread_id: tool_context
.and_then(ToolRunContext::thread_id)
+ .or(run_context.thread_id.as_deref())
.map(str::to_owned),
- run_context: Default::default(),
+ run_context: run_context.clone(),
worker_thread_id: None,
initial_history: None,
checkpoint_dir: None,
@@ -271,7 +404,7 @@ pub(crate) async fn dispatch_subagent(
outcome.agent_id.clone(),
question.clone(),
);
- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
+ if let Some(progress) = run_context.progress.clone() {
let _ = progress
.send(AgentProgress::SubagentAwaitingUser {
agent_id: outcome.agent_id.clone(),
@@ -316,7 +449,7 @@ pub(crate) async fn dispatch_subagent(
// stays "running" forever — `publish_subagent_completed` only
// fires the internal DomainEvent bus, not the per-request
// progress channel the UI's timeline is driven from.
- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
+ if let Some(progress) = run_context.progress.clone() {
let _ = progress
.send(AgentProgress::SubagentCompleted {
agent_id: outcome.agent_id.clone(),
@@ -380,7 +513,7 @@ pub(crate) async fn dispatch_subagent(
// Same progress-sink mirror as the `Completed` arm above —
// an incomplete stop is still lifecycle-completed, so the
// timeline row must be released from "running" here too.
- if let Some(progress) = current_parent().and_then(|p| p.on_progress.clone()) {
+ if let Some(progress) = run_context.progress.clone() {
let _ = progress
.send(AgentProgress::SubagentCompleted {
agent_id: outcome.agent_id.clone(),
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs
index eb1a195ff8..1254dd42e6 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/dispatch_tests.rs
@@ -1,8 +1,60 @@
use super::*;
+use async_trait::async_trait;
+use std::sync::Arc;
use tinytools::Tool;
use crate::agent::tools::AskClarificationTool;
+struct DelegationRegistrationTool {
+ name: &'static str,
+ parameters: serde_json::Value,
+}
+
+#[async_trait]
+impl Tool for DelegationRegistrationTool {
+ fn name(&self) -> &str {
+ self.name
+ }
+
+ fn description(&self) -> &str {
+ "test delegation registration"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ self.parameters.clone()
+ }
+
+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {
+ Ok(tinytools::ToolResult::success("unused"))
+ }
+}
+
+#[test]
+fn typed_dispatch_registration_recognises_every_synthesised_delegate_surface() {
+ let integration = Arc::new(DelegationRegistrationTool {
+ name: "delegate_to_integrations_agent",
+ parameters: serde_json::json!({
+ "properties": { "toolkit": { "enum": ["gmail"] } }
+ }),
+ });
+ for tool in [
+ Arc::new(DelegationRegistrationTool {
+ name: "delegate_to",
+ parameters: serde_json::json!({}),
+ }) as Arc<dyn Tool>,
+ Arc::new(DelegationRegistrationTool {
+ name: "delegate_researcher",
+ parameters: serde_json::json!({}),
+ }),
+ integration,
+ ] {
+ assert!(
+ DelegationDispatch::for_tool(tool).is_some(),
+ "every synthesised delegation name must select the typed dispatch"
+ );
+ }
+}
+
#[test]
fn ask_clarification_tool_re_exported() {
let tool = AskClarificationTool::new();
@@ -25,6 +77,7 @@ async fn dispatch_subagent_returns_tool_error_when_agent_unknown() {
None,
None,
DispatchMode::Blocking,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new(),
)
.await
.expect("dispatch_subagent should not return Err on these inputs");
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs
index 71b6161f51..f4c0144e87 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/skill_delegation.rs
@@ -202,110 +202,128 @@ impl Tool for SkillDelegationTool {
_options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- let raw_toolkit = args
- .get("toolkit")
+ execute_skill_delegation(
+ &self.tool_name,
+ &self.connected_toolkits,
+ args,
+ tool_context,
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),
+ )
+ .await
+ }
+}
+
+/// Execute an integration hand-off with an explicit child run carrier.
+pub(crate) async fn execute_skill_delegation(
+ tool_name: &str,
+ connected_toolkits: &[(String, String)],
+ args: serde_json::Value,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+) -> anyhow::Result<ToolResult> {
+ let raw_toolkit = args
+ .get("toolkit")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ log::debug!(
+ "[skill-delegation] execute start tool='{}' raw_toolkit={:?} prompt_chars={}",
+ tool_name,
+ raw_toolkit,
+ args.get("prompt")
.and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
+ .map(|s| s.chars().count())
+ .unwrap_or(0)
+ );
+ if raw_toolkit.is_empty() {
+ log::debug!(
+ "[skill-delegation] reject: missing `toolkit` argument for tool='{}'",
+ tool_name
+ );
+ return Ok(ToolResult::error(format!(
+ "{}: `toolkit` is required and must match a connected integration slug",
+ tool_name
+ )));
+ }
+ let slug = sanitise_slug(&raw_toolkit);
+ let mut live_connected: Option<Vec<String>> = None;
+ let mut known = connected_toolkits
+ .iter()
+ .any(|(known_slug, _)| known_slug == &slug);
+ if !known {
+ // Safety net for same-thread OAuth races: do one live status
+ // refresh before rejecting an unknown toolkit, mirroring the
+ // spawn_subagent integrations pre-flight.
+ live_connected = fetch_live_connected_toolkit_slugs_once().await;
+ }
+ let (known_after_recheck, allowed) =
+ resolve_connected_toolkits(connected_toolkits, &slug, live_connected.as_deref());
+ if known_after_recheck && !known {
+ log::info!(
+ "[skill-delegation] toolkit '{}' accepted after live re-check (session schema stale)",
+ slug
+ );
+ }
+ known = known_after_recheck;
+ if !known {
log::debug!(
- "[skill-delegation] execute start tool='{}' raw_toolkit={:?} prompt_chars={}",
- self.tool_name,
+ "[skill-delegation] reject: toolkit '{}' (sanitised='{}') not in connected set {:?}",
raw_toolkit,
- args.get("prompt")
- .and_then(|v| v.as_str())
- .map(|s| s.chars().count())
- .unwrap_or(0)
+ slug,
+ allowed
);
- if raw_toolkit.is_empty() {
- log::debug!(
- "[skill-delegation] reject: missing `toolkit` argument for tool='{}'",
- self.tool_name
- );
- return Ok(ToolResult::error(format!(
- "{}: `toolkit` is required and must match a connected integration slug",
- self.tool_name
- )));
- }
- let slug = sanitise_slug(&raw_toolkit);
- let mut live_connected: Option<Vec<String>> = None;
- let mut known = self
- .connected_toolkits
- .iter()
- .any(|(known_slug, _)| known_slug == &slug);
- if !known {
- // Safety net for same-thread OAuth races: do one live status
- // refresh before rejecting an unknown toolkit, mirroring the
- // spawn_subagent integrations pre-flight.
- live_connected = fetch_live_connected_toolkit_slugs_once().await;
- }
- let (known_after_recheck, allowed) =
- resolve_connected_toolkits(&self.connected_toolkits, &slug, live_connected.as_deref());
- if known_after_recheck && !known {
- log::info!(
- "[skill-delegation] toolkit '{}' accepted after live re-check (session schema stale)",
- slug
- );
- }
- known = known_after_recheck;
- if !known {
- log::debug!(
- "[skill-delegation] reject: toolkit '{}' (sanitised='{}') not in connected set {:?}",
- raw_toolkit,
- slug,
- allowed
- );
- return Ok(ToolResult::error(format!(
- "{}: toolkit `{raw_toolkit}` is not connected — allowed: [{}]",
- self.tool_name,
- allowed.join(", ")
- )));
- }
-
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- if prompt.is_empty() {
- log::debug!(
- "[skill-delegation] reject: empty `prompt` for tool='{}' toolkit='{}'",
- self.tool_name,
- slug
- );
- return Ok(ToolResult::error(format!(
- "{}: `prompt` is required",
- self.tool_name
- )));
- }
-
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty());
+ return Ok(ToolResult::error(format!(
+ "{}: toolkit `{raw_toolkit}` is not connected — allowed: [{}]",
+ tool_name,
+ allowed.join(", ")
+ )));
+ }
+ let prompt = args
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
+ if prompt.is_empty() {
log::debug!(
- "[skill-delegation] dispatching toolkit='{}' to integrations_agent (prompt_chars={})",
- slug,
- prompt.chars().count()
+ "[skill-delegation] reject: empty `prompt` for tool='{}' toolkit='{}'",
+ tool_name,
+ slug
);
- // Integration delegations stay blocking: their outcomes (send the
- // email, create the page, …) are usually approval-gated mid-turn and
- // the orchestrator's reply reports the concrete result. The durable
- // async default applies to archetype delegations only for now.
- super::dispatch_subagent(
- "integrations_agent",
- &self.tool_name,
- &prompt,
- Some(&slug),
- model_override,
- tool_context,
- super::dispatch::DispatchMode::Blocking,
- )
- .await
+ return Ok(ToolResult::error(format!(
+ "{}: `prompt` is required",
+ tool_name
+ )));
}
+
+ let model_override = args
+ .get("model")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty());
+
+ log::debug!(
+ "[skill-delegation] dispatching toolkit='{}' to integrations_agent (prompt_chars={})",
+ slug,
+ prompt.chars().count()
+ );
+ // Integration delegations stay blocking: their outcomes (send the
+ // email, create the page, …) are usually approval-gated mid-turn and
+ // the orchestrator's reply reports the concrete result. The durable
+ // async default applies to archetype delegations only for now.
+ super::dispatch_subagent(
+ "integrations_agent",
+ tool_name,
+ &prompt,
+ Some(&slug),
+ model_override,
+ tool_context,
+ super::dispatch::DispatchMode::Blocking,
+ run_context,
+ )
+ .await
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index 502d5f4fa8..40b6263744 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -12,12 +12,14 @@ use tinyagents_registry::{
};
use crate::agent::orchestration::tools::{
- AgentPrepareContextDispatch, ContinueSubagentDispatch, SpawnAsyncSubagentDispatch,
- SpawnParallelAgentsDispatch, SpawnSubagentDispatch, SpawnWorkerThreadDispatch,
+ AgentPrepareContextDispatch, ContinueSubagentDispatch, 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;
/// Register every admitted tool from `tool_sets` onto `harness` (and its
/// `capability_registry` projection), project the visible agent set as
@@ -114,6 +116,12 @@ pub(super) fn register_turn_tools_and_agents(
harness.register_tool_dispatch(Arc::new(AgentPrepareContextDispatch::new(
adapter,
)));
+ } else if name == "delegate_to_personality" {
+ harness.register_tool_dispatch(Arc::new(DelegateToPersonalityDispatch::new(
+ adapter,
+ )));
+ } else if let Some(dispatch) = DelegationDispatch::for_tool(adapter.clone()) {
+ harness.register_tool_dispatch(Arc::new(dispatch));
} else {
harness.register_tool(adapter);
}
diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rs
index 2759742e97..061e68ee7e 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_to_personality::DelegateToPersonalityDispatch;
pub use delegate_to_personality::DelegateToPersonalityTool;
pub use plan_exit::{PlanExitTool, PLAN_EXIT_MARKER};
pub use remember_preference::RememberPreferenceTool;
diff --git a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs
index 4054bcd5dc..01529e142f 100644
--- a/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs
+++ b/crates/openhuman-core/src/agent/tools/delegate_to_personality.rs
@@ -1,17 +1,50 @@
//! Tool: `delegate_to_personality` — delegate a task to a personality-specific agent.
use crate::agent::harness::definition::AgentDefinitionRegistry;
-use crate::agent::harness::fork_context::current_parent;
use crate::agent::harness::subagent_runner::{run_subagent, SubagentRunOptions};
use crate::agent::profiles::AgentProfileStore;
use crate::agent::profiles::PersonalityContext;
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};
pub struct DelegateToPersonalityTool;
+/// Typed harness dispatch for personality delegation.
+pub(crate) struct DelegateToPersonalityDispatch {
+ tool: Arc<dyn Tool>,
+}
+
+impl DelegateToPersonalityDispatch {
+ pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
+ Self { tool }
+ }
+}
+
+#[async_trait]
+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
+ for DelegateToPersonalityDispatch
+{
+ 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);
+ execute_delegate_to_personality(arguments, Some(&context), parent.data.child()).await
+ }
+}
+
impl Default for DelegateToPersonalityTool {
fn default() -> Self {
Self::new()
@@ -73,207 +106,224 @@ impl Tool for DelegateToPersonalityTool {
_options: ToolCallOptions,
tool_context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
- let personality_id = args
- .get("personality_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
+ execute_delegate_to_personality(
+ args,
+ tool_context,
+ crate::agent::tinyagents::host::OpenHumanRunContext::from_current_scopes(),
+ )
+ .await
+ }
+}
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
+/// Execute personality delegation with an explicit child run carrier.
+pub(crate) async fn execute_delegate_to_personality(
+ args: serde_json::Value,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+) -> anyhow::Result<ToolResult> {
+ let personality_id = args
+ .get("personality_id")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
- let context = args
- .get("context")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
+ let prompt = args
+ .get("prompt")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .trim()
+ .to_string();
- if personality_id.is_empty() {
- return Ok(ToolResult::error(
- "delegate_to_personality: `personality_id` is required.",
- ));
- }
- if prompt.is_empty() {
+ let context = args
+ .get("context")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string());
+
+ if personality_id.is_empty() {
+ return Ok(ToolResult::error(
+ "delegate_to_personality: `personality_id` is required.",
+ ));
+ }
+ if prompt.is_empty() {
+ return Ok(ToolResult::error(
+ "delegate_to_personality: `prompt` is required.",
+ ));
+ }
+
+ let parent_ctx = match run_context.parent.clone() {
+ Some(ctx) => ctx,
+ None => {
return Ok(ToolResult::error(
- "delegate_to_personality: `prompt` is required.",
+ "delegate_to_personality: no parent execution context available.",
));
}
+ };
- let parent_ctx = match current_parent() {
- Some(ctx) => ctx,
- None => {
- return Ok(ToolResult::error(
- "delegate_to_personality: no parent execution context available.",
- ));
- }
- };
+ tracing::debug!(
+ personality_id = %personality_id,
+ "[delegate_to_personality] resolving personality profile"
+ );
+
+ let store = AgentProfileStore::new(parent_ctx.workspace_dir.clone());
+ // Guard: only the master personality may delegate. This prevents a
+ // delegated sub-agent from recursing back through this tool — there is
+ // no built-in depth counter on cross-personality delegation, so we gate
+ // at the entry point.
+ let (state, active_profile) = match store.resolve(None) {
+ Ok(result) => result,
+ Err(e) => {
+ return Ok(ToolResult::error(format!(
+ "delegate_to_personality: failed to resolve active profile: {e}"
+ )));
+ }
+ };
+ if !active_profile.is_master {
tracing::debug!(
- personality_id = %personality_id,
- "[delegate_to_personality] resolving personality profile"
+ active_profile_id = %active_profile.id,
+ "[delegate_to_personality] rejected — caller is not the master personality"
);
+ return Ok(ToolResult::error(format!(
+ "delegate_to_personality: only the master personality may delegate \
+ (active='{}', is_master=false).",
+ active_profile.id
+ )));
+ }
- let store = AgentProfileStore::new(parent_ctx.workspace_dir.clone());
-
- // Guard: only the master personality may delegate. This prevents a
- // delegated sub-agent from recursing back through this tool — there is
- // no built-in depth counter on cross-personality delegation, so we gate
- // at the entry point.
- let (state, active_profile) = match store.resolve(None) {
- Ok(result) => result,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: failed to resolve active profile: {e}"
- )));
- }
- };
- if !active_profile.is_master {
+ // Reuse the state already loaded above — no second store.resolve() call needed.
+ let profile = match state.profiles.iter().find(|p| p.id == personality_id) {
+ Some(p) => p.clone(),
+ None => {
tracing::debug!(
- active_profile_id = %active_profile.id,
- "[delegate_to_personality] rejected — caller is not the master personality"
+ personality_id = %personality_id,
+ "[delegate_to_personality] profile resolve failed"
);
return Ok(ToolResult::error(format!(
- "delegate_to_personality: only the master personality may delegate \
- (active='{}', is_master=false).",
- active_profile.id
+ "delegate_to_personality: personality '{personality_id}' not found."
)));
}
+ };
- // Reuse the state already loaded above — no second store.resolve() call needed.
- let profile = match state.profiles.iter().find(|p| p.id == personality_id) {
- Some(p) => p.clone(),
- None => {
- tracing::debug!(
- personality_id = %personality_id,
- "[delegate_to_personality] profile resolve failed"
- );
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: personality '{personality_id}' not found."
- )));
- }
- };
+ let personality_ctx =
+ PersonalityContext::from_profile(&parent_ctx.workspace_dir, profile.clone());
- let personality_ctx =
- PersonalityContext::from_profile(&parent_ctx.workspace_dir, profile.clone());
+ tracing::debug!(
+ personality_id = %personality_id,
+ agent_id = %profile.agent_id,
+ memory_suffix = %personality_ctx.memory_suffix,
+ "[delegate_to_personality] personality resolved, delegating"
+ );
- tracing::debug!(
- personality_id = %personality_id,
- agent_id = %profile.agent_id,
- memory_suffix = %personality_ctx.memory_suffix,
- "[delegate_to_personality] personality resolved, delegating"
- );
+ // TODO(phase-2): Memory isolation not yet enforced during delegation.
+ // The personality gets its own SQLite DB (plumbing exists in
+ // UnifiedMemory::new_with_memory_dir), but run_subagent currently
+ // receives the parent's memory instance. To fix: construct a new
+ // UnifiedMemory using personality_ctx.memory_suffix and pass it through
+ // SubagentRunOptions (needs an additional field there).
+ // Also: composio_integrations allowlist is not yet filtered during
+ // delegation — personality_ctx.composio_allowlist exists but is not
+ // applied to the SubagentRunOptions toolkit_override.
+ //
+ // Until these are wired, the sub-agent gets the personality's
+ // voice/identity at the prompt level but still writes to the parent's
+ // memory store and has access to all parent integrations.
+ let mut personality_preamble = format!(
+ "You are acting as the personality `{}` (\"{}\"). {}",
+ profile.id, profile.name, profile.description
+ );
+ if let Some(ref soul) = personality_ctx.soul_md_override {
+ let soul_truncated: String = soul.chars().take(800).collect();
+ personality_preamble.push_str("\n\n[Personality SOUL.md]\n");
+ personality_preamble.push_str(&soul_truncated);
+ }
+ if let Some(ref mem) = personality_ctx.memory_md_override {
+ let mem_truncated: String = mem.chars().take(800).collect();
+ personality_preamble.push_str("\n\n[Personality MEMORY.md]\n");
+ personality_preamble.push_str(&mem_truncated);
+ }
+ let combined_context = match context.as_deref() {
+ Some(ctx_str) => format!("{personality_preamble}\n\n[Caller Context]\n{ctx_str}"),
+ None => personality_preamble,
+ };
- // TODO(phase-2): Memory isolation not yet enforced during delegation.
- // The personality gets its own SQLite DB (plumbing exists in
- // UnifiedMemory::new_with_memory_dir), but run_subagent currently
- // receives the parent's memory instance. To fix: construct a new
- // UnifiedMemory using personality_ctx.memory_suffix and pass it through
- // SubagentRunOptions (needs an additional field there).
- // Also: composio_integrations allowlist is not yet filtered during
- // delegation — personality_ctx.composio_allowlist exists but is not
- // applied to the SubagentRunOptions toolkit_override.
- //
- // Until these are wired, the sub-agent gets the personality's
- // voice/identity at the prompt level but still writes to the parent's
- // memory store and has access to all parent integrations.
- let mut personality_preamble = format!(
- "You are acting as the personality `{}` (\"{}\"). {}",
- profile.id, profile.name, profile.description
- );
- if let Some(ref soul) = personality_ctx.soul_md_override {
- let soul_truncated: String = soul.chars().take(800).collect();
- personality_preamble.push_str("\n\n[Personality SOUL.md]\n");
- personality_preamble.push_str(&soul_truncated);
+ // Look up the agent definition for this personality's agent_id
+ let registry = match AgentDefinitionRegistry::global() {
+ Some(reg) => reg,
+ None => {
+ return Ok(ToolResult::error(
+ "delegate_to_personality: agent definition registry not initialized.",
+ ));
}
- if let Some(ref mem) = personality_ctx.memory_md_override {
- let mem_truncated: String = mem.chars().take(800).collect();
- personality_preamble.push_str("\n\n[Personality MEMORY.md]\n");
- personality_preamble.push_str(&mem_truncated);
+ };
+
+ let definition = match registry.get(&profile.agent_id) {
+ Some(def) => def,
+ None => {
+ return Ok(ToolResult::error(format!(
+ "delegate_to_personality: agent definition '{}' not found in registry.",
+ profile.agent_id
+ )));
}
- let combined_context = match context.as_deref() {
- Some(ctx_str) => format!("{personality_preamble}\n\n[Caller Context]\n{ctx_str}"),
- None => personality_preamble,
- };
+ };
- // Look up the agent definition for this personality's agent_id
- let registry = match AgentDefinitionRegistry::global() {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "delegate_to_personality: agent definition registry not initialized.",
- ));
- }
- };
+ let workspace_descriptor = tool_context
+ .and_then(|ctx| ctx.workspace().cloned())
+ .or_else(|| run_context.workspace.clone());
+ let worktree_action_dir = workspace_descriptor
+ .as_ref()
+ .map(|descriptor| descriptor.root.clone());
+ if let Some(descriptor) = workspace_descriptor.as_ref() {
+ tracing::debug!(
+ personality_id = %personality_id,
+ workspace_root = %descriptor.root.display(),
+ policy_id = %descriptor.policy_id,
+ "[delegate_to_personality] using ToolExecutionContext workspace root"
+ );
+ }
- let definition = match registry.get(&profile.agent_id) {
- Some(def) => def,
- None => {
- return Ok(ToolResult::error(format!(
- "delegate_to_personality: agent definition '{}' not found in registry.",
- profile.agent_id
- )));
- }
- };
+ let options = SubagentRunOptions {
+ context: Some(combined_context),
+ model_override: profile.model_override.clone(),
+ toolkit_override: None,
+ skill_filter_override: None,
+ task_id: None,
+ thread_id: tool_context
+ .and_then(ToolRunContext::thread_id)
+ .or(run_context.thread_id.as_deref())
+ .map(str::to_owned),
+ run_context,
+ worker_thread_id: None,
+ initial_history: None,
+ checkpoint_dir: None,
+ worktree_action_dir,
+ workspace_descriptor,
+ run_queue: None,
+ };
- let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- let worktree_action_dir = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- if let Some(descriptor) = workspace_descriptor.as_ref() {
+ match run_subagent(definition, &prompt, options).await {
+ Ok(outcome) => {
tracing::debug!(
personality_id = %personality_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[delegate_to_personality] using ToolExecutionContext workspace root"
+ iterations = outcome.iterations,
+ elapsed_ms = outcome.elapsed.as_millis(),
+ "[delegate_to_personality] delegation completed"
);
+ Ok(ToolResult::success(format!(
+ "[Personality: {}]\n{}",
+ profile.name, outcome.output
+ )))
}
-
- let options = SubagentRunOptions {
- context: Some(combined_context),
- model_override: profile.model_override.clone(),
- 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,
- worktree_action_dir,
- workspace_descriptor,
- run_queue: None,
- };
-
- match run_subagent(definition, &prompt, options).await {
- Ok(outcome) => {
- tracing::debug!(
- personality_id = %personality_id,
- iterations = outcome.iterations,
- elapsed_ms = outcome.elapsed.as_millis(),
- "[delegate_to_personality] delegation completed"
- );
- Ok(ToolResult::success(format!(
- "[Personality: {}]\n{}",
- profile.name, outcome.output
- )))
- }
- Err(e) => {
- tracing::debug!(
- personality_id = %personality_id,
- error = %e,
- "[delegate_to_personality] delegation failed"
- );
- Ok(ToolResult::error(format!(
- "delegate_to_personality failed for '{}': {e}",
- personality_id
- )))
- }
+ Err(e) => {
+ tracing::debug!(
+ personality_id = %personality_id,
+ error = %e,
+ "[delegate_to_personality] delegation failed"
+ );
+ Ok(ToolResult::error(format!(
+ "delegate_to_personality failed for '{}': {e}",
+ personality_id
+ )))
}
}
}