Skip to content

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

refactor(orchestration): remove legacy subagent control surfaces

Steven Enamakel8ed070813802
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs
deleted file mode 100644
index 3c06b89bbd..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/steering.rs
+++ /dev/null
@@ -1,105 +0,0 @@
-//! OpenHuman's `RunQueue` fallback for TinyAgents detached steering.
-
-use tinyagents_harness::ids::TaskId;
-use tinyagents_harness::run_queue::QueueLane;
-use tinyagents_orchestration::steering::{steer_detached, SteerAccess, SteerError};
-
-use super::cancel::now_ms;
-use super::registry::{control_admits, owner_key, registry, RunningSubagentMetadata};
-
-/// Inject an instruction into a detached sub-agent owned by `parent_session`.
-pub async fn steer(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: &str,
- parent_session: &str,
- text: String,
- lane: QueueLane,
-) -> Result<(), SteerError> {
- let owner = owner_key(ctx, parent_session).map_err(|_| SteerError::NotOwned)?;
- let route = steer_detached(
- registry(),
- task_id,
- SteerAccess::Owner(&owner),
- text,
- lane,
- |metadata: RunningSubagentMetadata, lane: QueueLane, text: String| async move {
- metadata
- .run_queue
- .push(
- lane,
- crate::agent::queued_turn::QueuedTurn {
- id: uuid::Uuid::new_v4().to_string(),
- text,
- client_id: "steer_subagent".to_string(),
- thread_id: task_id.to_string(),
- queued_at_ms: now_ms(),
- model_override: None,
- temperature: None,
- locale: None,
- },
- )
- .await;
- },
- )
- .await?;
- tracing::info!(
- task_id,
- lane = tinyagents_orchestration::steering::queue_lane_name(lane),
- ?route,
- "[running_subagents] steered detached task"
- );
- Ok(())
-}
-
-/// User-control variant for JSON-RPC sub-agent controls.
-///
-/// The caller's profile is checked against the task metadata before using the
-/// trusted upstream route. Desktop controls retain authority over process
-/// workers, while SaaS controls remain scoped to their captured profile.
-pub(crate) async fn steer_control(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: &str,
- text: String,
- lane: QueueLane,
-) -> Result<(), SteerError> {
- let key = TaskId::new(task_id);
- let snapshot = registry()
- .snapshot_trusted(&key)
- .map_err(SteerError::from)?;
- if !control_admits(ctx, &snapshot.metadata) {
- return Err(SteerError::NotOwned);
- }
- let route = steer_detached(
- registry(),
- task_id,
- SteerAccess::Trusted,
- text,
- lane,
- |metadata: RunningSubagentMetadata, lane: QueueLane, text: String| async move {
- metadata
- .run_queue
- .push(
- lane,
- crate::agent::queued_turn::QueuedTurn {
- id: uuid::Uuid::new_v4().to_string(),
- text,
- client_id: "subagent_control_rpc".to_string(),
- thread_id: task_id.to_string(),
- queued_at_ms: now_ms(),
- model_override: None,
- temperature: None,
- locale: None,
- },
- )
- .await;
- },
- )
- .await?;
- tracing::info!(
- task_id,
- lane = tinyagents_orchestration::steering::queue_lane_name(lane),
- ?route,
- "[running_subagents] control-steered detached task"
- );
- Ok(())
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs
deleted file mode 100644
index a916c533ed..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents/wait.rs
+++ /dev/null
@@ -1,63 +0,0 @@
-//! Blocking-with-timeout collection of a sub-agent's terminal result, with a
-//! durable task-store fallback for a sub-agent this process never registered
-//! in-memory (e.g. after a core restart).
-
-use std::path::Path;
-use std::time::Duration;
-
-use tinyagents_orchestration::subagent::{
- wait_detached, wait_detached_or_durable_with_owners, DetachedSubagentOwners, WaitError,
- WaitOutcome,
-};
-
-use super::registry::{admit_workspace, owner_key, registry};
-
-/// Block until `task_id` reaches a terminal status or `timeout` elapses.
-pub(crate) async fn wait(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: &str,
- parent_session: &str,
- timeout: Duration,
-) -> Result<WaitOutcome, WaitError> {
- let owner = owner_key(ctx, parent_session)?;
- let Some(context) = ctx.resolved() else {
- return wait_detached(registry(), task_id, &owner, timeout).await;
- };
- let Ok(workspace_dir) = context.workspace_dir() else {
- return wait_detached(registry(), task_id, &owner, timeout).await;
- };
- admit_workspace(ctx, &workspace_dir)?;
- let store = super::resolve::scoped_task_store(ctx, &workspace_dir)?;
- let owners = DetachedSubagentOwners::new(&owner, parent_session);
- wait_detached_or_durable_with_owners(
- registry(),
- store.as_ref(),
- &super::super::background_completions::router_for_workspace_ctx(ctx, &workspace_dir),
- task_id,
- owners,
- timeout,
- )
- .await
-}
-
-pub(crate) async fn wait_in_workspace(
- ctx: &crate::core::runtime::DispatchCtx,
- task_id: &str,
- parent_session: &str,
- workspace_dir: &Path,
- timeout: Duration,
-) -> Result<WaitOutcome, WaitError> {
- admit_workspace(ctx, workspace_dir)?;
- let owner = owner_key(ctx, parent_session)?;
- let store = super::resolve::scoped_task_store(ctx, workspace_dir)?;
- let owners = DetachedSubagentOwners::new(&owner, parent_session);
- wait_detached_or_durable_with_owners(
- registry(),
- store.as_ref(),
- &super::super::background_completions::router_for_workspace_ctx(ctx, workspace_dir),
- task_id,
- owners,
- timeout,
- )
- .await
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs b/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs
deleted file mode 100644
index 7be68e0fc1..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/running_subagents_steering_tests.rs
+++ /dev/null
@@ -1,153 +0,0 @@
-use super::*;
-use tinyagents_orchestration::steering::SteerError;
-
-#[tokio::test]
-async fn steer_pushes_into_the_subagent_queue() {
- let _guard = test_guard_async().await;
- let rq = run_queue();
- let tx = register_test("task-steer", "session-A", rq.clone());
-
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-steer",
- "session-A",
- "refocus on memory safety".into(),
- QueueLane::Steer,
- )
- .await
- .expect("steer should succeed");
-
- let status = rq.status().await;
- assert_eq!(status.steers, 1, "steer should land in the steer lane");
-
- // collect mode goes to the collect lane
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-steer",
- "session-A",
- "extra context".into(),
- QueueLane::Collect,
- )
- .await
- .unwrap();
- assert_eq!(rq.status().await.collects, 1);
-
- let _ = tx.send(DetachedSubagentStatus::Completed {
- output: "done".into(),
- iterations: 1,
- });
- prune("task-steer");
-}
-
-#[tokio::test]
-async fn steer_prefers_registered_tinyagents_handle() {
- let _guard = test_guard_async().await;
- let rq = run_queue();
- let tx = register_test("task-registered-steer", "session-A", rq.clone());
- let handle = SteeringHandle::allow_all();
- let task_id = TaskId::new("task-registered-steer");
- shared_steering_registry().register(task_id.clone(), handle.clone());
-
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-registered-steer",
- "session-A",
- "refocus".into(),
- QueueLane::Steer,
- )
- .await
- .expect("steer should succeed");
-
- let status = rq.status().await;
- assert_eq!(status.steers, 0, "registered handle bypasses RunQueue");
- let commands = handle.drain();
- assert_eq!(commands.len(), 1);
- match &commands[0] {
- SteeringCommand::InjectMessage(message) => {
- assert_eq!(message.text(), "[User steering message]: refocus");
- }
- other => panic!("expected injected steering message, got {other:?}"),
- }
-
- let _ = shared_steering_registry().deregister(&task_id);
- let _ = tx.send(DetachedSubagentStatus::Completed {
- output: "done".into(),
- iterations: 1,
- });
- prune("task-registered-steer");
-}
-
-#[tokio::test]
-async fn steer_rejects_cross_parent_and_unknown() {
- let _guard = test_guard_async().await;
- let rq = run_queue();
- let _tx = register_test("task-owned", "session-owner", rq);
-
- assert_eq!(
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-owned",
- "session-intruder",
- "x".into(),
- QueueLane::Steer
- )
- .await,
- Err(SteerError::NotOwned)
- );
- assert_eq!(
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-missing",
- "session-owner",
- "x".into(),
- QueueLane::Steer
- )
- .await,
- Err(SteerError::Unknown)
- );
- prune("task-owned");
-}
-
-#[tokio::test]
-async fn steer_after_terminal_is_rejected() {
- let _guard = test_guard_async().await;
- let rq = run_queue();
- let tx = register_test("task-term", "session-A", rq);
- let _ = tx.send(DetachedSubagentStatus::Failed {
- error: "boom".into(),
- });
-
- assert_eq!(
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-term",
- "session-A",
- "x".into(),
- QueueLane::Steer
- )
- .await,
- Err(SteerError::Unknown)
- );
- prune("task-term");
-}
-
-#[tokio::test]
-async fn detached_subagent_rejects_followup_lane() {
- let _guard = test_guard_async().await;
- let rq = run_queue();
- let _tx = register_test("task-no-followup", "session-A", rq.clone());
-
- assert_eq!(
- steer(
- &crate::core::runtime::DispatchCtx::ambient(),
- "task-no-followup",
- "session-A",
- "not a new turn".into(),
- QueueLane::Followup,
- )
- .await,
- Err(SteerError::UnsupportedLane)
- );
- assert_eq!(rq.status().await.total, 0);
- prune("task-no-followup");
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_host.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_host.rs
deleted file mode 100644
index 841226fbfc..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_host.rs
+++ /dev/null
@@ -1,315 +0,0 @@
-use async_trait::async_trait;
-use serde_json::json;
-use serde_json::Value;
-
-use tinytools::ToolRunContext;
-use tinytools::{
- PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolExposure, ToolResult, ToolTimeout,
-};
-
-pub struct ArchetypeDelegationTool {
- pub tool_name: String,
- /// The agent this tool routes to, in the shape
- /// [`crate::tools::host_extensions::delegation_target`] reads back off the
- /// erased host-extension slot.
- ///
- /// A newtype rather than a bare `String` because that slot is one `Any` per
- /// tool: a downcast to `String` would happily match any *other* tool that
- /// parked a string there. It holds the id rather than deriving it because
- /// [`Tool::host_extension`] hands out a borrow, so there must be something
- /// to borrow from — and one field, not two, is what stops the exposed
- /// target drifting from the routed one.
- pub agent_id: DelegationTarget,
- pub tool_description: String,
-}
-
-/// The agent a synthesised `delegate_*` tool routes to.
-///
-/// Lets a caller that holds only `&dyn Tool` ask "which agent does this reach?"
-/// — the question the toolpack route hint needs answered, and the reason the
-/// hint does not need its own copy of every agent's `delegate_name`. The tool
-/// set a session was actually built with is the single source of truth: a
-/// delegate that is not in it cannot be named as a route, which is exactly the
-/// property we want.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct DelegationTarget(pub String);
-
-#[async_trait]
-impl Tool for ArchetypeDelegationTool {
- fn name(&self) -> &str {
- &self.tool_name
- }
-
- fn description(&self) -> &str {
- &self.tool_description
- }
-
- fn exposure(&self) -> ToolExposure {
- ToolExposure::Hidden
- }
-
- /// Publishes the routing target on the erased host-extension slot, the same
- /// way `UseSkillTool` publishes its pack handle. `traits::delegation_target`
- /// reads it back; every other tool returns `None` and pays nothing.
- fn host_extension(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {
- Some(&self.agent_id)
- }
-
- /// The delegation envelope: `prompt` and `blocking` only.
- ///
- /// This schema is emitted for every synthesised `delegate_*` tool on the
- /// wire, so each word is billed per delegate on every request. Fully
- /// described it was 356 tokens per delegate; the structured hand-off fields
- /// (`objective`, `evidence`, `constraints`, `must_not_assume`,
- /// `expected_output`, `citation_requirement`, `model`) are no longer
- /// advertised because a self-contained `prompt` carries the same content.
- /// They are still read by [`render_structured_handoff`], so a caller that
- /// sends them keeps working. `blocking` keeps its description because its
- /// default is behaviour-critical and not inferable from the name.
- ///
- /// Shared by archetype delegates through [`delegation_envelope_properties`]; enforced by
- /// `envelope_descriptions_stay_within_budget`.
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["prompt"],
- "properties": delegation_envelope_properties()
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::System
- }
-
- /// Run **without** the global per-tool wall-clock deadline. This tool is a
- /// delegation primitive: it hands a task to a bounded sub-agent
- /// (`tools_agent` → `delegate_tools_agent`, `code_executor` → `run_code`,
- /// …) and awaits that agent's full run. Under the default `Inherit` policy
- /// the whole delegation is hard-killed at the single-tool timeout (120s) —
- /// so any sub-agent run that legitimately exceeds two minutes is truncated
- /// mid-flight (Sentry TAURI-RUST-K29 `delegate_tools_agent` and
- /// TAURI-RUST-8HB `run_code`: thousands of 120.000s truncations). The
- /// child's lifetime is already bounded internally — by its `max_iterations`,
- /// the run cancellation token, and each inner tool's own timeout — so it
- /// governs its own duration independently of the parent turn.
- fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {
- ToolTimeout::Unbounded
- }
-
- 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> {
- let mut run_context = crate::agent::tinyagents::host::OpenHumanRunContext::new().with_core(
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)
- .into_core(),
- );
- run_context.thread_id = tool_context
- .and_then(ToolRunContext::thread_id)
- .map(ToOwned::to_owned);
- execute_archetype_delegation(
- &self.agent_id.0,
- &self.tool_name,
- args,
- tool_context,
- run_context,
- )
- .await
- }
-}
-
-/// Execute an archetype hand-off with an explicit child run carrier.
-pub(crate) async fn execute_archetype_delegation(
- agent_id: &str,
- tool_name: &str,
- args: serde_json::Value,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
-) -> anyhow::Result<ToolResult> {
- execute_archetype_delegation_with_live_parent(
- agent_id,
- tool_name,
- args,
- tool_context,
- run_context,
- None,
- )
- .await
-}
-
-/// Typed-harness counterpart that preserves a live parent for the blocking
-/// archetype child.
-pub(crate) async fn execute_archetype_delegation_with_live_parent(
- agent_id: &str,
- tool_name: &str,
- 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 raw_prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
-
- if raw_prompt.is_empty() {
- return Ok(ToolResult::error(format!(
- "{}: `prompt` is required",
- tool_name
- )));
- }
- let prompt = render_structured_handoff(&raw_prompt, &args);
- let prompt = match crate::attachments::delegation_prompt(
- &run_context.dispatch_ctx(),
- &prompt,
- &args,
- tool_context
- .and_then(|ctx| ctx.workspace())
- .or(run_context.workspace.as_ref()),
- run_context.origin.as_ref(),
- )
- .await
- {
- Ok(prompt) => prompt,
- Err(error) => {
- return Ok(ToolResult::error(format!(
- "image forwarding failed: {error}"
- )));
- }
- };
-
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty());
-
- // Async by default: the delegated specialist runs as a durable,
- // resumable worker and its result comes back as a new chat turn.
- // `blocking: true` is the opt-in for results that must gate this
- // reply. (`dispatch_subagent` itself falls back to blocking when
- // there is no chat thread to deliver an async result into.)
- let blocking = args
- .get("blocking")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- let mode = if blocking {
- super::dispatch::DispatchMode::Blocking
- } else {
- super::dispatch::DispatchMode::PreferAsync
- };
-
- super::dispatch::dispatch_subagent_with_live_parent(
- agent_id,
- tool_name,
- &prompt,
- model_override,
- tool_context,
- mode,
- run_context,
- live_parent,
- )
- .await
-}
-
-pub(super) fn render_structured_handoff(prompt: &str, args: &Value) -> String {
- let mut out = String::new();
- out.push_str("Task:\n");
- out.push_str(prompt.trim());
-
- push_optional_string(&mut out, "Objective", args.get("objective"));
- push_optional_array(&mut out, "Evidence", args.get("evidence"));
- push_optional_array(&mut out, "Constraints", args.get("constraints"));
- push_optional_array(&mut out, "Must not assume", args.get("must_not_assume"));
- push_optional_string(&mut out, "Expected output", args.get("expected_output"));
- push_optional_string(
- &mut out,
- "Citation requirement",
- args.get("citation_requirement"),
- );
-
- out
-}
-
-/// The advertised hand-off envelope shared by every member delegate. Only `prompt` and
-/// `blocking` are offered; the structured fields (`objective`, `evidence`,
-/// `constraints`, `must_not_assume`, `expected_output`,
-/// `citation_requirement`, `model`) are still read by
-/// [`render_structured_handoff`] when a caller sends them.
-pub(super) fn delegation_envelope_properties() -> Value {
- serde_json::json!({
- "prompt": {
- "type": "string",
- "description": "The whole task, self-contained: the worker has no memory of this chat."
- },
- "image_paths": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Image paths relative to the acting workspace."
- },
- "blocking": {
- "type": "boolean",
- "description": "Default false: async worker, result arrives as a later turn. true: waits, and the result gates this reply."
- }
- })
-}
-
-fn push_optional_string(out: &mut String, label: &str, value: Option<&Value>) {
- let Some(text) = value.and_then(Value::as_str).map(str::trim) else {
- return;
- };
- if text.is_empty() {
- return;
- }
- out.push_str("\n\n");
- out.push_str(label);
- out.push_str(":\n");
- out.push_str(text);
-}
-
-fn push_optional_array(out: &mut String, label: &str, value: Option<&Value>) {
- let Some(items) = value.and_then(Value::as_array) else {
- return;
- };
- let strings: Vec<&str> = items
- .iter()
- .filter_map(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .collect();
- if strings.is_empty() {
- return;
- }
- out.push_str("\n\n");
- out.push_str(label);
- out.push_str(":\n");
- for item in strings {
- out.push_str("- ");
- out.push_str(item);
- out.push('\n');
- }
- if out.ends_with('\n') {
- out.pop();
- }
-}
-
-#[cfg(test)]
-#[path = "archetype_delegation_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_tests.rs
deleted file mode 100644
index fbec949a0d..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation_tests.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-use super::*;
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-
-fn sample_tool() -> ArchetypeDelegationTool {
- ArchetypeDelegationTool {
- tool_name: "delegate_researcher".to_string(),
- agent_id: DelegationTarget("researcher".to_string()),
- tool_description: "Use for web and docs research.".to_string(),
- }
-}
-
-#[test]
-fn metadata_methods_expose_name_description_and_system_category() {
- let tool = sample_tool();
- assert_eq!(tool.name(), "delegate_researcher");
- assert_eq!(tool.description(), "Use for web and docs research.");
- assert_eq!(tool.permission_level(), PermissionLevel::Execute);
- assert_eq!(tool.category(), ToolCategory::System);
-}
-
-#[test]
-fn delegation_opts_out_of_the_global_tool_timeout() {
- // A delegated sub-agent run (delegate_tools_agent / run_code / …) can
- // legitimately outlast the single-tool wall-clock default (120s): under
- // `Inherit` every such run is hard-killed and truncated (Sentry
- // TAURI-RUST-K29 / TAURI-RUST-8HB). The child bounds its own lifetime
- // via its max_iterations, the run cancellation token, and each inner
- // tool's own timeout — so this primitive must be Unbounded, like
- // long-running scripting tools.
- assert_eq!(
- sample_tool().timeout_policy(&json!({})),
- ToolTimeout::Unbounded,
- );
-}
-
-#[test]
-fn parameters_schema_advertises_async_default_blocking_opt_in() {
- // Delegations are async by default (durable worker + follow-up
- // delivery turn); `blocking: true` is the explicit opt-in for
- // results that must gate the current reply. The flag must be
- // advertised but never required.
- let schema = sample_tool().parameters_schema();
- let blocking = &schema["properties"]["blocking"];
- assert_eq!(blocking["type"], "boolean");
- let desc = blocking["description"].as_str().unwrap_or_default();
- assert!(desc.contains("async"), "explains the async default: {desc}");
- assert!(
- desc.contains("Default false"),
- "names which value is the default: {desc}"
- );
- // The resume contract (`subagent_session_id`, `continue_subagent`,
- // `steer_subagent`, …) used to be spelled out here, at 19x the cost.
- // It now lives once in the orchestrator prompt, which
- // `prompt_documents_the_stripped_envelope_fields` pins.
- assert_eq!(schema["required"], json!(["prompt"]));
-}
-
-#[test]
-fn parameters_schema_requires_prompt_only() {
- let tool = sample_tool();
- let schema = tool.parameters_schema();
- assert_eq!(schema["type"], "object");
- assert_eq!(schema["required"], json!(["prompt"]));
- assert_eq!(schema["properties"]["prompt"]["type"], "string");
-
- // Only `prompt`, `blocking`, and explicit `image_paths` are advertised: the structured hand-off
- // fields cost ~150 tokens per delegate on every request, and a
- // self-contained `prompt` carries the same content. They are still
- // parsed (see `structured_handoff_renders_compact_child_prompt`), so a
- // caller that sends them keeps working; they are just not offered.
- let props = schema["properties"]
- .as_object()
- .expect("properties is an object");
- let mut present: Vec<&str> = props.keys().map(String::as_str).collect();
- present.sort_unstable();
- assert_eq!(present, vec!["blocking", "image_paths", "prompt"]);
-}
-
-/// Every `description` in the envelope, as `(json-pointer-ish path, text)`.
-fn collect_descriptions(node: &Value, path: &str, out: &mut Vec<(String, String)>) {
- match node {
- Value::Object(map) => {
- for (key, value) in map {
- if key == "description" {
- if let Some(text) = value.as_str() {
- out.push((path.to_string(), text.to_string()));
- }
- } else {
- collect_descriptions(value, &format!("{path}/{key}"), out);
- }
- }
- }
- Value::Array(items) => {
- for (idx, item) in items.iter().enumerate() {
- collect_descriptions(item, &format!("{path}/{idx}"), out);
- }
- }
- _ => {}
- }
-}
-
-#[test]
-fn envelope_descriptions_stay_within_budget() {
- // This schema is emitted once per synthesised `delegate_*` tool, so prose
- // here is billed per delegate per turn. Fully described it was 356 tokens
- // each; the envelope keeps three short fields. `prompt` (which says the worker has
- // no memory of this chat) and `blocking` (whose default is not in its
- // name), and explicit image forwarding stay under the ~50-token cap.
- let schema = sample_tool().parameters_schema();
- let mut found = Vec::new();
- collect_descriptions(&schema, "", &mut found);
-
- let mut fields: Vec<&str> = found.iter().map(|(path, _)| path.as_str()).collect();
- fields.sort_unstable();
- assert_eq!(
- fields,
- vec![
- "/properties/blocking",
- "/properties/image_paths",
- "/properties/prompt"
- ],
- "a field or description came back into the delegation envelope; \
- every word here is paid per delegate on every request"
- );
-
- // ~4 chars per token on this vocabulary, so 220 chars ~= the 50-token cap.
- for (field, text) in &found {
- assert!(
- text.len() <= 220,
- "{field} description is {} chars, over the ~50-token cap: {text}",
- text.len()
- );
- }
- let prompt_desc = schema["properties"]["prompt"]["description"]
- .as_str()
- .unwrap_or_default();
- assert!(
- prompt_desc.contains("no memory of this chat"),
- "the prompt field must say the worker starts cold: {prompt_desc}"
- );
-}
-
-#[test]
-fn prompt_documents_the_stripped_envelope_fields() {
- // The advertised envelope is `prompt` + `blocking`; what the model must
- // still be taught once, in the parent prompt, is when to block and how to
- // resume a paused worker. The unadvertised hand-off fields must NOT be
- // taught there any more: a prompt naming fields the schema does not offer
- // sends the model arguments it cannot see.
- const ORCHESTRATOR_PROMPT: &str =
- include_str!("../../../agent_registry/agents/orchestrator/prompt.md");
-
- for needle in ["blocking: true", "continue_subagent"] {
- assert!(
- ORCHESTRATOR_PROMPT.contains(needle),
- "orchestrator/prompt.md no longer teaches `{needle}`"
- );
- }
- for stale in ["must_not_assume", "expected_output", "citation_requirement"] {
- assert!(
- !ORCHESTRATOR_PROMPT.contains(stale),
- "orchestrator/prompt.md still names `{stale}`, which the delegation \
- schema no longer advertises"
- );
- }
-}
-
-#[test]
-fn structured_handoff_renders_compact_child_prompt() {
- let rendered = render_structured_handoff(
- "Check this",
- &json!({
- "prompt": "Check this",
- "objective": "Answer with supported claims only.",
- "evidence": ["file:src/lib.rs", "tool output: count=3", ""],
- "constraints": ["Do not edit files"],
- "must_not_assume": ["Current service state"],
- "expected_output": "Findings list",
- "citation_requirement": "file_paths",
- }),
- );
-
- assert!(rendered.contains("Task:\nCheck this"));
- assert!(rendered.contains("Objective:\nAnswer with supported claims only."));
- assert!(rendered.contains("Evidence:\n- file:src/lib.rs\n- tool output: count=3"));
- assert!(rendered.contains("Must not assume:\n- Current service state"));
- assert!(rendered.contains("Citation requirement:\nfile_paths"));
- assert!(!rendered.contains("\"model\""));
-}
-
-#[tokio::test]
-async fn execute_rejects_missing_or_blank_prompt() {
- let tool = sample_tool();
-
- let missing = tool.execute(json!({})).await.unwrap();
- assert!(missing.is_error);
- assert!(missing.output().contains("`prompt` is required"));
-
- let blank = tool.execute(json!({ "prompt": " " })).await.unwrap();
- assert!(blank.is_error);
- assert!(blank.output().contains("`prompt` is required"));
-}
-
-#[tokio::test]
-async fn execute_accepts_non_empty_prompt_and_reaches_dispatch_path() {
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let tool = sample_tool();
- let result = tool
- .execute(json!({ "prompt": "find the answer" }))
- .await
- .unwrap();
-
- let out = result.output();
- assert!(
- !out.contains("`prompt` is required"),
- "non-empty prompt should bypass local validation, got: {out}"
- );
-}
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
deleted file mode 100644
index b1e15ab9f1..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/close_subagent_tests.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-use super::*;
-
-#[tokio::test]
-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 missing = tool.execute(json!({})).await.unwrap();
- assert!(missing.is_error);
- assert!(missing.output().contains("subagent_session_id"));
-
- let outside = tool
- .execute(json!({"subagent_session_id":"subsess-1"}))
- .await
- .unwrap();
- assert!(outside.is_error);
- assert!(outside.output().contains("live harness control dispatch"));
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs b/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs
deleted file mode 100644
index 1d2ab265b3..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/continue_subagent_host.rs
+++ /dev/null
@@ -1,667 +0,0 @@
-//! Tool: `continue_subagent` — resume a paused sub-agent with a follow-up
-//! message (typically the user's answer to a clarification question).
-//!
-//! When a sub-agent calls `ask_user_clarification`, its harness loop exits
-//! early, checkpoints the full conversation history, and returns an
-//! `AwaitingUser` envelope to the parent. The orchestrator surfaces the
-//! question to the user, and when the user answers, calls this tool to
-//! resume the same sub-agent from its checkpoint with the user's response
-//! appended to the conversation history.
-
-use crate::agent::orchestration::tools::dispatch::{incomplete_stop, stopped_subagent_result};
-use crate::agent::subagent_host::{
- continue_subagent, continue_subagent_via_driver_tool, load_subagent_checkpoint,
- SubagentRunOptions, SubagentRunStatus,
-};
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use crate::progress::AgentProgress;
-use async_trait::async_trait;
-use serde_json::json;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinytools::ToolRunContext;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-pub struct ContinueSubagentTool;
-
-pub(crate) struct ContinueSubagentDispatch {
- tool: Arc<dyn Tool>,
-}
-
-impl ContinueSubagentDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for ContinueSubagentDispatch
-{
- 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());
- ContinueSubagentTool::new()
- .execute_with_live_parent_context(
- arguments,
- Some(&context),
- parent.data.child(),
- Some(parent),
- )
- .await
- }
-}
-
-impl Default for ContinueSubagentTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl ContinueSubagentTool {
- pub fn new() -> Self {
- Self
- }
-
- /// Resume a durable sub-agent session (no pause checkpoint on disk).
- ///
- /// Accepts either the transient `task_id` (`sub-…`) or the durable
- /// `subagent_session_id` in the tool's `task_id` argument — the ambient
- /// `[active_subagents]` roster advertises both. The resume routes through
- /// `spawn_subagent` pinned to the session's `task_key`, so the
- /// reusable-session machinery reattaches: a `running` worker is steered,
- /// an `idle` one is relaunched seeded with its persisted `latest_history`
- /// plus the new message, and the finished result is delivered back into
- /// the parent chat as a new turn.
- async fn resume_from_durable_store(
- &self,
- parent: &crate::agent::harness::fork_context::ParentExecutionContext,
- task_id: &str,
- agent_id: &str,
- message: &str,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> anyhow::Result<ToolResult> {
- use crate::agent::orchestration::subagent_sessions::{self, SubagentSessionStore};
-
- let store = SubagentSessionStore::new(parent.workspace_dir.clone());
- let sessions = match subagent_sessions::list_for_parent(&store, &parent.session_id, None) {
- Ok(sessions) => sessions,
- Err(err) => {
- return Ok(ToolResult::error(format!(
- "continue_subagent: no checkpoint found for task_id '{task_id}' and \
- the durable session store could not be read: {err}"
- )));
- }
- };
- let session = sessions.iter().find(|s| {
- s.subagent_session_id == task_id || s.current_task_id.as_deref() == Some(task_id)
- });
- let Some(session) = session else {
- return Ok(ToolResult::error(format!(
- "continue_subagent: no checkpoint and no durable session found for \
- task_id '{task_id}'. Check the [active_subagents] roster (or call \
- list_subagents) and pass that subagent_session_id — or delegate a \
- fresh task if the worker was closed."
- )));
- };
- // The session id already identifies a worker within this parent's
- // store. Accept it in `agent_id` too when a caller copies the roster's
- // session id into both fields, but keep rejecting unrelated agents.
- if session.agent_id != agent_id && session.subagent_session_id != agent_id {
- return Ok(ToolResult::error(format!(
- "continue_subagent: agent_id mismatch — durable session '{}' belongs to \
- '{}', caller passed '{agent_id}'",
- session.subagent_session_id, session.agent_id
- )));
- }
- if !session.status.reusable() {
- return Ok(ToolResult::error(format!(
- "continue_subagent: durable session '{}' is {:?} and cannot be resumed. \
- Delegate a fresh task instead.",
- session.subagent_session_id, session.status
- )));
- }
-
- tracing::info!(
- task_id = %task_id,
- subagent_session_id = %session.subagent_session_id,
- agent_id = %session.agent_id,
- status = ?session.status,
- "[continue_subagent] resuming durable session via reusable async path"
- );
-
- let mut async_args = json!({
- "agent_id": session.agent_id.clone(),
- "prompt": message,
- "task_key": session.task_key.clone(),
- "task_title": session.task_title.clone(),
- });
- if let (Some(obj), Some(model)) = (async_args.as_object_mut(), &session.model) {
- obj.insert(
- "model".to_string(),
- serde_json::Value::String(model.clone()),
- );
- }
- let detached_parent =
- crate::agent::subagent_host::detached_subagent_parent(live_parent, "async-subagent")?;
- super::spawn_subagent::SpawnSubagentTool::new()
- .execute_with_live_parent_context(
- async_args,
- tool_context,
- run_context,
- detached_parent,
- )
- .await
- }
-}
-
-#[async_trait]
-impl Tool for ContinueSubagentTool {
- fn name(&self) -> &str {
- "continue_subagent"
- }
-
- fn description(&self) -> &str {
- "Resume an existing sub-agent with a follow-up, keeping its context: pass the `task_id` \
- from a `[SUBAGENT_AWAITING_USER]` envelope or a `subagent_session_id` from the roster. \
- Always prefer this to re-delegating."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["task_id", "agent_id", "message"],
- "properties": {
- "task_id": {
- "type": "string",
- "description": "task_id from the envelope, or the worker's subagent_session_id from the roster."
- },
- "agent_id": {
- "type": "string",
- "description": "The worker's agent_id (from the envelope or roster). For a durable session, its subagent_session_id is also accepted here when used as task_id."
- },
- "message": {
- "type": "string",
- "description": "The user's answer or follow-up message to send to the paused sub-agent."
- }
- }
- })
- }
-
- 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 ContinueSubagentTool {
- 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 task_id = args
- .get("task_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- let agent_id = args
- .get("agent_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();
-
- if task_id.is_empty() {
- return Ok(ToolResult::error(
- "continue_subagent: `task_id` is required",
- ));
- }
- // `task_id` is model-authored and is about to be joined into a
- // filesystem path twice: once to read the pause checkpoint below, and
- // again — via `SubagentRunOptions::task_id` — to write one if the
- // resumed child pauses a second time. `../../../../tmp/pwn` would walk
- // both clean out of the checkpoint directory, so it is rejected at the
- // boundary rather than only at the sink.
- if !crate::agent::subagent_host::is_safe_task_id(&task_id) {
- return Ok(ToolResult::error(format!(
- "continue_subagent: `task_id` must be a plain identifier \
- (letters, digits, `-`, `_`); got '{task_id}'"
- )));
- }
- if agent_id.is_empty() {
- return Ok(ToolResult::error(
- "continue_subagent: `agent_id` is required",
- ));
- }
- if message.is_empty() {
- return Ok(ToolResult::error(
- "continue_subagent: `message` is required (the user's answer)",
- ));
- }
-
- let parent = match run_context.parent.clone() {
- Some(p) => p,
- None => {
- return Ok(ToolResult::error(
- "continue_subagent: no parent execution context available",
- ));
- }
- };
-
- // Load checkpoint
- let checkpoint_dir = parent.workspace_dir.join(".openhuman/subagent_checkpoints");
- let checkpoint = match load_subagent_checkpoint(&checkpoint_dir, &task_id) {
- Ok(checkpoint) => checkpoint,
- Err(error) => {
- // A missing file is the *expected* case, not a failure: a
- // `subsess-…` id from the `[active_subagents]` roster is a
- // durable-session id, which never has a pause checkpoint (those
- // are keyed by task id and only written when a child exits on
- // `ask_user_clarification`). Logging it at INFO with
- // `error=No such file or directory` made the designed happy
- // path read as a broken one — which is what #5928 was filed on.
- // Any other IO error here really is one, so it stays loud.
- tracing::debug!(task_id = %task_id, error = %error, "[continue_subagent] no scoped pause checkpoint; resolving durable session");
- // Durable-session fallback: the sub-agent did not pause on a
- // clarification (no checkpoint), but it may be a durable
- // worker from this or an earlier turn — resumable with its
- // full prior history via the reusable async path. This is
- // what lets the orchestrator continue a finished
- // workflow_builder ("looks good, save it") instead of
- // re-delegating a fresh, stateless one.
- return self
- .resume_from_durable_store(
- &parent,
- &task_id,
- &agent_id,
- &message,
- tool_context,
- run_context,
- live_parent.ok_or_else(|| {
- anyhow::anyhow!("continue_subagent requires a live harness run context")
- })?,
- )
- .await;
- }
- };
- let original_key = checkpoint.task_key.clone().ok_or_else(|| {
- anyhow::anyhow!("continue_subagent: checkpoint omitted original task key")
- })?;
- let checkpoint_resume = crate::agent::subagent_host::checkpoint_resume(&checkpoint);
-
- if checkpoint.agent_id != agent_id {
- return Ok(ToolResult::error(format!(
- "continue_subagent: agent_id mismatch — checkpoint has '{}', \
- caller passed '{agent_id}'",
- checkpoint.agent_id
- )));
- }
-
- // Look up the agent definition
- let registry =
- match AgentDefinitionRegistry::for_core_context(run_context.dispatch_ctx().into_core())
- {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "continue_subagent: AgentDefinitionRegistry not initialised",
- ));
- }
- };
- let definition = match registry.get(&agent_id) {
- Some(def) => def,
- None => {
- return Ok(ToolResult::error(format!(
- "continue_subagent: unknown agent_id '{agent_id}'"
- )));
- }
- };
-
- tracing::info!(
- task_id = %task_id,
- agent_id = %agent_id,
- message_chars = message.chars().count(),
- "[continue_subagent] resuming sub-agent with a durable user answer"
- );
-
- let parent_session = parent.session_id.clone();
- let progress_sink = parent.on_progress.clone();
-
- // Publish resumed event (reuse SubagentSpawned with a note)
- crate::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.clone(),
- agent_id.clone(),
- "typed".to_string(),
- task_id.clone(),
- message.chars().count(),
- );
-
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentSpawned {
- agent_id: agent_id.clone(),
- task_id: task_id.clone(),
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars: message.chars().count(),
- prompt: message.to_string(),
- worker_thread_id: checkpoint.worker_thread_id.clone(),
- display_name: definition.display_name.clone(),
- parent_call_id: crate::tools::host_extensions::tool_call_id(tool_context),
- })
- .await;
- }
-
- // The neutral lifecycle reloads the durable history and the host
- // planner appends `message` exactly once. Do not preload a second
- // history here: it would be overwritten by resume loading or duplicate
- // the user answer on an already-resumed pause.
- let workspace_descriptor = tool_context
- .and_then(|ctx| ctx.workspace().cloned())
- .or_else(|| run_context.workspace.clone());
- if let Some(descriptor) = workspace_descriptor.as_ref() {
- tracing::debug!(
- task_id = %task_id,
- agent_id = %agent_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[continue_subagent] using ToolExecutionContext workspace root"
- );
- }
- let options = SubagentRunOptions {
- skill_filter_override: checkpoint.skill_filter_override,
- context: None,
- model_override: checkpoint.model_override,
- task_id: Some(task_id.clone()),
- thread_id: tool_context
- .and_then(ToolRunContext::thread_id)
- .or(run_context.thread_id.as_deref())
- .map(str::to_owned),
- run_context,
- worker_thread_id: checkpoint.worker_thread_id.clone(),
- initial_history: None,
- checkpoint_dir: Some(checkpoint_dir.clone()),
- workspace_descriptor,
- run_queue: None,
- message_run_queue: None,
- };
-
- // Run the sub-agent from its checkpoint
- let continuation = if let Some(parent) = live_parent {
- continue_subagent_via_driver_tool(
- parent,
- original_key,
- definition.clone(),
- message.clone(),
- options,
- checkpoint_resume,
- )
- .await
- .map(|(outcome, _public_job_id)| outcome)
- } else {
- continue_subagent(original_key, definition, &message, options).await
- };
- match continuation {
- Ok(outcome) => {
- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
- match &outcome.status {
- SubagentRunStatus::AwaitingUser {
- question,
- options: _,
- checkpoint: pause_checkpoint,
- } => {
- // Another round of clarification
- 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: checkpoint.worker_thread_id.clone(),
- checkpoint_path: pause_checkpoint
- .as_ref()
- .map(|p| p.to_string_lossy().to_string()),
- })
- .await;
- }
- }
- // Built by the shared helper, not hand-rolled here.
- // This path used to `format!` its own copy with the
- // question interpolated RAW — the exact hole
- // `awaiting_user_envelope` exists to close: a
- // sub-agent-authored question containing a newline and
- // a literal `[/SUBAGENT_AWAITING_USER]` closed the
- // block early and injected resume instructions the
- // orchestrator then trusted. The helper JSON-encodes
- // it. The hand-rolled copy also omitted the "do NOT
- // re-spawn" instruction that the #4291 fix added.
- let envelope = super::awaiting_user::awaiting_user_envelope(
- &outcome.task_id,
- &outcome.agent_id,
- checkpoint.worker_thread_id.as_deref(),
- question,
- pause_checkpoint.is_some(),
- );
- Ok(ToolResult::success(envelope))
- }
- SubagentRunStatus::Completed => {
- // The lifecycle persistence boundary atomically marks
- // terminal state and retires the scoped pause.
-
- 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(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- stop: None,
- })
- .await;
- }
- }
- Ok(ToolResult::success(outcome.output))
- }
- SubagentRunStatus::Incomplete { reason } => {
- // The continued sub-agent stopped short again (stuck halt
- // / iteration cap). Hand back the partial progress framed
- // as incomplete rather than a clean success (#4096).
- // The run is no longer awaiting input, so the checkpoint
- // written for the prior AwaitingUser pause is stale —
- // clean it up best-effort, mirroring the Completed arm.
- tracing::info!(
- agent_id = %outcome.agent_id,
- task_id = %outcome.task_id,
- reason = %reason,
- "[continue_subagent] sub-agent stopped incomplete after continue"
- );
- 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(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. 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 its partial progress. Do NOT \
- report this as done; relay the partial result and the blocker to the \
- user, or take a different approach.",
- outcome.task_id, outcome.agent_id, outcome.output,
- );
- Ok(stopped_subagent_result(
- "continue_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,
- "[continue_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(
- "continue_subagent: sub-agent was cancelled",
- ))
- }
- }
- }
- Err(err) => {
- let message = err.to_string();
- tracing::error!(
- task_id = %task_id,
- agent_id = %agent_id,
- "[continue_subagent] sub-agent execution failed"
- );
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session,
- task_id.clone(),
- agent_id.clone(),
- message.clone(),
- );
- if let Some(ref tx) = progress_sink {
- let _ = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: agent_id.clone(),
- task_id: task_id.clone(),
- error: message.clone(),
- })
- .await;
- }
- Ok(ToolResult::error(format!(
- "continue_subagent failed: {message}"
- )))
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/list_subagents_tests.rs
deleted file mode 100644
index 876c86d286..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/list_subagents_tests.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use super::*;
-use crate::agent::orchestration::subagent_sessions;
-
-#[test]
-fn schema_has_no_required_fields() {
- let schema = ListSubagentsTool::new().parameters_schema();
- assert!(schema
- .get("required")
- .and_then(|v| v.as_array())
- .expect("required")
- .is_empty());
-}
-
-#[test]
-fn summary_projection_does_not_include_history() {
- let raw = serde_json::to_string(&DurableSubagentSessionSummary {
- subagent_session_id: "subsess-1".into(),
- parent_thread_id: Some("thread-1".into()),
- worker_thread_id: Some("worker-1".into()),
- agent_id: "researcher".into(),
- display_name: Some("Researcher".into()),
- model: Some("agentic-v1".into()),
- sandbox_mode: "workspace".into(),
- action_root: None,
- task_key: "task".into(),
- task_title: "Task".into(),
- current_task_id: Some("sub-1".into()),
- status: subagent_sessions::DurableSubagentStatus::Idle,
- reusable: true,
- latest_error: None,
- created_at: "now".into(),
- updated_at: "now".into(),
- last_used_at: "now".into(),
- })
- .unwrap();
- assert!(!raw.contains("latestHistory"));
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.json b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.json
deleted file mode 100644
index 29491fb99d..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "type": "object",
- "required": [
- "message"
- ],
- "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 over task_id for cross-turn messaging."
- },
- "message": {
- "type": "string",
- "description": "Instruction or data to inject into the running sub-agent."
- },
- "mode": {
- "type": "string",
- "enum": [
- "steer",
- "collect"
- ],
- "default": "steer",
- "description": "steer = a new instruction the sub-agent must address; collect = silent additional context."
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_schema_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_schema_tests.rs
deleted file mode 100644
index 0058399198..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_schema_tests.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_steer_subagent() -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["message"],
- "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 over task_id for cross-turn messaging."
- },
- "message": {
- "type": "string",
- "description": "Instruction or data to inject into the running sub-agent."
- },
- "mode": {
- "type": "string",
- "enum": ["steer", "collect"],
- "default": "steer",
- "description": "steer = a new instruction the sub-agent must address; collect = silent additional context."
- }
- }
- })
-}
-
-#[test]
-fn steer_subagent_static_schema_matches_json_literal() {
- let tool = SteerSubagentTool;
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_steer_subagent()
- );
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_tests.rs
deleted file mode 100644
index 155775cd46..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/steer_subagent_tests.rs
+++ /dev/null
@@ -1,40 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn schema_requires_task_id_and_message() {
- let schema = SteerSubagentTool::new().parameters_schema();
- let required = schema
- .get("required")
- .and_then(|v| v.as_array())
- .expect("required list");
- assert!(required.iter().any(|v| v.as_str() == Some("message")));
-}
-
-#[tokio::test]
-async fn missing_task_id_is_rejected() {
- let tool = SteerSubagentTool::new();
- let res = tool.execute(json!({ "message": "go" })).await.unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("subagent_session_id"));
-}
-
-#[tokio::test]
-async fn missing_message_is_rejected() {
- let tool = SteerSubagentTool::new();
- let res = tool.execute(json!({ "task_id": "sub-1" })).await.unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("message"));
-}
-
-#[tokio::test]
-async fn outside_agent_turn_is_rejected() {
- // No PARENT_CONTEXT task-local installed in a bare test.
- let tool = SteerSubagentTool::new();
- let res = tool
- .execute(json!({ "task_id": "sub-1", "message": "go" }))
- .await
- .unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("outside of an agent turn"));
-}
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
deleted file mode 100644
index 729d779a9f..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_control_surfaces.rs
+++ /dev/null
@@ -1,428 +0,0 @@
-//! OpenHuman declarations and response projection helpers for shared
-//! TinyAgents sub-agent controls.
-//!
-//! Actual query, await, message delivery, and close behavior is dispatched to
-//! TinyAgents' Jobs and Message tools by the live host registration. These
-//! host tools retain the product names, schemas, metadata, and response
-//! envelopes only.
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyagents_orchestration::subagent::SubagentResumeRef;
-use tinytools::{PermissionLevel, Tool, ToolResult, ToolTimeout};
-
-use crate::agent::orchestration::subagent_sessions::{
- DurableSubagentSessionSummary, DurableSubagentStatus,
-};
-use tinyagents_tasks::{OrchestrationTaskRecord, OrchestrationTaskStatus};
-
-pub struct ListSubagentsTool;
-pub struct WaitSubagentTool;
-pub struct SteerSubagentTool;
-pub struct CloseSubagentTool;
-
-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) -> Value {
- json!({"type":"object", "required":[], "properties":{}})
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::error(
- "list_subagents requires a live harness control dispatch",
- ))
- }
-}
-
-impl WaitSubagentTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for WaitSubagentTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-const DEFAULT_TIMEOUT_SECS: u64 = 120;
-const MAX_TIMEOUT_SECS: u64 = 3600;
-
-/// Resolve the product wait deadline used by both the model schema and the
-/// harness timeout policy.
-pub(crate) fn requested_timeout_secs(args: &Value) -> u64 {
- args.get("timeout_secs")
- .and_then(Value::as_u64)
- .unwrap_or(DEFAULT_TIMEOUT_SECS)
- .clamp(1, MAX_TIMEOUT_SECS)
-}
-
-#[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."
- }
-
- fn timeout_policy(&self, args: &Value) -> ToolTimeout {
- ToolTimeout::Millis(requested_timeout_secs(args).saturating_mul(1000))
- }
-
- fn parameters_schema(&self) -> 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: Value) -> anyhow::Result<ToolResult> {
- let task_id = args
- .get("task_id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
- let session_id = args
- .get("subagent_session_id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
- if task_id.is_empty() && session_id.is_empty() {
- return Ok(ToolResult::error(
- "wait_subagent: `subagent_session_id` or `task_id` is required",
- ));
- }
- Ok(ToolResult::error(
- "wait_subagent called outside of an agent turn",
- ))
- }
-}
-
-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) -> Value {
- crate::tools::schema_cache::static_schema!(include_str!("steer_subagent.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let task_id = args
- .get("task_id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
- let session_id = args
- .get("subagent_session_id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
- let message = args
- .get("message")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim();
- if task_id.is_empty() && 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"));
- }
- Ok(ToolResult::error(
- "steer_subagent called outside of an agent turn",
- ))
- }
-}
-
-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) -> 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: Value) -> anyhow::Result<ToolResult> {
- if args
- .get("subagent_session_id")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim()
- .is_empty()
- {
- return Ok(ToolResult::error(
- "close_subagent: `subagent_session_id` is required",
- ));
- }
- Ok(ToolResult::error(
- "close_subagent requires a live harness control dispatch",
- ))
- }
-}
-
-/// Product status overlay retained for the host's legacy session envelope.
-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 crate::agent::orchestration::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",
- }
-}
-
-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())
- )
-}
-
-pub(crate) fn wait_status_payload(
- reference: Option<&SubagentResumeRef>,
- task_id: &str,
- status: &str,
- iterations: Option<usize>,
- detail: Option<&str>,
- next_action: &str,
-) -> 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 = "close_subagent_tests.rs"]
-mod close_tests;
-#[cfg(test)]
-#[path = "list_subagents_tests.rs"]
-mod list_tests;
-#[cfg(test)]
-#[path = "steer_subagent_schema_tests.rs"]
-mod steer_schema_tests;
-#[cfg(test)]
-#[path = "steer_subagent_tests.rs"]
-mod steer_tests;
-#[cfg(test)]
-#[path = "wait_subagent_tests.rs"]
-mod wait_tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs b/crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs
deleted file mode 100644
index d49582d6bc..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/subagent_dispatch_host.rs
+++ /dev/null
@@ -1,597 +0,0 @@
-//! Subagent dispatch logic shared by all agent delegation tools.
-
-use crate::agent::subagent_host::{
- run_subagent_via_driver_tool, SubagentRunOptions, SubagentRunStatus,
-};
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use crate::progress::AgentProgress;
-use async_trait::async_trait;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::{ToolDispatch, ToolExecutionContext};
-use tinytools::ToolRunContext;
-use tinytools::{ToolCallOptions, ToolResult};
-
-mod dispatch_outcomes;
-pub(crate) use dispatch_outcomes::*;
-
-/// Typed dispatch for the delegation tools synthesised from the active agent.
-///
-/// These tools are dynamic, so their common registration resolves the admitted
-/// target from its name and passes the live parent carrier explicitly. This is
-/// the recursive boundary: it never reconstructs product state from a task
-/// local or a downcast.
-pub(crate) struct DelegationDispatch {
- tool: Arc<dyn tinytools::Tool>,
- kind: DelegationDispatchKind,
-}
-
-enum DelegationDispatchKind {
- Archetype { agent_id: String },
-}
-
-impl DelegationDispatch {
- pub(crate) fn for_tool(
- tool: Arc<dyn tinytools::Tool>,
- delegation_target: Option<String>,
- ) -> Option<Self> {
- let kind = match tool.name() {
- // The target is carried by the registered host extension, not
- // inferred from an ambient registry or a tool's spelling. This
- // keeps hidden packed delegates scoped to the catalogue that
- // actually supplied them.
- _ if delegation_target.is_some() => DelegationDispatchKind::Archetype {
- agent_id: delegation_target.expect("checked above"),
- },
- _ => return None,
- };
- Some(Self { tool, kind })
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext> for DelegationDispatch {
- fn tool(&self) -> Arc<dyn tinytools::Tool> {
- self.tool.clone()
- }
-
- /// Delegated output must use the stricter agent-output screening policy.
- fn output_origin(&self) -> tinyagents_harness::host::ContentOrigin {
- tinyagents_harness::host::ContentOrigin::Agent
- }
-
- 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 tool_context = ToolExecutionContext::from_run_context(parent, _call_id.clone());
- let child = parent.data.child();
- match &self.kind {
- DelegationDispatchKind::Archetype { agent_id } => {
- super::archetype_delegation::execute_archetype_delegation_with_live_parent(
- agent_id,
- self.tool.name(),
- arguments,
- Some(&tool_context),
- child,
- Some(parent),
- )
- .await
- }
- }
- }
-}
-
-/// How a delegated sub-agent run should be scheduled relative to the parent
-/// turn.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum DispatchMode {
- /// Run the sub-agent as a durable async worker (the default for
- /// interactive archetype delegations): the tool returns immediately with
- /// an `[async_subagent_ref]` carrying `task_id` + `subagent_session_id`,
- /// and the finished result is delivered back into the parent chat as a
- /// new system-injected turn (`background_delivery`). Falls back to
- /// [`DispatchMode::Blocking`] when there is no parent agent turn or no
- /// current chat thread to deliver the result into (cron/CLI contexts) —
- /// an async result with nowhere to land would be silently lost.
- PreferAsync,
- /// Run the sub-agent inline and return its final output in this turn.
- Blocking,
-}
-
-/// Dispatch one inline child against the caller's actual TinyAgents parent
-/// when the typed tool boundary has one. Standalone callers retain the
-/// explicit-carrier fallback above because no live parent exists for them.
-pub(crate) async fn dispatch_subagent_with_live_parent(
- agent_id: &str,
- tool_name: &str,
- prompt: &str,
- model_override: Option<&str>,
- tool_context: Option<&dyn ToolRunContext>,
- mode: DispatchMode,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: Option<&RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,
-) -> anyhow::Result<ToolResult> {
- let parent_workspace_descriptor = tool_context
- .and_then(|ctx| ctx.workspace().cloned())
- .or_else(|| run_context.workspace.clone());
- let registry =
- match AgentDefinitionRegistry::for_core_context(run_context.dispatch_ctx().into_core()) {
- Some(reg) => reg,
- None => {
- return Ok(ToolResult::error(
- "Agent registry not initialised. This usually means the \
- core process started without calling \
- AgentDefinitionRegistry::init_global at startup.",
- ));
- }
- };
-
- let definition = match registry.get(agent_id) {
- Some(def) => def,
- None => {
- return Ok(ToolResult::error(format!(
- "{tool_name}: agent '{agent_id}' not found in registry"
- )));
- }
- };
-
- let parent_ctx = run_context.parent.clone();
- if let Some(ctx) = &parent_ctx {
- if !ctx.allowed_subagent_ids.contains(&definition.id) {
- log::warn!(
- "[agent] blocked delegation via {}: parent={} requested={} allowed={:?}",
- tool_name,
- ctx.agent_definition_id,
- definition.id,
- ctx.allowed_subagent_ids
- );
- return Ok(ToolResult::error(format!(
- "{tool_name}: agent '{}' is not in parent agent '{}' subagents.allowlist",
- definition.id, ctx.agent_definition_id
- )));
- }
- }
-
- // Registry and policy failures are deterministic and safe to report even
- // to a raw tool caller. Executing a valid delegation still requires the
- // typed harness carrier below, which supplies cancellation and authority.
- let Some(live_parent) = live_parent else {
- return Ok(ToolResult::error(
- "delegation requires a live harness run context.",
- ));
- };
-
- // ── Forward the current turn's attached image(s) to a vision sub-agent ──
- // The orchestrator runs on a non-vision tier and keeps the user's image as a
- // text placeholder (`[Image: … #att:<id>]`), so a delegated sub-agent would
- // otherwise get a text-only task and report "no image". When the target
- // sub-agent's model is vision-capable, prepend the placeholder(s) to its
- // prompt so its own turn rehydrates the image from the on-disk sidecar.
- let forwarded_prompt;
- let prompt: &str = {
- let images = &run_context.attachment_placeholders;
- let subagent_model = match model_override {
- Some(m) => m.to_string(),
- None => {
- let parent_model = parent_ctx
- .as_ref()
- .map(|p| p.model_name.as_str())
- .unwrap_or("");
- definition.model.resolve(parent_model)
- }
- };
- if crate::attachments::should_forward_parent_images(prompt)
- && !images.is_empty()
- && (agent_id == "vision_agent"
- || crate::inference::provider::factory::oh_tier_supports_vision(&subagent_model))
- {
- log::info!(
- "[agent] forwarding {} image placeholder(s) to vision sub-agent '{}'",
- images.len(),
- agent_id
- );
- forwarded_prompt = format!("{}\n\n{}", images.join("\n"), prompt);
- &forwarded_prompt
- } else {
- prompt
- }
- };
-
- if agent_id == "vision_agent" {
- match crate::attachments::has_resolvable_image(
- &run_context.dispatch_ctx(),
- prompt,
- parent_workspace_descriptor.as_ref(),
- run_context.origin.as_ref(),
- )
- .await
- {
- Ok(true) => (),
- Ok(false) => {
- return Ok(ToolResult::error(
- "vision_agent requires a resolvable image attachment or image_paths.",
- ));
- }
- Err(error) => {
- return Ok(ToolResult::error(format!(
- "vision image unavailable: {error}"
- )));
- }
- }
- }
-
- // ── Async-by-default delegation (#continuity) ─────────────────────────
- // Interactive delegations route through the durable async sub-agent
- // machinery: the parent gets an immediate `[async_subagent_ref]` with a
- // stable `subagent_session_id` it can steer/wait/continue by, the session
- // (including full history) is persisted in the per-workspace
- // `subagent_sessions` store, and the finished result is inserted into the
- // parent thread as a NEW turn via `background_completions` +
- // `background_delivery`. This is what keeps a `build_workflow` proposal
- // resumable on the next user turn instead of respawning a fresh,
- // stateless builder (the "day 0 context" bug).
- if mode == DispatchMode::PreferAsync {
- let has_parent_turn = parent_ctx.is_some();
- let has_delivery_thread = tool_context
- .and_then(ToolRunContext::thread_id)
- .or(run_context.thread_id.as_deref())
- .is_some();
- if has_parent_turn && has_delivery_thread {
- let mut async_args = serde_json::json!({
- "agent_id": definition.id.clone(),
- "prompt": prompt,
- "task_title":
- crate::agent::orchestration::subagent_sessions::task_title_from_prompt(
- prompt,
- ),
- });
- if let (Some(obj), Some(model)) = (async_args.as_object_mut(), model_override) {
- obj.insert(
- "model".to_string(),
- serde_json::Value::String(model.to_string()),
- );
- }
- log::info!(
- "[agent] routing {tool_name} delegation of '{}' to durable async sub-agent \
- (result will be delivered as a follow-up turn)",
- definition.id
- );
- // Box the forwarded future: `SpawnSubagentTool`'s
- // `execute_with_context` future is large, and embedding it inline
- // in every delegation tool's future (which itself nests inside
- // agent-turn futures) overflows the test-thread stack on deep
- // parallel-delegation flows.
- return Box::pin(async move {
- let detached_parent = crate::agent::subagent_host::detached_subagent_parent(
- live_parent,
- "async-subagent",
- )?;
- super::spawn_subagent::SpawnSubagentTool::new()
- .execute_with_live_parent_context(
- async_args,
- tool_context,
- run_context,
- detached_parent,
- )
- .await
- })
- .await;
- }
- log::info!(
- "[agent] {tool_name}: async delegation requested but parent_turn={} \
- delivery_thread={} — falling back to blocking dispatch",
- has_parent_turn,
- has_delivery_thread
- );
- }
-
- // Past this point the run is synchronous whichever mode was requested:
- // the async branch above returns when it is taken, so a `PreferAsync`
- // that fell through registers no durable worker either and its result
- // must say so (#6033).
- let mode = DispatchMode::Blocking;
-
- let parent_session = parent_ctx
- .as_ref()
- .map(|p| p.session_id.clone())
- .unwrap_or_else(|| "standalone".into());
- let task_id = format!("sub-{}", uuid::Uuid::new_v4());
-
- crate::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.clone(),
- definition.id.clone(),
- "typed".to_string(),
- task_id.clone(),
- prompt.chars().count(),
- );
-
- // Also send to the per-request progress sink so the web channel bridge
- // emits `subagent_spawned` to the frontend (same pattern as spawn_subagent_surface.rs).
- 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: false,
- prompt_chars: prompt.chars().count(),
- prompt: prompt.to_string(),
- worker_thread_id: None,
- display_name: Some(definition.display_name().to_string()),
- parent_call_id: crate::tools::host_extensions::tool_call_id(tool_context),
- })
- .await;
- }
-
- log::info!(
- "[agent] delegating to {} via {} prompt_chars={}",
- agent_id,
- tool_name,
- prompt.chars().count()
- );
-
- if let Some(descriptor) = parent_workspace_descriptor.as_ref() {
- tracing::debug!(
- agent_id,
- tool_name,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[agent] using ToolExecutionContext workspace root for delegated subagent"
- );
- }
- let options = SubagentRunOptions {
- skill_filter_override: None,
- context: None,
- model_override: model_override.map(str::to_string),
- task_id: Some(task_id.clone()),
- thread_id: tool_context
- .and_then(ToolRunContext::thread_id)
- .or(run_context.thread_id.as_deref())
- .map(str::to_owned),
- run_context: run_context.clone(),
- worker_thread_id: None,
- initial_history: None,
- checkpoint_dir: None,
- workspace_descriptor: parent_workspace_descriptor,
- run_queue: None,
- message_run_queue: None,
- };
-
- let run =
- run_subagent_via_driver_tool(live_parent, definition.clone(), prompt.to_owned(), options)
- .await
- .map(|(outcome, _job_id)| outcome);
- match run {
- Ok(outcome) => {
- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
- match &outcome.status {
- // The delegated sub-agent paused on `ask_user_clarification`.
- // The runner has already checkpointed its conversation, so the
- // orchestrator must relay the question and resume via
- // `continue_subagent` — NOT re-spawn a fresh, stateless
- // sub-agent. Dropping this status was the #4291 infinite re-spawn
- // loop: a paused sub-agent was reported as a plain success, the
- // orchestrator's only continuation was to re-delegate, and the new
- // run paused again. Mirrors the `spawn_subagent` AwaitingUser path.
- SubagentRunStatus::AwaitingUser {
- question,
- 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(progress) = run_context.progress.clone() {
- let _ = progress
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- question: question.clone(),
- // Synchronous delegate dispatch has no worker
- // sub-thread (that is a `spawn_subagent` concept).
- worker_thread_id: None,
- checkpoint_path: checkpoint
- .as_ref()
- .map(|p| p.to_string_lossy().to_string()),
- })
- .await;
- }
- }
- log::info!(
- "[agent] {} paused for user input via {} (task_id={}) — \
- returning awaiting-user envelope; orchestrator must resume \
- with continue_subagent, not re-delegate",
- agent_id,
- tool_name,
- outcome.task_id,
- );
- Ok(awaiting_outcome_to_tool_result(
- &outcome,
- question,
- checkpoint.is_some(),
- ))
- }
- SubagentRunStatus::Completed => {
- 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,
- );
- // Also send to the per-request progress sink (mirrors
- // `spawn_subagent_surface.rs`) so the web channel bridge emits
- // `subagent_done` to the frontend. Without this the delegated
- // subagent's timeline row (created on `SubagentSpawned` above)
- // stays "running" forever — `publish_subagent_completed` only
- // fires the internal DomainEvent bus, not the per-request
- // progress channel the UI's timeline is driven from.
- if let Some(progress) = run_context.progress.clone() {
- let _ = progress
- .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(),
- // Synchronous delegate dispatch inherits the
- // parent's workspace context.
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- stop: None,
- })
- .await;
- }
- }
- log::info!(
- "[agent] {} completed via {} iterations={} output_chars={}",
- agent_id,
- tool_name,
- outcome.iterations,
- outcome.output.chars().count()
- );
- // A sub-agent that emitted a tool call instead of executing one
- // "completes" with markup where the answer should be. Passing
- // that through reads as a finished result, so frame it the way
- // an iteration-cap stop is framed (#6033, #4096 precedent).
- if is_unexecuted_tool_call_stub(&outcome.output) {
- log::info!(
- "[agent] {} returned an unexecuted tool-call stub (task_id={} output_chars={}) — reframing as incomplete",
- tool_name,
- outcome.task_id,
- outcome.output.chars().count()
- );
- return Ok(ToolResult::success(incomplete_envelope(
- tool_name,
- "returned an unexecuted tool call instead of a result",
- &outcome.output,
- mode,
- )));
- }
- Ok(ToolResult::success(with_inline_result_note(
- outcome.output,
- mode,
- )))
- }
- // A stuck halt / iteration-cap stop returns `Incomplete`; frame the
- // partial progress so the orchestrator can't mistake it for a
- // finished result or re-run the identical delegation unchanged
- // (#4096). Still a lifecycle-completed run, so publish
- // SubagentCompleted like the `Completed` arm.
- SubagentRunStatus::Incomplete { reason } => {
- 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,
- );
- // Same progress-sink mirror as the `Completed` arm above —
- // an incomplete stop is still lifecycle-completed, so the
- // timeline row must be released from "running" here too.
- if let Some(progress) = run_context.progress.clone() {
- let _ = progress
- .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(),
- // Not audited for whether this child's spend reached the
- // parent turn's ledger, so it stays silent: omission adds
- // nothing, which is the status quo. See the field's docs.
- usage: None,
- stop: incomplete_stop(reason, outcome.failure_cause.clone()),
- })
- .await;
- }
- }
- log::info!(
- "[agent] {} stopped incomplete via {} (task_id={}) iterations={} — \
- returning partial-progress envelope, not a finished result",
- agent_id,
- tool_name,
- outcome.task_id,
- outcome.iterations,
- );
- Ok(stopped_subagent_result(
- tool_name,
- &outcome.agent_id,
- &outcome.task_id,
- reason,
- outcome.failure_cause.clone(),
- incomplete_envelope(tool_name, reason, &outcome.output, mode),
- ))
- }
- SubagentRunStatus::Cancelled => {
- log::info!(
- "[agent] {} was cancelled via {} (task_id={})",
- agent_id,
- tool_name,
- outcome.task_id,
- );
- 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(progress) = run_context.progress.clone() {
- let _ = progress
- .send(AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- error: message,
- })
- .await;
- }
- }
- Ok(ToolResult::error(format!(
- "{tool_name}: delegated sub-agent was cancelled"
- )))
- }
- }
- }
- Err(err) => {
- let message = err.to_string();
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session,
- task_id,
- definition.id.clone(),
- message.clone(),
- );
- // Make the failure unmistakable to the orchestrator: the delegated
- // task did NOT run, so it must not be reported as success or have
- // its output fabricated. Without this guardrail a weak orchestrator
- // can narrate a plausible success from the bare error text — the
- // "hallucinated success" half of #3193 (e.g. claiming `run_code`
- // wrote a file when the coding model 404'd and nothing executed).
- Ok(ToolResult::error(format_subagent_failure(
- tool_name, &message,
- )))
- }
- }
-}
-
-#[cfg(test)]
-#[path = "dispatch_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs
deleted file mode 100644
index 626697542c..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/wait_subagent_tests.rs
+++ /dev/null
@@ -1,92 +0,0 @@
-use super::*;
-
-#[test]
-fn schema_requires_task_id() {
- let schema = WaitSubagentTool::new().parameters_schema();
- let required = schema
- .get("required")
- .and_then(|v| v.as_array())
- .expect("required list");
- assert!(required.is_empty());
-}
-
-#[tokio::test]
-async fn missing_task_id_is_rejected() {
- let res = WaitSubagentTool::new().execute(json!({})).await.unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("subagent_session_id"));
-}
-
-#[tokio::test]
-async fn outside_agent_turn_is_rejected() {
- let res = WaitSubagentTool::new()
- .execute(json!({ "task_id": "sub-1" }))
- .await
- .unwrap();
- assert!(res.is_error);
- assert!(res.output().contains("outside of an agent turn"));
-}
-
-#[test]
-fn running_wait_message_includes_agent_id_and_tick_instruction() {
- let reference = tinyagents_orchestration::subagent::SubagentResumeRef {
- task_id: "sub-1".into(),
- agent_id: "researcher".into(),
- subagent_session_id: Some("subsess-1".into()),
- };
- let message = format_running_wait_message(Some(&reference), "sub-1", 1);
-
- assert!(message.contains("Sub-agent `researcher` is still running"));
- assert!(message.contains("[subagent_wait_result]"));
- assert!(message.contains("\"agentId\":\"researcher\""));
- assert!(message.contains("\"timeout_tick\""));
- assert!(message.contains("\"timeout_secs\":1"));
-}
-
-/// The tool must own its deadline. Under the inherited per-tool-call
-/// timeout the harness killed the wait before it could report "still
-/// running", so a long-but-healthy sub-agent surfaced as a tool failure.
-#[test]
-fn timeout_policy_is_owned_not_inherited() {
- let tool = WaitSubagentTool::new();
- assert_eq!(
- tool.timeout_policy(&json!({})),
- ToolTimeout::Millis(DEFAULT_TIMEOUT_SECS * 1000)
- );
- assert!(matches!(
- tool.timeout_policy(&json!({"timeout_secs": 1800})),
- ToolTimeout::Millis(1_800_000)
- ));
-}
-
-/// The advertised wait and the harness deadline are resolved by one
-/// function precisely so they cannot drift apart; if they ever did, the
-/// shorter one silently wins and the graceful path is unreachable again.
-#[test]
-fn policy_and_wait_resolve_the_same_seconds() {
- let tool = WaitSubagentTool::new();
- for args in [
- json!({}),
- json!({"timeout_secs": 1}),
- json!({"timeout_secs": 900}),
- json!({"timeout_secs": 99_999}),
- json!({"timeout_secs": 0}),
- ] {
- let ToolTimeout::Millis(policy) = tool.timeout_policy(&args) else {
- panic!("wait_subagent must return an explicit Millis policy");
- };
- assert_eq!(policy, requested_timeout_secs(&args) * 1000);
- }
-}
-
-/// Out-of-range requests clamp rather than error, so a model asking for a
-/// very long wait still gets the longest legal one.
-#[test]
-fn requested_timeout_clamps_into_range() {
- assert_eq!(requested_timeout_secs(&json!({"timeout_secs": 0})), 1);
- assert_eq!(
- requested_timeout_secs(&json!({"timeout_secs": 99_999})),
- MAX_TIMEOUT_SECS
- );
- assert_eq!(requested_timeout_secs(&json!({})), DEFAULT_TIMEOUT_SECS);
-}