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
fix(goals): handle tool execution errors gracefully
Steven Enamakel37c62d90caa3
diff --git a/crates/openhuman-core/src/agent/goals/mod.rs b/crates/openhuman-core/src/agent/goals/mod.rsindex e7f311ecb9..d3a36b4e6e 100644--- a/crates/openhuman-core/src/agent/goals/mod.rs+++ b/crates/openhuman-core/src/agent/goals/mod.rs@@ -11,7 +11,7 @@ pub mod store;pub mod tools;pub use tinyagents_graph::goals::{ThreadGoal, ThreadGoalStatus};-pub use tools::{GoalCompleteTool, GoalGetTool, GoalSetTool};+pub use tools::goal_tools;/// Serialize a [`ThreadGoal`] for the `goal` field on `ThreadGoalUpdated` //// `threads.goal_get`. `ThreadGoal` is owned by `tinyagents-graph`, so this isdiff --git a/crates/openhuman-core/src/agent/goals/tools.rs b/crates/openhuman-core/src/agent/goals/tools.rsindex 2a68ce65a3..1c25f58550 100644--- a/crates/openhuman-core/src/agent/goals/tools.rs+++ b/crates/openhuman-core/src/agent/goals/tools.rs@@ -1,270 +1,47 @@-//! OpenHuman `Tool` adapters for tinyagents' model-facing goal controls.+//! Host wiring for tinyagents' model-facing goal controls.//!-//! These let the orchestrator (and any agent that allowlists them) read and-//! drive the current thread's goal. Ownership is **asymmetric** (Codex parity):-//! the model may create/replace the goal (`goal_set`), read it (`goal_get`), and-//! mark it complete (`goal_complete`). Pause / resume / budget-limit are-//! system-driven and have no model tool.-//!-//! The target thread is resolved from the TinyAgents run context — tools never take a `thread_id` arg, so-//! the model can't address another thread's goal. Each tool is sandboxed to a-//! single `workspace_dir` captured at construction.--use std::path::PathBuf;--use async_trait::async_trait;-use serde_json::json;--use super::store;-use super::ThreadGoal;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolRunContext};--/// Render a goal as a compact, model-readable block.-fn render_goal(goal: &ThreadGoal) -> String {- let budget = match (goal.token_budget, goal.budget_remaining()) {- (Some(b), Some(rem)) => format!("{} used / {b} budget ({rem} left)", goal.tokens_used),- _ => format!("{} used / no budget", goal.tokens_used),- };- format!(- "[thread_goal]\nstatus: {}\nobjective: {}\ntokens: {budget}\n[/thread_goal]",- goal.status.as_str(),- goal.objective- )-}--/// The JSON every goal tool answers with: the goal as structured data (the-/// crate's camelCase `ThreadGoal`, or `null` when the thread has none) plus a-/// `text` rendering for transcripts. The frontend reads `goal` off the tool-/// result to draw the goal banner; the model reads either.-fn goal_payload(goal: Option<&ThreadGoal>, note: &str) -> String {- let text = match goal {- Some(goal) if note.is_empty() => render_goal(goal),- Some(goal) => format!("{note}\n{}", render_goal(goal)),- None => note.to_string(),- };- json!({- "goal": goal.map(|goal| serde_json::to_value(goal).unwrap_or(serde_json::Value::Null)),- "text": text,- })- .to_string()-}--/// Resolve the caller thread id or return a uniform tool error.-fn require_thread_id(context: Option<&dyn ToolRunContext>) -> Result<String, ToolResult> {- context- .and_then(ToolRunContext::thread_id)- .map(str::to_owned)- .ok_or_else(|| ToolResult::error("thread goal tools require an active chat thread"))-}--/// `goal_get` — read the current thread goal.-pub struct GoalGetTool {- workspace_dir: PathBuf,-}--impl GoalGetTool {- pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }- }-}--#[async_trait]-impl Tool for GoalGetTool {- fn name(&self) -> &str {- "goal_get"- }-- fn description(&self) -> &str {- "Read this thread's goal — the durable objective you're pursuing across \- turns — with its status (active/paused/budget_limited/complete) and token \- usage. Returns 'no goal set' when the thread has none."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_with_context(args, ToolCallOptions::default(), None)- .await- }-- async fn execute_with_context(- &self,- _args: serde_json::Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id(context) {- Ok(id) => id,- Err(e) => return Ok(e),- };- log::debug!("[thread_goals] tool=goal_get thread_id={thread_id}");- match store::get(&self.workspace_dir, &thread_id).await {- Ok(Some(goal)) => Ok(ToolResult::success(goal_payload(Some(&goal), ""))),- Ok(None) => Ok(ToolResult::success(goal_payload(- None,- "no goal set for this thread",- ))),- Err(e) => Ok(ToolResult::error(e)),- }- }-}--/// `goal_set` — create or replace this thread's goal.-pub struct GoalSetTool {- workspace_dir: PathBuf,-}--impl GoalSetTool {- pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }- }-}--#[async_trait]-impl Tool for GoalSetTool {- fn name(&self) -> &str {- "goal_set"- }-- fn description(&self) -> &str {- "Set (or replace) this thread's goal — the durable objective you should \- keep pursuing across turns until it's complete. Use at the start of a \- non-trivial request, or to refine the objective as it sharpens. Changing \- the objective resets usage counters. Optionally set a token_budget; when \- reached, the goal pauses with a progress summary."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["objective"],- "properties": {- "objective": {- "type": "string",- "description": "The durable objective — what 'done' looks like for this thread."- },- "token_budget": {- "type": "integer",- "minimum": 1,- "description": "Optional token ceiling for the goal. Omit for no limit."- }- }+//! `goal_get` / `goal_set` / `goal_complete` are owned by+//! [`tinyagents_graph::goals`] (`GoalTool`); ownership stays asymmetric+//! (pause / resume / budget-limit are system-driven and have no model tool).+//! This module only supplies what is OpenHuman's: the workspace-backed goal+//! store and the `ThreadGoalUpdated` domain event the UI chip listens to.++use std::path::Path;+use std::sync::Arc;++use tinyagents_graph::goals::{GoalTool, GoalToolKind, GoalUpdateHook};+use tinytools::Tool;++use super::{goal_to_value, store, ThreadGoal};++/// The model-facing goal tools for `workspace_dir`, each publishing+/// `DomainEvent::ThreadGoalUpdated` after a write.+pub fn goal_tools(workspace_dir: &Path) -> Vec<Box<dyn Tool>> {+ let goal_store = store::goals_store(workspace_dir);+ let hook: GoalUpdateHook = Arc::new(publish_goal_updated);+ GoalToolKind::MODEL_FACING+ .into_iter()+ .map(|kind| {+ Box::new(GoalTool::new(kind, goal_store.clone()).with_update_hook(hook.clone()))+ as Box<dyn Tool>})- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- 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,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id(context) {- Ok(id) => id,- Err(e) => return Ok(e),- };- let Some(objective) = args.get("objective").and_then(|v| v.as_str()) else {- return Ok(ToolResult::error("Missing 'objective' parameter"));- };- let token_budget = args.get("token_budget").and_then(|v| v.as_u64());- log::debug!("[thread_goals] tool=goal_set thread_id={thread_id} budget={token_budget:?}");- match store::set(&self.workspace_dir, &thread_id, objective, token_budget).await {- Ok(goal) => {- // Emit the live-update event so the UI chip refreshes immediately.- crate::core::bus::BUS.publish(- crate::core::events::DomainEvent::ThreadGoalUpdated {- thread_id: goal.thread_id.clone(),- goal_id: goal.goal_id.clone(),- status: goal.status.as_str().to_string(),- goal: Some(super::goal_to_value(&goal)),- },- );- Ok(ToolResult::success(goal_payload(Some(&goal), "Goal set.")))- }- Err(e) => Ok(ToolResult::error(e)),- }- }-}--/// `goal_complete` — mark this thread's goal complete (evidence-backed success).-pub struct GoalCompleteTool {- workspace_dir: PathBuf,-}--impl GoalCompleteTool {- pub fn new(workspace_dir: PathBuf) -> Self {- Self { workspace_dir }- }-}--#[async_trait]-impl Tool for GoalCompleteTool {- fn name(&self) -> &str {- "goal_complete"- }-- fn description(&self) -> &str {- "Mark this thread's goal complete. Only call this when concrete evidence \- confirms the objective is satisfied — completing stops autonomous \- continuation."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- 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,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let thread_id = match require_thread_id(context) {- Ok(id) => id,- Err(e) => return Ok(e),- };- log::debug!("[thread_goals] tool=goal_complete thread_id={thread_id}");- match store::complete(&self.workspace_dir, &thread_id).await {- Ok(goal) => {- crate::core::bus::BUS.publish(- crate::core::events::DomainEvent::ThreadGoalUpdated {- thread_id: goal.thread_id.clone(),- goal_id: goal.goal_id.clone(),- status: goal.status.as_str().to_string(),- goal: Some(super::goal_to_value(&goal)),- },- );- Ok(ToolResult::success(goal_payload(- Some(&goal),- "Goal marked complete.",- )))- }- Err(e) => Ok(ToolResult::error(e)),- }- }+ .collect()+}++/// Emit the live-update event so the UI chip refreshes immediately.+fn publish_goal_updated(goal: &ThreadGoal) {+ tracing::debug!(+ thread_id = %goal.thread_id,+ goal_id = %goal.goal_id,+ status = goal.status.as_str(),+ "[thread_goals] tool wrote goal, publishing ThreadGoalUpdated"+ );+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ThreadGoalUpdated {+ thread_id: goal.thread_id.clone(),+ goal_id: goal.goal_id.clone(),+ status: goal.status.as_str().to_string(),+ goal: Some(goal_to_value(goal)),+ });}#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/goals/tools_tests.rs b/crates/openhuman-core/src/agent/goals/tools_tests.rsindex 94383268ea..aaf0d59c3a 100644--- a/crates/openhuman-core/src/agent/goals/tools_tests.rs+++ b/crates/openhuman-core/src/agent/goals/tools_tests.rs@@ -1,4 +1,5 @@use super::*;+use serde_json::json;use tinytools::{ToolCallOptions, ToolRunContext};struct ThreadContext(&'static str);@@ -9,19 +10,22 @@ impl ToolRunContext for ThreadContext {}}-/// Every goal tool answers with `{ goal, text }`: the structured goal the UI-/// reads and the rendered block the transcript shows.-fn payload(res: &tinytools::ToolResult) -> serde_json::Value {- serde_json::from_str(&res.text())- .unwrap_or_else(|e| panic!("goal payload is JSON: {e}: {}", res.text()))+#[test]+fn exposes_only_the_model_facing_goal_tools() {+ let tmp = tempfile::tempdir().unwrap();+ let names: Vec<String> = goal_tools(tmp.path())+ .iter()+ .map(|tool| tool.name().to_string())+ .collect();+ assert_eq!(names, ["goal_get", "goal_set", "goal_complete"]);}#[tokio::test]-async fn set_get_complete_via_tools_in_thread_scope() {+async fn set_persists_to_the_workspace_store_and_answers_goal_and_text() {let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- let context = ThreadContext("thread-tools");- let set = GoalSetTool::new(dir.clone());+ let tools = goal_tools(tmp.path());+ let set = tools.iter().find(|t| t.name() == "goal_set").unwrap();+ let context = ThreadContext("thread-host-tools");let res = set.execute_with_context(json!({ "objective": "land the PR", "token_budget": 5000 }),@@ -31,62 +35,14 @@ async fn set_get_complete_via_tools_in_thread_scope() {.await.unwrap();assert!(!res.is_error, "{}", res.text());- let set_payload = payload(&res);- assert_eq!(set_payload["goal"]["objective"], "land the PR");- assert_eq!(set_payload["goal"]["status"], "active");- assert_eq!(set_payload["goal"]["tokenBudget"], 5000);- assert_eq!(set_payload["goal"]["tokensUsed"], 0);- let text = set_payload["text"].as_str().unwrap();- assert!(text.starts_with("Goal set."), "{text}");- assert!(text.contains("objective: land the PR"), "{text}");-- let get = GoalGetTool::new(dir.clone());- let res = get- .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))- .await- .unwrap();- let get_payload = payload(&res);- assert_eq!(get_payload["goal"]["status"], "active");- assert_eq!(get_payload["goal"]["goalId"], set_payload["goal"]["goalId"]);- assert!(get_payload["text"]- .as_str()- .unwrap()- .contains("status: active"));+ let payload: serde_json::Value = serde_json::from_str(&res.text()).unwrap();+ assert_eq!(payload["goal"]["objective"], "land the PR");+ assert_eq!(payload["goal"]["tokenBudget"], 5000);+ assert!(payload["text"].as_str().unwrap().starts_with("Goal set."));- let done = GoalCompleteTool::new(dir.clone());- let res = done- .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))+ let stored = store::get(tmp.path(), "thread-host-tools").await- .unwrap();- let done_payload = payload(&res);- assert_eq!(done_payload["goal"]["status"], "complete");- assert!(done_payload["text"]- .as_str().unwrap()- .starts_with("Goal marked complete."));-}--#[tokio::test]-async fn tools_error_without_thread_scope() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- let set = GoalSetTool::new(dir.clone());- let res = set.execute(json!({ "objective": "x" })).await.unwrap();- assert!(res.is_error);- assert!(res.text().contains("active chat thread"));-}--#[tokio::test]-async fn get_reports_absent_goal() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- let context = ThreadContext("empty-thread");- let get = GoalGetTool::new(dir.clone());- let res = get- .execute_with_context(json!({}), ToolCallOptions::default(), Some(&context))- .await- .unwrap();- let absent = payload(&res);- assert!(absent["goal"].is_null(), "{absent}");- assert_eq!(absent["text"], "no goal set for this thread");+ .expect("goal persisted through the workspace store");+ assert_eq!(stored.objective, "land the PR");}diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex 6eea89b3dd..de0304c67d 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -684,16 +684,9 @@ pub fn all_tools_with_runtime(// taken. `goal_get`/`goal_set`/`goal_complete` — pause/resume/budget are// system-driven and have no model tool.{- let goal_dir = root_config.workspace_dir.clone();- tools.push(Box::new(crate::agent::goals::GoalGetTool::new(- goal_dir.clone(),- )));- tools.push(Box::new(crate::agent::goals::GoalSetTool::new(- goal_dir.clone(),- )));- tools.push(Box::new(crate::agent::goals::GoalCompleteTool::new(- goal_dir,- )));+ tools.extend(crate::agent::goals::goal_tools(+ &root_config.workspace_dir,+ ));}#[cfg(feature = "modules")]