The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: files changed crates/openhuman-core/src/agent/orchestration/delegation.rs,crates/openhuman-co
Steven Enamakelf212a5a61357
diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsdeleted file mode 100644index 0a7a4223f9..0000000000--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ /dev/null@@ -1,360 +0,0 @@-//! OpenHuman policy and worker adapters for the multi-stage delegation tool.-//!-//! TinyAgents' `DelegationTool` owns the durable plan→execute⇄review→finalize-//! mechanics. This module supplies the product-specific stage prompts, target-//! definition, checkpoint configuration, approval interpretation, and result-//! projection. Each host stage worker enters the shared subagent driver so its-//! lifecycle is visible to the same Jobs and Message tools as other children.-//!-//! The host retains its caller context, trust and progress policy; it does not-//! implement the generic graph state machine or job lifecycle.--use std::sync::Arc;--use crate::agent::subagent_host::{- run_subagent_via_driver_tool, SubagentRunOptions, SubagentRunStatus,-};-use crate::agent::tinyagents::host::OpenHumanRunContext;-use crate::agent_registry::host_definition::AgentDefinition;-use crate::config::Config;-use crate::progress::AgentProgress;-use tinyagents_graph::checkpoint::Checkpointer;-use tinyagents_graph::delegation::{- DelegationConfig, DelegationStage, DelegationStageOutput, DelegationState,-};-use tinyagents_harness::context::{RunConfig, RunContext};-use tinyagents_harness::tool::ToolDispatch;-use tinytools::{- PermissionLevel, ToolCallOptions, ToolCategory, ToolResult, ToolScope, ToolTimeout,- WorkspaceDescriptor,-};--const LOG_TARGET: &str = "agent_orchestration::delegation";--/// Derives one delegation stage's run context and host data from the stage-/// parent. The host carrier is pointed at the stage run's own linked child-/// token, so a graph cancel still reaches the stage through the parent while-/// cancelling the stage leaves the graph (and its siblings) running.-pub(crate) fn stage_run_contexts(- stage_parent: &RunContext<OpenHumanRunContext>,- workspace: Option<WorkspaceDescriptor>,-) -> tinyagents_harness::Result<(RunContext<OpenHumanRunContext>, OpenHumanRunContext)> {- let mut stage_context = stage_parent.data.child();- stage_context.workspace = workspace.or(stage_context.workspace);- let mut stage_run = stage_parent.child(- RunConfig::new(format!("delegation-stage-{}", uuid::Uuid::new_v4())),- stage_context.clone(),- )?;- stage_context.cancellation = stage_run.cancellation.clone();- stage_run.data.cancellation = stage_run.cancellation.clone();- Ok((stage_run, stage_context))-}--/// Typed live entrypoint for the durable delegation graph.-///-/// The graph does create a durable graph id for its checkpoints, but each-/// stage retains the caller's cancellation, origin, dispatch, progress,-/// conversation thread, and workspace through the supplied carrier.-pub(crate) async fn run_subagent_delegation_with_parent_context(- config: Arc<Config>,- definition: AgentDefinition,- task_prompt: String,- max_revisions: usize,- parent_workspace_descriptor: Option<WorkspaceDescriptor>,- live_parent: Arc<RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,-) -> Result<ToolResult, String> {- let thread_id = format!("delegrun-{}", uuid::Uuid::new_v4());- // The graph and every stage share this cancellation token. A stage gets an- // owned host carrier before it enters `run_subagent`, rather than making a- // fresh context after the graph has spawned work.- // Durable graph checkpoints live in the storage backend, in the acting- // agent's scope (`DriverCheckpointer`).- let checkpointer = open_delegation_checkpointer(&config)?;-- tracing::info!(- target: LOG_TARGET,- agent_id = %definition.id,- thread_id = %thread_id,- max_revisions,- "[delegation] starting durable sub-agent delegation"- );- if let Some(descriptor) = parent_workspace_descriptor.as_ref() {- tracing::debug!(- target: LOG_TARGET,- agent_id = %definition.id,- thread_id = %thread_id,- workspace_root = %descriptor.root.display(),- policy_id = %descriptor.policy_id,- "[delegation] using ToolExecutionContext workspace root"- );- }-- let invocation_agent_id = definition.id.clone();- let invocation_task_prompt = task_prompt.clone();- let stage_parent = live_parent.clone();- let run_stage = move |_stage_args: serde_json::Value,- stage: DelegationStage,- state: DelegationState| {- let definition = definition.clone();- let task = task_prompt.clone();- let workspace_descriptor = parent_workspace_descriptor.clone();- let stage_parent = stage_parent.clone();- async move {- let prompt = build_stage_prompt(stage, &task, &state);- let (stage_parent, stage_context) =- stage_run_contexts(&stage_parent, workspace_descriptor.clone())- .map_err(|error| format!("delegation stage context: {error}"))?;- match run_subagent_via_driver_tool(- &stage_parent,- definition,- prompt.clone(),- delegation_subagent_options(workspace_descriptor, stage_context),- )- .await- {- Ok((outcome, _public_job_id)) => {- let should_emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();- match outcome.status {- SubagentRunStatus::Completed => {}- SubagentRunStatus::AwaitingUser {- question,- checkpoint,- ..- } => {- // A durable delegation graph cannot safely advance- // plan/review state while one of its stages is- // paused. Surface the exact durable child handle so- // the caller can continue that stage instead of- // silently stranding the checkpoint behind a generic- // graph error.- if should_emit_lifecycle_effects {- let parent_session = stage_parent- .data- .parent- .as_ref()- .map(|parent| parent.session_id.clone())- .unwrap_or_else(|| "standalone".to_string());- 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) = stage_parent.data.progress.clone() {- let _ = progress- .send(AgentProgress::SubagentAwaitingUser {- agent_id: outcome.agent_id.clone(),- task_id: outcome.task_id.clone(),- question: question.clone(),- worker_thread_id: None,- checkpoint_path: checkpoint- .as_ref()- .map(|path| path.to_string_lossy().to_string()),- })- .await;- }- }- return Err(format!(- "[SUBAGENT_AWAITING_USER]\nagent_id: {}\ntask_id: {}\nquestion: {}\ncheckpointed: {}\n[/SUBAGENT_AWAITING_USER]\n\- delegation stage {stage:?} is awaiting user input; relay the answer with continue_subagent using this task_id.",- outcome.agent_id,- outcome.task_id,- serde_json::to_string(&question).unwrap_or_else(|_| {- "\"<unserializable question>\"".to_string()- }),- checkpoint.is_some(),- ));- }- SubagentRunStatus::Incomplete { reason } => {- return Err(format!(- "delegation stage {stage:?} stopped incomplete: {reason}"- ));- }- SubagentRunStatus::Cancelled => {- return Err(format!("delegation stage {stage:?} was cancelled"));- }- }- let approved = matches!(stage, DelegationStage::Review)- && review_approves(&outcome.output);- Ok(DelegationStageOutput {- text: outcome.output,- approved,- // Persist the exact prompt this stage sent so the- // execute step's `StepRecord` carries its provenance- // (read only for the execute stage; #3884).- prompt: Some(prompt),- })- }- Err(e) => Err(format!("delegation stage {stage:?} failed: {e}")),- }- }- };- let config_checkpointer = Arc::clone(&checkpointer);- let config_thread_id = thread_id.clone();- let config_factory =- move |_state: &(), parent: &RunContext<OpenHumanRunContext>, _args: &serde_json::Value| {- DelegationConfig {- max_revisions,- checkpointer: Some(Arc::clone(&config_checkpointer)),- thread_id: Some(config_thread_id.clone()),- cancel: parent.cancellation.clone(),- // Automated delegation: preserve the host's existing worker-output- // review policy while the generic tool owns graph lifecycle mechanics.- ..DelegationConfig::default()- }- };- let result_agent_id = invocation_agent_id.clone();- let tool = tinyagents_orchestration::subagent::DelegationTool::new(config_factory, run_stage)- .with_tool_name("delegate_graph")- .with_description("Durable plan, execute, review, and finalize delegation.")- .with_parameters(serde_json::json!({- "type": "object",- "required": ["task"],- "properties": {"task": {"type": "string"}}- }))- .with_resumable_execution()- .with_review_approval_policy(- tinyagents_orchestration::subagent::ReviewApprovalPolicy::WorkerOutput,- )- .with_metadata(- PermissionLevel::Execute,- ToolScope::All,- ToolCategory::System,- ToolTimeout::Unbounded,- )- .with_result_projection(move |result| match result {- Ok(outcome) if outcome.pending.is_some() => {- let pending = outcome.pending.expect("checked above");- ToolResult::json(serde_json::json!({- "status": "pending",- "state": outcome.state,- "pending": {- "interrupt_id": pending.interrupt_id,- "node": pending.node,- "payload": pending.payload,- "thread_id": pending.thread_id,- }- }))- }- Ok(outcome) if outcome.state.cancelled => {- ToolResult::error(format!("delegate_graph cancelled for '{result_agent_id}'."))- }- Ok(outcome) => {- let state = outcome.state;- let final_output = state- .final_output- .unwrap_or_else(|| "(delegation produced no final output)".to_string());- let note = if state.revisions > 0 {- " (after revision)"- } else {- ""- };- ToolResult::success(format!(- "[Delegated to {result_agent_id}{note}, {} review pass(es)]\n{final_output}",- state.reviews.len()- ))- }- Err(error) => ToolResult::error(format!(- "delegate_graph failed for '{result_agent_id}': {error}"- )),- });-- tool.execute(- &(),- tinyagents_harness::CallId::new(format!("delegation-{thread_id}")),- serde_json::json!({- "agent_id": invocation_agent_id,- "task": invocation_task_prompt,- "max_revisions": max_revisions- }),- ToolCallOptions::default(),- &live_parent,- )- .await- .map_err(|error| format!("delegate_graph failed: {error}"))-}--/// Per-stage prompt builder: each stage sees the task plus the accumulated state-/// (the plan for `execute`, the latest result for `review`, and the latest-/// reviewer feedback when re-executing after a revision request).-fn build_stage_prompt(stage: DelegationStage, task: &str, state: &DelegationState) -> String {- match stage {- DelegationStage::Plan => format!(- "Produce a short, concrete, numbered plan to accomplish the task below. \- Reply with the plan only.\n\n[Task]\n{task}"- ),- DelegationStage::Execute => {- let plan = state.plan.as_deref().unwrap_or("(no plan produced)");- let feedback = state- .reviews- .last()- .map(|r| format!("\n\n[Reviewer feedback to address]\n{r}"))- .unwrap_or_default();- format!(- "Carry out the plan below for the task and return the completed result.\n\n\- [Task]\n{task}\n\n[Plan]\n{plan}{feedback}"- )- }- DelegationStage::Review => {- let result = state.last_result().unwrap_or("(no execution produced)");- format!(- "Review the result below against the task. If it fully and correctly \- accomplishes the task, reply with `APPROVE` on the first line. Otherwise \- reply with `REVISE` on the first line followed by specific, actionable \- feedback.\n\n[Task]\n{task}\n\n[Result]\n{result}"- )- }- }-}--/// A review stage approves when its first line begins with `APPROVE`.-fn review_approves(output: &str) -> bool {- output- .lines()- .next()- .map(|l| l.trim().to_ascii_uppercase())- .map(|l| l.starts_with("APPROVE"))- .unwrap_or(false)-}--/// Default sub-agent options for a delegation stage — a fresh UUID task id per-/// call (so retries/revisions don't collide), everything else inherited.-fn delegation_subagent_options(- workspace_descriptor: Option<WorkspaceDescriptor>,- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,-) -> SubagentRunOptions {- SubagentRunOptions {- skill_filter_override: None,- context: None,- model_override: None,- task_id: None,- thread_id: run_context.thread_id.clone(),- run_context,- worker_thread_id: None,- initial_history: None,- checkpoint_dir: None,- workspace_descriptor,- run_queue: None,- message_run_queue: None,- }-}--/// Open the delegation graph's durable checkpointer: the acting agent's scope-/// on the storage backend ([`crate::storage::local::open`]).-pub fn open_delegation_checkpointer(- config: &Config,-) -> Result<Arc<dyn Checkpointer<DelegationState>>, String> {- let scoped = crate::storage::local::open("delegation", &config.workspace_dir)- .and_then(|opened| opened.scoped())- .map_err(|e| format!("open the storage for graph checkpoints: {e:#}"))?;- Ok(Arc::new(- tinyagents_graph::checkpoint::DriverCheckpointer::<DelegationState>::with_namespace(- Arc::clone(scoped.documents()),- "delegation",- ),- ))-}--#[cfg(test)]-#[path = "delegation_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/orchestration/delegation_tests.rs b/crates/openhuman-core/src/agent/orchestration/delegation_tests.rsdeleted file mode 100644index e489395c2a..0000000000--- a/crates/openhuman-core/src/agent/orchestration/delegation_tests.rs+++ /dev/null@@ -1,34 +0,0 @@-use super::*;--fn root() -> RunContext<OpenHumanRunContext> {- OpenHumanRunContext::new().into_tinyagents(RunConfig::new("delegation-root"))-}--#[test]-fn stage_host_data_carries_the_stage_runs_linked_token() {- let graph_parent = root();- let (stage_run, stage_context) = stage_run_contexts(&graph_parent, None).expect("stage");-- assert_eq!(stage_run.depth(), 1);- // The graph cancelling reaches the stage's host carrier through the parent.- graph_parent.cancellation.cancel();- assert!(stage_run.cancellation.is_cancelled());- assert!(stage_context.cancellation.is_cancelled());- assert!(stage_run.data.cancellation.is_cancelled());-}--#[test]-fn cancelling_a_stage_spares_the_graph_and_its_siblings() {- let graph_parent = root();- let (stage_a, ctx_a) = stage_run_contexts(&graph_parent, None).expect("stage a");- let (stage_b, ctx_b) = stage_run_contexts(&graph_parent, None).expect("stage b");-- stage_a.cancellation.cancel();- assert!(ctx_a.cancellation.is_cancelled());- assert!(stage_a.data.cancellation.is_cancelled());- assert!(!stage_b.data.cancellation.is_cancelled());- assert!(!graph_parent.cancellation.is_cancelled());- assert!(!graph_parent.data.cancellation.is_cancelled());- assert!(!stage_b.cancellation.is_cancelled());- assert!(!ctx_b.cancellation.is_cancelled());-}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rsdeleted file mode 100644index a41def3529..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph.rs+++ /dev/null@@ -1,274 +0,0 @@-//! Tool: `delegate_graph` — run a multi-stage, durable sub-agent delegation.-//!-//! Where `spawn_subagent` hands a sub-task to a single sub-agent turn,-//! `delegate_graph` runs TinyAgents' resumable plan→execute⇄review→finalize-//! tool. OpenHuman supplies the chosen agent, stage prompts, worker execution,-//! checkpoints, and product result projection through-//! [`run_subagent_delegation_with_parent_context`](crate::agent::orchestration::delegation::run_subagent_delegation_with_parent_context).-//! Each stage is also-//! registered with the shared subagent Jobs service.-//!-//! Use it for non-trivial sub-tasks that benefit from a self-review/revision-//! loop; use `spawn_subagent` for a single focused hand-off.--use crate::agent::orchestration::delegation::run_subagent_delegation_with_parent_context;-use crate::agent_registry::host_definition::AgentDefinitionRegistry;-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};--/// Default reviewer-requested revision budget when the caller omits it.-const DEFAULT_MAX_REVISIONS: usize = 2;-/// Hard ceiling so a caller can't request an unbounded execute⇄review loop.-const MAX_MAX_REVISIONS: usize = 5;--/// Runs the durable multi-stage delegation graph for a chosen sub-agent.-pub struct DelegateGraphTool;--/// Typed harness dispatch for the durable graph delegation tool. This must be-/// registered before the synthesized `delegate_*` family: `delegate_graph`-/// has its own plan→execute→review semantics and is not an archetype target.-pub(crate) struct DelegateGraphDispatch {- tool: Arc<dyn Tool>,-}--impl DelegateGraphDispatch {- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {- Self { tool }- }-}--#[async_trait]-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for DelegateGraphDispatch-{- fn tool(&self) -> Arc<dyn Tool> {- self.tool.clone()- }-- async fn execute(- &self,- _state: &(),- _call_id: tinyagents_harness::CallId,- arguments: serde_json::Value,- _options: ToolCallOptions,- parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- ) -> anyhow::Result<ToolResult> {- let context = ToolExecutionContext::from_run_context(parent, _call_id.clone());- let graph_parent = parent- .child(- tinyagents_harness::context::RunConfig::new(format!(- "delegation-graph-{}",- uuid::Uuid::new_v4()- )),- parent.data.child(),- )- .map_err(|error| anyhow::anyhow!(error.to_string()))?;- DelegateGraphTool::new()- .execute_with_live_parent_context(- arguments,- Some(&context),- parent.data.child(),- Some(Arc::new(graph_parent)),- )- .await- }-}--impl Default for DelegateGraphTool {- fn default() -> Self {- Self::new()- }-}--impl DelegateGraphTool {- pub fn new() -> Self {- Self- }-}--#[cfg(test)]-#[path = "delegate_graph_tests.rs"]-mod tests;--#[async_trait]-impl Tool for DelegateGraphTool {- fn name(&self) -> &str {- // Distinct from the config-driven `delegate` tool (`DelegateTool`, added- // when `[agents]` are configured) so the two don't collide in the- // first-match tool registry — a shared `delegate` name made whichever- // registered first shadow the other. This is the graph delegation path.- "delegate_graph"- }-- fn description(&self) -> &str {- "Delegate a non-trivial sub-task to a specialised sub-agent that PLANS, \- EXECUTES, then REVIEWS and revises its own work before returning a final \- result (a durable plan→execute→review→finalize loop). Prefer this over \- `spawn_subagent` when the sub-task benefits from a self-review/revision \- pass. Provide `agent_id` and a complete, self-contained `task` (the \- sub-agent has no memory of this conversation)."- }-- 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, researcher, summarizer)."- })- } else {- json!({- "type": "string",- "enum": agent_ids,- "description": "Sub-agent id from the registry."- })- };-- json!({- "type": "object",- "required": ["agent_id", "task"],- "properties": {- "agent_id": agent_id_schema,- "task": {- "type": "string",- "description": "Complete, self-contained description of the task. Include all context the sub-agent needs — it cannot see this conversation."- },- "max_revisions": {- "type": "integer",- "minimum": 0,- "maximum": MAX_MAX_REVISIONS,- "description": "Maximum reviewer-requested revisions before finalizing (default 2)."- }- }- })- }-- 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> {- 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);- self.execute_with_parent_context(args, tool_context, run_context)- .await- }-}--impl DelegateGraphTool {- /// Execute the concrete durable graph with an explicit child carrier.- 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- }-- /// The typed harness creates an owned graph child before invoking this- /// path. The graph's static stage callback then derives direct children- /// from it without dropping lineage.- 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<Arc<RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>>,- ) -> anyhow::Result<ToolResult> {- let Some(live_parent) = live_parent else {- return Ok(ToolResult::error(- "delegate_graph requires a live harness run context.",- ));- };- let agent_id = match args.get("agent_id").and_then(|v| v.as_str()) {- Some(s) if !s.trim().is_empty() => s.trim().to_string(),- _ => return Ok(ToolResult::error("delegate_graph: `agent_id` is required.")),- };- let task = match args.get("task").and_then(|v| v.as_str()) {- Some(s) if !s.trim().is_empty() => s.to_string(),- _ => return Ok(ToolResult::error("delegate_graph: `task` is required.")),- };- let max_revisions = args- .get("max_revisions")- .and_then(|v| v.as_u64())- .map(|n| (n as usize).min(MAX_MAX_REVISIONS))- .unwrap_or(DEFAULT_MAX_REVISIONS);-- // The live parent is the authority for this invocation. Looking only- // at `CoreContext::current()` can select another concurrent tenant's- // catalogue (or none at all) when callers execute the typed tool with- // an explicit parent carrier. Keep the process registry as the legacy- // fallback for contexts that do not carry an agent-local catalogue.- let registry =- match AgentDefinitionRegistry::for_core_context(run_context.dispatch_ctx().into_core())- {- Some(reg) => reg,- None => {- return Ok(ToolResult::error(- "delegate_graph: agent definition registry not initialized.",- ));- }- };- let definition = match registry.get(&agent_id) {- Some(def) => def.clone(),- None => {- return Ok(ToolResult::error(format!(- "delegate_graph: agent definition '{agent_id}' not found in registry."- )));- }- };-- let config =- match crate::config::ops::load_current_or_init(&run_context.dispatch_ctx()).await {- Ok(cfg) => Arc::new(cfg),- Err(e) => {- return Ok(ToolResult::error(format!(- "delegate_graph: failed to load config: {e}"- )));- }- };-- match run_subagent_delegation_with_parent_context(- config,- definition,- task,- max_revisions,- tool_context- .and_then(|ctx| ctx.workspace().cloned())- .or_else(|| run_context.workspace.clone()),- live_parent,- )- .await- {- Ok(result) => Ok(result),- Err(e) => Ok(ToolResult::error(format!(- "delegate_graph failed for '{agent_id}': {e}"- ))),- }- }-}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph_tests.rsdeleted file mode 100644index f9bcc33272..0000000000--- a/crates/openhuman-core/src/agent/orchestration/tools/delegate_graph_tests.rs+++ /dev/null@@ -1,24 +0,0 @@-use super::*;--#[tokio::test]-async fn validation_errors_name_the_delegate_graph_tool() {- let tool: Arc<dyn Tool> = Arc::new(DelegateGraphTool::new());- let dispatch = DelegateGraphDispatch::new(tool);- let parent = crate::agent::tinyagents::host::OpenHumanRunContext::new().into_tinyagents(- tinyagents_harness::context::RunConfig::new("delegate-graph-test"),- );-- let result = dispatch- .execute(- &(),- tinyagents_harness::CallId::new("delegate-graph-test-call"),- serde_json::json!({"task": "test validation"}),- ToolCallOptions::default(),- &parent,- )- .await- .expect("validation returns a tool result");-- assert!(result.is_error);- assert_eq!(result.output(), "delegate_graph: `agent_id` is required.");-}diff --git a/crates/openhuman-core/src/agent/tinyagents/topology_collision_tests.rs b/crates/openhuman-core/src/agent/tinyagents/topology_collision_tests.rsdeleted file mode 100644index d0f4b0aa5e..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/topology_collision_tests.rs+++ /dev/null@@ -1,41 +0,0 @@-#[test]-fn all_topologies_names_do_not_collide_with_production_tools() {- let tmp = tempfile::tempdir().expect("create tempdir");- let config = std::sync::Arc::new(crate::config::Config::default());- let security = std::sync::Arc::new(crate::security::SecurityPolicy::default());- let audit = std::sync::Arc::new(- crate::security::AuditLogger::new(- crate::config::AuditConfig {- enabled: false,- log_path: "audit.log".into(),- max_size_mb: 10,- },- tmp.path().to_path_buf(),- )- .expect("create audit logger"),- );- let browser = crate::config::BrowserConfig::default();- let http = crate::config::HttpRequestConfig::default();- let agents = std::collections::HashMap::new();-- let tools = crate::tools::ops::all_tools(- config.clone(),- &security,- audit,- &browser,- &http,- tmp.path(),- &agents,- &config,- );- let tool_names: std::collections::HashSet<_> = tools.iter().map(|t| t.name()).collect();-- let reports = crate::agent::tinyagents::tool_registration::host_graph_topologies();- for report in &reports {- assert!(- !tool_names.contains(report.name),- "graph name '{}' collides with registered tool of the same name",- report.name- );- }-}diff --git a/crates/openhuman-core/src/agent_runs/command_center/mod.rs b/crates/openhuman-core/src/agent_runs/command_center/mod.rsdeleted file mode 100644index 3320031fcf..0000000000--- a/crates/openhuman-core/src/agent_runs/command_center/mod.rs+++ /dev/null@@ -1,17 +0,0 @@-//! Background agent command center (issue #3373).-//!-//! A read-only product surface over the durable run ledger: it lists recent-//! background agent runs grouped by a normalized status model (needs-input /-//! working / completed / failed / stopped) and lets a reviewer stop, retry,-//! continue or follow up on a run. The projection, bucket mapping and control-//! transitions live upstream in-//! `tinyagents_session::run_ledger::command_center`; this module is the-//! `openhuman.agent_work_*` RPC surface and the agent-registry display-name-//! lookup.--mod schemas;--pub use schemas::{- all_controller_schemas as all_command_center_controller_schemas,- all_registered_controllers as all_command_center_registered_controllers,-};diff --git a/crates/openhuman-core/src/agent_runs/command_center/schemas.rs b/crates/openhuman-core/src/agent_runs/command_center/schemas.rsdeleted file mode 100644index a5c207d9eb..0000000000--- a/crates/openhuman-core/src/agent_runs/command_center/schemas.rs+++ /dev/null@@ -1,235 +0,0 @@-//! Controller schema + JSON-RPC dispatcher for the background agent command-//! center. Exposes `openhuman.agent_work_list` (read-only) over the durable-//! run ledger. Handlers delegate to [`super::ops`]; no business logic here.--use crate::core::runtime::DispatchCtx;-use serde_json::{Map, Value};--use tinyagents_session::run_ledger::command_center::ControlVerb;--use crate::agent_registry::host_definition::AgentDefinitionRegistry;-use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::Outcome;-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};--/// Controller schemas exposed by the command center.-pub fn all_controller_schemas() -> Vec<ControllerSchema> {- vec![- schema_for("agent_work_list"),- schema_for("agent_work_control"),- ]-}--/// Registered controllers (schema + handler) for the command center.-pub fn all_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: schema_for("agent_work_list"),- handler: handle_agent_work_list,- },- RegisteredController {- schema: schema_for("agent_work_control"),- handler: handle_agent_work_control,- },- ]-}--fn schema_for(function: &str) -> ControllerSchema {- match function {- "agent_work_list" => ControllerSchema {- namespace: "agent_work",- function: "list",- description: "List recent background agent runs grouped by command-center status \- bucket (needs_input / working / completed / failed / stopped).",- inputs: vec![optional_u64(- "limit",- "Max recent runs to scan (default 200, max 500).",- )],- outputs: vec![json_output(- "result",- "CommandCenterView with five status groups and a total count.",- )],- },- "agent_work_control" => ControllerSchema {- namespace: "agent_work",- function: "control",- description: "Apply a control verb to one background agent run, transitioning its \- durable ledger status and recording a run event. Actions: stop \- (cancel a live run), retry (re-queue a failed/stopped run), continue \- (answer an awaiting-input run), follow_up (record a new instruction). \- `message` is required for continue and follow_up.",- inputs: vec![- required_str("runId", "Ledger run id from a command-center row."),- required_str(- "action",- "Control verb: stop | retry | continue | follow_up.",- ),- optional_str(- "message",- "User message — required for continue and follow_up.",- ),- optional_str("reason", "Optional reason recorded when stopping."),- ],- outputs: vec![json_output(- "row",- "The updated AgentWorkRow after the transition.",- )],- },- _ => ControllerSchema {- namespace: "agent_work",- function: "unknown",- description: "unknown command center function",- inputs: vec![],- outputs: vec![],- },- }-}--fn handle_agent_work_list(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let cid = new_correlation_id();- log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.entry");- let config = ctx.load_config()- .await- .inspect_err(|err| {- log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.config_failed err={err}");- })?;- let limit = params- .get("limit")- .and_then(|v| v.as_u64())- .map(|v| v as u32);- let view = crate::storage::sessions::with_ledger_async(&config.workspace_dir, |ledger| async move {- ledger.list_agent_work(limit, &resolve_display_name).await- })- .await- .map_err(|e| {- let s = e.to_string();- log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] list.error err={s}");- s- })?;- to_json(view)- })-}--fn handle_agent_work_control(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let cid = new_correlation_id();- log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.entry");- let config = ctx.load_config()- .await- .inspect_err(|err| {- log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.config_failed err={err}");- })?;- let run_id = require_str(¶ms, "runId")?;- let action = require_str(¶ms, "action")?;- let verb = ControlVerb::parse(&action).ok_or_else(|| {- let s = format!("unknown control action: {action}");- log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.unknown_action action={action}");- s- })?;- let message = opt_str(¶ms, "message");- let reason = opt_str(¶ms, "reason");- log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.parsed run_id={run_id} verb={}", verb.as_str());- let row = crate::storage::sessions::with_ledger_async(&config.workspace_dir, |ledger| {- let run_id = run_id.clone();- let message = message.clone();- let reason = reason.clone();- async move {- ledger- .apply_control(- &run_id,- verb,- message.as_deref(),- reason.as_deref(),- &resolve_display_name,- )- .await- }- })- .await- .map_err(|e| {- let s = e.to_string();- log::warn!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.error err={s}");- s- })?;- log::debug!(target: "command_center_rpc", "[command_center_rpc][{cid}] control.success run_id={run_id} status={}", row.status);- to_json(serde_json::json!({ "row": row }))- })-}--/// Resolve an agent id to its registry display name, if the registry is up and-/// the agent is known. Returns `None` otherwise (e.g. custom/removed agents).-fn resolve_display_name(agent_id: &str) -> Option<String> {- AgentDefinitionRegistry::current().and_then(|registry| {- registry- .get(agent_id)- .map(|definition| definition.display_name().to_string())- })-}--fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {- Outcome::new(value, vec![]).into_cli_compatible_json()-}--fn new_correlation_id() -> String {- uuid::Uuid::new_v4().simple().to_string()[..8].to_string()-}--fn optional_u64(name: &'static str, comment: &'static str) -> FieldSchema {- FieldSchema {- name,- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment,- required: false,- }-}--fn required_str(name: &'static str, comment: &'static str) -> FieldSchema {- FieldSchema {- name,- ty: TypeSchema::String,- comment,- required: true,- }-}--fn optional_str(name: &'static str, comment: &'static str) -> FieldSchema {- FieldSchema {- name,- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment,- required: false,- }-}--/// Extract a required non-empty string param, or an RPC-facing error.-fn require_str(params: &Map<String, Value>, key: &str) -> Result<String, String> {- params- .get(key)- .and_then(Value::as_str)- .filter(|s| !s.trim().is_empty())- .map(str::to_string)- .ok_or_else(|| format!("missing required param: {key}"))-}--/// Extract an optional non-empty string param.-fn opt_str(params: &Map<String, Value>, key: &str) -> Option<String> {- params- .get(key)- .and_then(Value::as_str)- .filter(|s| !s.trim().is_empty())- .map(str::to_string)-}--fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {- FieldSchema {- name,- ty: TypeSchema::Json,- comment,- required: true,- }-}--#[cfg(test)]-#[path = "schemas_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent_runs/command_center/schemas_tests.rs b/crates/openhuman-core/src/agent_runs/command_center/schemas_tests.rsdeleted file mode 100644index d126a26f92..0000000000--- a/crates/openhuman-core/src/agent_runs/command_center/schemas_tests.rs+++ /dev/null@@ -1,126 +0,0 @@-use super::*;-use crate::core::runtime::DispatchCtx;--#[test]-fn registered_controllers_match_schemas() {- let schemas = all_controller_schemas();- let registered = all_registered_controllers();- assert_eq!(schemas.len(), registered.len());- assert_eq!(schemas.len(), 2);- assert!(schemas.iter().all(|s| s.namespace == "agent_work"));- assert_eq!(schema_for("agent_work_list").function, "list");- assert_eq!(schema_for("agent_work_control").function, "control");-}--#[test]-fn unknown_agent_has_no_display_name() {- assert_eq!(resolve_display_name("__definitely_not_an_agent__"), None);-}--#[test]-fn an_unknown_function_gets_the_unknown_schema() {- let s = schema_for("no_such_function");- assert_eq!(s.namespace, "agent_work");- assert_eq!(s.function, "unknown");-}--#[test]-fn require_and_optional_strings_ignore_blank_values() {- let mut params = Map::new();- params.insert("present".into(), Value::String("x".into()));- params.insert("blank".into(), Value::String(" ".into()));- assert_eq!(require_str(¶ms, "present").unwrap(), "x");- assert_eq!(- require_str(¶ms, "blank").unwrap_err(),- "missing required param: blank"- );- assert_eq!(- require_str(¶ms, "absent").unwrap_err(),- "missing required param: absent"- );- assert_eq!(opt_str(¶ms, "present").as_deref(), Some("x"));- assert_eq!(opt_str(¶ms, "blank"), None);- assert_eq!(opt_str(¶ms, "absent"), None);-}--async fn with_scratch_workspace<F, Fut>(handler: F) -> Result<Value, String>-where- F: FnOnce() -> Fut,- Fut: std::future::Future<Output = Result<Value, String>>,-{- let tmp = tempfile::tempdir().expect("tempdir");- let _env = crate::config::test_env::EnvVarGuard::workspace_async(tmp.path()).await;- handler().await-}--fn params(value: Value) -> Map<String, Value> {- value.as_object().cloned().unwrap_or_default()-}--#[tokio::test]-async fn listing_work_on_an_empty_ledger_answers() {- let v = with_scratch_workspace(|| {- handle_agent_work_list(- DispatchCtx::process_default(),- params(serde_json::json!({ "limit": 5 })),- )- })- .await- .expect("an empty ledger lists as an empty view");- assert_eq!(v["total"], 0, "{v}");- assert!(- v["groups"]- .as_array()- .unwrap()- .iter()- .all(|g| g["rows"] == serde_json::json!([])),- "{v}"- );-}--#[tokio::test]-async fn control_requires_a_run_id_and_action() {- let err = with_scratch_workspace(|| {- handle_agent_work_control(DispatchCtx::process_default(), Map::new())- })- .await- .unwrap_err();- assert_eq!(err, "missing required param: runId");- let err = with_scratch_workspace(|| {- handle_agent_work_control(- DispatchCtx::process_default(),- params(serde_json::json!({ "runId": "r1" })),- )- })- .await- .unwrap_err();- assert_eq!(err, "missing required param: action");-}--#[tokio::test]-async fn control_refuses_an_unknown_action() {- let err = with_scratch_workspace(|| {- handle_agent_work_control(- DispatchCtx::process_default(),- params(serde_json::json!({ "runId": "r1", "action": "explode" })),- )- })- .await- .unwrap_err();- assert_eq!(err, "unknown control action: explode");-}--#[tokio::test]-async fn control_of_an_unknown_run_is_an_error_not_a_panic() {- let err = with_scratch_workspace(|| {- handle_agent_work_control(- DispatchCtx::process_default(),- params(- serde_json::json!({ "runId": "no-such-run", "action": "stop", "reason": "test" }),- ),- )- })- .await- .unwrap_err();- assert!(!err.is_empty());-}diff --git a/crates/openhuman-core/src/tools/delegate.rs b/crates/openhuman-core/src/tools/delegate.rsdeleted file mode 100644index 1336278433..0000000000--- a/crates/openhuman-core/src/tools/delegate.rs+++ /dev/null@@ -1,332 +0,0 @@-use crate::config::DelegateAgentConfig;-use crate::inference::provider::factory::make_openhuman_backend_model_for_options;-use crate::inference::provider::{ProviderRuntimeOptions, INFERENCE_BACKEND_ID};-use crate::security::policy::ToolOperation;-use crate::security::SecurityPolicy;-use crate::tools::timeout::tool_execution_timeout_secs;-use async_trait::async_trait;-use serde_json::json;-use std::collections::HashMap;-use std::sync::Arc;-use std::time::Duration;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::tool::ToolDispatch;-use tinyinference_llm::message::Message;-use tinyinference_llm::model::ModelRequest;-use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};--/// Tool that delegates a subtask to a named agent with a different-/// provider/model configuration. Enables multi-agent workflows where-/// a primary agent can hand off specialized work (research, coding,-/// summarization) to purpose-built sub-agents.-pub struct DelegateTool {- agents: Arc<HashMap<String, DelegateAgentConfig>>,- security: Arc<SecurityPolicy>,- /// Provider runtime options inherited from root config.- provider_runtime_options: ProviderRuntimeOptions,- /// Depth at which this tool instance lives in the delegation chain.- depth: u32,-}--/// Host adapter that places the config-defined one-shot executor behind the-/// shared driver lifecycle while retaining the configured Tool instance.-pub(crate) struct DelegateToolDispatch {- tool: Arc<dyn Tool>,-}--impl DelegateToolDispatch {- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {- Self { tool }- }-}--#[async_trait]-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>- for DelegateToolDispatch-{- 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 agent_id = arguments- .get("agent")- .and_then(serde_json::Value::as_str)- .map(str::trim)- .filter(|agent| !agent.is_empty())- .unwrap_or("delegate")- .to_owned();- crate::agent::subagent_host::run_configured_delegate_via_driver_tool(- parent,- self.tool.clone(),- arguments,- agent_id,- )- .await- .map_err(|error| anyhow::anyhow!("delegate: {error}"))- }-}--impl DelegateTool {- pub fn new(- agents: HashMap<String, DelegateAgentConfig>,- security: Arc<SecurityPolicy>,- ) -> Self {- Self::new_with_options(agents, security, ProviderRuntimeOptions::default())- }-- pub fn new_with_options(- agents: HashMap<String, DelegateAgentConfig>,- security: Arc<SecurityPolicy>,- provider_runtime_options: ProviderRuntimeOptions,- ) -> Self {- Self {- agents: Arc::new(agents),- security,- provider_runtime_options,- depth: 0,- }- }-- /// Create a DelegateTool for a sub-agent (with incremented depth).- /// When sub-agents eventually get their own tool registry, construct- /// their DelegateTool via this method with `depth: parent.depth + 1`.- pub fn with_depth(- agents: HashMap<String, DelegateAgentConfig>,- security: Arc<SecurityPolicy>,- depth: u32,- ) -> Self {- Self::with_depth_and_options(agents, security, depth, ProviderRuntimeOptions::default())- }-- pub fn with_depth_and_options(- agents: HashMap<String, DelegateAgentConfig>,- security: Arc<SecurityPolicy>,- depth: u32,- provider_runtime_options: ProviderRuntimeOptions,- ) -> Self {- Self {- agents: Arc::new(agents),- security,- provider_runtime_options,- depth,- }- }-}--#[async_trait]-impl Tool for DelegateTool {- fn name(&self) -> &str {- "delegate"- }-- fn description(&self) -> &str {- "Delegate a subtask to a specialized agent. Use when: a task benefits from a different model \- (e.g. fast summarization, deep reasoning, code generation). The sub-agent runs a single \- prompt and returns its response."- }-- fn parameters_schema(&self) -> serde_json::Value {- let agent_names: Vec<&str> = self.agents.keys().map(|s: &String| s.as_str()).collect();- json!({- "type": "object",- "additionalProperties": false,- "properties": {- "agent": {- "type": "string",- "minLength": 1,- "description": format!(- "Name of the agent to delegate to. Available: {}",- if agent_names.is_empty() {- "(none configured)".to_string()- } else {- agent_names.join(", ")- }- )- },- "prompt": {- "type": "string",- "minLength": 1,- "description": "The task/prompt to send to the sub-agent"- },- "context": {- "type": "string",- "description": "Optional context to prepend (e.g. relevant code, prior findings)"- }- },- "required": ["agent", "prompt"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_inner(args, None).await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- tool_context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_inner(args, tool_context).await- }-}--impl DelegateTool {- async fn execute_inner(- &self,- args: serde_json::Value,- tool_context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let agent_name = args- .get("agent")- .and_then(|v| v.as_str())- .map(str::trim)- .ok_or_else(|| anyhow::anyhow!("Missing 'agent' parameter"))?;-- if agent_name.is_empty() {- return Ok(ToolResult::error("'agent' parameter must not be empty"));- }-- let prompt = args- .get("prompt")- .and_then(|v| v.as_str())- .map(str::trim)- .ok_or_else(|| anyhow::anyhow!("Missing 'prompt' parameter"))?;-- if prompt.is_empty() {- return Ok(ToolResult::error("'prompt' parameter must not be empty"));- }-- let context = args- .get("context")- .and_then(|v| v.as_str())- .map(str::trim)- .unwrap_or("");-- // Look up agent config- let agent_config = match self.agents.get(agent_name) {- Some(cfg) => cfg,- None => {- let available: Vec<&str> =- self.agents.keys().map(|s: &String| s.as_str()).collect();- return Ok(ToolResult::error(format!(- "Unknown agent '{agent_name}'. Available agents: {}",- if available.is_empty() {- "(none configured)".to_string()- } else {- available.join(", ")- }- )));- }- };-- // Check recursion depth (immutable — set at construction, incremented for sub-agents)- if self.depth >= agent_config.max_depth {- return Ok(ToolResult::error(format!(- "Delegation depth limit reached ({depth}/{max}). \- Cannot delegate further to prevent infinite loops.",- depth = self.depth,- max = agent_config.max_depth- )));- }-- if let Err(error) = self- .security- .enforce_tool_operation(ToolOperation::Act, "delegate")- {- return Ok(ToolResult::error(error));- }-- // `metadata` below is diagnostic only; the managed model owns the- // actual backend wire extension so configured delegates cannot lose- // their parent's thread between typed dispatch and provider invoke.- let thread_id = tool_context.and_then(ToolRunContext::thread_id);- let model = match make_openhuman_backend_model_for_options(- &self.provider_runtime_options,- &agent_config.model,- thread_id,- ) {- Ok((model, _resolved)) => model,- Err(error) => {- return Ok(ToolResult::error(format!(- "Agent '{agent_name}' failed: {error}"- )));- }- };-- // Build the message- let full_prompt = if context.is_empty() {- prompt.to_string()- } else {- format!("[Context]\n{context}\n\n[Task]\n{prompt}")- };-- let temperature = agent_config.temperature.unwrap_or(0.7);-- let delegate_timeout_secs = tool_execution_timeout_secs();- // Wrap the provider call in a timeout to prevent indefinite blocking- let mut request = ModelRequest::new(- agent_config- .system_prompt- .as_deref()- .map(Message::system)- .into_iter()- .chain(std::iter::once(Message::user(full_prompt)))- .collect(),- )- .with_model(agent_config.model.clone())- .with_temperature(temperature);- request.metadata = json!({- "openhuman": {- "thread_id": tool_context.and_then(ToolRunContext::thread_id),- "workspace_root": tool_context- .and_then(ToolRunContext::workspace)- .map(|workspace| workspace.root.display().to_string()),- }- });-- let result = tokio::time::timeout(- Duration::from_secs(delegate_timeout_secs),- model.invoke(&(), request),- )- .await;-- let result = match result {- Ok(inner) => inner,- Err(_elapsed) => {- return Ok(ToolResult::error(format!(- "Agent '{agent_name}' timed out after {delegate_timeout_secs}s"- )));- }- };-- match result {- Ok(response) => {- let mut rendered = response.text();- if rendered.trim().is_empty() {- rendered = "[Empty response]".to_string();- }-- Ok(ToolResult::success(format!(- "[Agent '{agent_name}' ({}/{})]\n{rendered}",- INFERENCE_BACKEND_ID, agent_config.model- )))- }- Err(e) => Ok(ToolResult::error(format!(- "Agent '{agent_name}' failed: {e}",- ))),- }- }-}--#[cfg(test)]-#[path = "delegate_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/delegate_tests.rs b/crates/openhuman-core/src/tools/delegate_tests.rsdeleted file mode 100644index 6bbf5e9267..0000000000--- a/crates/openhuman-core/src/tools/delegate_tests.rs+++ /dev/null@@ -1,232 +0,0 @@-use super::*;-use crate::security::{AutonomyLevel, SecurityPolicy};--fn test_security() -> Arc<SecurityPolicy> {- Arc::new(SecurityPolicy::default())-}--fn sample_agents() -> HashMap<String, DelegateAgentConfig> {- let mut agents = HashMap::new();- agents.insert(- "researcher".to_string(),- DelegateAgentConfig {- model: "llama3".to_string(),- system_prompt: Some("You are a research assistant.".to_string()),- temperature: Some(0.3),- max_depth: 3,- },- );- agents.insert(- "coder".to_string(),- DelegateAgentConfig {- model: crate::config::DEFAULT_MODEL.to_string(),- system_prompt: None,- temperature: None,- max_depth: 2,- },- );- agents-}--#[test]-fn name_and_schema() {- let tool = DelegateTool::new(sample_agents(), test_security());- assert_eq!(tool.name(), "delegate");- let schema = tool.parameters_schema();- assert!(schema["properties"]["agent"].is_object());- assert!(schema["properties"]["prompt"].is_object());- assert!(schema["properties"]["context"].is_object());- let required = schema["required"].as_array().unwrap();- assert!(required.contains(&json!("agent")));- assert!(required.contains(&json!("prompt")));- assert_eq!(schema["additionalProperties"], json!(false));- assert_eq!(schema["properties"]["agent"]["minLength"], json!(1));- assert_eq!(schema["properties"]["prompt"]["minLength"], json!(1));-}--#[test]-fn description_not_empty() {- let tool = DelegateTool::new(sample_agents(), test_security());- assert!(!tool.description().is_empty());-}--#[test]-fn schema_lists_agent_names() {- let tool = DelegateTool::new(sample_agents(), test_security());- let schema = tool.parameters_schema();- let desc = schema["properties"]["agent"]["description"]- .as_str()- .unwrap();- assert!(desc.contains("researcher") || desc.contains("coder"));-}--#[tokio::test]-async fn missing_required_params_are_rejected() {- let tool = DelegateTool::new(sample_agents(), test_security());- assert!(tool.execute(json!({"prompt": "test"})).await.is_err());- assert!(tool.execute(json!({"agent": "researcher"})).await.is_err());-}--#[tokio::test]-async fn unknown_agent_returns_error() {- let tool = DelegateTool::new(sample_agents(), test_security());- let result = tool- .execute(json!({"agent": "nonexistent", "prompt": "test"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("Unknown agent"));-}--#[tokio::test]-async fn depth_limit_enforced() {- // Global limit, then coder's own max_depth=2 blocking at depth 2.- for (agent, depth) in [("researcher", 3), ("coder", 2)] {- let tool = DelegateTool::with_depth(sample_agents(), test_security(), depth);- let result = tool- .execute(json!({"agent": agent, "prompt": "test"}))- .await- .unwrap();- assert!(result.is_error, "{agent}@{depth}");- assert!(result.output().contains("depth limit"), "{agent}@{depth}");- }-}--#[test]-fn empty_agents_schema() {- let tool = DelegateTool::new(HashMap::new(), test_security());- let schema = tool.parameters_schema();- let desc = schema["properties"]["agent"]["description"]- .as_str()- .unwrap();- assert!(desc.contains("none configured"));-}--#[tokio::test]-async fn blank_agent_or_prompt_rejected() {- let tool = DelegateTool::new(sample_agents(), test_security());- for args in [- json!({"agent": " ", "prompt": "test"}),- json!({"agent": "researcher", "prompt": " \t "}),- ] {- let result = tool.execute(args.clone()).await.unwrap();- assert!(result.is_error, "{args}");- assert!(result.output().contains("must not be empty"), "{args}");- }-}--#[tokio::test]-async fn whitespace_agent_name_trimmed_and_found() {- let tool = DelegateTool::new(sample_agents(), test_security());- // " researcher " with surrounding whitespace — after trim becomes "researcher"- let result = tool- .execute(json!({"agent": " researcher ", "prompt": "test"}))- .await- .unwrap();- // Should find "researcher" after trim — will fail at provider level- // since ollama isn't running, but must NOT get "Unknown agent".- assert!(!result.output().contains("Unknown agent"));-}--#[tokio::test]-async fn delegation_blocked_in_readonly_mode() {- let readonly = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::ReadOnly,- ..SecurityPolicy::default()- });- let tool = DelegateTool::new(sample_agents(), readonly);- let result = tool- .execute(json!({"agent": "researcher", "prompt": "test"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("read-only mode"));-}--#[tokio::test]-async fn delegation_blocked_when_rate_limited() {- let limited = Arc::new(SecurityPolicy {- max_actions_per_hour: 0,- ..SecurityPolicy::default()- });- let tool = DelegateTool::new(sample_agents(), limited);- let result = tool- .execute(json!({"agent": "researcher", "prompt": "test"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("Rate limit exceeded"));-}--#[tokio::test]-async fn delegate_context_is_prepended_to_prompt() {- let mut agents = HashMap::new();- agents.insert(- "tester".to_string(),- DelegateAgentConfig {- model: "test-model".to_string(),- system_prompt: None,- temperature: None,- max_depth: 3,- },- );- let tool = DelegateTool::new(agents, test_security());- let result = tool- .execute(json!({- "agent": "tester",- "prompt": "do something",- "context": "some context data"- }))- .await- .unwrap();-- assert!(result.is_error);- assert!(- result.output().contains("Agent 'tester' failed") || result.output().contains("timed out")- );-}--#[tokio::test]-async fn delegate_empty_context_omits_prefix() {- let mut agents = HashMap::new();- agents.insert(- "tester".to_string(),- DelegateAgentConfig {- model: "test-model".to_string(),- system_prompt: None,- temperature: None,- max_depth: 3,- },- );- let tool = DelegateTool::new(agents, test_security());- let result = tool- .execute(json!({- "agent": "tester",- "prompt": "do something",- "context": ""- }))- .await- .unwrap();-- assert!(result.is_error);- assert!(- result.output().contains("Agent 'tester' failed") || result.output().contains("timed out")- );-}--#[test]-fn delegate_depth_construction() {- let tool = DelegateTool::with_depth(sample_agents(), test_security(), 5);- assert_eq!(tool.depth, 5);-}--#[tokio::test]-async fn delegate_no_agents_configured() {- let tool = DelegateTool::new(HashMap::new(), test_security());- let result = tool- .execute(json!({"agent": "any", "prompt": "test"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.output().contains("none configured"));-}