The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore(subagent): remove legacy async subagent spawn modules
Steven Enamakelcc49f14dba74
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_completion.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_completion.rsdeleted file mode 100644index 5716df1300..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_completion.rs+++ /dev/null@@ -1,363 +0,0 @@-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_async_subagent_host_impl.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_host_impl.rsdeleted file mode 100644index a2fc479f30..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_host_impl.rs+++ /dev/null@@ -1,510 +0,0 @@-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- );- return Ok(ToolResult::error(format!(- "spawn_async_subagent: failed to continue existing running task '{}' in session '{}'; refusing to start a duplicate: {err}",- running_task_id, session.subagent_session_id- )));- }- }- }- }- }-- 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(®istration_task_id, ®istration_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_async_subagent_surface.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rsdeleted file mode 100644index 6940c1af17..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_surface.rs+++ /dev/null@@ -1,686 +0,0 @@-//! 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;diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rssimilarity index 100%rename from crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_tests.rsrename to crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_async_tests.rsdiff --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.rsdeleted file mode 100644index 11dc8d1055..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_host_impl.rs+++ /dev/null@@ -1,565 +0,0 @@-#[async_trait]-impl Tool for SpawnSubagentTool {- fn name(&self) -> &str {- "spawn_subagent"- }-- fn description(&self) -> &str {- "Delegate a task to a specialised sub-agent only when direct \- response or direct tools are insufficient. Handles ONE delegated task \- per call: by default it runs as a reusable async worker and returns \- immediately — pass `blocking: true` to run it inline and get the \- sub-agent's final output back in this turn. To run several independent \- workers at once (e.g. \"a separate worker for each X\", a council \- of opinions, or \"fan out over N items\"), issue separate async \- sub-agent requests and collect their results. \- See the Delegation \- Guide in the system prompt for available agent_ids and when to \- use each."- }-- fn parameters_schema(&self) -> serde_json::Value {- spawn_subagent_parameters_schema()- }-- 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_parent_context(- args,- tool_context,- crate::agent::tinyagents::host::OpenHumanRunContext::new().with_core(- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)- .into_core(),- ),- )- .await- }-}--impl SpawnSubagentTool {- pub(crate) async fn execute_with_parent_context(- &self,- args: serde_json::Value,- tool_context: Option<&dyn ToolRunContext>,- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,- ) -> anyhow::Result<ToolResult> {- self.execute_with_live_parent_context(args, tool_context, run_context, None)- .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,- live_parent: Option<- &tinyagents_harness::context::RunContext<- crate::agent::tinyagents::host::OpenHumanRunContext,- >,- >,- ) -> anyhow::Result<ToolResult> {- let dispatch = run_context.dispatch_ctx();- // ── Argument extraction with back-compat ───────────────────────- let agent_id = args- .get("agent_id")- .and_then(|v| v.as_str())- // keep until v0.66 (review after 2027-01-11): frozen session schemas- // and stored calls may still use archetype; see the parameter schema.- .or_else(|| args.get("archetype").and_then(|v| v.as_str()))- .unwrap_or("")- .trim()- .to_string();-- let prompt = args- .get("prompt")- .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 model_override = args- .get("model")- .and_then(|v| v.as_str())- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty());-- // Worker threads are now always created for delegations that may- // need follow-up (checkpoint + replay for ask_user_clarification).- // The `dedicated_thread` parameter is accepted but no longer- // gates thread creation — every delegation gets a persistent- // worker thread. (#3049 supersedes the #1624 disable.)- let dedicated_thread = args- .get("dedicated_thread")- .and_then(|v| v.as_bool())- .unwrap_or(false);- let blocking = args- .get("blocking")- .and_then(|v| v.as_bool())- .unwrap_or(false);-- // ── Validation ─────────────────────────────────────────────────- if agent_id.is_empty() {- return Ok(ToolResult::error(- "spawn_subagent: `agent_id` (or legacy `archetype`) is required",- ));- }- if prompt.is_empty() {- return Ok(ToolResult::error("spawn_subagent: `prompt` is required"));- }- let registry =- match AgentDefinitionRegistry::for_core_context(run_context.dispatch_ctx().into_core())- {- Some(reg) => reg,- None => {- return Ok(ToolResult::error(- "spawn_subagent: AgentDefinitionRegistry has not been initialised. \- This usually means the core process started without calling \- AgentDefinitionRegistry::init_global at startup.",- ));- }- };-- let definition = match registry.get(agent_id.as_str()) {- Some(def) => def,- None => {- let available: Vec<&str> = registry.list().iter().map(|d| d.id.as_str()).collect();- return Ok(ToolResult::error(format!(- "spawn_subagent: unknown agent_id '{agent_id}'. Available: {}",- available.join(", ")- )));- }- };-- if let Some(parent_ctx) = run_context.parent.as_ref() {- if !parent_ctx.allowed_subagent_ids.contains(&definition.id) {- log::warn!(- "[spawn_subagent] blocked subagent outside parent allowlist parent_agent={} requested_agent={} allowed={:?}",- parent_ctx.agent_definition_id,- definition.id,- parent_ctx.allowed_subagent_ids- );- return Ok(ToolResult::error(format!(- "spawn_subagent: agent '{}' is not in parent agent '{}' subagents.allowlist",- definition.id, parent_ctx.agent_definition_id- )));- }- log::debug!(- "[spawn_subagent] subagent allowlist check passed parent_agent={} requested_agent={}",- parent_ctx.agent_definition_id,- definition.id- );- }-- // Input, registry, allowlist, and integration validation are safe to- // perform without a live run. A valid spawn must still fail closed- // unless its typed harness parent carries authority and cancellation.- let Some(live_parent) = live_parent else {- return Ok(ToolResult::error(- "spawn_subagent requires a live harness run context.",- ));- };-- // Async-by-default only holds where the finished result has somewhere- // to land. `spawn_async_subagent` delivers thread-addressed (see- // `background_delivery`), so outside a chat turn (flow `agent` node,- // CLI, cron) it now refuses outright (B40). Self-heal to blocking- // dispatch here rather than forwarding into that guard: the caller- // asked to delegate, and running the sub-agent inline is the one mode- // that both executes it and returns its output. Mirrors the- // `has_delivery_thread` fallback the `delegate_*` tools already do in- // `subagent_dispatch_host.rs::dispatch_subagent`.- let parent_thread_id = tool_context- .and_then(ToolRunContext::thread_id)- .or(run_context.thread_id.as_deref())- .map(str::to_owned);- let has_delivery_thread = parent_thread_id.is_some();- if !blocking && !has_delivery_thread {- log::info!(- "[spawn_subagent] async delegation requested for '{}' but no delivery thread \- (flow node / CLI / cron context) — falling back to blocking dispatch",- definition.id- );- }- if !blocking && has_delivery_thread {- let mut async_args = args;- if let Some(obj) = async_args.as_object_mut() {- obj.insert(- "agent_id".to_string(),- serde_json::Value::String(definition.id.clone()),- );- if obj.get("task_title").is_none() {- let title =- crate::agent::orchestration::subagent_sessions::task_title_from_prompt(- &prompt,- );- obj.insert("task_title".to_string(), serde_json::Value::String(title));- }- }- tracing::info!(- target: "spawn_subagent",- agent_id = %definition.id,- "[spawn_subagent] routing to reusable async sub-agent by default"- );- let detached_parent = crate::agent::subagent_host::detached_subagent_parent(- live_parent,- "async-subagent",- )?;- return super::spawn_async_subagent::SpawnAsyncSubagentTool::new()- .execute_with_live_parent_context(- async_args,- tool_context,- run_context,- detached_parent,- )- .await;- }-- // ── Publish SubagentSpawned event ──────────────────────────────- let parent_session = run_context- .parent- .as_ref()- .map(|p| p.session_id.clone())- .unwrap_or_else(|| "standalone".into());- let task_id = format!("sub-{}", uuid::Uuid::new_v4());-- // Persist this delegation as a reopenable worker sub-thread, seeded- // with the prompt, so the parent↔subagent conversation survives- // navigation and restarts. Best-effort: with no parent context or thread store the run- // still proceeds live-only (`worker_thread_id: None`).- let worker_thread_id = run_context.parent.as_ref().and_then(|p| {- let parent_thread_id = parent_thread_id.as_ref()?;- let title: String = prompt.chars().take(60).collect();- crate::threads::worker_thread::create_worker_thread(- &dispatch,- p.workspace_dir.clone(),- parent_thread_id,- &definition.id,- &title,- &prompt,- )- .ok()- });-- crate::agent::orchestration::subagent_events::publish_subagent_spawned(- parent_session.clone(),- definition.id.clone(),- "typed".to_string(),- task_id.clone(),- prompt.chars().count(),- );-- if let Some(progress) = run_context.progress.clone() {- let _ = progress- .send(AgentProgress::SubagentSpawned {- agent_id: definition.id.clone(),- task_id: task_id.clone(),- mode: "typed".to_string(),- dedicated_thread,- 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 workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());- if let Some(descriptor) = workspace_descriptor.as_ref() {- tracing::debug!(- task_id = %task_id,- agent_id = %definition.id,- workspace_root = %descriptor.root.display(),- policy_id = %descriptor.policy_id,- "[spawn_subagent] using ToolExecutionContext workspace root"- );- }- let progress_sink = run_context.progress.clone();- let parent_workspace_dir = run_context- .parent- .as_ref()- .map(|parent| parent.workspace_dir.clone());- let options = SubagentRunOptions {- skill_filter_override: None,- context,- model_override,- task_id: Some(task_id.clone()),- thread_id: parent_thread_id,- run_context,- worker_thread_id: worker_thread_id.clone(),- initial_history: None,- checkpoint_dir: None,- workspace_descriptor,- run_queue: None,- message_run_queue: None,- };-- let run =- run_subagent_via_driver_tool(live_parent, definition.clone(), prompt.clone(), options)- .await- .map(|(outcome, _job_id)| outcome);- match run {- Ok(outcome) => {- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();- match &outcome.status {- SubagentRunStatus::AwaitingUser {- question,- options: _,- checkpoint,- } => {- if emit_lifecycle_effects {- crate::agent::orchestration::subagent_events::publish_subagent_awaiting_user(- parent_session,- outcome.task_id.clone(),- outcome.agent_id.clone(),- question.clone(),- );- if let Some(ref tx) = progress_sink {- let _ = tx- .send(AgentProgress::SubagentAwaitingUser {- agent_id: outcome.agent_id.clone(),- task_id: outcome.task_id.clone(),- question: question.clone(),- worker_thread_id: worker_thread_id.clone(),- checkpoint_path: checkpoint- .as_ref()- .map(|p| p.to_string_lossy().to_string()),- })- .await;- }- }- let envelope = super::awaiting_user::awaiting_user_envelope(- &outcome.task_id,- &outcome.agent_id,- worker_thread_id.as_deref(),- question,- checkpoint.is_some(),- );- Ok(ToolResult::success(envelope))- }- SubagentRunStatus::Completed => {- tinyagents_harness::artifacts::note_artifact_handoff(- tinyagents_harness::artifacts::HANDOFF_STAGE_CONSUMED,- &outcome.agent_id,- &outcome.task_id,- &outcome.artifact_paths,- );- if emit_lifecycle_effects {- crate::agent::orchestration::subagent_events::publish_subagent_completed(- parent_session,- outcome.task_id.clone(),- outcome.agent_id.clone(),- outcome.elapsed.as_millis() as u64,- outcome.output.chars().count(),- outcome.iterations,- );-- if let Some(ref tx) = progress_sink {- let _ = tx- .send(AgentProgress::SubagentCompleted {- agent_id: outcome.agent_id.clone(),- task_id: outcome.task_id.clone(),- elapsed_ms: outcome.elapsed.as_millis() as u64,- iterations: outcome.iterations as u32,- output_chars: outcome.output.chars().count(),- output: outcome.output.clone(),- // BLOCKING spawn: this child's usage DID reach the parent's- // ledger, so `chat_done` already carries its tokens AND its- // cost. Populating here would double both. See the field's docs.- usage: None,- stop: None,- })- .await;- }- }-- if dedicated_thread {- let workspace_dir = parent_workspace_dir- .clone()- .unwrap_or_else(|| PathBuf::from("."));- let parent_visible = match persist_worker_thread(- &dispatch,- &workspace_dir,- &definition.id,- &prompt,- &outcome,- ) {- Ok(thread_id) => render_worker_thread_result(- &thread_id,- &definition.id,- &outcome,- ),- Err(error) => {- tracing::error!(- target: "spawn_subagent",- agent_id = %definition.id,- error = %error,- "[spawn_subagent] dedicated_thread persistence failed; \- returning full sub-agent output inline"- );- format!(- "{}\n\n[worker_thread_error] failed to persist worker thread: {}",- outcome.output, error- )- }- };- return Ok(ToolResult::success(parent_visible));- }-- Ok(ToolResult::success(outcome.output))- }- SubagentRunStatus::Incomplete { reason } => {- // The sub-agent stopped WITHOUT reaching its goal (a- // no-progress circuit breaker halted it, or it hit the- // iteration cap). Hand the orchestrator a structured- // envelope carrying BOTH the blocker and the partial- // progress — NOT the "nothing happened" failure envelope- // (work WAS done) and NOT a bare success it would narrate- // as done or re-spin (#4096).- tracing::info!(- agent_id = %outcome.agent_id,- task_id = %outcome.task_id,- iterations = outcome.iterations,- "[spawn_subagent] sub-agent stopped incomplete — returning structured handback"- );- if emit_lifecycle_effects {- crate::agent::orchestration::subagent_events::publish_subagent_completed(- parent_session,- outcome.task_id.clone(),- outcome.agent_id.clone(),- outcome.elapsed.as_millis() as u64,- outcome.output.chars().count(),- outcome.iterations,- );- if let Some(ref tx) = progress_sink {- let _ = tx- .send(AgentProgress::SubagentCompleted {- agent_id: outcome.agent_id.clone(),- task_id: outcome.task_id.clone(),- elapsed_ms: outcome.elapsed.as_millis() as u64,- iterations: outcome.iterations as u32,- output_chars: outcome.output.chars().count(),- output: outcome.output.clone(),- // BLOCKING spawn: this child's usage DID reach the parent's- // ledger, so `chat_done` already carries its tokens AND its- // cost. Populating here would double both. See the field's docs.- usage: None,- stop: incomplete_stop(- reason,- outcome.failure_cause.clone(),- ),- })- .await;- }- }- let envelope = format!(- "[SUBAGENT_INCOMPLETE]\n\- task_id: {}\n\- agent_id: {}\n\- reason: the sub-agent {reason}\n\- progress:\n{}\n\- [/SUBAGENT_INCOMPLETE]\n\n\- The sub-agent did NOT finish. Above is the partial progress it \- made. Do NOT report this as done or fabricate a result. Decide: \- relay the partial result and the blocker to the user, continue with \- a different approach, or escalate — but do not re-run the identical \- delegation unchanged.",- outcome.task_id, outcome.agent_id, outcome.output,- );- Ok(stopped_subagent_result(- "spawn_subagent",- &outcome.agent_id,- &outcome.task_id,- reason,- outcome.failure_cause.clone(),- envelope,- ))- }- SubagentRunStatus::Cancelled => {- tracing::info!(- agent_id = %outcome.agent_id,- task_id = %outcome.task_id,- "[spawn_subagent] sub-agent cancelled"- );- if emit_lifecycle_effects {- let message = "sub-agent was cancelled".to_string();- crate::agent::orchestration::subagent_events::publish_subagent_failed(- parent_session,- outcome.task_id.clone(),- outcome.agent_id.clone(),- message.clone(),- );- if let Some(ref tx) = progress_sink {- let _ = tx- .send(AgentProgress::SubagentFailed {- agent_id: outcome.agent_id.clone(),- task_id: outcome.task_id.clone(),- error: message,- })- .await;- }- }- Ok(ToolResult::error(- "spawn_subagent: delegated sub-agent was cancelled",- ))- }- }- }- Err(err) => {- let message = err.to_string();- let parent_visible_error = Self::classify_subagent_failure(&message);- // Log only non-sensitive context: agent_id and task_id. The raw- // error message and classified summary may contain user prompts or- // payload fragments — emit only a short type/kind indicator.- let error_kind = message- .split(':')- .next()- .map(str::trim)- .unwrap_or("unknown");- tracing::error!(- agent_id = %definition.id,- task_id = %task_id,- error_kind = %error_kind,- "[spawn_subagent] sub-agent execution failed"- );- crate::agent::orchestration::subagent_events::publish_subagent_failed(- parent_session,- task_id.clone(),- definition.id.clone(),- message.clone(),- );-- if let Some(ref tx) = progress_sink {- let _ = tx- .send(AgentProgress::SubagentFailed {- agent_id: definition.id.clone(),- task_id: task_id.clone(),- error: message.clone(),- })- .await;- }- // Surface as a non-fatal tool error so the parent model- // can react and (e.g.) retry with different params.- Ok(ToolResult::error(parent_visible_error))- }- }- }-}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_projection.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_projection.rssimilarity index 100%rename from crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_projection.rsrename to crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_projection.rsdiff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_request.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_request.rssimilarity index 100%rename from crates/openhuman-core/src/agent/orchestration/tools/spawn_async_subagent_request.rsrename to crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_request.rsdiff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_schema.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_schema.rsdeleted file mode 100644index b61b5fc1e9..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_schema.rs+++ /dev/null@@ -1,78 +0,0 @@-// `spawn_subagent`'s parameter schema.-//-// Textually included into `spawn_subagent_surface.rs` beside-// `spawn_subagent_host_impl.rs`, so it shares that module's imports. Split out-// because the impl fragment had grown to 803 lines against the layout gate's-// pin, and this is the one part of it that answers a question of its own —-// "what arguments does this tool take?" — with no dependence on the execution-// path around it. It is a pure function of the agent registry.-//-// Behaviour is unchanged: the same statements, returning the same value. The-// trait method now delegates here, because a trait impl must stay one block.--/// The `spawn_subagent` JSON schema, with `agent_id` enumerated from the live-/// registry when one is initialised.-fn spawn_subagent_parameters_schema() -> serde_json::Value {- // Build the agent_id enum dynamically from the global registry- // when it's been initialised. Falls back to a string-with-hint- // when the registry hasn't been set up yet (e.g. early tests).- let agent_ids: Vec<String> = 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. code_executor, researcher, summarizer)."- })- } else {- json!({- "type": "string",- "enum": agent_ids,- "description": "Sub-agent id from the registry."- })- };-- json!({- "type": "object",- "required": ["agent_id", "prompt"],- "properties": {- "agent_id": agent_id_schema,- // keep until v0.66 (review after 2027-01-11): resumed sessions freeze- // their tool schemas; retirement needs persisted-call evidence.- // Back-compat alias — older callers used `archetype`.- "archetype": {- "type": "string",- "description": "Deprecated alias for `agent_id`. Use `agent_id` going forward."- },- "prompt": {- "type": "string",- "description": "Clear, specific instruction for the sub-agent. The sub-agent has no memory of the parent's conversation, so include all context the sub-agent needs to act."- },- "context": {- "type": "string",- "description": "Optional context blob from prior task results. Rendered as a `[Context]` block before the prompt."- },- "model": {- "type": "string",- "description": "Optional exact model id for this spawn only. Keeps the parent provider/routing, but pins the child agent to this model instead of the agent definition's default."- },- "dedicated_thread": {- "type": "boolean",- "description": "Legacy compatibility flag. Delegations now always create a persistent worker thread when parent context is available, so this flag no longer gates thread creation."- },- "blocking": {- "type": "boolean",- "description": "Explicitly run the sub-agent inline and return its final output. Defaults to false; reusable async delegation is the default."- },- "task_key": {- "type": "string",- "description": "Optional deterministic identity key for reusable async delegation. Defaults to a normalized prompt/title."- },- "fresh": {- "type": "boolean",- "description": "When true, bypass reusable subagent matching and create a fresh durable worker."- }- }- })-}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.rsdeleted file mode 100644index a8bcbd8253..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_subagent_surface.rs+++ /dev/null@@ -1,234 +0,0 @@-//! Tool: `spawn_subagent` — delegate a sub-task to a specialised sub-agent.-//!-//! The orchestrator (or any parent agent that has this tool registered)-//! calls `spawn_subagent` to hand off a focused sub-task. The runner-//! looks up the requested [`AgentDefinition`] in the global registry,-//! filters the parent's tool registry per the definition, builds a-//! narrow system prompt, and runs an inner tool-call loop using the-//! parent's provider. The sub-agent's intra-loop history is collapsed-//! into a single text result that the parent receives as a normal-//! `tool_result`.-//!-//! Sub-agents always run in "typed" mode: a narrow archetype-specific-//! prompt with a filtered tool list, on a cheaper model where applicable.-//!-use crate::agent::orchestration::tools::dispatch::{incomplete_stop, stopped_subagent_result};-use crate::agent::subagent_host::{- run_subagent_via_driver_tool, SubagentRunOptions, SubagentRunOutcome, SubagentRunStatus,-};-use crate::agent_registry::host_definition::AgentDefinitionRegistry;-use crate::core::runtime::DispatchCtx;-use crate::progress::AgentProgress;-use crate::threads::store::{self as conversations, ConversationMessage, CreateConversationThread};-use async_trait::async_trait;-use serde_json::json;-use std::path::PathBuf;-use std::sync::Arc;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};-use tinytools::ToolRunContext;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};--/// Spawns a sub-agent of the requested type to handle a delegated task.-///-/// Registered into the parent agent's tool list by-/// [`crate::tools::ops::all_tools_with_runtime`]. The orchestrator-/// archetype's tool whitelist already includes `spawn_subagent`, so-/// orchestrated runs see it; non-orchestrator parents see it too unless-/// explicitly removed.-pub struct SpawnSubagentTool;--pub(crate) struct SpawnSubagentDispatch {- tool: Arc<dyn Tool>,-}--impl SpawnSubagentDispatch {- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {- Self { tool }- }-}--#[async_trait]-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for SpawnSubagentDispatch-{- 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());- SpawnSubagentTool::new()- .execute_with_live_parent_context(- arguments,- Some(&context),- parent.data.child(),- Some(parent),- )- .await- }-}--impl Default for SpawnSubagentTool {- fn default() -> Self {- Self::new()- }-}--impl SpawnSubagentTool {- pub fn new() -> Self {- Self- }-- fn classify_subagent_failure(message: &str) -> String {- let lower = message.to_lowercase();- let upstream_unhealthy = lower.contains("no healthy upstream")- || lower.contains("upstream_unhealthy")- || lower.contains("upstream unavailable")- || lower.contains("service unavailable")- || lower.contains("provider call failed: all providers/models failed");-- if upstream_unhealthy {- return format!(- "spawn_subagent failed: upstream inference unavailable \- (LLM provider outage/capacity). This is NOT a Composio/integration auth issue. \- Avoid immediate repeated retries; ask user to retry shortly.\nDetails: {message}"- );- }-- format!("spawn_subagent failed: {message}")- }-}--include!("spawn_subagent_host_impl.rs");-include!("spawn_subagent_schema.rs");--/// Trim a raw prompt down to a thread-list-friendly title.-///-/// Mirrors the visible-character cap the UI threads list uses so titles-/// stay readable when the orchestrator hands in a multi-paragraph prompt.-const WORKER_THREAD_TITLE_MAX_CHARS: usize = 80;--fn build_worker_thread_title(prompt: &str) -> String {- let collapsed: String = prompt.split_whitespace().collect::<Vec<_>>().join(" ");- if collapsed.is_empty() {- return "Worker task".to_string();- }- let mut iter = collapsed.chars();- let truncated: String = iter.by_ref().take(WORKER_THREAD_TITLE_MAX_CHARS).collect();- if iter.next().is_some() {- format!("{truncated}…")- } else {- truncated- }-}--fn persist_worker_thread(- ctx: &DispatchCtx,- workspace_dir: &std::path::Path,- agent_id: &str,- prompt: &str,- outcome: &SubagentRunOutcome,-) -> Result<String, String> {- let thread_id = format!("worker-{}", uuid::Uuid::new_v4());- let title = build_worker_thread_title(prompt);- let now = chrono::Utc::now().to_rfc3339();-- conversations::ensure_thread(- ctx,- workspace_dir.to_path_buf(),- CreateConversationThread {- id: thread_id.clone(),- title,- created_at: now.clone(),- parent_thread_id: None,- labels: Some(vec!["tasks".to_string()]),- personality_id: None,- working_dir: None,- },- )- .map_err(|err| format!("ensure_thread: {err}"))?;-- conversations::append_message(- ctx,- workspace_dir.to_path_buf(),- &thread_id,- ConversationMessage {- id: format!("user:{}", outcome.task_id),- content: prompt.to_string(),- message_type: "text".to_string(),- extra_metadata: json!({- "scope": "worker_thread",- "agent_id": agent_id,- "task_id": outcome.task_id,- }),- sender: "user".to_string(),- created_at: now.clone(),- },- )- .map_err(|err| format!("append user message: {err}"))?;-- conversations::append_message(- ctx,- workspace_dir.to_path_buf(),- &thread_id,- ConversationMessage {- id: format!("agent:{}", outcome.task_id),- content: outcome.output.clone(),- message_type: "text".to_string(),- extra_metadata: json!({- "scope": "worker_thread",- "agent_id": outcome.agent_id,- "task_id": outcome.task_id,- "elapsed_ms": outcome.elapsed.as_millis() as u64,- "iterations": outcome.iterations,- }),- sender: "agent".to_string(),- created_at: chrono::Utc::now().to_rfc3339(),- },- )- .map_err(|err| format!("append agent message: {err}"))?;-- Ok(thread_id)-}--/// Build a parent-thread tool_result that refers the user to the worker-/// thread instead of dumping the sub-agent's full transcript inline.-///-/// The `[worker_thread_ref] … [/worker_thread_ref]` envelope carries-/// machine-readable metadata the UI parses to render a clickable card; the-/// surrounding prose stays informative for the LLM that reads the result.-fn render_worker_thread_result(- thread_id: &str,- agent_id: &str,- outcome: &SubagentRunOutcome,-) -> String {- let payload = json!({- "thread_id": thread_id,- "label": "worker",- "agent_id": agent_id,- "task_id": outcome.task_id,- "elapsed_ms": outcome.elapsed.as_millis() as u64,- "iterations": outcome.iterations,- });- format!(- "Spawned worker thread `{thread_id}` for the delegated task. The \- user can open it from the thread list (label: `worker`) to see \- the sub-agent's full transcript. Continue from a brief summary \- in this thread instead of relaying the entire run.\n\n\- [worker_thread_ref]\n{payload}\n[/worker_thread_ref]",- thread_id = thread_id,- payload = serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string()),- )-}--#[cfg(test)]-#[path = "spawn_subagent_tests.rs"]-mod tests;