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
refactor(agent): delegate plan_exit and model resolution to the harness
Steven Enamakele068638c9b0a
diff --git a/crates/openhuman-core/src/agent/registration.rs b/crates/openhuman-core/src/agent/registration.rsindex 4451ddc819..16cf097f9e 100644--- a/crates/openhuman-core/src/agent/registration.rs+++ b/crates/openhuman-core/src/agent/registration.rs@@ -58,19 +58,8 @@ pub(crate) fn dialogue_tools(action_dir: &Path, root_config: &Config) -> Vec<Box// Interactive plan-review gate: parks the live turn on a thread-scoped// plan the user must approve before execution (Codex/Claude plan mode).Box::new(crate::plan_review::RequestPlanReviewTool::new()),- Box::new(tinyagents_harness::tool::PlanExitTool::new(std::sync::Arc::new(- |context| {- let thread_id = context.thread_id()?;- let dispatch_ctx = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(Some(context));- let tenant = dispatch_ctx.tenant().ok()?;- if crate::plan_review::gate::global()- .parked_review_for_thread(&tenant, thread_id)- .is_some()- {- return None;- }- Some(crate::threads::run_mode::handle_for_thread(&dispatch_ctx, thread_id))- },+ Box::new(super::tools::PlanExitTool::new(std::sync::Arc::new(+ super::tools::plan_exit::mode_lookup,))),// Workflow composition: `run_workflow` runs another workflow as a// subagent and (by default) waits on its result like a function call;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/fetched_site.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/fetched_site.rsindex b5fd80e9bd..570891d1c2 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/fetched_site.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/fetched_site.rs@@ -26,18 +26,16 @@ pub(super) fn fetched_site_policy(tool: &str,error: &str,) -> Option<Option<(&'static str, usize)>> {- if tool != WEB_FETCH_TOOL {- return None;- }- let status = tinytools_std::network::web_fetch::status_of(error)?;+ use tinytools::status::FetchedSiteRecovery;+ let failure = tinytools::status::classify_web_fetch_status(tool, error, false)?;tracing::debug!(- status,+ status = failure.status,"[tinyagents::mw] web_fetch site status — not a credential failure");- Some(match status {- 401 | 403 => Some(("site_refused", 2)),- 429 | 500..=599 => Some(("transient", 2)),- _ => None,+ Some(match failure.recovery {+ FetchedSiteRecovery::SiteRefused => Some(("site_refused", 2)),+ FetchedSiteRecovery::Transient => Some(("transient", 2)),+ FetchedSiteRecovery::Ordinary => None,})}@@ -58,9 +56,12 @@ pub(super) fn fetch_host_scope(tool: &str, field: &str, value: &str) -> Option<S/// failure into a terminal inference or transient tool failure. Everything else/// is read whole.pub(super) fn heuristic_text<'a>(tool: &str, failure_text: &'a str) -> &'a str {- if fetched_site_policy(tool, failure_text) == Some(None) {- failure_text.lines().next().unwrap_or(failure_text)- } else {- failure_text+ match tinytools::status::classify_web_fetch_status(tool, failure_text, false) {+ Some(failure)+ if failure.recovery == tinytools::status::FetchedSiteRecovery::Ordinary =>+ {+ failure.headline(failure_text)+ }+ _ => failure_text,}}diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex ae3192428c..8f2c17396c 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -54,7 +54,6 @@ pub(crate) mod tool_registration;mod turn_exec;mod turn_exec_native;mod turn_middleware;-pub(crate) mod turn_model_resolver;mod turn_outcome;mod turn_plan;pub(crate) mod turn_policy;diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rsindex fa2254b99e..4bd90787b2 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs@@ -183,7 +183,7 @@ async fn drive_turn(// Wrap concrete routes before the invocation-local hosted resolver captures them.let turn_models = turn_models.with_budget(run_context.model_budget.as_ref());let hosted_model_resolver = hosted_root.as_ref().map(|_| {- Arc::new(crate::inference::turn_models::TurnModelResolver::from_turn_models(&turn_models))+ Arc::new(turn_models.resolver())as Arc<dyn tinyagents_harness::host::ModelResolver<()>>});// The host security adapter must see the exact same `Arc`-shared instancesdiff --git a/crates/openhuman-core/src/agent/tinyagents/turn_model_resolver.rs b/crates/openhuman-core/src/agent/tinyagents/turn_model_resolver.rsdeleted file mode 100644index e6c090eb05..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/turn_model_resolver.rs+++ /dev/null@@ -1,21 +0,0 @@-//! Bind OpenHuman's prebuilt turn models to the harness-owned resolver.--use std::sync::Arc;--use crate::inference::provider::model::TurnChatModel;-use crate::inference::turn_models::TurnModels;-use tinyagents_harness::host::PrebuiltModelResolver;-use tinyinference_llm::model::ErrorSlotModel;--/// Keep the lead's typed provider error in the turn slot while the owner-/// resolver selects child routes from the same prebuilt bundle.-pub(crate) fn from_turn_models(models: &TurnModels) -> PrebuiltModelResolver<()> {- PrebuiltModelResolver::new(- models.primary.clone(),- models.routes.iter().cloned().collect(),- )- .with_lead_model(Arc::new(ErrorSlotModel::new(- models.primary.clone(),- models.error_slot.clone(),- )) as TurnChatModel)-}diff --git a/crates/openhuman-core/src/agent/tools.rs b/crates/openhuman-core/src/agent/tools.rsindex 9b87033eb6..c0491ee8f4 100644--- a/crates/openhuman-core/src/agent/tools.rs+++ b/crates/openhuman-core/src/agent/tools.rs@@ -26,6 +26,6 @@ mod plan_exit;// them to a disabled-error.mod todo;-pub use plan_exit::{PlanExitTool, PLAN_EXIT_MARKER};+pub use tinyagents_harness::tool::plan_exit::{PlanExitTool, PLAN_EXIT_MARKER};pub use todo::TodoTool;pub(crate) use todo::TodoToolDispatch;diff --git a/crates/openhuman-core/src/agent/tools/plan_exit.rs b/crates/openhuman-core/src/agent/tools/plan_exit.rsindex db94bda655..76864fa216 100644--- a/crates/openhuman-core/src/agent/tools/plan_exit.rs+++ b/crates/openhuman-core/src/agent/tools/plan_exit.rs@@ -1,142 +1,20 @@-//! `plan_exit` — signal the end of a plan-mode pass.-//!-//! Coding-harness baseline tool (issue #1205). When a plan-mode agent-//! is ready to hand off to an execution-mode agent, it calls-//! `plan_exit { plan }`. The tool returns a structured marker AND flips the-//! calling thread's `RunMode` (`threads::run_mode::set_mode`) back-//! to `Build`, so the very next tool exposure/execution check on that thread-//! sees every tool again — the actual gating lives in-//! `PlanModeMiddleware` (wired per-turn in `turn_middleware.rs`), not here;-//! this tool only flips the live handle the middleware reads.-//!-//! Threadless callers (no `ToolRunContext::thread_id`, e.g. a test double or-//! a run with no thread identity) have no per-thread mode to flip — the-//! marker is still returned so the plan text is not lost.--use async_trait::async_trait;-use serde_json::json;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};--/// Stable marker the harness greps for to detect a plan→build hand-off.-pub const PLAN_EXIT_MARKER: &str = "[plan_exit]";--pub struct PlanExitTool;--impl PlanExitTool {- pub fn new() -> Self {- Self- }-}--impl Default for PlanExitTool {- fn default() -> Self {- Self::new()- }-}--#[async_trait]-impl Tool for PlanExitTool {- fn name(&self) -> &str {- "plan_exit"- }-- fn description(&self) -> &str {- "Exit plan mode and hand off the plan to execution. Call this once \- the plan is complete — the wrapped harness will switch to build \- mode (when wired). The `plan` argument is the user-facing plan \- text that downstream agents will execute against."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "plan": {- "type": "string",- "description": "Markdown-formatted plan text to hand off."- }- },- "required": ["plan"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::None- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, None).await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, context).await- }-}--impl PlanExitTool {- async fn execute_in_context(- &self,- args: serde_json::Value,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let plan = args- .get("plan")- .and_then(|v| v.as_str())- .ok_or_else(|| anyhow::anyhow!("Missing 'plan' parameter"))?;- let trimmed = plan.trim();- if trimmed.is_empty() {- return Ok(ToolResult::error("`plan` must not be empty"));- }- if let Some(thread_id) = context.and_then(ToolRunContext::thread_id) {- let dispatch_ctx =- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context);- let tenant = dispatch_ctx.tenant().ok();- // Only flip to Build when there is no plan review still parked on- // this thread. A review resolves (approve/reject/revise) before- // `request_plan_review` returns control to the agent, so by the- // time a well-behaved agent calls `plan_exit` after an approval- // the review is already gone from the gate's parked map — this- // check is a no-op there. It only matters for a mis-timed or- // concurrent `plan_exit` call that races a still-pending review:- // flipping the mode early would unlock every tool for the thread- // before the user has actually approved anything.- if tenant.as_ref().is_some_and(|tenant| {- crate::plan_review::gate::global()- .parked_review_for_thread(tenant, thread_id)- .is_some()- }) {- tracing::warn!(- thread_id = %thread_id,- "[tool][plan_exit] a plan review is still parked on this thread — not flipping to build"- );- } else if tenant.is_none() {- tracing::warn!(- thread_id = %thread_id,- "[tool][plan_exit] tenant context is unavailable — not flipping to build"- );- } else {- tracing::info!(- thread_id = %thread_id,- "[tool][plan_exit] flipping thread run mode to build"- );- crate::threads::run_mode::set_mode(- &crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context),- thread_id,- tinyagents_harness::middleware::RunMode::Build,- );- }- } else {- tracing::debug!("[tool][plan_exit] no thread id on this run context — nothing to flip");- }- Ok(ToolResult::success(format!(- "{PLAN_EXIT_MARKER}\n{trimmed}"- )))- }+//! OpenHuman's tenant-aware lookup for the harness-owned `plan_exit` tool.++use tinyagents_harness::middleware::RunModeHandle;+use tinytools::ToolRunContext;++/// Resolve the live thread mode only when no plan review is still pending.+pub(crate) fn mode_lookup(context: &dyn ToolRunContext) -> Option<RunModeHandle> {+ let thread_id = context.thread_id()?;+ let dispatch_ctx = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(Some(context));+ let tenant = dispatch_ctx.tenant().ok()?;+ if crate::plan_review::gate::global()+ .parked_review_for_thread(&tenant, thread_id)+ .is_some()+ {+ return None;+ }+ Some(crate::threads::run_mode::handle_for_thread(&dispatch_ctx, thread_id))}#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs b/crates/openhuman-core/src/agent/tools/plan_exit_tests.rsindex acd7924161..afcc97cfc3 100644--- a/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs+++ b/crates/openhuman-core/src/agent/tools/plan_exit_tests.rs@@ -39,7 +39,7 @@ async fn plan_exit_does_not_flip_while_a_review_is_parked() {// Let the review register as parked before racing plan_exit against it.tokio::time::sleep(std::time::Duration::from_millis(20)).await;- let tool = PlanExitTool::new();+ let tool = PlanExitTool::new(std::sync::Arc::new(super::super::plan_exit::mode_lookup));let ctx = ThreadContext(thread_id);let result = tool.execute_with_context(@@ -92,7 +92,7 @@ async fn plan_exit_does_not_flip_while_a_review_is_parked() {#[tokio::test]async fn plan_exit_emits_marker() {- let tool = PlanExitTool::new();+ let tool = PlanExitTool::new(std::sync::Arc::new(super::super::plan_exit::mode_lookup));let result = tool.execute(json!({ "plan": "1. Read X\n2. Edit Y" })).await@@ -105,14 +105,14 @@ async fn plan_exit_emits_marker() {#[tokio::test]async fn plan_exit_rejects_empty() {- let tool = PlanExitTool::new();+ let tool = PlanExitTool::new(std::sync::Arc::new(super::super::plan_exit::mode_lookup));let result = tool.execute(json!({ "plan": " " })).await.unwrap();assert!(result.is_error);}#[test]fn plan_exit_metadata() {- let tool = PlanExitTool::new();+ let tool = PlanExitTool::new(std::sync::Arc::new(super::super::plan_exit::mode_lookup));assert_eq!(tool.name(), "plan_exit");assert_eq!(tool.permission_level(), PermissionLevel::None);}diff --git a/crates/openhuman-core/src/inference/turn_models.rs b/crates/openhuman-core/src/inference/turn_models.rsindex dba2c56836..0ae78bab8f 100644--- a/crates/openhuman-core/src/inference/turn_models.rs+++ b/crates/openhuman-core/src/inference/turn_models.rs@@ -3,7 +3,6 @@use std::sync::Arc;-pub(crate) use crate::agent::tinyagents::turn_model_resolver::TurnModelResolver;use crate::core::runtime::DispatchCtx;use crate::inference::provider::model::{BuiltTurnModels, TierRoutes, TurnChatModel};@@ -50,6 +49,17 @@ pub(crate) struct TurnModels {}impl TurnModels {+ /// Bind the already selected turn routes to the harness-owned resolver.+ pub(crate) fn resolver(&self) -> tinyagents_harness::host::PrebuiltModelResolver<()> {+ tinyagents_harness::host::PrebuiltModelResolver::new(+ self.primary.clone(),+ self.routes.iter().cloned().collect::<Vec<_>>(),+ )+ .with_lead_model(Arc::new(tinyinference_llm::model::ErrorSlotModel::new(+ self.primary.clone(),+ self.error_slot.clone(),+ )))+ }/// Whether the primary provider is local / self-hosted.pub(crate) fn is_local(&self) -> bool {self.is_localdiff --git a/crates/openhuman-core/src/inference/turn_models_tests.rs b/crates/openhuman-core/src/inference/turn_models_tests.rsindex 14a7b0addb..04e9a96531 100644--- a/crates/openhuman-core/src/inference/turn_models_tests.rs+++ b/crates/openhuman-core/src/inference/turn_models_tests.rs@@ -6,7 +6,8 @@ use tinyagents_harness::host::{ModelResolveRequest, ModelResolver};use tinyinference_llm::message::ContentBlock;use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};-use super::{TurnModelResolver, TurnModels};+use super::TurnModels;+use tinyagents_harness::host::PrebuiltModelResolver as TurnModelResolver;use crate::agent::tinyagents::TurnModelSource;#[tokio::test]@@ -240,7 +241,7 @@ async fn a_sub_agents_provider_failure_is_not_recorded_as_the_leads() {let models = TurnModelSource::from_model(model).build("m", 0.0, None, None).expect("turn models");- let resolver = TurnModelResolver::from_turn_models(&models);+ let resolver = models.resolver();let child = resolver.resolve(&ModelResolveRequest::new("researcher")).await@@ -265,7 +266,7 @@ async fn a_sub_agents_success_does_not_clear_the_leads_recorded_failure() {let models = TurnModelSource::from_model(model).build("m", 0.0, None, None).expect("turn models");- let resolver = TurnModelResolver::from_turn_models(&models);+ let resolver = models.resolver();let lead = resolver.resolve(&ModelResolveRequest::new("orchestrator").as_team_lead()).await@@ -302,7 +303,7 @@ async fn a_sub_agents_route_failure_leaves_the_leads_slot_untouched() {.build("m", 0.0, None, None).expect("turn models").with_test_route("hint:burst", route.clone());- let resolver = TurnModelResolver::from_turn_models(&models);+ let resolver = models.resolver();let lead = resolver.resolve(&ModelResolveRequest::new("orchestrator").as_team_lead())@@ -348,7 +349,7 @@ async fn a_sub_agents_route_success_does_not_clear_the_leads_slot() {.build("m", 0.0, None, None).expect("turn models").with_test_route("hint:burst", route.clone());- let resolver = TurnModelResolver::from_turn_models(&models);+ let resolver = models.resolver();let lead = resolver.resolve(&ModelResolveRequest::new("orchestrator").as_team_lead())