Skip to content

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

feat(orchestration): add async subagent spawn tool

Steven Enamakelc3452ad27c6a
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
index e69de29bb2..5716df1300 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_completion.rs
@@ -0,0 +1,363 @@
+use super::*;
+use crate::agent::orchestration::background_completions::CompletionTarget;
+use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;
+use crate::agent::subagent_host::{SubagentRunOutcome, SubagentRunStatus};
+use crate::core::runtime::{CoreContext, DispatchCtx};
+use crate::progress::AgentProgress;
+use crate::security::turn_origin::AgentTurnOrigin;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+pub(super) fn make_completion(
+ completion_core: Option<Arc<CoreContext>>,
+ completion_origin: Option<AgentTurnOrigin>,
+ progress_sink: Option<tokio::sync::mpsc::Sender<AgentProgress>>,
+ background_workspace_dir: PathBuf,
+ background_dispatch: DispatchCtx,
+ background_agent_id: String,
+ background_task_id: String,
+ background_parent_session: String,
+ completion_target: CompletionTarget,
+ completion_worker_thread_id: Option<String>,
+ background_store: SubagentSessionStore,
+ background_subagent_session_id: String,
+ background_parent_thread_id: Option<String>,
+) -> impl Fn(
+ String,
+ Result<SubagentRunOutcome, String>,
+ bool,
+) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>
+ + Send
+ + Sync
+ + 'static {
+ move |_target: String,
+ result: Result<SubagentRunOutcome, String>,
+ emit_lifecycle_effects: bool|
+ -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>> {
+ let core = completion_core.clone();
+ let origin = completion_origin.clone();
+ let progress_sink = progress_sink.clone();
+ let background_workspace_dir = background_workspace_dir.clone();
+ let background_dispatch = background_dispatch.clone();
+ let background_agent_id = background_agent_id.clone();
+ let background_task_id = background_task_id.clone();
+ let background_parent_session = background_parent_session.clone();
+ let completion_target = completion_target.clone();
+ let background_worker_thread_id = completion_worker_thread_id.clone();
+ let background_store = background_store.clone();
+ let background_subagent_session_id = background_subagent_session_id.clone();
+ let background_parent_thread_id = background_parent_thread_id.clone();
+ Box::pin(async move {
+ let finish = async move {
+ let mut abort_report =
+ AbortReport::arm(progress_sink, &background_agent_id, &background_task_id);
+ let result = result.map_err(anyhow::Error::msg);
+ match result {
+ Ok(outcome) => {
+ match outcome.status {
+ SubagentRunStatus::Completed => {
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_completed failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ // A workflow proposal from the child's tool history is
+ // durable state, not prose: persist it into the parent chat
+ // thread (survives reload / reconnect) and carry the full
+ // payload in the delivery notice for the follow-up turn.
+ if emit_lifecycle_effects {
+ let delivery_summary = attach_workflow_proposal(
+ &background_dispatch,
+ &background_workspace_dir,
+ background_parent_thread_id.as_deref(),
+ &outcome.task_id,
+ &outcome.agent_id,
+ &outcome.final_history,
+ outcome.output.clone(),
+ );
+ completion_target
+ .completed(
+ &outcome.task_id,
+ &outcome.agent_id,
+ delivery_summary,
+ )
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_completed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+ abort_report
+ .deliver(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ // Detached by construction: this tool
+ // takes `detached_child()`, so this child's
+ // spend never reached the parent turn's
+ // ledger or `chat_done`. See the field docs.
+ usage: Some(outcome.usage),
+ stop: None,
+ })
+ .await;
+ }
+ }
+ SubagentRunStatus::Incomplete { ref reason } => {
+ // Async sub-agent stopped short (stuck halt / iteration
+ // cap). Mark the session finished and deliver the PARTIAL
+ // progress back to the parent, framed so it is not
+ // mistaken for a completed result (#4096).
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_incomplete failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ let framed = format!(
+ "[SUBAGENT_INCOMPLETE] the sub-agent {reason} and did not finish. \
+ Partial progress:\n{}",
+ outcome.output
+ );
+ // An incomplete run may still have produced a full
+ // proposal before stalling — preserve it durably too.
+ if emit_lifecycle_effects {
+ let framed = attach_workflow_proposal(
+ &background_dispatch,
+ &background_workspace_dir,
+ background_parent_thread_id.as_deref(),
+ &outcome.task_id,
+ &outcome.agent_id,
+ &outcome.final_history,
+ framed,
+ );
+ completion_target
+ .completed(&outcome.task_id, &outcome.agent_id, framed)
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_completed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ outcome.elapsed.as_millis() as u64,
+ outcome.output.chars().count(),
+ outcome.iterations,
+ );
+ abort_report
+ .deliver(AgentProgress::SubagentCompleted {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ elapsed_ms: outcome.elapsed.as_millis() as u64,
+ iterations: outcome.iterations as u32,
+ output_chars: outcome.output.chars().count(),
+ output: outcome.output.clone(),
+ // Detached by construction: this tool
+ // takes `detached_child()`, so this child's
+ // spend never reached the parent turn's
+ // ledger or `chat_done`. See the field docs.
+ usage: Some(outcome.usage),
+ stop: incomplete_stop(
+ reason,
+ outcome.failure_cause.clone(),
+ ),
+ })
+ .await;
+ }
+ }
+ SubagentRunStatus::Cancelled => {
+ let reason = match background_store.load() {
+ Ok(rows) => rows
+ .into_iter()
+ .find(|row| {
+ row.subagent_session_id
+ == background_subagent_session_id
+ && row.current_task_id.as_deref()
+ == Some(outcome.task_id.as_str())
+ })
+ .and_then(|row| row.latest_error),
+ Err(error) => {
+ log::warn!(
+ "[subagent_reuse] cancellation reason lookup failed subagent_session_id={} task_id={} error={error}",
+ background_subagent_session_id,
+ outcome.task_id
+ );
+ None
+ }
+ };
+ let error = match reason
+ .as_deref()
+ .map(str::trim)
+ .filter(|reason| !reason.is_empty())
+ {
+ Some(reason) => {
+ format!("async sub-agent was cancelled. Reason: {reason}")
+ }
+ None => "async sub-agent was cancelled".to_string(),
+ };
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_cancelled failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ if emit_lifecycle_effects {
+ completion_target
+ .failed(&outcome.task_id, &outcome.agent_id, &error)
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_failed(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ error.clone(),
+ );
+ abort_report
+ .deliver(AgentProgress::SubagentFailed {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ error,
+ })
+ .await;
+ }
+ }
+ SubagentRunStatus::AwaitingUser {
+ ref question,
+ ref checkpoint,
+ ..
+ } => {
+ if let Err(err) = subagent_sessions::mark_finished(
+ &background_store,
+ &background_subagent_session_id,
+ &outcome.task_id,
+ &outcome.status,
+ outcome.final_history.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_awaiting_user failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ outcome.task_id,
+ outcome.agent_id,
+ err
+ );
+ }
+ // #4896: a detached child that pauses for input won't continue
+ // on its own — queue a framed notice so the parent chat learns it
+ // needs input, not "Accepted". Same idle-gated path as a success.
+ if emit_lifecycle_effects {
+ completion_target
+ .awaiting_input(
+ &outcome.task_id,
+ &outcome.agent_id,
+ question,
+ checkpoint.is_some(),
+ )
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_awaiting_user(
+ background_parent_session,
+ outcome.task_id.clone(),
+ outcome.agent_id.clone(),
+ question.clone(),
+ );
+ abort_report
+ .deliver(AgentProgress::SubagentAwaitingUser {
+ agent_id: outcome.agent_id,
+ task_id: outcome.task_id,
+ question: question.clone(),
+ worker_thread_id: background_worker_thread_id.clone(),
+ checkpoint_path: checkpoint
+ .as_ref()
+ .map(|path| path.to_string_lossy().to_string()),
+ })
+ .await;
+ }
+ }
+ }
+ }
+ Err(err) => {
+ let error = err.to_string();
+ if let Err(store_err) = subagent_sessions::mark_failed(
+ &background_store,
+ &background_subagent_session_id,
+ &background_task_id,
+ error.clone(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_failed failed subagent_session_id={} task_id={} agent_id={} error={}",
+ background_subagent_session_id,
+ background_task_id,
+ background_agent_id,
+ store_err
+ );
+ }
+ // #4896: a detached child that errors previously only
+ // published an event — nothing reached chat, so the parent
+ // turn finalized on "Accepted" and the failure was lost.
+ // Queue a framed failure notice so background_delivery
+ // surfaces it as a follow-up chat turn.
+ if emit_lifecycle_effects {
+ completion_target
+ .failed(&background_task_id, &background_agent_id, &error)
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_failed(
+ background_parent_session,
+ background_task_id.clone(),
+ background_agent_id.clone(),
+ error.clone(),
+ );
+ abort_report
+ .deliver(AgentProgress::SubagentFailed {
+ agent_id: background_agent_id,
+ task_id: background_task_id,
+ error,
+ })
+ .await;
+ }
+ }
+ }
+ abort_report.disarm();
+ };
+ match core {
+ Some(core) => {
+ crate::core::runtime::CoreContext::scope_with_turn_origin(
+ core,
+ origin,
+ Box::pin(finish),
+ )
+ .await
+ }
+ None => finish.await,
+ }
+ })
+ }
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
new file mode 100644
index 0000000000..54afd0d725
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs
@@ -0,0 +1,506 @@
+impl SpawnAsyncSubagentTool {
+ async fn execute_with_context_inner(
+ &self,
+ args: serde_json::Value,
+ _options: ToolCallOptions,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+ detached_parent: Option<
+ tinyagents_harness::context::RunContext<
+ crate::agent::tinyagents::host::OpenHumanRunContext,
+ >,
+ >,
+ ) -> anyhow::Result<ToolResult> {
+ let dispatch = run_context.dispatch_ctx();
+ let AsyncSpawnArgs {
+ agent_id,
+ prompt,
+ context,
+ model_override,
+ task_title,
+ task_key,
+ force_fresh,
+ } = decode_async_spawn_args(&args);
+
+ if let Some(refusal) = refuse_empty_spawn_args(&agent_id, &prompt) {
+ return Ok(refusal);
+ }
+ let Some(detached_parent) = detached_parent else {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent requires a live harness run context.",
+ ));
+ };
+
+ let parent = match run_context.parent.clone() {
+ Some(parent) => parent,
+ None => {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent called outside of an agent turn",
+ ));
+ }
+ };
+
+ // Preserve the actual caller's authority before any filesystem/session
+ // effects. A scoped refusal cannot become an accepted/running reference.
+ if let Err(error) = running_subagents::admit_spawn(&dispatch, &parent.workspace_dir) {
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: registration refused: {error}"
+ )));
+ }
+
+ let registry =
+ match AgentDefinitionRegistry::for_core_context(run_context.dispatch_ctx().into_core())
+ {
+ Some(registry) => registry,
+ None => {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: AgentDefinitionRegistry has not been initialised",
+ ));
+ }
+ };
+ let definition = match registry.get(&agent_id).cloned() {
+ Some(definition) => definition,
+ None => {
+ let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: unknown agent_id '{agent_id}'. Available: {}",
+ available.join(", ")
+ )));
+ }
+ };
+
+ let fleet = if parent.visible_tool_names.is_empty() {
+ FleetToolSet::for_parent(&parent.agent_definition_id)
+ } else {
+ FleetToolSet::from_visible_tool_names(&parent.visible_tool_names)
+ };
+
+ if !parent.allowed_subagent_ids.contains(&definition.id) {
+ log::warn!(
+ "[spawn_async_subagent] blocked subagent outside allowlist parent={} requested={} allowed={:?}",
+ parent.agent_definition_id,
+ definition.id,
+ parent.allowed_subagent_ids
+ );
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",
+ definition.id, parent.agent_definition_id
+ )));
+ }
+
+ let parent_session = parent.session_id.clone();
+ let progress_sink = parent.on_progress.clone();
+ let parent_thread_id = tool_context
+ .and_then(ToolRunContext::thread_id)
+ .or(run_context.thread_id.as_deref())
+ .map(str::to_owned);
+
+ if let Some(refusal) = refuse_missing_delivery_thread(
+ parent_thread_id.as_deref(),
+ &parent.agent_definition_id,
+ &definition.id,
+ ) {
+ return Ok(refusal);
+ }
+ let store = SubagentSessionStore::new(parent.workspace_dir.clone());
+ let workspace_descriptor = tool_context
+ .and_then(|ctx| ctx.workspace().cloned())
+ .or_else(|| run_context.workspace.clone());
+ let effective_action_root = workspace_descriptor
+ .as_ref()
+ .map(|workspace| {
+ tracing::debug!(
+ workspace_root = %workspace.root.display(),
+ policy_id = %workspace.policy_id,
+ "[spawn_async_subagent] using ToolExecutionContext workspace root"
+ );
+ workspace.root.clone()
+ })
+ .or_else(|| {
+ crate::security::live_policy::effective_in(&dispatch)
+ .map(|policy| policy.action_dir.clone())
+ });
+ let selector = SubagentSessionSelector {
+ parent_session: parent_session.clone(),
+ parent_thread_id: parent_thread_id.clone(),
+ agent_id: definition.id.clone(),
+ model: model_override.clone(),
+ sandbox_mode: format!("{:?}", definition.sandbox_mode),
+ action_root: subagent_sessions::action_root_key(effective_action_root.as_deref()),
+ task_key: task_key.clone(),
+ };
+
+ let reusable = if force_fresh {
+ match subagent_sessions::find_reusable(&store, &selector) {
+ Ok(Some(session)) => {
+ let jobs = crate::core::runtime::slot_for::<
+ tinyagents_harness_tools::subagents::SubAgentJobRegistry,
+ >(&dispatch);
+ let cancelled = subagent_sessions::cancel_driver_job_for_observed_session(
+ &store,
+ &parent.workspace_dir.join(".openhuman/subagent_checkpoints"),
+ &jobs,
+ &session,
+ &parent_session,
+ parent_thread_id.as_deref(),
+ );
+ if !cancelled {
+ let _ = running_subagents::cancel_by_session_in_workspace(
+ &dispatch,
+ &session.subagent_session_id,
+ &parent_session,
+ &parent.workspace_dir,
+ );
+ }
+ match subagent_sessions::close_if_current(&store, &session) {
+ Ok(true) => {}
+ Ok(false) => {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: reusable session changed during fresh start; retry with the current session",
+ ));
+ }
+ Err(err) => {
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: failed to close reusable session: {err}"
+ )));
+ }
+ }
+ }
+ Ok(None) => {}
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] fresh lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ definition.id,
+ task_key,
+ err
+ );
+ }
+ }
+ None
+ } else {
+ match subagent_sessions::find_reusable(&store, &selector) {
+ Ok(session) => session,
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] lookup failed parent_thread_id={} agent_id={} task_key={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ definition.id,
+ task_key,
+ err
+ );
+ None
+ }
+ }
+ };
+ let reuse_decision = subagent_sessions::reuse_decision(reusable.as_ref(), force_fresh);
+ let follow_up_prompt = reusable_follow_up_message(&prompt, context.as_deref());
+
+ if let Some(session) = reusable.as_ref() {
+ if session.status == DurableSubagentStatus::Running {
+ if let Some(ref running_task_id) = session.current_task_id {
+ match steer_reusable_session(
+ &detached_parent,
+ &session.subagent_session_id,
+ follow_up_prompt.clone(),
+ )
+ .await
+ {
+ Ok(()) => {
+ log::info!(
+ "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ running_task_id,
+ definition.id,
+ reuse_decision.as_str()
+ );
+ let payload = async_subagent_ref_payload(
+ running_task_id,
+ &session.subagent_session_id,
+ &definition.id,
+ session.worker_thread_id.as_deref(),
+ true,
+ reuse_decision.as_str(),
+ "running",
+ &fleet,
+ );
+ let follow_up = if fleet.can_wait() {
+ "Use the structured reference below to send more input, wait, or perform a short timeout tick."
+ } else {
+ "Its result is delivered to you automatically on a later turn; do not wait or poll for it."
+ };
+ return Ok(ToolResult::success(format!(
+ "Continued reusable async sub-agent `{}`. It is already running and will pick up the new instruction at its next step. \
+ {}\n\n[async_subagent_ref]\n{}\n[/async_subagent_ref]",
+ payload["agent_id"].as_str().unwrap_or("subagent"),
+ follow_up,
+ serde_json::to_string(&payload)
+ .unwrap_or_else(|_| "{}".to_string())
+ )));
+ }
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] running steer failed parent_thread_id={} subagent_session_id={} task_id={} agent_id={} error={:?}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ session.subagent_session_id,
+ running_task_id,
+ definition.id,
+ err
+ );
+ }
+ }
+ }
+ }
+ }
+
+ let task_id = format!("sub-{}", uuid::Uuid::new_v4());
+ if let Some(thread_id) = parent_thread_id.as_deref() {
+ if crate::agent::orchestration::background_completions::mark_stopped_task_if_thread_stopped(
+ &dispatch,
+ &parent.workspace_dir,
+ thread_id,
+ &task_id,
+ ) {
+ return Ok(ToolResult::error(
+ "spawn_async_subagent: parent thread is stopped or deleted",
+ ));
+ }
+ }
+ // Capture the admitted parent generation before creating a worker
+ // thread, writing a durable running session, or publishing spawn
+ // events. A denied lifecycle admission must leave no phantom child.
+ let completion_target = match crate::agent::orchestration::background_completions::CompletionTarget::new(
+ dispatch.clone(),
+ parent.workspace_dir.clone(),
+ parent_session.clone(),
+ parent_thread_id.clone(),
+ ) {
+ Ok(target) => target,
+ Err(error) => {
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: parent lifecycle admission failed: {error}"
+ )));
+ }
+ };
+ let worker_thread_id = reusable
+ .as_ref()
+ .and_then(|session| session.worker_thread_id.clone())
+ .or_else(|| {
+ parent_thread_id.as_ref().and_then(|parent_thread_id| {
+ crate::threads::worker_thread::create_worker_thread(
+ &dispatch,
+ parent.workspace_dir.clone(),
+ parent_thread_id,
+ &definition.id,
+ &task_title,
+ &prompt,
+ )
+ .ok()
+ })
+ });
+ if let (Some(session), Some(worker_thread_id)) =
+ (reusable.as_ref(), worker_thread_id.as_ref())
+ {
+ if session.worker_thread_id.as_deref() == Some(worker_thread_id.as_str()) {
+ crate::threads::worker_thread::append_reuse_follow_up(
+ &dispatch,
+ parent.workspace_dir.clone(),
+ worker_thread_id,
+ &definition.id,
+ &task_id,
+ &follow_up_prompt,
+ (parent_thread_id.as_deref(), &session.subagent_session_id),
+ );
+ }
+ }
+ let durable_session = match subagent_sessions::upsert_running(
+ &store,
+ SubagentSessionUpsert {
+ selector,
+ display_name: Some(definition.display_name().to_string()),
+ task_title: task_title.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ task_id: task_id.clone(),
+ lifecycle_key: Some(
+ tinyagents_orchestration::subagent::SubagentTaskKey::from_context(
+ &detached_parent,
+ task_id.clone(),
+ parent_thread_id.clone(),
+ ),
+ ),
+ parent_epoch: completion_target.parent_epoch(),
+ },
+ reusable.as_ref(),
+ ) {
+ Ok(session) => session,
+ Err(err) => {
+ log::warn!(
+ "[subagent_reuse] upsert failed parent_thread_id={} task_id={} agent_id={} reuse_decision={} error={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ task_id,
+ definition.id,
+ reuse_decision.as_str(),
+ err
+ );
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: failed to persist reusable sub-agent session: {err}"
+ )));
+ }
+ };
+
+ let initial_history = reusable
+ .as_ref()
+ .and_then(|session| session.latest_history.clone())
+ .map(|mut history| {
+ history.push(TranscriptMessage::user(follow_up_prompt.clone()));
+ history
+ });
+
+ log::info!(
+ "[subagent_reuse] parent_thread_id={} subagent_session_id={} task_id={} agent_id={} reuse_decision={} task_key={}",
+ parent_thread_id.as_deref().unwrap_or("none"),
+ durable_session.subagent_session_id,
+ task_id,
+ definition.id,
+ reuse_decision.as_str(),
+ task_key
+ );
+
+ crate::agent::orchestration::subagent_events::publish_subagent_spawned(
+ parent_session.clone(),
+ definition.id.clone(),
+ "async".to_string(),
+ task_id.clone(),
+ prompt.chars().count(),
+ );
+ if let Some(ref tx) = progress_sink {
+ let _ = tx
+ .send(AgentProgress::SubagentSpawned {
+ agent_id: definition.id.clone(),
+ task_id: task_id.clone(),
+ mode: "async".to_string(),
+ dedicated_thread: worker_thread_id.is_some(),
+ prompt_chars: prompt.chars().count(),
+ prompt: prompt.clone(),
+ worker_thread_id: worker_thread_id.clone(),
+ display_name: Some(definition.display_name().to_string()),
+ parent_call_id: crate::tools::host_extensions::tool_call_id(tool_context),
+ })
+ .await;
+ }
+
+ let background_workspace_dir = parent.workspace_dir.clone();
+ let background_dispatch = dispatch.clone();
+ let background_agent_id = definition.id.clone();
+ let background_task_id = task_id.clone();
+ let background_parent_session = parent_session.clone();
+ let background_worker_thread_id = worker_thread_id.clone();
+ let background_store = store.clone();
+ let background_subagent_session_id = durable_session.subagent_session_id.clone();
+ let background_thread_id = background_worker_thread_id
+ .clone()
+ .unwrap_or_else(|| background_subagent_session_id.clone());
+ let background_parent_thread_id = parent_thread_id.clone();
+ log::debug!(
+ "[spawn_async_subagent] register task_id={} parent_session={} parent_thread_id={}",
+ task_id,
+ parent_session,
+ background_parent_thread_id.as_deref().unwrap_or("none")
+ );
+ let completion_core = dispatch.clone().into_core();
+ let completion_origin = detached_parent.data.origin.clone();
+ let completion_worker_thread_id = background_worker_thread_id.clone();
+ let registration_progress = progress_sink.clone();
+ let registration_completion_target = completion_target.clone();
+ let registration_parent_session = parent_session.clone();
+ let registration_agent_id = definition.id.clone();
+ let registration_task_id = task_id.clone();
+ let completion = completion::make_completion(
+ completion_core,
+ completion_origin,
+ progress_sink.clone(),
+ background_workspace_dir,
+ background_dispatch,
+ background_agent_id,
+ background_task_id,
+ background_parent_session,
+ completion_target,
+ completion_worker_thread_id,
+ background_store,
+ background_subagent_session_id,
+ background_parent_thread_id,
+ );
+ let background_prompt = add_background_contract(&prompt);
+ let options = SubagentRunOptions {
+ skill_filter_override: None,
+ context,
+ model_override,
+ task_id: Some(task_id.clone()),
+ thread_id: Some(background_thread_id),
+ run_context: detached_parent.data.child(),
+ worker_thread_id: background_worker_thread_id,
+ initial_history,
+ checkpoint_dir: None,
+ workspace_descriptor,
+ run_queue: None,
+ message_run_queue: None,
+ };
+ if let Err(error) = crate::agent::subagent_host::spawn_async_via_driver_tool(
+ &detached_parent,
+ definition.clone(),
+ background_prompt,
+ options,
+ completion,
+ )
+ .await
+ {
+ if let Err(store_err) = subagent_sessions::mark_failed(
+ &store,
+ &durable_session.subagent_session_id,
+ &task_id,
+ error.to_string(),
+ ) {
+ log::warn!(
+ "[subagent_reuse] mark_failed after driver registration error subagent_session_id={} task_id={} agent_id={} error={}",
+ durable_session.subagent_session_id,
+ task_id,
+ definition.id,
+ store_err
+ );
+ }
+ let message = error.to_string();
+ registration_completion_target
+ .failed(&registration_task_id, &registration_agent_id, &message)
+ .await;
+ crate::agent::orchestration::subagent_events::publish_subagent_failed(
+ registration_parent_session,
+ registration_task_id.clone(),
+ registration_agent_id.clone(),
+ message.clone(),
+ );
+ if let Some(progress) = registration_progress {
+ let _ = progress
+ .send(AgentProgress::SubagentFailed {
+ agent_id: registration_agent_id,
+ task_id: registration_task_id,
+ error: message,
+ })
+ .await;
+ }
+ return Ok(ToolResult::error(format!(
+ "spawn_async_subagent: failed to register detached sub-agent: {error}"
+ )));
+ }
+
+ Ok(accepted_spawn_result(
+ &task_id,
+ &durable_session.subagent_session_id,
+ &definition.id,
+ worker_thread_id.as_deref(),
+ reusable.is_some(),
+ reuse_decision.as_str(),
+ &fleet,
+ ))
+ }
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
index e69de29bb2..6940c1af17 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs
@@ -0,0 +1,686 @@
+//! Tool: `spawn_async_subagent` - fire-and-forget sub-agent delegation.
+//!
+//! Unlike `spawn_subagent`, this tool returns as soon as the child run is
+//! accepted. Completion/failure is reported through normal sub-agent lifecycle
+//! events and, when possible, persisted in the child worker thread.
+
+use super::subagent_abort_report::AbortReport;
+use crate::agent::orchestration::fleet_tools::FleetToolSet;
+use crate::agent::orchestration::running_subagents;
+use crate::agent::orchestration::subagent_sessions::{
+ self, DurableSubagentStatus, SubagentSessionSelector, SubagentSessionStore,
+ SubagentSessionUpsert,
+};
+use crate::agent::orchestration::tools::dispatch::incomplete_stop;
+use crate::agent::subagent_host::SubagentRunOptions;
+use crate::agent_registry::host_definition::AgentDefinitionRegistry;
+use crate::core::runtime::DispatchCtx;
+use crate::progress::AgentProgress;
+use crate::threads::store::{self as conversations, ConversationMessage};
+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 tinyagents_session::transcript::TranscriptMessage;
+use tinytools::ToolRunContext;
+use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
+
+pub struct SpawnAsyncSubagentTool {
+ /// The ids this instance advertises in its `agent_id` enum. Empty means
+ /// the whole registry. See [`SpawnAsyncSubagentTool::scoped`].
+ advertised_ids: Vec<String>,
+}
+
+/// Harness dispatch for the detached child path. It owns the typed parent run
+/// so the spawned child receives the caller's carrier before `tokio::spawn`.
+pub(crate) struct SpawnAsyncSubagentDispatch {
+ tool: Arc<dyn Tool>,
+}
+
+impl SpawnAsyncSubagentDispatch {
+ pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
+ Self { tool }
+ }
+}
+
+#[async_trait]
+impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
+ for SpawnAsyncSubagentDispatch
+{
+ fn tool(&self) -> Arc<dyn Tool> {
+ self.tool.clone()
+ }
+
+ async fn execute(
+ &self,
+ _state: &(),
+ _call_id: tinyagents_harness::CallId,
+ arguments: serde_json::Value,
+ _options: ToolCallOptions,
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let context = ToolExecutionContext::from_run_context(parent, _call_id.clone());
+ let detached_parent =
+ crate::agent::subagent_host::detached_subagent_parent(parent, "async-subagent")?;
+ SpawnAsyncSubagentTool::new()
+ .execute_with_live_parent_context(
+ arguments,
+ Some(&context),
+ parent.data.child(),
+ detached_parent,
+ )
+ .await
+ }
+}
+
+impl SpawnAsyncSubagentTool {
+ pub fn new() -> Self {
+ Self {
+ advertised_ids: Vec::new(),
+ }
+ }
+
+ /// An instance whose schema advertises only `ids`, the parent's
+ /// `[subagents]` allowlist.
+ ///
+ /// [`scope_spawn_async_subagent_spec`] narrows the session's spec view,
+ /// but on native tool calling the wire schema is read from the registered
+ /// tool itself (`CanonicalSharedToolAdapter::for_name` → `Tool::spec`),
+ /// so the narrowed view never reached the provider: a captured
+ /// orchestrator request carried all 19 registry ids. The session builder
+ /// swaps this instance in so both views agree. Execution is unchanged;
+ /// `execute` enforces the allowlist either way.
+ pub fn scoped(mut ids: Vec<String>) -> Self {
+ ids.sort();
+ ids.dedup();
+ Self {
+ advertised_ids: ids,
+ }
+ }
+}
+
+/// Route reusable-session input through the same generic Message operation
+/// installed for model calls. Durable session id lookup keeps the host from
+/// steering an unrelated live task by a raw task-id string.
+async fn steer_reusable_session(
+ parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ session_id: &str,
+ message: String,
+) -> Result<(), String> {
+ use tinyagents_harness::tool::ToolDispatch;
+ use tinyagents_harness_tools::subagents::{SubAgentJobRegistry, SubAgentMessageTool};
+ use tinytools::{ToolCallOptions, ToolTimeout};
+
+ let context = &parent.data;
+ let product_parent = context
+ .parent
+ .as_ref()
+ .ok_or_else(|| "reusable async subagent has no durable parent".to_owned())?;
+ let thread_id = parent.thread_id().map(|id| id.as_str().to_owned());
+ let owner = crate::agent::tinyagents::tool_registration::subagent_owner_key(
+ &product_parent.workspace_dir,
+ &product_parent.session_id,
+ thread_id.as_deref(),
+ );
+ let owner_scope: Arc<dyn Fn(u64) -> String + Send + Sync> = Arc::new(move |_| owner.clone());
+ let jobs =
+ (*crate::core::runtime::slot_for::<SubAgentJobRegistry>(&context.dispatch_ctx())).clone();
+ let store: Arc<dyn tinyagents_orchestration::subagent::SubagentSessionStore> = Arc::new(
+ crate::agent::orchestration::subagent_sessions::OpenHumanTinySubagentSessionStore::new(
+ product_parent.workspace_dir.clone(),
+ product_parent.session_id.clone(),
+ thread_id.clone(),
+ ),
+ );
+ let parent_session = product_parent.session_id.clone();
+ let dispatch = SubAgentMessageTool::new(jobs)
+ .with_tool_name("steer_subagent")
+ .with_argument_fields("task_id", "subagent_session_id", "message", "__request_id")
+ .with_lane_field("mode")
+ .with_owner_scope(owner_scope)
+ .with_sessions(store, move |_| parent_session.clone())
+ .with_metadata(
+ PermissionLevel::Execute,
+ tinytools::ToolScope::All,
+ tinytools::ToolCategory::System,
+ ToolTimeout::Inherit,
+ );
+ let result = ToolDispatch::execute(
+ &dispatch,
+ &(),
+ tinyagents_harness::CallId::new(format!("reuse-steer-{session_id}")),
+ json!({
+ "subagent_session_id": session_id,
+ "message": message,
+ "mode": "steer",
+ }),
+ ToolCallOptions::default(),
+ parent,
+ )
+ .await
+ .map_err(|error| error.to_string())?;
+ if result.is_error {
+ Err(result.output())
+ } else {
+ Ok(())
+ }
+}
+
+impl Default for SpawnAsyncSubagentTool {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Narrow a session's `spawn_async_subagent` schema to the ids the parent may
+/// actually dispatch.
+///
+/// The tool is registered once per process, so its `agent_id` enum is built
+/// from the whole registry: 30-odd ids, of which the orchestrator's
+/// `[subagents]` allowlist admits about twenty. `execute` already refuses the
+/// rest, so advertising them only bought a refused call and a slice of schema
+/// on every turn. Called from the per-session spec view
+/// (`builder::visible_tool_specs_for_policy`), the same place `use_skill`'s
+/// pack index is narrowed. A missing or empty allowlist leaves the spec alone:
+/// wildcard parents keep the full registry.
+pub fn scope_spawn_async_subagent_spec(spec: &mut tinytools::ToolSpec, allowed: &[String]) {
+ if allowed.is_empty() {
+ return;
+ }
+ let Some(enum_slot) = spec
+ .parameters
+ .pointer_mut("/properties/agent_id/enum")
+ .filter(|value| value.is_array())
+ else {
+ return;
+ };
+ let mut ids: Vec<String> = allowed.to_vec();
+ ids.sort();
+ ids.dedup();
+ *enum_slot = serde_json::Value::Array(ids.into_iter().map(serde_json::Value::String).collect());
+ if let Some(description) = spec
+ .parameters
+ .pointer_mut("/properties/agent_id/description")
+ {
+ *description = serde_json::Value::String(
+ "Sub-agent id (only these are dispatchable from here).".to_string(),
+ );
+ }
+}
+
+#[async_trait]
+impl Tool for SpawnAsyncSubagentTool {
+ fn name(&self) -> &str {
+ "spawn_async_subagent"
+ }
+
+ fn description(&self) -> &str {
+ "Fire-and-forget a sub-agent for background work this reply does not depend on \
+ (archiving, cleanup, background investigation). Returns immediately; never for \
+ user-visible answers, writes, financial actions, or anything that gates your reply."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ let scoped = !self.advertised_ids.is_empty();
+ let agent_ids: Vec<String> = if scoped {
+ self.advertised_ids.clone()
+ } else {
+ AgentDefinitionRegistry::current()
+ .map(|reg| reg.list().iter().map(|d| d.id.clone()).collect())
+ .unwrap_or_default()
+ };
+
+ let agent_id_schema = if agent_ids.is_empty() {
+ json!({
+ "type": "string",
+ "description": "Sub-agent id (e.g. researcher, summarizer)."
+ })
+ } else {
+ json!({
+ "type": "string",
+ "enum": agent_ids,
+ "description": if scoped {
+ "Sub-agent id (only these are dispatchable from here)."
+ } else {
+ "Sub-agent id from the registry."
+ }
+ })
+ };
+
+ json!({
+ "type": "object",
+ "required": ["agent_id", "prompt"],
+ "properties": {
+ "agent_id": agent_id_schema,
+ "prompt": {
+ "type": "string",
+ "description": "Self-contained instruction with all needed context; the worker cannot ask the user."
+ },
+ "context": {
+ "type": "string",
+ "description": "Optional prior results, rendered as a `[Context]` block before the prompt."
+ },
+ "model": {
+ "type": "string",
+ "description": "Optional exact model id for this spawn only."
+ },
+ "task_title": {
+ "type": "string",
+ "description": "Optional short title for the worker thread."
+ },
+ "task_key": {
+ "type": "string",
+ "description": "Optional identity key for reusing an existing worker."
+ },
+ "fresh": {
+ "type": "boolean",
+ "description": "Force a fresh worker instead of reusing a matching one."
+ }
+ }
+ })
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Execute
+ }
+
+ 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> {
+ self.execute_with_context_inner(
+ args,
+ options,
+ tool_context,
+ crate::agent::tinyagents::host::OpenHumanRunContext::new().with_core(
+ crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)
+ .into_core(),
+ ),
+ None,
+ )
+ .await
+ }
+}
+
+impl SpawnAsyncSubagentTool {
+ /// Drive the tool the way a live parent turn does, over an explicit
+ /// `parent` execution context. Tests only: production turns reach the tool
+ /// through [`SpawnAsyncSubagentDispatch`] with their own carrier.
+ #[cfg(test)]
+ pub(crate) async fn execute_under_parent(
+ &self,
+ args: serde_json::Value,
+ options: ToolCallOptions,
+ tool_context: Option<&dyn ToolRunContext>,
+ parent: crate::agent::harness::ParentExecutionContext,
+ ) -> anyhow::Result<ToolResult> {
+ let live_parent = super::live_parent_run_context("direct-async-subagent", parent);
+ let detached_parent =
+ crate::agent::subagent_host::detached_subagent_parent(&live_parent, "async-subagent")?;
+ self.execute_with_context_inner(
+ args,
+ options,
+ tool_context,
+ live_parent.data.child(),
+ Some(detached_parent),
+ )
+ .await
+ }
+
+ pub(crate) async fn execute_with_live_parent_context(
+ &self,
+ args: serde_json::Value,
+ tool_context: Option<&dyn ToolRunContext>,
+ run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
+ detached_parent: RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ self.execute_with_context_inner(
+ args,
+ ToolCallOptions::default(),
+ tool_context,
+ run_context,
+ Some(detached_parent),
+ )
+ .await
+ }
+}
+
+#[path = "spawn_async_subagent_completion.rs"]
+mod completion;
+
+include!("spawn_async_subagent_host_impl.rs");
+include!("spawn_async_subagent_request.rs");
+include!("spawn_async_subagent_projection.rs");
+
+/// Settle a late registration refusal before an accepted response is built.
+#[cfg(test)]
+fn finish_spawn_registration(
+ registration: Result<(), running_subagents::RegistrationError>,
+ store: &SubagentSessionStore,
+ session_id: &str,
+ task_id: &str,
+) -> Result<(), String> {
+ if let Err(error) = registration {
+ let refusal = format!("spawn_async_subagent: registration refused: {error}");
+ subagent_sessions::mark_failed(store, session_id, task_id, refusal.clone()).map_err(
+ |failure| format!("{refusal}; failed to settle persisted session: {failure}"),
+ )?;
+ return Err(refusal);
+ }
+ Ok(())
+}
+
+/// Format the user-facing acceptance text around a structured async sub-agent reference.
+///
+/// The wording follows what the parent can actually do: a parent without
+/// `wait_subagent` (the orchestrator, #5701) is told the result arrives on its
+/// own and not to poll, instead of being invited to "wait for completion".
+fn format_async_subagent_accepted(
+ agent_id: &str,
+ payload_json: &str,
+ fleet: &FleetToolSet,
+) -> String {
+ // Steering and waiting are independent fleet capabilities: a parent can
+ // have `wait_subagent` without `steer_subagent` (or vice versa), so the
+ // guidance text is built from each independently rather than gated
+ // entirely on `can_wait()` — otherwise a wait-only parent is told to
+ // "send more input" through a tool it does not have.
+ let can_send = fleet.has("steer_subagent");
+ let can_wait = fleet.can_wait();
+ let guidance = match (can_send, can_wait) {
+ (true, true) => {
+ "Use the structured reference below to send more input, wait for completion, or perform a short timeout tick to check status. If the user does not need the result now, continue without blocking."
+ }
+ (true, false) => {
+ "Use the structured reference below to send more input if needed. You cannot and need not wait or poll for it (no shell/sleep, no fake status checks); its result is delivered to you automatically on a later turn. If the user does not need the result now, continue without blocking."
+ }
+ (false, true) => {
+ "Use the structured reference below to wait for completion or perform a short timeout tick to check status. If the user does not need the result now, continue without blocking."
+ }
+ (false, false) => {
+ "Its result is delivered to you automatically on a later turn — you cannot and need not wait or poll for it (no shell/sleep, no fake status checks). Reply to the user now with what you know, say the result is on its way, and continue. The structured reference below lists the only follow-up tools you have for this worker."
+ }
+ };
+ format!(
+ "Accepted async sub-agent `{agent_id}`. {guidance}
+
+[async_subagent_ref]
+{payload_json}
+[/async_subagent_ref]"
+ )
+}
+
+/// Build the machine-readable reference the orchestrator uses to follow up on a worker.
+///
+/// Only tools in `fleet` are offered: an instruction naming a tool the parent
+/// cannot see costs an iteration of confused reasoning per delegation.
+fn async_subagent_ref_payload(
+ task_id: &str,
+ subagent_session_id: &str,
+ agent_id: &str,
+ worker_thread_id: Option<&str>,
+ reused: bool,
+ reuse_decision: &str,
+ status: &str,
+ fleet: &FleetToolSet,
+) -> serde_json::Value {
+ let mut instructions = serde_json::Map::new();
+ let mut next_actions: Vec<String> = Vec::new();
+
+ if fleet.has("steer_subagent") {
+ instructions.insert(
+ "send_message".into(),
+ json!({
+ "tool": "steer_subagent",
+ "description": "Send additional instructions or context to this running async sub-agent.",
+ "arguments": {
+ "subagent_session_id": subagent_session_id,
+ "message": "<message>",
+ "mode": "steer"
+ }
+ }),
+ );
+ next_actions.push("call steer_subagent to send more input".into());
+ }
+ if fleet.has("wait_subagent") {
+ instructions.insert(
+ "wait".into(),
+ json!({
+ "tool": "wait_subagent",
+ "description": "Block until the async sub-agent finishes, up to the timeout.",
+ "arguments": { "subagent_session_id": subagent_session_id, "timeout_secs": 120 }
+ }),
+ );
+ instructions.insert(
+ "timeout_tick".into(),
+ json!({
+ "tool": "wait_subagent",
+ "description": "Perform a short status tick without committing the parent to a long wait.",
+ "arguments": { "subagent_session_id": subagent_session_id, "timeout_secs": 1 }
+ }),
+ );
+ next_actions.push("call wait_subagent with timeout_secs to collect the result".into());
+ next_actions
+ .push("call wait_subagent with timeout_secs=1 as a timeout tick/status check".into());
+ let reminder = format!(
+ "Check async sub-agent {agent_id} status with wait_subagent using subagent_session_id {subagent_session_id}."
+ );
+ if fleet.has("wait") {
+ instructions.insert(
+ "delayed_tick".into(),
+ json!({
+ "tool": "wait",
+ "description": "Trigger a delayed callback before checking this async sub-agent again.",
+ "arguments": { "duration_secs": 30, "message": reminder }
+ }),
+ );
+ }
+ if fleet.has("wait_loop") {
+ instructions.insert(
+ "delayed_loop".into(),
+ json!({
+ "tool": "wait_loop",
+ "description": "Trigger repeatable delayed callbacks while this async sub-agent is still relevant.",
+ "arguments": {
+ "duration_secs": 30,
+ "message": reminder,
+ "loop_key": subagent_session_id,
+ "iteration": 1
+ }
+ }),
+ );
+ }
+ if fleet.has("wait") || fleet.has("wait_loop") {
+ next_actions.push(
+ "call wait or wait_loop with the returned message to trigger a delayed status check".into(),
+ );
+ }
+ }
+ if fleet.has("continue_subagent") {
+ instructions.insert(
+ "answer_or_resume".into(),
+ json!({
+ "tool": "continue_subagent",
+ "description": "Answer this worker if it pauses on ask_user_clarification (awaiting_user), or resume it later with a follow-up that keeps its context.",
+ "arguments": { "subagent_session_id": subagent_session_id, "message": "<answer or follow-up>" }
+ }),
+ );
+ next_actions.push(
+ "call continue_subagent only if this worker reports awaiting_user, or to resume it with a follow-up".into(),
+ );
+ }
+ if fleet.has("list_subagents") {
+ next_actions.push("call list_subagents to re-enumerate your workers if this reference scrolls out of context".into());
+ }
+ next_actions.push(if fleet.can_wait() {
+ "continue without waiting when the current user reply does not depend on the result".into()
+ } else {
+ "continue now: the result is delivered to you automatically on a later turn; never poll for it".into()
+ });
+
+ json!({
+ "task_id": task_id,
+ "taskId": task_id,
+ "subagent_session_id": subagent_session_id,
+ "subagentSessionId": subagent_session_id,
+ "agent_id": agent_id,
+ "agentId": agent_id,
+ "mode": "async",
+ "status": status,
+ "worker_thread_id": worker_thread_id,
+ "workerThreadId": worker_thread_id,
+ "reused": reused,
+ "reuse_decision": reuse_decision,
+ "reuseDecision": reuse_decision,
+ "result_delivery": "automatic",
+ "instructions": instructions,
+ "next_actions": next_actions
+ })
+}
+
+fn add_background_contract(prompt: &str) -> String {
+ format!(
+ "[Background Contract]\n\
+ Run this task without requiring attention from the parent or user. \
+ Do not call ask_user_clarification. If required information is missing, \
+ make the safest best-effort progress and record the limitation in your final output.\n\n\
+ [Task]\n{prompt}"
+ )
+}
+
+fn durable_task_key_source(
+ args: &serde_json::Value,
+ prompt: &str,
+ context: Option<&str>,
+) -> String {
+ if let Some(task_key) = args
+ .get("task_key")
+ .and_then(|v| v.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ return task_key.to_string();
+ }
+
+ match context.map(str::trim).filter(|s| !s.is_empty()) {
+ Some(context) => format!("{prompt}\n\n[Context]\n{context}"),
+ None => prompt.to_string(),
+ }
+}
+
+/// Scan a finished child's history for the LAST `workflow_proposal` tool
+/// result (the workflow_builder's `propose_workflow` / `revise_workflow` /
+/// `edit_workflow` all return `{"type":"workflow_proposal", ...}` JSON).
+/// Returns the parsed payload, or `None` when the run produced no proposal.
+/// Lives here (not in `flows`) so the always-on orchestration path has no
+/// dependency on the feature-gated flows domain — it is a generic scan for a
+/// structured tool payload.
+pub(crate) fn extract_workflow_proposal_from_history(
+ history: &[TranscriptMessage],
+) -> Option<serde_json::Value> {
+ history
+ .iter()
+ .rev()
+ .filter(|message| message.role == "tool")
+ .find_map(|message| {
+ let value: serde_json::Value = serde_json::from_str(message.content.trim()).ok()?;
+ (value.get("type").and_then(|t| t.as_str()) == Some("workflow_proposal"))
+ .then_some(value)
+ })
+}
+
+/// Durably surface a workflow proposal found in a finished child's history:
+/// persist it as a parent-thread conversation message (metadata carries the
+/// full payload so the UI can rehydrate the proposal card after reload) and
+/// append a `[workflow_proposal]` envelope to the delivery summary so the
+/// follow-up turn presents it faithfully. Returns the (possibly extended)
+/// summary; on any persistence error the summary still carries the envelope —
+/// losing durability must not lose delivery.
+fn attach_workflow_proposal(
+ ctx: &DispatchCtx,
+ workspace_dir: &std::path::Path,
+ parent_thread_id: Option<&str>,
+ task_id: &str,
+ agent_id: &str,
+ final_history: &[TranscriptMessage],
+ summary: String,
+) -> String {
+ let Some(proposal) = extract_workflow_proposal_from_history(final_history) else {
+ return summary;
+ };
+ let proposal_json = match serde_json::to_string(&proposal) {
+ Ok(json) => json,
+ Err(err) => {
+ log::warn!(
+ "[spawn_async_subagent] workflow proposal re-serialize failed task_id={task_id} error={err}"
+ );
+ return summary;
+ }
+ };
+ let name = proposal
+ .get("name")
+ .and_then(|n| n.as_str())
+ .unwrap_or("Untitled workflow");
+ log::info!(
+ "[spawn_async_subagent] extracted workflow proposal '{name}' task_id={task_id} \
+ ({} chars) — persisting to parent thread {:?}",
+ proposal_json.len(),
+ parent_thread_id
+ );
+ if let Some(thread_id) = parent_thread_id {
+ let persisted = conversations::append_message(
+ ctx,
+ workspace_dir.to_path_buf(),
+ thread_id,
+ ConversationMessage {
+ id: format!("workflow-proposal:{task_id}"),
+ content: format!("Workflow proposal ready: {name}"),
+ message_type: "text".to_string(),
+ extra_metadata: json!({
+ "scope": "workflow_proposal",
+ "proposal": proposal,
+ "task_id": task_id,
+ "agent_id": agent_id,
+ }),
+ sender: "agent".to_string(),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ },
+ );
+ if let Err(err) = persisted {
+ log::warn!(
+ "[spawn_async_subagent] workflow proposal persistence failed \
+ thread_id={thread_id} task_id={task_id} error={err} — proposal still \
+ rides the delivery notice"
+ );
+ }
+ }
+ format!(
+ "{summary}\n\n[workflow_proposal]\n{proposal_json}\n[/workflow_proposal]\n\
+ (The full proposal above was also saved to the chat thread; present it to the \
+ user for review — do not re-run the builder unless they ask for changes.)"
+ )
+}
+
+fn reusable_follow_up_message(prompt: &str, context: Option<&str>) -> String {
+ let mut message = String::from("[Follow-up instruction for reusable sub-agent]\n");
+ if let Some(context) = context.map(str::trim).filter(|s| !s.is_empty()) {
+ message.push_str("\n[Context]\n");
+ message.push_str(context);
+ message.push_str("\n\n");
+ }
+ message.push_str("[Task]\n");
+ message.push_str(prompt);
+ message
+}
+
+#[cfg(test)]
+#[path = "spawn_async_subagent_tests.rs"]
+mod tests;