Skip to content

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

fix(orchestration): remove duplicate subagent control tool modules

Steven Enamakel318373f40fb5
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs
deleted file mode 100644
index 87602d2a6f..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent.rs
+++ /dev/null
@@ -1,202 +0,0 @@
-//! Tool: `close_subagent` - retire a reusable durable sub-agent session.
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::subagent_sessions::SubagentSessionStore;
-use crate::agent::orchestration::{running_subagents, subagent_sessions};
-use async_trait::async_trait;
-use serde_json::json;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
-
-pub struct CloseSubagentTool;
-
-pub(crate) struct CloseSubagentDispatch {
- tool: Arc<dyn Tool>,
-}
-impl CloseSubagentDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for CloseSubagentDispatch
-{
- 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());
- CloseSubagentTool::new()
- .execute_with_parent_context(arguments, parent.data.parent.clone(), Some(&context))
- .await
- }
-}
-
-impl CloseSubagentTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for CloseSubagentTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for CloseSubagentTool {
- fn name(&self) -> &str {
- "close_subagent"
- }
-
- fn description(&self) -> &str {
- "Close a reusable sub-agent session so future delegation creates a fresh worker. \
- If that session is currently running, it is cancelled first."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["subagent_session_id"],
- "properties": {
- "subagent_session_id": {
- "type": "string",
- "description": "Durable subagent_session_id returned by reusable async delegation."
- }
- }
- })
- }
-
- 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, None, tool_context)
- .await
- }
-}
-
-impl CloseSubagentTool {
- async fn execute_with_parent_context(
- &self,
- args: serde_json::Value,
- parent: Option<ParentExecutionContext>,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let subagent_session_id = args
- .get("subagent_session_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- if subagent_session_id.is_empty() {
- return Ok(ToolResult::error(
- "close_subagent: `subagent_session_id` is required",
- ));
- }
- let parent = match parent {
- Some(parent) => parent,
- None => {
- return Ok(ToolResult::error(
- "close_subagent called outside of an agent turn",
- ));
- }
- };
- let store = SubagentSessionStore::new(parent.workspace_dir.clone());
- let parent_thread_id = tool_context.and_then(ToolRunContext::thread_id);
- let observed = match subagent_sessions::list_for_parent(
- &store,
- &parent.session_id,
- parent_thread_id,
- ) {
- Ok(sessions) => sessions.into_iter().find(|session| {
- session.subagent_session_id == subagent_session_id
- && session.parent_thread_id.as_deref() == parent_thread_id
- }),
- Err(err) => {
- return Ok(ToolResult::error(format!(
- "close_subagent: failed to read sub-agent sessions: {err}"
- )));
- }
- };
- let Some(observed) = observed else {
- log::warn!(
- "[subagent_reuse] close rejected parent_session={} parent_thread_id={} subagent_session_id={}",
- parent.session_id,
- parent_thread_id.unwrap_or("none"),
- subagent_session_id
- );
- return Ok(ToolResult::error(
- "close_subagent: sub-agent session not found for this parent thread",
- ));
- };
- let dispatch =
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context);
- let thread_id = tool_context.and_then(ToolRunContext::thread_id);
- let jobs = crate::core::runtime::slot_for::<
- tinyagents_orchestration::subagent::SubAgentJobRegistry,
- >(&dispatch);
- let store = SubagentSessionStore::new(parent.workspace_dir.clone());
- let cancelled = observed.status != subagent_sessions::DurableSubagentStatus::Closed
- && (subagent_sessions::cancel_driver_job_for_observed_session(
- &store,
- &parent.workspace_dir.join(".openhuman/subagent_checkpoints"),
- &jobs,
- &observed,
- &parent.session_id,
- thread_id,
- ) || running_subagents::cancel_by_session_in_workspace(
- &dispatch,
- &subagent_session_id,
- &parent.session_id,
- &parent.workspace_dir,
- )
- .is_some());
- match subagent_sessions::close_if_current(&store, &observed) {
- Ok(false) => Ok(ToolResult::error(
- "close_subagent: session changed while it was being closed; retry with its current reference",
- )),
- Err(err) => Ok(ToolResult::error(format!(
- "close_subagent: failed to update sub-agent session: {err}"
- ))),
- Ok(true) => {
- log::info!(
- "[subagent_reuse] close subagent_session_id={} parent_session={} closed={} cancelled_running={}",
- subagent_session_id,
- parent.session_id,
- true,
- cancelled
- );
- Ok(ToolResult::success(format!(
- "Closed reusable sub-agent session `{subagent_session_id}` (closed=true, cancelled_running={cancelled})."
- )))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "close_subagent_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs
index 39a270d68e..b1e15ab9f1 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs
@@ -1,133 +1,19 @@
use super::*;
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::config::AgentConfig;
-use std::collections::HashSet;
-use std::path::Path;
-use std::sync::Arc;
-use tinyagents_harness::context::RunConfig;
-use tinyagents_harness::tool::ToolDispatch;
-use tinytools_agent::dialect::ToolCallFormat;
#[tokio::test]
-async fn missing_session_id_is_rejected() {
- let res = CloseSubagentTool::new().execute(json!({})).await.unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("subagent_session_id"));
-}
-
-#[tokio::test]
-async fn rejects_session_from_different_parent_thread() {
- let workspace = tempfile::TempDir::new().expect("workspace");
- let store = SubagentSessionStore::new(workspace.path().to_path_buf());
- let session = seed_session(&store, "thread-b");
-
- let res = close_for_thread(workspace.path(), "thread-a", &session.subagent_session_id).await;
-
- assert!(res.is_error);
- assert!(res.output().contains("not found for this parent thread"));
- assert!(
- subagent_sessions::find_reusable(&store, &selector("thread-b"))
- .unwrap()
- .is_some()
- );
-}
-
-#[tokio::test]
-async fn closes_session_owned_by_current_parent_thread() {
- let workspace = tempfile::TempDir::new().expect("workspace");
- let store = SubagentSessionStore::new(workspace.path().to_path_buf());
- let session = seed_session(&store, "thread-a");
+async fn close_contract_keeps_required_session_reference_and_requires_live_dispatch() {
+ let tool = CloseSubagentTool::new();
+ let schema = tool.parameters_schema();
+ assert_eq!(schema["required"], json!(["subagent_session_id"]));
- let res = close_for_thread(workspace.path(), "thread-a", &session.subagent_session_id).await;
+ let missing = tool.execute(json!({})).await.unwrap();
+ assert!(missing.is_error);
+ assert!(missing.output().contains("subagent_session_id"));
- assert!(!res.is_error, "{}", res.output());
- assert!(res.output().contains("closed=true"));
- assert!(
- subagent_sessions::find_reusable(&store, &selector("thread-a"))
- .unwrap()
- .is_none()
- );
-}
-
-async fn close_for_thread(
- workspace: &Path,
- thread_id: &str,
- subagent_session_id: &str,
-) -> tinytools::ToolResult {
- let parent = parent_context(workspace);
- let run = crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .with_parent(parent)
- .into_tinyagents(RunConfig::new("close-subagent-test").with_thread(thread_id));
- CloseSubagentDispatch::new(Arc::new(CloseSubagentTool::new()))
- .execute(
- &(),
- tinyagents_harness::ids::CallId::new("close-subagent-test"),
- json!({ "subagent_session_id": subagent_session_id }),
- tinytools::ToolCallOptions::default(),
- &run,
- )
+ let outside = tool
+ .execute(json!({"subagent_session_id":"subsess-1"}))
.await
- .expect("close dispatch")
-}
-
-fn seed_session(
- store: &SubagentSessionStore,
- parent_thread_id: &str,
-) -> subagent_sessions::DurableSubagentSession {
- subagent_sessions::upsert_running(
- store,
- subagent_sessions::SubagentSessionUpsert {
- selector: selector(parent_thread_id),
- display_name: Some("Researcher".into()),
- task_title: "Task".into(),
- worker_thread_id: Some("worker-1".into()),
- task_id: "sub-1".into(),
- lifecycle_key: None,
- },
- None,
- )
- .unwrap()
-}
-
-fn selector(parent_thread_id: &str) -> subagent_sessions::SubagentSessionSelector {
- subagent_sessions::SubagentSessionSelector {
- parent_session: "parent-session".into(),
- parent_thread_id: Some(parent_thread_id.into()),
- agent_id: "researcher".into(),
- model: None,
- sandbox_mode: "workspace".into(),
- action_root: None,
- task_key: "task".into(),
- }
-}
-
-fn parent_context(workspace_dir: &Path) -> ParentExecutionContext {
- let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
- Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));
- ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "orchestrator".into(),
- allowed_subagent_ids: HashSet::new(),
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(model),
- all_tools: Arc::new(Vec::new()),
- all_tool_specs: Arc::new(Vec::new()),
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".into(),
- temperature: 0.0,
- workspace_dir: workspace_dir.to_path_buf(),
- agent_config: AgentConfig::default(),
- workflows: Arc::new(Vec::new()),
- memory_context: Arc::new(None),
- session_id: "parent-session".into(),
- channel: "test".into(),
- connected_integrations: Vec::new(),
- tool_call_format: ToolCallFormat::Native,
- session_key: "parent-key".into(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- host_env: Default::default(),
- }
+ .unwrap();
+ assert!(outside.is_error);
+ assert!(outside.output().contains("live harness control dispatch"));
}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs b/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs
deleted file mode 100644
index 9d1b3d48ba..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-//! Tool: `list_subagents` - inspect reusable sub-agent sessions for this parent.
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::{
- running_subagents,
- subagent_sessions::{
- self, DurableSubagentSessionSummary, DurableSubagentStatus, SubagentSessionStore,
- },
-};
-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_tasks::{OrchestrationTaskRecord, OrchestrationTaskStatus};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};
-
-pub struct ListSubagentsTool;
-
-pub(crate) struct ListSubagentsDispatch {
- tool: Arc<dyn Tool>,
-}
-impl ListSubagentsDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for ListSubagentsDispatch
-{
- 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());
- ListSubagentsTool::new()
- .execute_with_parent_context(arguments, parent.data.parent.clone(), Some(&context))
- .await
- }
-}
-
-impl ListSubagentsTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ListSubagentsTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for ListSubagentsTool {
- fn name(&self) -> &str {
- "list_subagents"
- }
-
- fn description(&self) -> &str {
- "List active or reusable durable sub-agents owned by the current parent thread."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": [],
- "properties": {}
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- 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, None, tool_context)
- .await
- }
-}
-
-impl ListSubagentsTool {
- async fn execute_with_parent_context(
- &self,
- _args: serde_json::Value,
- parent: Option<ParentExecutionContext>,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let parent = match parent {
- Some(parent) => parent,
- None => {
- return Ok(ToolResult::error(
- "list_subagents called outside of an agent turn",
- ));
- }
- };
- let parent_thread_id = tool_context.and_then(ToolRunContext::thread_id);
- let store = SubagentSessionStore::new(parent.workspace_dir.clone());
- match subagent_sessions::list_for_parent(&store, &parent.session_id, parent_thread_id) {
- Ok(sessions) => {
- let summaries: Vec<DurableSubagentSessionSummary> = sessions
- .iter()
- .map(|session| {
- let mut summary = DurableSubagentSessionSummary::from(session);
- overlay_task_store_status(
- &mut summary,
- &parent.workspace_dir,
- &parent.session_id,
- );
- summary
- })
- .collect();
- log::debug!(
- "[subagent_reuse] list parent_thread_id={} parent_session={} count={}",
- parent_thread_id.unwrap_or("none"),
- parent.session_id,
- summaries.len()
- );
- Ok(ToolResult::success(format!(
- "[subagent_sessions]\n{}\n[/subagent_sessions]",
- serde_json::to_string_pretty(&summaries).unwrap_or_else(|_| "[]".to_string())
- )))
- }
- Err(err) => Ok(ToolResult::error(format!(
- "list_subagents: failed to read sub-agent sessions: {err}"
- ))),
- }
- }
-}
-
-pub(crate) fn overlay_task_store_status(
- summary: &mut DurableSubagentSessionSummary,
- workspace_dir: &std::path::Path,
- parent_session: &str,
-) {
- if summary.status == DurableSubagentStatus::Closed {
- return;
- }
- let Some(task_id) = summary.current_task_id.clone() else {
- return;
- };
- let record = match running_subagents::task_record_for_task_in_workspace(
- workspace_dir,
- &task_id,
- parent_session,
- ) {
- Ok(record) => record,
- Err(tinyagents_orchestration::subagent::WaitError::Unknown) => return,
- Err(tinyagents_orchestration::subagent::WaitError::RegistryPoisoned) => {
- log::warn!(
- "[subagent_reuse] task store overlay skipped task_id={} reason=registry_poisoned",
- task_id
- );
- return;
- }
- Err(tinyagents_orchestration::subagent::WaitError::NotOwned) => {
- log::warn!(
- "[subagent_reuse] task store overlay rejected task_id={} subagent_session_id={} reason=not_owned",
- task_id,
- summary.subagent_session_id
- );
- return;
- }
- };
-
- let previous = summary.status;
- apply_task_record_overlay(summary, record);
- if summary.status != previous {
- log::debug!(
- "[subagent_reuse] overlaid task store status subagent_session_id={} task_id={} previous={:?} status={:?}",
- summary.subagent_session_id,
- task_id,
- previous,
- summary.status
- );
- }
-}
-
-fn apply_task_record_overlay(
- summary: &mut DurableSubagentSessionSummary,
- record: OrchestrationTaskRecord,
-) {
- match record.status {
- OrchestrationTaskStatus::Pending
- | OrchestrationTaskStatus::Running
- | OrchestrationTaskStatus::CancelRequested => {
- summary.status = DurableSubagentStatus::Running;
- summary.reusable = true;
- }
- OrchestrationTaskStatus::Awaiting => {
- summary.status = DurableSubagentStatus::AwaitingUser;
- summary.reusable = false;
- }
- OrchestrationTaskStatus::Completed => {
- summary.status = DurableSubagentStatus::Idle;
- summary.reusable = true;
- summary.latest_error = None;
- }
- OrchestrationTaskStatus::Failed
- | OrchestrationTaskStatus::TimedOut
- | OrchestrationTaskStatus::Abandoned
- | OrchestrationTaskStatus::Cancelled => {
- summary.status = DurableSubagentStatus::Failed;
- summary.reusable = false;
- summary.latest_error = Some(record.error.unwrap_or_else(|| {
- format!(
- "sub-agent reached durable task status `{}`",
- durable_status_label(record.status)
- )
- }));
- }
- }
-}
-
-fn durable_status_label(status: OrchestrationTaskStatus) -> &'static str {
- match status {
- OrchestrationTaskStatus::Pending => "pending",
- OrchestrationTaskStatus::Running => "running",
- OrchestrationTaskStatus::Awaiting => "awaiting",
- OrchestrationTaskStatus::Completed => "completed",
- OrchestrationTaskStatus::Failed => "failed",
- OrchestrationTaskStatus::CancelRequested => "cancel_requested",
- OrchestrationTaskStatus::Cancelled => "cancelled",
- OrchestrationTaskStatus::TimedOut => "timed_out",
- OrchestrationTaskStatus::Abandoned => "abandoned",
- }
-}
-
-#[cfg(test)]
-#[path = "list_subagents_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs
deleted file mode 100644
index 57ca26f070..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.rs
+++ /dev/null
@@ -1,213 +0,0 @@
-//! Tool: `steer_subagent` — inject a message into a running async sub-agent.
-//!
-//! Pairs with `spawn_async_subagent`: that tool returns a `task_id` for a child
-//! running in the background. `steer_subagent` pushes a message into that child's
-//! steering queue, which the steering forwarder in the child's turn
-//! (`TurnSpec::run`) drains mid-flight — so the parent can
-//! redirect or feed data to a running sub-agent
-//! without waiting for it to finish or restarting it. Mirrors Codex `send_input`.
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::running_subagents;
-use crate::tools::schema_cache::static_schema;
-use async_trait::async_trait;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::run_queue::QueueLane;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinyagents_orchestration::subagent::SteerError;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-pub struct SteerSubagentTool;
-
-pub(crate) struct SteerSubagentDispatch {
- tool: Arc<dyn Tool>,
-}
-impl SteerSubagentDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for SteerSubagentDispatch
-{
- 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());
- SteerSubagentTool::new()
- .execute_with_parent_context(arguments, parent.data.parent.clone(), Some(&context))
- .await
- }
-}
-
-impl SteerSubagentTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for SteerSubagentTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for SteerSubagentTool {
- fn name(&self) -> &str {
- "steer_subagent"
- }
-
- fn description(&self) -> &str {
- "Send a message into a running async sub-agent, redirecting it or feeding it data mid-run without restarting. It is picked up at the next step. `mode: steer` (default) is an instruction it must address; `mode: collect` is silent context. Returns immediately."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- static_schema!(include_str!("steer_subagent.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_parent_context(args, None, None).await
- }
-}
-
-impl SteerSubagentTool {
- async fn execute_with_parent_context(
- &self,
- args: serde_json::Value,
- parent: Option<ParentExecutionContext>,
- tool_context: Option<&dyn tinytools::ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let task_id = args
- .get("task_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let subagent_session_id = args
- .get("subagent_session_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let message = args
- .get("message")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let (lane, mode) = match args.get("mode").and_then(|v| v.as_str()).unwrap_or("steer") {
- "collect" => (QueueLane::Collect, "collect"),
- _ => (QueueLane::Steer, "steer"),
- };
-
- if task_id.is_empty() && subagent_session_id.is_empty() {
- return Ok(ToolResult::error(
- "steer_subagent: `subagent_session_id` or `task_id` is required",
- ));
- }
- if message.is_empty() {
- return Ok(ToolResult::error("steer_subagent: `message` is required"));
- }
-
- let parent = match parent {
- Some(parent) => parent,
- None => {
- return Ok(ToolResult::error(
- "steer_subagent called outside of an agent turn",
- ));
- }
- };
- let parent_session = parent.session_id;
- let dispatch =
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context);
-
- let resolved_task_id = if task_id.is_empty() {
- match running_subagents::task_id_for_session_in_workspace(
- &dispatch,
- &subagent_session_id,
- &parent_session,
- &parent.workspace_dir,
- ) {
- Ok(id) => id,
- Err(tinyagents_orchestration::subagent::WaitError::Unknown) => {
- return Ok(ToolResult::error(format!(
- "steer_subagent: no running sub-agent with subagent_session_id `{subagent_session_id}`."
- )));
- }
- Err(tinyagents_orchestration::subagent::WaitError::NotOwned) => {
- return Ok(ToolResult::error(format!(
- "steer_subagent: sub-agent session `{subagent_session_id}` was not started by this agent."
- )));
- }
- Err(tinyagents_orchestration::subagent::WaitError::RegistryPoisoned) => {
- return Ok(ToolResult::error(
- "steer_subagent: the sub-agent registry is unavailable; try again."
- .to_string(),
- ));
- }
- }
- } else {
- task_id.clone()
- };
-
- log::info!(
- "[steer_subagent] task_id={} subagent_session_id={} mode={} chars={}",
- resolved_task_id,
- if subagent_session_id.is_empty() {
- "none"
- } else {
- &subagent_session_id
- },
- mode,
- message.chars().count()
- );
-
- match running_subagents::steer(&dispatch, &resolved_task_id, &parent_session, message, lane)
- .await
- {
- Ok(()) => Ok(ToolResult::success(format!(
- "Steered sub-agent `{resolved_task_id}` ({mode}). It will pick this up at its next step. \
- Use wait_subagent with its subagent_session_id or task_id to collect its result."
- ))),
- Err(SteerError::Unknown) => Ok(ToolResult::error(format!(
- "steer_subagent: no running sub-agent with task_id `{resolved_task_id}`. It may have already \
- finished — use wait_subagent to collect its result, or check the task_id."
- ))),
- Err(SteerError::NotOwned) => Ok(ToolResult::error(format!(
- "steer_subagent: sub-agent `{resolved_task_id}` was not started by this agent and cannot be steered."
- ))),
- Err(SteerError::AlreadyDone) => Ok(ToolResult::error(format!(
- "steer_subagent: sub-agent `{resolved_task_id}` has already finished. Use wait_subagent to collect its result."
- ))),
- Err(SteerError::UnsupportedLane) => Ok(ToolResult::error(
- "steer_subagent: only steer and collect messages can be delivered to a running sub-agent",
- )),
- Err(_) => Ok(ToolResult::error(format!(
- "steer_subagent: unable to deliver a message to sub-agent `{resolved_task_id}`"
- ))),
- }
- }
-}
-
-#[cfg(test)]
-#[path = "steer_subagent_tests.rs"]
-mod tests;
-
-#[cfg(test)]
-#[path = "steer_subagent_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/subagent_control_surfaces.rs b/crates/openhuman-core/src/agent/orchestration/tools/subagent_control_surfaces.rs
index 13be0a3b6f..264ee4271c 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_control_surfaces.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/subagent_control_surfaces.rs
@@ -14,6 +14,7 @@ use tinytools::{PermissionLevel, Tool, ToolResult, ToolTimeout};
use crate::agent::orchestration::subagent_sessions::{
DurableSubagentSessionSummary, DurableSubagentStatus,
};
+use crate::agent::orchestration::subagent_sessions;
use tinyagents_tasks::{OrchestrationTaskRecord, OrchestrationTaskStatus};
pub struct ListSubagentsTool;
@@ -394,3 +395,6 @@ mod steer_tests;
#[cfg(test)]
#[path = "steer_subagent_schema_tests.rs"]
mod steer_schema_tests;
+#[cfg(test)]
+#[path = "close_subagent_tests.rs"]
+mod close_tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs
deleted file mode 100644
index 5003a63309..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent.rs
+++ /dev/null
@@ -1,466 +0,0 @@
-//! Tool: `wait_subagent` — block until a running async sub-agent finishes.
-//!
-//! Pairs with `spawn_async_subagent` / `steer_subagent`: once the parent has
-//! fanned out background work, `wait_subagent` collects a child's final result
-//! inline (with a timeout), instead of relying solely on lifecycle events.
-//! Mirrors Codex `wait`.
-
-use std::time::Duration;
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::running_subagents;
-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_orchestration::subagent::{
- DetachedSubagentStatus, SubagentResumeRef, WaitError, WaitOutcome,
-};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};
-
-const DEFAULT_TIMEOUT_SECS: u64 = 120;
-/// Ceiling on a single wait. Matches Codex's `wait_agent` maximum of one hour:
-/// a wait that is long is fine, because reaching it is a *successful* "still
-/// running" result the model can act on, not a failure.
-const MAX_TIMEOUT_SECS: u64 = 3600;
-
-/// The wait this call should perform, resolved identically for the harness
-/// deadline ([`WaitSubagentTool::timeout_policy`]) and the wait itself.
-///
-/// These two MUST agree. This tool is designed to be polled: on expiry it
-/// returns [`ToolResult::success`] saying the sub-agent is still running and
-/// inviting another call. That graceful path is only reachable if the tool
-/// out-lives its own wait — under the default [`ToolTimeout::Inherit`] the
-/// generic 120s per-tool-call deadline killed the *tool* first, turning a
-/// designed success into an `error` result. The repeated-failure breaker then
-/// classifies "timed out" as transient, retries the identical call 8 times and
-/// halts the turn — which is how a working coding sub-agent lost its work.
-pub(crate) fn requested_timeout_secs(args: &serde_json::Value) -> u64 {
- args.get("timeout_secs")
- .and_then(|v| v.as_u64())
- .unwrap_or(DEFAULT_TIMEOUT_SECS)
- .clamp(1, MAX_TIMEOUT_SECS)
-}
-
-pub struct WaitSubagentTool;
-
-pub(crate) struct WaitSubagentDispatch {
- tool: Arc<dyn Tool>,
-}
-
-impl WaitSubagentDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for WaitSubagentDispatch
-{
- 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());
- WaitSubagentTool::new()
- .execute_with_parent_context(arguments, parent.data.parent.clone(), Some(&context))
- .await
- }
-}
-
-impl WaitSubagentTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for WaitSubagentTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for WaitSubagentTool {
- fn name(&self) -> &str {
- "wait_subagent"
- }
-
- fn description(&self) -> &str {
- "Block until an async sub-agent finishes and return its result. `timeout_secs` defaults to 120, max 3600; timing out is a normal outcome you can retry, so prefer one long wait over tight polling."
- }
-
- /// Let the wait own its own deadline instead of inheriting the generic
- /// per-tool-call one.
- ///
- /// Without this the harness kills the tool at the global `Inherit` timeout
- /// (120s by default) *before* the wait can return its "still running"
- /// success, so a legitimate long wait is reported as a tool failure. The
- /// harness adds its own small grace on top of `Millis`, so the tool always
- /// gets to finish and report first. Same reasoning as
- /// `spawn_parallel_agents`, which opts out for the same class of bug.
- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {
- ToolTimeout::Millis(requested_timeout_secs(args).saturating_mul(1000))
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": [],
- "properties": {
- "task_id": {
- "type": "string",
- "description": "Transient task_id returned by reusable async delegation."
- },
- "subagent_session_id": {
- "type": "string",
- "description": "Durable subagent_session_id returned by reusable async delegation. Preferred for cross-turn waits."
- },
- "timeout_secs": {
- "type": "integer",
- "minimum": 1,
- "maximum": MAX_TIMEOUT_SECS,
- "description": "Max seconds to block before returning a 'still running' result. Default 120."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_parent_context(args, None, None).await
- }
-}
-
-impl WaitSubagentTool {
- async fn execute_with_parent_context(
- &self,
- args: serde_json::Value,
- parent: Option<ParentExecutionContext>,
- tool_context: Option<&dyn tinytools::ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let task_id = args
- .get("task_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let subagent_session_id = args
- .get("subagent_session_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- if task_id.is_empty() && subagent_session_id.is_empty() {
- return Ok(ToolResult::error(
- "wait_subagent: `subagent_session_id` or `task_id` is required",
- ));
- }
-
- let timeout_secs = requested_timeout_secs(&args);
-
- let parent = match parent {
- Some(parent) => parent,
- None => {
- return Ok(ToolResult::error(
- "wait_subagent called outside of an agent turn",
- ));
- }
- };
- let parent_session = parent.session_id;
- let dispatch =
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context);
-
- let resolved_task_id = if task_id.is_empty() {
- match running_subagents::task_id_for_session_in_workspace(
- &dispatch,
- &subagent_session_id,
- &parent_session,
- &parent.workspace_dir,
- ) {
- Ok(id) => id,
- Err(WaitError::Unknown) => {
- return Ok(ToolResult::error(format!(
- "wait_subagent: no running sub-agent with subagent_session_id `{subagent_session_id}`."
- )));
- }
- Err(WaitError::NotOwned) => {
- return Ok(ToolResult::error(format!(
- "wait_subagent: sub-agent session `{subagent_session_id}` was not started by this agent."
- )));
- }
- Err(WaitError::RegistryPoisoned) => {
- return Ok(ToolResult::error(
- "wait_subagent: the sub-agent registry is unavailable; try again."
- .to_string(),
- ));
- }
- }
- } else {
- task_id.clone()
- };
-
- log::info!(
- "[wait_subagent] task_id={} subagent_session_id={} timeout_secs={}",
- resolved_task_id,
- if subagent_session_id.is_empty() {
- "none"
- } else {
- &subagent_session_id
- },
- timeout_secs
- );
-
- let resume_ref = running_subagents::resume_ref_for_task_in_workspace(
- &dispatch,
- &resolved_task_id,
- &parent_session,
- &parent.workspace_dir,
- )
- .ok();
-
- match running_subagents::wait_in_workspace(
- &dispatch,
- &resolved_task_id,
- &parent_session,
- &parent.workspace_dir,
- Duration::from_secs(timeout_secs),
- )
- .await
- {
- Ok(WaitOutcome::Terminal(DetachedSubagentStatus::Completed { output, iterations })) => {
- log::debug!(
- "[wait_subagent] outcome=completed task_id={} iterations={}",
- resolved_task_id,
- iterations
- );
- // The parent is collecting this result inline and will present
- // it in this turn, so suppress the detached completion's separate
- // background-delivery turn — otherwise the same result is
- // re-answered as a duplicate. Only the Completed arm marks:
- // AwaitingUser/Failed never record a completion, and a
- // still-Running/TimedOut sub-agent has no terminal result yet, so
- // a genuinely-later completion must still surface.
- crate::agent::orchestration::background_completions::mark_collected(
- &parent.workspace_dir,
- &resolved_task_id,
- );
- let status = wait_status_payload(
- resume_ref.as_ref(),
- &resolved_task_id,
- "completed",
- Some(iterations),
- None,
- "synthesize the sub-agent output into the parent response",
- );
- Ok(ToolResult::success(format!(
- "Sub-agent `{}` completed in {iterations} iteration(s).\n\n[subagent_wait_result]\n{}\n[/subagent_wait_result]\n\n{output}",
- status["agent_id"].as_str().unwrap_or("subagent"),
- serde_json::to_string(&status).unwrap_or_else(|_| "{}".to_string())
- )))
- }
- Ok(WaitOutcome::Terminal(DetachedSubagentStatus::AwaitingUser { question })) => {
- log::debug!(
- "[wait_subagent] outcome=awaiting_user task_id={} question_chars={}",
- resolved_task_id,
- question.chars().count()
- );
- let status = wait_status_payload(
- resume_ref.as_ref(),
- &resolved_task_id,
- "awaiting_user",
- None,
- Some(&question),
- "ask the user for the missing information, then call continue_subagent",
- );
- let mut message = format!(
- "Sub-agent `{}` paused for clarification and did not finish: {question}\n\n\
- It cannot proceed unattended. Resume it with continue_subagent once you have an answer.\n\n[subagent_wait_result]\n{}\n[/subagent_wait_result]",
- status["agent_id"].as_str().unwrap_or("subagent"),
- serde_json::to_string(&status).unwrap_or_else(|_| "{}".to_string())
- );
- if let Some(reference) = resume_ref {
- message.push_str("\n\n[subagent_resume_ref]\n");
- message.push_str(
- &serde_json::to_string(&serde_json::json!({
- "task_id": reference.task_id,
- "agent_id": reference.agent_id,
- "subagent_session_id": reference.subagent_session_id,
- "tool": "continue_subagent"
- }))
- .unwrap_or_else(|_| "{}".to_string()),
- );
- message.push_str("\n[/subagent_resume_ref]");
- } else {
- log::debug!(
- "[wait_subagent] resume_ref_unavailable task_id={}",
- resolved_task_id
- );
- }
- Ok(ToolResult::success(message))
- }
- Ok(WaitOutcome::Terminal(DetachedSubagentStatus::Failed { error })) => {
- log::debug!(
- "[wait_subagent] outcome=failed task_id={} error={}",
- resolved_task_id,
- error
- );
- let status = wait_status_payload(
- resume_ref.as_ref(),
- &resolved_task_id,
- "failed",
- None,
- Some(&error),
- "report the failure or retry with a corrected instruction",
- );
- Ok(ToolResult::error(format!(
- "Sub-agent `{}` failed: {error}\n\n[subagent_wait_result]\n{}\n[/subagent_wait_result]",
- status["agent_id"].as_str().unwrap_or("subagent"),
- serde_json::to_string(&status).unwrap_or_else(|_| "{}".to_string())
- )))
- }
- // `Running` is never terminal; treat defensively as a timeout-style result.
- Ok(WaitOutcome::Terminal(DetachedSubagentStatus::Running)) => {
- log::debug!(
- "[wait_subagent] outcome=running task_id={} timeout_secs={}",
- resolved_task_id,
- timeout_secs
- );
- Ok(ToolResult::success(format_running_wait_message(
- resume_ref.as_ref(),
- &resolved_task_id,
- timeout_secs,
- )))
- }
- Ok(WaitOutcome::TimedOut(_)) => {
- log::debug!(
- "[wait_subagent] outcome=timed_out task_id={} timeout_secs={}",
- resolved_task_id,
- timeout_secs
- );
- Ok(ToolResult::success(format_running_wait_message(
- resume_ref.as_ref(),
- &resolved_task_id,
- timeout_secs,
- )))
- }
- Err(WaitError::Unknown) => {
- log::debug!(
- "[wait_subagent] outcome=unknown task_id={}",
- resolved_task_id
- );
- Ok(ToolResult::error("wait_subagent: no sub-agent was found for that reference. It may have already finished and \
- been collected, or the task_id is wrong.".to_string()))
- }
- Err(WaitError::NotOwned) => {
- log::debug!(
- "[wait_subagent] outcome=not_owned task_id={}",
- resolved_task_id
- );
- Ok(ToolResult::error(
- "wait_subagent: that sub-agent was not started by this agent.".to_string(),
- ))
- }
- Err(WaitError::RegistryPoisoned) => {
- log::warn!(
- "[wait_subagent] outcome=registry_poisoned task_id={}",
- resolved_task_id
- );
- Ok(ToolResult::error(
- "wait_subagent: the sub-agent registry is unavailable; try again.".to_string(),
- ))
- }
- }
- }
-}
-
-/// Render a timeout/running wait response with a structured status payload.
-pub(crate) fn format_running_wait_message(
- reference: Option<&SubagentResumeRef>,
- task_id: &str,
- timeout_secs: u64,
-) -> String {
- let status = wait_status_payload(
- reference,
- task_id,
- "running",
- None,
- None,
- "continue other work, call wait_subagent again, or call steer_subagent to send more input",
- );
- format!(
- "Sub-agent `{}` is still running after {timeout_secs}s.\n\n[subagent_wait_result]\n{}\n[/subagent_wait_result]\n\nContinue with other work and call wait_subagent again later, or steer_subagent to redirect it.",
- status["agent_id"].as_str().unwrap_or("subagent"),
- serde_json::to_string(&status).unwrap_or_else(|_| "{}".to_string())
- )
-}
-
-/// Build the machine-readable wait status block returned to the orchestrator.
-pub(crate) fn wait_status_payload(
- reference: Option<&SubagentResumeRef>,
- task_id: &str,
- status: &str,
- iterations: Option<usize>,
- detail: Option<&str>,
- next_action: &str,
-) -> serde_json::Value {
- let agent_id = reference.map(|r| r.agent_id.as_str()).unwrap_or("unknown");
- let subagent_session_id = reference.and_then(|r| r.subagent_session_id.as_deref());
- 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,
- "status": status,
- "iterations": iterations,
- "detail": detail,
- "next_action": next_action,
- "nextAction": next_action,
- "instructions": {
- "send_message": {
- "tool": "steer_subagent",
- "arguments": {
- "subagent_session_id": subagent_session_id,
- "task_id": task_id,
- "message": "<message>",
- "mode": "steer"
- }
- },
- "wait": {
- "tool": "wait_subagent",
- "arguments": {
- "subagent_session_id": subagent_session_id,
- "task_id": task_id,
- "timeout_secs": DEFAULT_TIMEOUT_SECS
- }
- },
- "timeout_tick": {
- "tool": "wait_subagent",
- "arguments": {
- "subagent_session_id": subagent_session_id,
- "task_id": task_id,
- "timeout_secs": 1
- }
- }
- }
- })
-}
-
-#[cfg(test)]
-#[path = "wait_subagent_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs
index ce9be26a11..23110b2b68 100644
--- a/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/tool_registration.rs
@@ -19,9 +19,8 @@ use tinyinference_llm::model::ChatModel;
use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};
use crate::agent::orchestration::tools::{
- CloseSubagentDispatch, ContinueSubagentDispatch, DelegateGraphDispatch, DelegationDispatch,
- ListSubagentsDispatch, SpawnAsyncSubagentDispatch, SpawnParallelAgentsDispatch,
- SpawnSubagentDispatch, SteerSubagentDispatch, WaitSubagentDispatch,
+ ContinueSubagentDispatch, DelegateGraphDispatch, DelegationDispatch,
+ SpawnAsyncSubagentDispatch, SpawnParallelAgentsDispatch, SpawnSubagentDispatch,
};
use crate::agent::tinyagents::host::run_context::HostOperationContext;
use crate::agent::tinyagents::host::OpenHumanRunContext;
@@ -115,10 +114,6 @@ pub(crate) fn typed_dispatch_for(
"spawn_worker_thread" => Arc::new(SpawnWorkerThreadDispatch::new(adapter)),
"spawn_subagent" => Arc::new(SpawnSubagentDispatch::new(adapter)),
"continue_subagent" => Arc::new(ContinueSubagentDispatch::new(adapter)),
- "wait_subagent" => Arc::new(WaitSubagentDispatch::new(adapter)),
- "steer_subagent" => Arc::new(SteerSubagentDispatch::new(adapter)),
- "close_subagent" => Arc::new(CloseSubagentDispatch::new(adapter)),
- "list_subagents" => Arc::new(ListSubagentsDispatch::new(adapter)),
"delegate_graph" => Arc::new(DelegateGraphDispatch::new(adapter)),
"delegate" => Arc::new(DelegateToolDispatch::new(adapter)),
"memory" => Arc::new(LiveToolContextDispatch::new(adapter)),