Skip to content

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

chore: files changed crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_host.r

Steven Enamakel771e57384789
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_host.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_host.rs
deleted file mode 100644
index c67772951f..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_host.rs
+++ /dev/null
@@ -1,431 +0,0 @@
-//! `delegate_to` — every archetype hand-off as one action-dispatched tool.
-//!
-//! Replaces the per-sub-agent fan-out where `collect_orchestrator_tools`
-//! synthesised one [`ArchetypeDelegationTool`] per named sub-agent. On the
-//! Master Agent that was **16 tools worth 17,746 bytes, 41% of its whole
-//! tool-schema budget** — and the schemas were not 16 different things. Every
-//! one of them carried a byte-identical copy of the delegation envelope
-//! (`prompt` / `objective` / `evidence` / `constraints` / `must_not_assume` /
-//! `expected_output` / `citation_requirement` / `model` / `blocking`), because
-//! `ArchetypeDelegationTool::parameters_schema` is one `json!` literal that
-//! does not read `self`. The only thing that differed between the 16 was the
-//! name and the target's `when_to_use` line.
-//!
-//! So the envelope is emitted once here and the 16 names become an `agent`
-//! enum, with each target's `when_to_use` kept verbatim in the description —
-//! the routing information survives in full, the repetition does not.
-//!
-//! The integration axis went a step further: connected Composio actions are
-//! `Deferred` tools reached through `tool_search` and called directly, so
-//! that axis has no delegation tool at all (`orchestrator_tools`). This one
-//! makes the sub-agent axis constant in the sub-agent dimension.
-//!
-//! # Why collapse rather than pack
-//!
-//! The toolpack mechanism (`load_skill` / `use_skill`) exists and would also
-//! remove these bytes, but it is the wrong tool for this family. A pack costs
-//! a round trip on first use, which is the right trade for a capability most
-//! turns never touch — crypto, MCP setup, the `.pptx` writer. Delegation is
-//! the orchestrator's *job*; putting a round trip in front of it would tax the
-//! single most common thing it does, on almost every turn.
-//!
-//! Collapsing has the opposite cost profile: one extra enum field on a call
-//! the model was making anyway, and no round trip at all. Frequency of use is
-//! what separates the two mechanisms — see `toolpacks::registry`, whose
-//! `DELIBERATELY_UNPACKED_FLEET_TOOLS` note draws the same line for the same
-//! reason.
-//!
-//! # The members stay registered
-//!
-//! Each `delegate_*` / `research` / `plan` / … tool remains in the registry as
-//! [`ToolExposure::Hidden`], exactly like the members of the collapsed `cron`
-//! and `memory` tools. They are off the wire, not gone: a replayed transcript,
-//! a saved skill, or a flow node that names `research` still resolves. Only
-//! the advertised surface shrinks.
-//!
-//! # The name
-//!
-//! `delegate_to`, not `delegate`: a config-driven [`DelegateTool`] already
-//! claims `delegate` whenever a user hand-writes an `[agents]` block, and the
-//! builder's collision guard resolves a clash by dropping the *synthesised*
-//! tool. Naming this one `delegate` would therefore have removed the
-//! orchestrator's entire delegation surface for exactly those users, silently.
-//!
-//! [`DelegateTool`]: crate::tools::delegate::DelegateTool
-//! [`ArchetypeDelegationTool`]: super::ArchetypeDelegationTool
-//! [`ToolExposure::Hidden`]: tinytools::ToolExposure::Hidden
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use super::archetype_delegation::{delegation_envelope_properties, render_structured_handoff};
-use tinytools::ToolRunContext;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolResult, ToolTimeout};
-
-/// The advertised name. A constant so the synthesis site, the prompt's
-/// delegation section and the tests cannot disagree about it.
-pub const DELEGATE_TO_TOOL_NAME: &str = "delegate_to";
-
-/// JSON-Schema extension that carries the exact selector-to-agent mapping the
-/// collapsed tool was built with. The harness registers tools behind `dyn
-/// Tool`, so this keeps the concrete tool's routing table alongside its
-/// advertised enum without a downcast or a later lookup against every global
-/// definition.
-pub(crate) const DISPATCH_TARGETS_SCHEMA_KEY: &str = "x-openhuman-delegation-targets";
-
-/// One routable sub-agent.
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct DelegateTarget {
- /// The name this target had when it was its own tool, and the value the
- /// `agent` enum takes. Keeping the old name as the enum value is what lets
- /// the orchestrator prompt go on naming `research` and `schedule_task`
- /// without a rewrite, and keeps dispatch events reading as they did.
- pub tool_name: String,
- /// The registry id the work is actually handed to.
- pub agent_id: String,
- /// The target's `when_to_use`, verbatim.
- pub description: String,
-}
-
-/// Every archetype hand-off as one tool.
-pub struct CollapsedDelegationTool {
- targets: Vec<DelegateTarget>,
- description: String,
-}
-
-impl CollapsedDelegationTool {
- /// Build the collapsed tool, or `None` when there is nothing to route to.
- ///
- /// `None` rather than an empty enum: a `delegate` tool whose `agent` has no
- /// valid value is a schema the model can only call wrongly.
- pub fn for_targets(targets: Vec<DelegateTarget>) -> Option<Self> {
- if targets.is_empty() {
- return None;
- }
- let description = build_description(&targets);
- Some(Self {
- targets,
- description,
- })
- }
-
- fn resolve(&self, agent: &str) -> Option<&DelegateTarget> {
- self.targets.iter().find(|t| t.tool_name == agent)
- }
-
- fn agent_enum(&self) -> Vec<&str> {
- self.targets.iter().map(|t| t.tool_name.as_str()).collect()
- }
-
- fn dispatch_targets_schema(&self) -> Value {
- Value::Array(
- self.targets
- .iter()
- .map(|target| {
- json!({
- "tool_name": target.tool_name,
- "agent_id": target.agent_id,
- })
- })
- .collect(),
- )
- }
-}
-
-fn build_description(targets: &[DelegateTarget]) -> String {
- let mut buf = String::from(
- "Hand a task to a specialist sub-agent. Set `agent` to one of the values below and pass \
- the task as `prompt`. Choose by what the task needs:",
- );
- for target in targets {
- buf.push_str("\n- `");
- buf.push_str(&prompt_safe(&target.tool_name));
- buf.push('`');
- let trimmed = target.description.trim();
- if !trimmed.is_empty() {
- buf.push_str(": ");
- buf.push_str(&prompt_safe(trimmed));
- }
- }
- buf
-}
-
-fn prompt_safe(value: &str) -> String {
- let mut out = String::with_capacity(value.len());
- for ch in value.chars() {
- match ch {
- '`' => out.push('\''),
- ch if ch.is_control() => out.push_str(&format!("\\u{{{:x}}}", ch as u32)),
- ch => out.push(ch),
- }
- }
- out
-}
-
-#[async_trait]
-impl Tool for CollapsedDelegationTool {
- fn name(&self) -> &str {
- DELEGATE_TO_TOOL_NAME
- }
-
- fn description(&self) -> &str {
- &self.description
- }
-
- /// The envelope, emitted **once**, plus the `agent` selector.
- ///
- /// The properties come from `delegation_envelope_properties` rather than a
- /// second literal: two copies of this object would be two places for the
- /// collapsed tool and its hidden members to disagree about what a hand-off
- /// carries, and `render_structured_handoff` reads the property names
- /// directly. One definition, both callers.
- fn parameters_schema(&self) -> Value {
- let mut schema = json!({
- "type": "object",
- "required": ["agent", "prompt"],
- "properties": {
- "agent": {
- "type": "string",
- "enum": self.agent_enum(),
- "description": "Which specialist to hand this to."
- }
- }
- });
- schema[DISPATCH_TARGETS_SCHEMA_KEY] = self.dispatch_targets_schema();
- let properties = schema["properties"]
- .as_object_mut()
- .expect("properties is an object literal above");
- if let Value::Object(envelope) = delegation_envelope_properties() {
- for (key, value) in envelope {
- properties.insert(key, value);
- }
- }
- schema
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Every member declares `Execute`, so there is no per-action variation
- // to resolve here. If a target ever needs more, this must become an
- // args-aware lookup like `cron`'s — a single level would then be
- // laundering one target's risk down to another's.
- PermissionLevel::Execute
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::System
- }
-
- /// Unbounded, matching the member tools this replaces.
- ///
- /// Under the default `Inherit` policy the whole delegation is hard-killed
- /// at the single-tool timeout (120s), truncating any sub-agent run that
- /// legitimately takes longer — the Sentry regression (TAURI-RUST-K29,
- /// TAURI-RUST-8HB) that put `Unbounded` on `ArchetypeDelegationTool` in the
- /// first place. The child bounds its own lifetime through `max_iterations`,
- /// the run cancellation token and each inner tool's own timeout.
- fn timeout_policy(&self, _args: &Value) -> ToolTimeout {
- ToolTimeout::Unbounded
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: 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_collapsed_delegation(&self.targets, args, tool_context, run_context).await
- }
-}
-
-/// Recover the concrete collapsed target table retained in the advertised
-/// schema for typed harness registration. Reject malformed metadata instead
-/// of widening the route to every entry in the process-wide definition
-/// registry.
-pub(crate) fn dispatch_targets_from_schema(schema: &Value) -> Result<Vec<DelegateTarget>, String> {
- let enum_names = schema
- .pointer("/properties/agent/enum")
- .and_then(Value::as_array)
- .ok_or_else(|| "delegate_to schema is missing `properties.agent.enum`".to_string())?;
- let enum_names: Vec<&str> = enum_names
- .iter()
- .map(|value| {
- value
- .as_str()
- .filter(|name| !name.trim().is_empty())
- .ok_or_else(|| "delegate_to agent enum contains a non-string value".to_string())
- })
- .collect::<Result<_, _>>()?;
- let encoded_targets = schema
- .get(DISPATCH_TARGETS_SCHEMA_KEY)
- .and_then(Value::as_array)
- .ok_or_else(|| "delegate_to schema is missing its target mapping".to_string())?;
- let targets: Vec<DelegateTarget> = encoded_targets
- .iter()
- .map(|value| {
- let object = value
- .as_object()
- .ok_or_else(|| "delegate_to target mapping entry is not an object".to_string())?;
- let required = |key: &str| {
- object
- .get(key)
- .and_then(Value::as_str)
- .filter(|value| !value.trim().is_empty())
- .map(str::to_owned)
- .ok_or_else(|| format!("delegate_to target mapping is missing `{key}`"))
- };
- Ok(DelegateTarget {
- tool_name: required("tool_name")?,
- agent_id: required("agent_id")?,
- // Descriptions are prompt-only routing guidance. The typed
- // dispatch needs the exact selector-to-agent mapping, not a
- // second copy of model-visible prose.
- description: String::new(),
- })
- })
- .collect::<Result<_, String>>()?;
- if targets.len() != enum_names.len()
- || targets
- .iter()
- .map(|target| target.tool_name.as_str())
- .ne(enum_names.iter().copied())
- || targets.iter().any(|target| {
- targets
- .iter()
- .filter(|candidate| candidate.tool_name == target.tool_name)
- .count()
- != 1
- })
- {
- return Err(
- "delegate_to target mapping does not exactly match its advertised agent enum".into(),
- );
- }
- Ok(targets)
-}
-
-/// Execute a collapsed hand-off with an explicit child run carrier.
-pub(crate) async fn execute_collapsed_delegation(
- targets: &[DelegateTarget],
- args: Value,
- tool_context: Option<&dyn ToolRunContext>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
-) -> anyhow::Result<ToolResult> {
- execute_collapsed_delegation_with_live_parent(targets, args, tool_context, run_context, None)
- .await
-}
-
-/// Typed-harness counterpart that preserves the exact parent run for a
-/// blocking child rather than recreating a synthetic root from host data.
-pub(crate) async fn execute_collapsed_delegation_with_live_parent(
- targets: &[DelegateTarget],
- args: 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 requested = args.get("agent").and_then(Value::as_str).map(str::trim);
- let Some(target) =
- requested.and_then(|agent| targets.iter().find(|target| target.tool_name == agent))
- else {
- return Ok(ToolResult::error(format!(
- "`agent` must be one of: {}. Got: {}",
- targets
- .iter()
- .map(|target| target.tool_name.as_str())
- .collect::<Vec<_>>()
- .join(", "),
- requested.filter(|s| !s.is_empty()).unwrap_or("(missing)")
- )));
- };
-
- let raw_prompt = args
- .get("prompt")
- .and_then(Value::as_str)
- .unwrap_or("")
- .trim()
- .to_string();
- if raw_prompt.is_empty() {
- return Ok(ToolResult::error(format!(
- "{DELEGATE_TO_TOOL_NAME}: `prompt` is required"
- )));
- }
- let prompt = render_structured_handoff(&raw_prompt, &args);
- let 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(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
-
- // Async by default, exactly as the member tools were: the specialist
- // runs as a durable, resumable worker and its result arrives as a new
- // chat turn. `blocking: true` is the opt-in for a result that must gate
- // this reply.
- let blocking = args
- .get("blocking")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let mode = if blocking {
- super::dispatch::DispatchMode::Blocking
- } else {
- super::dispatch::DispatchMode::PreferAsync
- };
-
- tracing::debug!(
- agent = %target.agent_id,
- via = %target.tool_name,
- "[delegate] dispatch"
- );
- // `target.tool_name`, not `DELEGATE_TO_TOOL_NAME`: the dispatch name rides
- // into run records and the UI, and reporting every hand-off as
- // `delegate` would erase which specialist was chosen from every trace.
- super::dispatch::dispatch_subagent_with_live_parent(
- &target.agent_id,
- &target.tool_name,
- &prompt,
- model_override,
- tool_context,
- mode,
- run_context,
- live_parent,
- )
- .await
-}
-
-#[cfg(test)]
-#[path = "collapsed_delegation_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_tests.rs
deleted file mode 100644
index 32cdb182b4..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/collapsed_delegation_tests.rs
+++ /dev/null
@@ -1,266 +0,0 @@
-//! Tests for the collapsed `delegate_to` tool.
-//!
-//! The load-bearing ones are the two that would let the collapse silently stop
-//! paying for itself: `the_envelope_is_emitted_once` (the saving) and
-//! `every_member_is_hidden_so_the_collapse_actually_saves_something` (that
-//! nothing ships both surfaces).
-
-use super::*;
-use crate::agent::orchestration::tools::ArchetypeDelegationTool;
-use tinytools::ToolExposure;
-
-fn targets() -> Vec<DelegateTarget> {
- vec![
- DelegateTarget {
- tool_name: "research".to_string(),
- agent_id: "researcher".to_string(),
- description: "Web research and source gathering.".to_string(),
- },
- DelegateTarget {
- tool_name: "review_code".to_string(),
- agent_id: "code_reviewer".to_string(),
- description: "Review a diff for correctness.".to_string(),
- },
- ]
-}
-
-fn tool() -> CollapsedDelegationTool {
- CollapsedDelegationTool::for_targets(targets()).expect("two targets is not empty")
-}
-
-#[test]
-fn an_empty_target_list_produces_no_tool() {
- // An `agent` enum with no valid value is a schema the model can only call
- // wrongly.
- assert!(CollapsedDelegationTool::for_targets(Vec::new()).is_none());
-}
-
-#[test]
-fn the_schema_advertises_every_target() {
- let schema = tool().parameters_schema();
- let listed: Vec<&str> = schema["properties"]["agent"]["enum"]
- .as_array()
- .expect("enum")
- .iter()
- .filter_map(|v| v.as_str())
- .collect();
- assert_eq!(listed, vec!["research", "review_code"]);
-}
-
-#[test]
-fn dispatch_target_mapping_matches_the_advertised_enum_and_agent_ids() {
- let tool = tool();
- let targets = dispatch_targets_from_schema(&tool.parameters_schema())
- .expect("concrete collapsed tool publishes a dispatch map");
- assert_eq!(
- targets
- .iter()
- .map(|target| (target.tool_name.as_str(), target.agent_id.as_str()))
- .collect::<Vec<_>>(),
- vec![("research", "researcher"), ("review_code", "code_reviewer")]
- );
-}
-
-#[test]
-fn the_schema_carries_the_whole_delegation_envelope() {
- // The collapse must advertise exactly the member envelope plus its own
- // `agent` selector: `prompt`, `blocking`, and `image_paths`. Structured hand-off
- // fields are no longer advertised by either tool (a self-contained
- // `prompt` carries them), but `render_structured_handoff` still reads
- // them, so a caller that sends them keeps its constraints.
- let schema = tool().parameters_schema();
- let props = schema["properties"].as_object().expect("properties");
- let mut names: Vec<&str> = props.keys().map(String::as_str).collect();
- names.sort_unstable();
- assert_eq!(names, vec!["agent", "blocking", "image_paths", "prompt"]);
- assert_eq!(schema["required"], serde_json::json!(["agent", "prompt"]));
-}
-
-#[test]
-fn the_envelope_is_emitted_once() {
- // The entire point of the collapse, asserted as a number rather than a
- // shape: one tool holding N targets must not cost what N tools cost.
- //
- // Without this, someone re-introducing a per-target schema (say, to give
- // each specialist its own `expected_output` description) would reproduce
- // the 17,746-byte regression this file exists to remove, and every other
- // test here would still pass.
- let many: Vec<DelegateTarget> = (0..16)
- .map(|i| DelegateTarget {
- tool_name: format!("target_{i}"),
- agent_id: format!("agent_{i}"),
- description: "A specialist.".to_string(),
- })
- .collect();
- let collapsed = CollapsedDelegationTool::for_targets(many).expect("non-empty");
- let bytes = serde_json::to_string(&collapsed.parameters_schema())
- .expect("schema serialises")
- .len();
-
- // One envelope (~900 B) plus 16 short enum values. Sixteen separate
- // schemas were ~17,700 B; the ceiling here is deliberately far below that
- // and far above the real figure, so it catches a reintroduced fan-out
- // without failing on ordinary wording changes.
- assert!(
- bytes < 2_000,
- "16 targets cost {bytes} B of schema — the envelope is being repeated"
- );
-}
-
-#[test]
-fn adding_a_target_costs_only_its_name_and_description() {
- // The property that makes the schema constant in the sub-agent dimension:
- // growth must be linear in the *description*, not in the envelope.
- let one = CollapsedDelegationTool::for_targets(vec![DelegateTarget {
- tool_name: "research".to_string(),
- agent_id: "researcher".to_string(),
- description: String::new(),
- }])
- .expect("non-empty");
- let two = CollapsedDelegationTool::for_targets(vec![
- DelegateTarget {
- tool_name: "research".to_string(),
- agent_id: "researcher".to_string(),
- description: String::new(),
- },
- DelegateTarget {
- tool_name: "plan".to_string(),
- agent_id: "planner".to_string(),
- description: String::new(),
- },
- ])
- .expect("non-empty");
-
- let cost = |t: &CollapsedDelegationTool| {
- serde_json::to_string(&t.parameters_schema())
- .expect("serialises")
- .len()
- + t.description().len()
- };
- // `plan` plus the enum quoting and list punctuation — tens of bytes, not
- // the ~1,100 a whole extra tool schema used to cost.
- assert!(
- cost(&two) - cost(&one) < 60,
- "a second target added {} B",
- cost(&two) - cost(&one)
- );
-}
-
-#[test]
-fn the_description_carries_each_targets_routing_line() {
- // The routing information is the one thing the collapse must not lose —
- // it is how the model picks a specialist at all.
- let tool = tool();
- let description = tool.description();
- assert!(description.contains("`research`"));
- assert!(description.contains("Web research and source gathering."));
- assert!(description.contains("`review_code`"));
- assert!(description.contains("Review a diff for correctness."));
-}
-
-#[test]
-fn a_target_with_no_when_to_use_still_lists_its_name() {
- let tool = CollapsedDelegationTool::for_targets(vec![DelegateTarget {
- tool_name: "mystery".to_string(),
- agent_id: "mystery_agent".to_string(),
- description: " ".to_string(),
- }])
- .expect("non-empty");
- assert!(tool.description().contains("`mystery`"));
- // No dangling ": " when the description is blank.
- assert!(!tool.description().contains("`mystery`: "));
-}
-
-#[tokio::test]
-async fn an_unknown_agent_is_an_error_naming_the_valid_ones() {
- let result = tool()
- .execute(serde_json::json!({"agent": "researchr", "prompt": "hi"}))
- .await
- .expect("dispatch does not fail the call");
- assert!(result.is_error);
- let text = format!("{result:?}");
- assert!(text.contains("researchr"), "names what was passed: {text}");
- assert!(text.contains("research"), "names the valid ones: {text}");
-}
-
-#[tokio::test]
-async fn a_missing_agent_is_an_error_rather_than_a_default_route() {
- // Defaulting to the first target would silently send work to the wrong
- // specialist, which is worse than failing.
- let result = tool()
- .execute(serde_json::json!({"prompt": "hi"}))
- .await
- .expect("dispatch does not fail the call");
- assert!(result.is_error);
- assert!(format!("{result:?}").contains("missing"));
-}
-
-#[tokio::test]
-async fn an_empty_prompt_is_rejected_before_dispatch() {
- let result = tool()
- .execute(serde_json::json!({"agent": "research", "prompt": " "}))
- .await
- .expect("dispatch does not fail the call");
- assert!(result.is_error);
- assert!(format!("{result:?}").contains("prompt"));
-}
-
-#[test]
-fn the_timeout_is_unbounded_like_the_members_it_replaces() {
- // Inheriting the 120s single-tool deadline would truncate every sub-agent
- // run that legitimately takes longer — the Sentry regression that put
- // `Unbounded` on `ArchetypeDelegationTool` in the first place.
- assert!(matches!(
- tool().timeout_policy(&serde_json::json!({})),
- tinytools::ToolTimeout::Unbounded
- ));
-}
-
-#[test]
-fn every_member_is_hidden_so_the_collapse_actually_saves_something() {
- // The load-bearing assertion, matching the one on the collapsed `cron` and
- // `memory` tools: leaving a member `Direct` would ship both surfaces and
- // save nothing, and nothing else in the build would notice.
- let member = ArchetypeDelegationTool {
- tool_name: "research".to_string(),
- agent_id: crate::agent::orchestration::tools::archetype_delegation::DelegationTarget(
- "researcher".to_string(),
- ),
- tool_description: "Web research.".to_string(),
- };
- assert_eq!(member.exposure(), ToolExposure::Hidden);
- // …while the collapsed tool itself stays on the wire.
- assert_eq!(tool().exposure(), ToolExposure::Direct);
-}
-
-#[test]
-fn the_member_and_the_collapsed_tool_agree_on_the_envelope() {
- // Both call `delegation_envelope_properties`, so this pins that neither
- // grew a private copy. A drift here is silent: the collapsed schema would
- // advertise a field `render_structured_handoff` never reads.
- let member = ArchetypeDelegationTool {
- tool_name: "research".to_string(),
- agent_id: crate::agent::orchestration::tools::archetype_delegation::DelegationTarget(
- "researcher".to_string(),
- ),
- tool_description: "Web research.".to_string(),
- };
- let member_props = member.parameters_schema()["properties"]
- .as_object()
- .expect("properties")
- .keys()
- .cloned()
- .collect::<std::collections::BTreeSet<_>>();
-
- let collapsed = tool().parameters_schema();
- let mut collapsed_props = collapsed["properties"]
- .as_object()
- .expect("properties")
- .keys()
- .cloned()
- .collect::<std::collections::BTreeSet<_>>();
- // The selector is the collapsed tool's own addition.
- assert!(collapsed_props.remove("agent"));
-
- assert_eq!(member_props, collapsed_props);
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs
index ae2d6d1927..964d506953 100644
--- a/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/tools/tools_e2e_tests.rs
@@ -2,7 +2,6 @@ use super::{ArchetypeDelegationTool, DelegationTarget, SpawnSubagentTool};
use crate::agent::harness::ParentExecutionContext;
use crate::agent_registry::host_definition::AgentDefinitionRegistry;
use crate::integrations::ConnectedIntegration;
-use crate::threads::store as conversations;
use async_trait::async_trait;
use parking_lot::Mutex;
use serde_json::json;
@@ -16,7 +15,6 @@ use tinytools_agent::dialect::ToolCallFormat;
const SPAWN_SUBAGENT_CANARY: &str = "tool-e2e-spawn-subagent-canary";
const ARCHETYPE_DELEGATION_CANARY: &str = "tool-e2e-archetype-delegation-canary";
-const WORKER_THREAD_CANARY: &str = "tool-e2e-worker-thread-canary";
#[tokio::test]
async fn spawn_subagent_tool_runs_child_agent_e2e() {
diff --git a/crates/openhuman-core/src/agent/session_host/turn/context.rs b/crates/openhuman-core/src/agent/session_host/turn/context.rs
deleted file mode 100644
index 6c9e0b5cc3..0000000000
--- a/crates/openhuman-core/src/agent/session_host/turn/context.rs
+++ /dev/null
@@ -1,96 +0,0 @@
-//! History, context, and system prompt management.
-
-use super::super::types::OpenHumanSessionHost;
-use crate::agent::prompts::{PromptContext, PromptTool};
-use tinytools::render_tool_policy_boundary;
-
-use anyhow::Result;
-
-impl OpenHumanSessionHost {
- /// Builds the system prompt for the current turn, including tool
- /// instructions.
- pub fn build_system_prompt(&self) -> Result<String> {
- // `visible_tool_specs` holds shared `Arc<ToolSpec>` leaves. Materialise
- // the canonical dialect input for this prompt build.
- let visible_specs_owned: Vec<tinytools::ToolSpec> = self
- .visible_tool_specs
- .iter()
- .map(|spec| spec.as_ref().clone())
- .collect();
- let instructions = self
- .tool_dispatcher
- .prompt_instructions(&visible_specs_owned);
- // Adapt the agent's whole callable surface into the shared PromptTool
- // shape that every prompt-building call-site uses. Temporary vec
- // borrows from the two tool `Arc`s and lives for the duration of the
- // prompt build. The synthesised delegates belong here: the catalogue
- // this renders is what tells the model a `delegate_*` tool exists.
- let all_tools = self.all_tool_refs();
- let mut prompt_tools = PromptTool::from_tool_refs(all_tools.iter().copied());
- prompt_tools.retain(|tool| !self.permanent_tool_names.contains(tool.name.as_ref()));
- let mut prompt_visible_tool_names =
- self.tool_policy_session.visible_tool_names_for_prompt();
- crate::agent::prompts::swap_deferred_for_discovery_bridge(
- &mut prompt_tools,
- &mut prompt_visible_tool_names,
- &self.deferred_tool_names,
- );
- // Load AGENTS.md instruction layers once per system-prompt build (never
- // re-read per turn — the caller builds the prompt once at session start
- // and reuses the bytes, preserving the frozen-prefix / KV-cache
- // contract). Global layer from the workspace dir; project layer from the
- // effective action dir. Gated by `agents_md_enabled`.
- let agents_md = if self.config.agents_md_enabled {
- crate::agent::prompts::load_agents_md_layers(&self.workspace_dir, &self.action_dir)
- } else {
- tracing::debug!(
- "[agents_md] disabled by config; skipping AGENTS.md injection for main agent"
- );
- tinyagents_harness::context::AgentsMdContent::default()
- };
- let ctx = PromptContext {
- workspace_dir: &self.workspace_dir,
- model_name: &self.model_name,
- agent_id: &self.agent_definition_name,
- tools: &prompt_tools,
- workflows: &self.workflows,
- dispatcher_instructions: &instructions,
- visible_tool_names: &prompt_visible_tool_names,
- tool_call_format: self.tool_dispatcher.tool_call_format(),
- connected_integrations: &self.connected_integrations,
- connected_identities_md: crate::integrations::render_connected_identities(
- &self.dispatch_ctx(),
- ),
- user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
- personality_roster: vec![], // TODO: build_personality_roster(&workspace_dir)
- agents_md_global: agents_md.global,
- agents_md_local: agents_md.local,
- };
- let prompt = self.prompt_builder.build(&ctx)?;
- // Appended, not prepended (#5704). Every line of this block is
- // session-scoped — agent id, channel, entry point, risk level, the
- // allowed-tool list — so putting it first moves the prompt's first
- // diverging byte to offset 0 and costs the inference backend's
- // automatic prefix cache everything behind it. That is the same
- // concern that keeps DateTimeSection out of `for_subagent` and keeps
- // the connected-server overview sorted. The model reads the whole
- // system message either way.
- //
- // It also keeps the archetype/persona as the prompt's opening line,
- // which the prepend had replaced with a constant heading for every
- // agent.
- let boundary = render_tool_policy_boundary(&self.tool_policy_session, 2048);
- Ok(append_tool_policy_boundary(prompt, boundary))
- }
-}
-
-/// Place the tool-policy boundary block relative to the assembled prompt.
-///
-/// Separated from [`OpenHumanSessionHost`] so the ordering can be tested without standing up a
-/// session: everything that decides the placement is in these two arguments.
-fn append_tool_policy_boundary(prompt: String, boundary: Option<String>) -> String {
- match boundary {
- Some(boundary) => format!("{prompt}\n\n{boundary}"),
- None => prompt,
- }
-}
diff --git a/crates/openhuman-core/src/agent/session_host/turn/mod.rs b/crates/openhuman-core/src/agent/session_host/turn/mod.rs
deleted file mode 100644
index e01ca7d84a..0000000000
--- a/crates/openhuman-core/src/agent/session_host/turn/mod.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-//! Host-specific prompt construction, tool policy refresh, and the model graph.
-//!
-//! Generic turn lifecycle is intentionally absent: it is owned by
-//! `tinyagents_runtime::Session` in `runtime_session`.
-
-mod context;
diff --git a/crates/openhuman-core/src/tools/impl/mod.rs b/crates/openhuman-core/src/tools/impl/mod.rs
index 8529ac0457..5eea8196d3 100644
--- a/crates/openhuman-core/src/tools/impl/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/mod.rs
@@ -6,7 +6,6 @@ pub mod network;
#[cfg(feature = "documents")]
pub mod presentation;
pub mod system;
-pub mod threads;
pub use browser::*;
#[cfg(feature = "documents")]
diff --git a/crates/openhuman-core/src/tools/impl/system/lsp.rs b/crates/openhuman-core/src/tools/impl/system/lsp.rs
deleted file mode 100644
index c029991ea0..0000000000
--- a/crates/openhuman-core/src/tools/impl/system/lsp.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-//! `lsp` — capability-gated LSP query stub.
-//!
-//! Coding-harness baseline tool (issue #1205). The full LSP integration
-//! (spawning language servers, JSON-RPC bridge, completion / hover /
-//! definition / references) is large enough to live in its own
-//! follow-up. This tool exists today as the **agent-facing surface +
-//! capability gate** so:
-//!
-//! 1. The schema is stable: prompts and downstream callers can be
-//! written against `{ language, kind, file, line, character, symbol }`
-//! without churn when the real backend lands.
-//! 2. The gate is observable: with `OPENHUMAN_LSP_ENABLED=1` set the
-//! tool registers; without it, it does not — so agents don't see a
-//! method that will always fail.
-//! 3. When enabled but no backend is wired, the tool returns a clear
-//! "not yet implemented" error instead of silently misbehaving.
-
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// Env var that gates LSP tool registration.
-pub const LSP_ENABLED_ENV: &str = "OPENHUMAN_LSP_ENABLED";
-
-/// Returns true when the LSP capability gate is on. Accepts `1`, `true`,
-/// `yes` (case-insensitive). Anything else (including unset) is off.
-pub fn lsp_capability_enabled() -> bool {
- match std::env::var(LSP_ENABLED_ENV) {
- Ok(v) => matches!(
- v.trim().to_ascii_lowercase().as_str(),
- "1" | "true" | "yes" | "on"
- ),
- Err(_) => false,
- }
-}
-
-pub struct LspTool;
-
-impl LspTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for LspTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for LspTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "lsp"
- }
-
- fn description(&self) -> &str {
- "Query a Language Server for code intelligence (definition, references, \
- hover, completion). Capability-gated: only registered when \
- OPENHUMAN_LSP_ENABLED=1. The server-spawning backend is a follow-up \
- — calls today return a `not yet implemented` error so callers can \
- feature-detect."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "kind": {
- "type": "string",
- "enum": ["definition", "references", "hover", "completion"],
- "description": "Which LSP query to run."
- },
- "language": {
- "type": "string",
- "description": "Language id (e.g. `rust`, `typescript`, `python`)."
- },
- "file": { "type": "string", "description": "Workspace-relative file path." },
- "line": { "type": "integer", "minimum": 0 },
- "character": { "type": "integer", "minimum": 0 },
- "symbol": {
- "type": "string",
- "description": "Optional symbol name (used by some kinds, e.g. references)."
- }
- },
- "required": ["kind", "language", "file"]
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::error(
- "lsp backend not yet implemented — capability gate is on but no language server is wired. Track this in the follow-up issue.",
- ))
- }
-}
-
-#[cfg(test)]
-#[path = "lsp_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/tools/impl/system/lsp_tests.rs b/crates/openhuman-core/src/tools/impl/system/lsp_tests.rs
deleted file mode 100644
index dacc5a0b21..0000000000
--- a/crates/openhuman-core/src/tools/impl/system/lsp_tests.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use super::*;
-use serde_json::json;
-use std::sync::Mutex;
-
-/// Serialize env-var mutation across tests in this module so they
-/// don't race each other under Rust's default parallel runner.
-static ENV_LOCK: Mutex<()> = Mutex::new(());
-
-#[test]
-fn lsp_name_and_schema() {
- let tool = LspTool::new();
- assert_eq!(tool.name(), "lsp");
- let schema = tool.parameters_schema();
- let required = schema["required"].as_array().unwrap();
- assert!(required.contains(&json!("kind")));
- assert!(required.contains(&json!("language")));
- assert!(required.contains(&json!("file")));
-}
-
-#[tokio::test]
-async fn lsp_returns_not_implemented_error() {
- let tool = LspTool::new();
- let result = tool
- .execute(json!({
- "kind": "definition", "language": "rust", "file": "src/main.rs",
- "line": 0, "character": 0
- }))
- .await
- .unwrap();
- assert!(result.is_error);
- assert!(result.output().contains("not yet implemented"));
-}
-
-#[test]
-fn lsp_capability_gate_off_by_default() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var(LSP_ENABLED_ENV).ok();
- std::env::remove_var(LSP_ENABLED_ENV);
- assert!(!lsp_capability_enabled());
- if let Some(v) = prev {
- std::env::set_var(LSP_ENABLED_ENV, v);
- }
-}
-
-#[test]
-fn lsp_capability_gate_accepts_truthy_values() {
- let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let prev = std::env::var(LSP_ENABLED_ENV).ok();
- for v in ["1", "true", "TRUE", "yes", "on"] {
- std::env::set_var(LSP_ENABLED_ENV, v);
- assert!(lsp_capability_enabled(), "expected truthy for {v:?}");
- }
- for v in ["0", "false", "no", "off", ""] {
- std::env::set_var(LSP_ENABLED_ENV, v);
- assert!(!lsp_capability_enabled(), "expected falsy for {v:?}");
- }
- match prev {
- Some(v) => std::env::set_var(LSP_ENABLED_ENV, v),
- None => std::env::remove_var(LSP_ENABLED_ENV),
- }
-}
diff --git a/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread.rs b/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread.rs
deleted file mode 100644
index ac46d701e6..0000000000
--- a/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread.rs
+++ /dev/null
@@ -1,485 +0,0 @@
-//! Tool: `spawn_worker_thread` — spawn a dedicated worker thread for a complex delegated task.
-//!
-//! Unlike `spawn_subagent`, which collapses sub-agent work into a single
-//! tool result in the current thread, `spawn_worker_thread` creates a new
-//! persisted thread with label `worker`. The sub-agent's full transcript
-//! is recorded into that thread, and the parent receives a compact
-//! reference (worker thread id) instead of the full output.
-//!
-//! Worker threads carry a hard cap on depth: a worker thread cannot spawn
-//! another worker thread.
-
-use crate::agent::subagent_host::{run_subagent_with_parent, SubagentRunOptions};
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use crate::threads::store as conversations;
-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};
-
-/// Spawns a sub-agent in a dedicated worker thread.
-pub struct SpawnWorkerThreadTool;
-
-pub(crate) struct SpawnWorkerThreadDispatch {
- tool: Arc<dyn Tool>,
-}
-
-impl SpawnWorkerThreadDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for SpawnWorkerThreadDispatch
-{
- 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());
- SpawnWorkerThreadTool::new()
- .execute_with_live_parent_context(
- arguments,
- Some(&context),
- parent.data.child(),
- Some(parent),
- )
- .await
- }
-}
-
-impl Default for SpawnWorkerThreadTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl SpawnWorkerThreadTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for SpawnWorkerThreadTool {
- fn name(&self) -> &str {
- "spawn_worker_thread"
- }
-
- fn description(&self) -> &str {
- "Spawn a dedicated worker thread for a complex delegated task. \
- Use this when the task is long or involves many steps that would \
- clutter the current conversation. The sub-agent runs in a fresh \
- thread labeled 'worker', and you receive the thread ID and a \
- summary. Worker threads cannot spawn other worker threads."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()
- .map(|reg| reg.list().iter().map(|d| d.id.clone()).collect())
- .unwrap_or_default();
-
- let agent_id_schema = if agent_ids.is_empty() {
- json!({
- "type": "string",
- "description": "Sub-agent id (e.g. code_executor, critic, planner)."
- })
- } else {
- json!({
- "type": "string",
- "enum": agent_ids,
- "description": "Sub-agent id from the registry."
- })
- };
-
- json!({
- "type": "object",
- "required": ["agent_id", "prompt", "task_title"],
- "properties": {
- "agent_id": agent_id_schema,
- "prompt": {
- "type": "string",
- "description": "Clear, specific instruction for the sub-agent. The sub-agent has no memory of the parent's conversation, so include all context the sub-agent needs to act."
- },
- "task_title": {
- "type": "string",
- "description": "A short, descriptive title for the worker thread (e.g. 'Researching Rust async patterns')."
- },
- "context": {
- "type": "string",
- "description": "Optional context blob from prior task results. Rendered as a `[Context]` block before the prompt."
- },
- "model": {
- "type": "string",
- "description": "Optional exact model id for this spawn only. Keeps the parent provider/routing, but pins the worker child agent to this model instead of the agent definition's default."
- }
- }
- })
- }
-
- 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 SpawnWorkerThreadTool {
- 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
- }
-
- /// Typed-harness entrypoint that retains the live parent for this inline
- /// child. The public `Tool` fallback has no live harness parent.
- 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<&RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,
- ) -> anyhow::Result<ToolResult> {
- let Some(live_parent) = live_parent else {
- return Ok(ToolResult::error(
- "spawn_worker_thread requires a live harness run context.",
- ));
- };
- let dispatch = run_context.dispatch_ctx();
- let started = std::time::Instant::now();
-
- let agent_id = args
- .get("agent_id")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
- let prompt = args
- .get("prompt")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .to_string();
- let task_title = args
- .get("task_title")
- .and_then(|v| v.as_str())
- .unwrap_or("Worker Task")
- .to_string();
- let context = args
- .get("context")
- .and_then(|v| v.as_str())
- .map(|s| s.to_string());
- let model_override = args
- .get("model")
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty());
-
- if agent_id.is_empty() || prompt.is_empty() {
- tracing::warn!(
- agent_id = %agent_id,
- prompt_empty = prompt.is_empty(),
- "[spawn_worker_thread] rejected: agent_id and prompt are required"
- );
- return Ok(ToolResult::error("agent_id and prompt are required"));
- }
-
- let parent = run_context
- .parent
- .clone()
- .ok_or_else(|| anyhow::anyhow!("no parent context"))?;
- let parent_session = parent.session_id.clone();
-
- // ── Depth Guard ────────────────────────────────────────────────
- // Check if the current thread is already a worker thread.
- let current_thread_id = tool_context
- .and_then(ToolRunContext::thread_id)
- .unwrap_or("unknown")
- .to_string();
-
- tracing::info!(
- agent_id = %agent_id,
- task_title = %task_title,
- current_thread_id = %current_thread_id,
- has_context = context.is_some(),
- "[spawn_worker_thread] invoked"
- );
-
- let threads = conversations::list_threads(&dispatch, parent.workspace_dir.clone())
- .map_err(|e| anyhow::anyhow!(e))?;
- if let Some(current_thread) = threads.iter().find(|t| t.id == current_thread_id) {
- let is_delegated_label = current_thread
- .labels
- .iter()
- .any(|label| label == "tasks" || label == "worker" || label == "agent-task");
- if is_delegated_label || current_thread.parent_thread_id.is_some() {
- tracing::warn!(
- agent_id = %agent_id,
- current_thread_id = %current_thread_id,
- is_delegated_label,
- has_parent_thread_id = current_thread.parent_thread_id.is_some(),
- elapsed_ms = started.elapsed().as_millis() as u64,
- "[spawn_worker_thread] depth guard blocked spawn from worker thread"
- );
- return Ok(ToolResult::error(
- "Worker threads cannot spawn other worker threads. Depth is capped at 1. Use spawn_subagent for inline delegation instead.",
- ));
- }
- }
-
- let registry = AgentDefinitionRegistry::current()
- .ok_or_else(|| anyhow::anyhow!("AgentDefinitionRegistry not initialised"))?;
-
- let definition = registry
- .get(&agent_id)
- .ok_or_else(|| anyhow::anyhow!("agent_id '{}' not found", agent_id))?;
-
- if !parent.allowed_subagent_ids.contains(&definition.id) {
- tracing::warn!(
- parent_agent = %parent.agent_definition_id,
- requested_agent = %definition.id,
- allowed = ?parent.allowed_subagent_ids,
- "[spawn_worker_thread] blocked subagent outside parent allowlist"
- );
- return Ok(ToolResult::error(format!(
- "spawn_worker_thread: agent '{}' is not in parent agent '{}' subagents.allowlist",
- definition.id, parent.agent_definition_id
- )));
- }
-
- tracing::debug!(
- parent_agent = %parent.agent_definition_id,
- requested_agent = %definition.id,
- "[spawn_worker_thread] subagent allowlist check passed"
- );
-
- // ── Create Worker Thread ───────────────────────────────────────
- // Shared with `spawn_subagent` so both delegation paths persist an
- // identical, reopenable sub-thread seeded with the prompt.
- let worker_thread_id = crate::threads::worker_thread::create_worker_thread(
- &dispatch,
- parent.workspace_dir.clone(),
- &current_thread_id,
- &agent_id,
- &task_title,
- &prompt,
- )
- .map_err(|e| anyhow::anyhow!(e))?;
-
- // We don't have an easy way to append a system message to the parent
- // thread here without triggering a re-render of the history the model
- // sees. Instead, we return the info in the tool result.
-
- // ── Run Subagent ──────────────────────────────────────────────
- let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- let worktree_action_dir = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- if let Some(descriptor) = workspace_descriptor.as_ref() {
- tracing::debug!(
- agent_id = %agent_id,
- worker_thread_id = %worker_thread_id,
- workspace_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[spawn_worker_thread] using ToolExecutionContext workspace root"
- );
- }
- let progress_sink = run_context.progress.clone();
- let options = SubagentRunOptions {
- skill_filter_override: None,
- context,
- model_override,
- task_id: None,
- thread_id: tool_context
- .and_then(ToolRunContext::thread_id)
- .map(str::to_owned),
- run_context,
- worker_thread_id: Some(worker_thread_id.clone()),
- initial_history: None,
- checkpoint_dir: None,
- worktree_action_dir,
- workspace_descriptor,
- run_queue: None,
- message_run_queue: None,
- };
-
- tracing::debug!(
- agent_id = %agent_id,
- worker_thread_id = %worker_thread_id,
- "[spawn_worker_thread] dispatching run_subagent"
- );
-
- let run =
- run_subagent_with_parent(live_parent, definition.clone(), prompt.clone(), options)
- .await;
- match run {
- Ok(outcome) => {
- let owns_effects = outcome.should_emit_lifecycle_effects();
- match outcome.status {
- crate::agent::subagent_host::SubagentRunStatus::Completed => {
- if owns_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,
- );
- }
- tracing::info!(
- agent_id = %agent_id,
- worker_thread_id = %worker_thread_id,
- task_id = %outcome.task_id,
- elapsed_ms = started.elapsed().as_millis() as u64,
- "[spawn_worker_thread] completed successfully"
- );
- Ok(ToolResult::success(format!(
- "Spawned worker thread `{worker_thread_id}` for the task: {task_title}. \
- The sub-agent has completed its work. You can find the full transcript \
- in the worker thread.\n\n\
- [worker_thread_ref]\n{}\n[/worker_thread_ref]",
- json!({
- "thread_id": worker_thread_id,
- "label": "worker",
- "agent_id": agent_id,
- "task_id": outcome.task_id,
- "status": "completed"
- })
- )))
- }
- crate::agent::subagent_host::SubagentRunStatus::AwaitingUser {
- question,
- checkpoint,
- ..
- } => {
- if owns_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) = progress_sink {
- let _ = progress
- .send(crate::progress::AgentProgress::SubagentAwaitingUser {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- question: question.clone(),
- worker_thread_id: Some(worker_thread_id.clone()),
- checkpoint_path: checkpoint
- .as_ref()
- .map(|path| path.to_string_lossy().to_string()),
- })
- .await;
- }
- }
- Ok(ToolResult::success(format!(
- "Worker thread `{worker_thread_id}` is awaiting user input: {question}\n\n\
- [worker_thread_ref]\n{}\n[/worker_thread_ref]",
- json!({
- "thread_id": worker_thread_id,
- "label": "worker",
- "agent_id": agent_id,
- "task_id": outcome.task_id,
- "status": "awaiting_user",
- "question": question,
- })
- )))
- }
- crate::agent::subagent_host::SubagentRunStatus::Incomplete { reason } => {
- if owns_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,
- );
- }
- Ok(ToolResult::error(format!(
- "Worker thread `{worker_thread_id}` stopped before finishing: {reason}"
- )))
- }
- crate::agent::subagent_host::SubagentRunStatus::Cancelled => {
- // Cancellation is not a completed lifecycle. Surface it
- // as failed/cancelled and deliberately do not publish a
- // completed event or progress record.
- if owns_effects {
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session,
- outcome.task_id.clone(),
- outcome.agent_id.clone(),
- "worker sub-agent was cancelled".into(),
- );
- if let Some(progress) = progress_sink {
- let _ = progress
- .send(crate::progress::AgentProgress::SubagentFailed {
- agent_id: outcome.agent_id.clone(),
- task_id: outcome.task_id.clone(),
- error: "worker sub-agent was cancelled".into(),
- })
- .await;
- }
- }
- Ok(ToolResult::error(format!(
- "Worker thread `{worker_thread_id}` was cancelled"
- )))
- }
- }
- }
- Err(err) => {
- tracing::error!(
- agent_id = %agent_id,
- worker_thread_id = %worker_thread_id,
- error = %err,
- elapsed_ms = started.elapsed().as_millis() as u64,
- "[spawn_worker_thread] execution failed"
- );
- Ok(ToolResult::error(format!(
- "Worker thread execution failed: {err}"
- )))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "spawn_worker_thread_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread_tests.rs b/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread_tests.rs
deleted file mode 100644
index 9d005fee02..0000000000
--- a/crates/openhuman-core/src/tools/impl/threads/spawn_worker_thread_tests.rs
+++ /dev/null
@@ -1,147 +0,0 @@
-use super::*;
-use crate::agent::harness::ParentExecutionContext;
-use crate::threads::store::CreateConversationThread;
-use std::path::PathBuf;
-use std::sync::Arc;
-use tempfile::TempDir;
-use tinyagents_harness::context::RunConfig;
-use tinyagents_harness::tool::ToolDispatch;
-
-fn test_parent_ctx(workspace_dir: PathBuf) -> ParentExecutionContext {
- let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
- Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
- "done",
- ]));
- ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "orchestrator".into(),
- allowed_subagent_ids: std::collections::HashSet::new(),
- session_id: "test".into(),
- session_key: "test".into(),
- session_parent_prefix: None,
- model_name: "test".into(),
- temperature: 0.4,
- workspace_dir,
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(model),
- channel: "test".into(),
- all_tools: Arc::new(vec![]),
- all_tool_specs: Arc::new(vec![]),
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- workflows: Arc::new(vec![]),
- memory_context: std::sync::Arc::new(None),
- connected_integrations: vec![],
- on_progress: None,
- run_queue: None,
- agent_config: crate::config::AgentConfig::default(),
- tool_call_format: tinytools_agent::dialect::ToolCallFormat::Native,
- host_env: Default::default(),
- }
-}
-
-#[tokio::test]
-async fn rejects_if_already_worker_thread() {
- let temp = TempDir::new().unwrap();
- let thread_id = "worker-123";
- conversations::ensure_thread(
- &crate::core::runtime::DispatchCtx::ambient(),
- temp.path().to_path_buf(),
- CreateConversationThread {
- id: thread_id.to_string(),
- title: "Worker".into(),
- created_at: chrono::Utc::now().to_rfc3339(),
- parent_thread_id: None,
- labels: Some(vec!["tasks".to_string()]),
- personality_id: None,
- working_dir: None,
- },
- )
- .unwrap();
-
- let result = spawn_from_thread(temp.path(), thread_id).await;
-
- assert!(result.is_error);
- assert!(result
- .output()
- .contains("cannot spawn other worker threads"));
-}
-
-#[tokio::test]
-async fn rejects_if_has_parent_thread_id() {
- let temp = TempDir::new().unwrap();
- let thread_id = "sub-123";
- conversations::ensure_thread(
- &crate::core::runtime::DispatchCtx::ambient(),
- temp.path().to_path_buf(),
- CreateConversationThread {
- id: thread_id.to_string(),
- title: "Sub".into(),
- created_at: chrono::Utc::now().to_rfc3339(),
- parent_thread_id: Some("parent".into()),
- labels: None,
- personality_id: None,
- working_dir: None,
- },
- )
- .unwrap();
-
- let result = spawn_from_thread(temp.path(), thread_id).await;
-
- assert!(result.is_error);
- assert!(result
- .output()
- .contains("cannot spawn other worker threads"));
-}
-
-async fn spawn_from_thread(workspace: &std::path::Path, thread_id: &str) -> tinytools::ToolResult {
- let parent = test_parent_ctx(workspace.to_path_buf());
- let run = crate::agent::tinyagents::host::OpenHumanRunContext::new()
- .with_parent(parent)
- .into_tinyagents(RunConfig::new("worker-depth-test").with_thread(thread_id));
- SpawnWorkerThreadDispatch::new(Arc::new(SpawnWorkerThreadTool::new()))
- .execute(
- &(),
- tinyagents_harness::ids::CallId::new("spawn-worker-thread-test"),
- json!({
- "agent_id": "task_manager_agent",
- "prompt": "do it",
- "task_title": "Task"
- }),
- tinytools::ToolCallOptions::default(),
- &run,
- )
- .await
- .expect("worker dispatch")
-}
-
-#[tokio::test]
-async fn rejects_agent_outside_parent_allowlist() {
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let temp = TempDir::new().unwrap();
- let parent = test_parent_ctx(temp.path().to_path_buf());
-
- let live = crate::agent::orchestration::tools::live_parent_run_context(
- "worker-allowlist-test",
- parent,
- );
- let tool = SpawnWorkerThreadTool::new();
- let result = tool
- .execute_with_live_parent_context(
- json!({
- "agent_id": "task_manager_agent",
- "prompt": "do it",
- "task_title": "Task"
- }),
- None,
- live.data.child(),
- Some(&live),
- )
- .await
- .unwrap();
-
- assert!(result.is_error);
- assert!(result.output().contains(
- "spawn_worker_thread: agent 'task_manager_agent' is not in parent agent 'orchestrator' subagents.allowlist"
- ));
-}