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/goals/README.md,crates/openhuman-core/src/agent
Steven Enamakelf4e4b867e1d6
diff --git a/crates/openhuman-core/src/agent/goals/README.md b/crates/openhuman-core/src/agent/goals/README.mddeleted file mode 100644index 607886db3f..0000000000--- a/crates/openhuman-core/src/agent/goals/README.md+++ /dev/null@@ -1,14 +0,0 @@-# Agent goals--TinyAgents owns goal types, lifecycle, persistence, budgets, and prompt-rendering. This directory contains OpenHuman runtime adapters for explicit-thread selection, tool registration, and turn accounting.--Goals are controlled by the agent tools and runtime. The conversation UI reads-them through the `threads.goal_get` RPC and renders the thread goal panel.--## Further reading--- [Parent module README](../README.md)-- [Agent harness architecture](../../../../../docs/gitbooks/en/developing/architecture/agent-harness.md)-- [Goals and todos](../../../../../docs/gitbooks/en/features/goals-and-todos.md)diff --git a/crates/openhuman-core/src/agent/goals/mod.rs b/crates/openhuman-core/src/agent/goals/mod.rsindex 43e1ee379a..99c70663d6 100644--- a/crates/openhuman-core/src/agent/goals/mod.rs+++ b/crates/openhuman-core/src/agent/goals/mod.rs@@ -1,23 +1,102 @@-//! Thin OpenHuman host adapters for [`tinyagents_graph::goals`].+//! OpenHuman adapters for TinyAgents' thread-goal lifecycle.//!-//! Tinyagents owns the goal types, lifecycle, persistence, prompt rendering,-//! graph continuation, and native harness tools. This module contains the-//! remaining OpenHuman-specific adapters: workspace-store resolution, domain-//! events, and bridges for-//! the shared tool contract and TinyAgents' stop-hook contract.--pub mod runtime;-pub mod tools;--use tinyagents_graph::goals::ThreadGoal;-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 is-/// kept as a raw `Value` rather than a typed field on the event. Falls back to-/// `Value::Null` on an (unexpected) serialization failure rather than-/// panicking or dropping the event.+//! TinyAgents owns persistence, model-facing controls, prompt rendering, and+//! accounting. OpenHuman resolves a context-scoped KV store and publishes the+//! existing thread-goal domain events consumed by RPC and the web channel.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, Weak};++use tinyagents_harness_tools::goals::{GoalObserver, GoalStore, ThreadGoal};+use tinytools::Tool;++/// Serialize a [`ThreadGoal`] for the existing goal event and RPC payload.#[must_use]pub fn goal_to_value(goal: &ThreadGoal) -> serde_json::Value {serde_json::to_value(goal).unwrap_or(serde_json::Value::Null)}++#[derive(Default)]+struct ScopedGoalStores(Mutex<HashMap<PathBuf, Weak<GoalStore>>>);++/// Returns the goal store owned by this dispatch context and workspace.+///+/// The scoped slot keeps the owner's update throttle alive across turns while+/// ensuring separate tenants and embedded agents never share goal state.+pub fn goal_store(+ workspace_dir: &Path,+ context: &crate::core::runtime::DispatchCtx,+) -> Arc<GoalStore> {+ let stores = crate::core::runtime::slot_for::<ScopedGoalStores>(context);+ let mut stores = stores+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(store) = stores.get(workspace_dir).and_then(Weak::upgrade) {+ return store;+ }++ let kv = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;+ let store = Arc::new(GoalStore::with_observer(kv, Arc::new(OpenHumanGoalObserver)));+ stores.insert(workspace_dir.to_path_buf(), Arc::downgrade(&store));+ store+}++struct OpenHumanGoalObserver;++impl GoalObserver for OpenHumanGoalObserver {+ fn on_updated(&self, goal: &ThreadGoal) {+ 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)),+ });+ }++ fn on_cleared(&self, thread_id: &str) {+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ThreadGoalCleared {+ thread_id: thread_id.to_string(),+ });+ }+}++/// The model-facing goal controls, backed by the context-scoped observer.+pub fn goal_tools(workspace_dir: &Path) -> Vec<Box<dyn Tool>> {+ let context = crate::core::runtime::DispatchCtx::ambient();+ let store = goal_store(workspace_dir, &context);+ tinyagents_harness_tools::goals::GoalToolKind::MODEL_FACING+ .into_iter()+ .map(|kind| {+ Box::new(tinyagents_harness_tools::goals::GoalTool::new(+ kind,+ Arc::clone(&store),+ )) as Box<dyn Tool>+ })+ .collect()+}++/// Best-effort account of receipt-backed usage against a thread's goal.+pub async fn account_turn(+ workspace_dir: &Path,+ context: &crate::core::runtime::DispatchCtx,+ thread_id: Option<&str>,+ input_tokens: u64,+ output_tokens: u64,+ elapsed: std::time::Duration,+) {+ let Some(thread_id) = thread_id.map(str::trim).filter(|id| !id.is_empty()) else {+ return;+ };+ if let Err(error) = goal_store(workspace_dir, context)+ .account_turn(thread_id, input_tokens, output_tokens, elapsed)+ .await+ {+ tracing::debug!(thread_id, %error, "[thread_goals] account_turn failed");+ }+}++#[cfg(test)]+#[path = "mod_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/goals/runtime.rs b/crates/openhuman-core/src/agent/goals/runtime.rsdeleted file mode 100644index f2a2e2ce69..0000000000--- a/crates/openhuman-core/src/agent/goals/runtime.rs+++ /dev/null@@ -1,222 +0,0 @@-//! OpenHuman accounting adapters for tinyagents thread goals.-//!-//! These are the pieces that make a stored goal actually steer the agent-//! (Codex parity):-//!-//! - [`account_turn_against_goal`] folds a completed turn's token + time usage-//! into the active goal, flipping it to `budget_limited` when the cap is-//! crossed.-//! - Goal budget policy is supplied by `tinyagents-hooks`; this module keeps-//! persistence and completed-turn accounting.--use std::path::Path;--use tinyagents_graph::goals::budget as crate_budget;-use tinyagents_graph::goals::{ThreadGoal, ThreadGoalStatus};--use crate::core::bus::BUS;-use crate::core::events::DomainEvent;--/// Load the goal for an explicitly supplied chat thread.-pub async fn load_for_thread(workspace_dir: &Path, thread_id: Option<&str>) -> Option<ThreadGoal> {- let thread_id = normalized_thread(thread_id)?;- let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::get(&store, &thread_id)- .await- .map_err(|e| e.to_string())- {- Ok(goal) => goal,- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] load_for_thread failed");- None- }- }-}--/// Reactivate a paused goal for an explicit thread (thread-resume semantics).-/// Best-effort: a failure is logged and surfaced as `Ok(None)`-style `None`.-pub async fn resume_for_thread(- workspace_dir: &Path,- thread_id: Option<&str>,-) -> Option<Option<ThreadGoal>> {- let thread_id = normalized_thread(thread_id)?;- let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::resume(&store, &thread_id)- .await- .map_err(|e| e.to_string())- {- Ok(goal) => {- if goal.status.is_active() {- BUS.publish(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)),- });- }- Some(Some(goal))- }- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] resume_for_thread failed");- None- }- }-}--/// Mark the active goal for an explicit thread `Complete` (the originating-/// task settled successfully). Best-effort; safe to call when there is no goal-/// or no thread id. Emits `ThreadGoalUpdated` so the UI chip refreshes.-///-/// This is the lifecycle counterpart the pause/resume pair was missing: without-/// a settle, a goal a finished task left behind stays `Active` and is-/// re-injected as an `[active_goal]` block on every later turn — including-/// unrelated chat (#1725). A caller that owns a task's lifecycle calls this-/// when the task reaches a terminal, satisfied state so the goal can't linger.-pub async fn complete_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {- let Some(thread_id) = normalized_thread(thread_id) else {- return;- };- let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::complete(&store, &thread_id)- .await- .map_err(|e| e.to_string())- {- Ok(goal) => {- if matches!(goal.status, ThreadGoalStatus::Complete) {- BUS.publish(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)),- });- }- }- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] complete_for_thread failed");- }- }-}--/// Delete the goal row for an explicit thread entirely (the originating task was-/// abandoned / superseded, and no completion contract should persist).-/// Best-effort; safe to call when there is no goal or thread id.-///-/// Clearing removes the row rather than moving it to a terminal status, so a-/// later turn loads `None` and injects no `[active_goal]` block at all — the-/// strongest guarantee that a stale objective cannot leak forward (#1725).-pub async fn clear_for_thread(workspace_dir: &Path, thread_id: Option<&str>) {- let Some(thread_id) = normalized_thread(thread_id) else {- return;- };- let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- match tinyagents_graph::goals::store::clear(&store, &thread_id)- .await- .map_err(|e| e.to_string())- {- Ok(existed) => {- if existed {- BUS.publish(DomainEvent::ThreadGoalCleared {- thread_id: thread_id.clone(),- });- }- }- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] clear_for_thread failed");- }- }-}--/// The per-turn token total used for budget accounting (prompt + completion).-fn turn_tokens(input: u64, output: u64) -> u64 {- crate_budget::turn_tokens(input, output)-}--/// Account a finished turn's usage against an explicit thread's goal.-///-/// The accounting rules are the crate's-/// ([`crate_budget::account_turn`](tinyagents_graph::goals::account_turn)):-/// only **active** goals are charged, so a paused/complete/budget-limited goal-/// doesn't accrue usage from incidental chat. OpenHuman runs no autonomous-/// goal continuation, so every accounted turn is user-initiated.-///-/// What is OpenHuman's here: receiving the owned thread from the turn and-/// emitting `ThreadGoalUpdated` when the status changes (e.g. →-/// `budget_limited`) so the UI chip refreshes. Best-effort throughout: a-/// failure is logged and swallowed so accounting never fails a user turn.-pub async fn account_turn_against_goal(- workspace_dir: &Path,- thread_id: Option<&str>,- input: u64,- output: u64,- secs: u64,-) {- let Some(thread_id) = normalized_thread(thread_id) else {- return;- };- let store = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- let prev = match tinyagents_graph::goals::store::get(&store, &thread_id)- .await- .map_err(|e| e.to_string())- {- Ok(Some(goal)) => goal,- Ok(None) => return,- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] account get failed");- return;- }- };- let prev_status = prev.status;- let prev_tokens_used = prev.tokens_used;-- match crate_budget::account_turn(&store, &thread_id, input, output, secs, true).await {- Ok(Some(updated)) => {- tracing::debug!(- thread_id = %thread_id,- goal_id = %updated.goal_id,- tokens_used = updated.tokens_used,- status = updated.status.as_str(),- "[thread_goals] accounted turn usage (+{} tok, +{secs}s)",- turn_tokens(input, output)- );- // Publish on any status transition, or — for a live budget- // display — when accumulated usage has moved by at least 5% of- // the configured budget since the last publish. Without the- // throttle every single turn's accounting would emit a socket- // event; the threshold keeps the UI's budget meter live without- // flooding the bus on chatty threads.- let status_changed = updated.status != prev_status;- let budget_moved = updated- .token_budget- .filter(|b| *b > 0)- .is_some_and(|budget| {- let delta = updated.tokens_used.saturating_sub(prev_tokens_used);- // 5% of budget, at least 1 token so a tiny budget still reports.- let threshold = (budget / 20).max(1);- delta >= threshold- });- if status_changed || budget_moved {- BUS.publish(DomainEvent::ThreadGoalUpdated {- thread_id: updated.thread_id.clone(),- goal_id: updated.goal_id.clone(),- status: updated.status.as_str().to_string(),- goal: Some(super::goal_to_value(&updated)),- });- }- }- Ok(None) => {}- Err(e) => {- tracing::debug!(thread_id = %thread_id, error = %e, "[thread_goals] account_turn failed");- }- }-}--fn normalized_thread(thread_id: Option<&str>) -> Option<String> {- thread_id- .map(str::trim)- .filter(|thread_id| !thread_id.is_empty())- .map(ToOwned::to_owned)-}--#[cfg(test)]-#[path = "runtime_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/goals/runtime_tests.rs b/crates/openhuman-core/src/agent/goals/runtime_tests.rsdeleted file mode 100644index b931b43fe2..0000000000--- a/crates/openhuman-core/src/agent/goals/runtime_tests.rs+++ /dev/null@@ -1,168 +0,0 @@-use super::*;-#[tokio::test]-async fn account_turn_charges_active_goal_and_trips_budget() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-acct",- "obj",- Some(100),- )- .await- .unwrap();- account_turn_against_goal(&dir, Some("t-acct"), 80, 40, 3).await; // 120 >= 100- let g = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-acct",- )- .await- .unwrap()- .unwrap();- assert_eq!(g.tokens_used, 120);- assert_eq!(g.status, ThreadGoalStatus::BudgetLimited);-}-#[tokio::test]-async fn account_turn_skips_non_active_goal() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-paused",- "obj",- Some(1000),- )- .await- .unwrap();- tinyagents_graph::goals::store::pause(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-paused",- )- .await- .unwrap();- account_turn_against_goal(&dir, Some("t-paused"), 500, 500, 1).await;- let g = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-paused",- )- .await- .unwrap()- .unwrap();- assert_eq!(g.tokens_used, 0, "paused goal must not accrue usage");-}--#[tokio::test]-async fn complete_for_thread_settles_active_goal() {- // A goal an originating task left behind is settled to `Complete` so a- // later turn stops re-injecting its `[active_goal]` block (#1725).- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-complete",- "obj",- Some(1000),- )- .await- .unwrap();- complete_for_thread(&dir, Some("t-complete")).await;- let g = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-complete",- )- .await- .unwrap()- .unwrap();- assert_eq!(- g.status,- ThreadGoalStatus::Complete,- "an originating task's settle must mark the goal Complete, not leave it Active"- );- assert!(- !g.status.is_active(),- "a completed goal must not stay active (it would keep steering unrelated turns)"- );-}--#[tokio::test]-async fn clear_for_thread_removes_the_goal_row() {- // Clearing deletes the row entirely, so a later turn loads `None` and- // injects no goal block at all — the strongest anti-leak guarantee.- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-clear",- "obj",- Some(1000),- )- .await- .unwrap();- clear_for_thread(&dir, Some("t-clear")).await;- let g = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-clear",- )- .await- .unwrap();- assert!(- g.is_none(),- "clearing must delete the goal row so no [active_goal] can leak forward"- );-}--#[tokio::test]-async fn complete_and_clear_are_safe_without_a_goal_or_thread() {- // Best-effort contract: both are no-ops (never panic) when there is no- // goal for the thread, and when called outside any thread scope.- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- complete_for_thread(&dir, Some("t-empty")).await;- clear_for_thread(&dir, Some("t-empty")).await;- assert!(tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-empty"- )- .await- .unwrap()- .is_none());- // No ambient thread scope at all.- complete_for_thread(&dir, None).await;- clear_for_thread(&dir, None).await;-}--#[tokio::test]-async fn account_turn_clears_suppression_without_losing_usage() {- let tmp = tempfile::tempdir().unwrap();- let dir = tmp.path().to_path_buf();- let goal = tinyagents_graph::goals::store::set(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- "obj",- Some(1000),- )- .await- .unwrap();- tinyagents_graph::goals::store::set_continuation_suppressed_if(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- &goal.goal_id,- true,- )- .await- .unwrap();-- account_turn_against_goal(&dir, Some("t-suppressed"), 80, 40, 3).await;-- let updated = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(&dir).kv,- "t-suppressed",- )- .await- .unwrap()- .unwrap();- assert_eq!(updated.goal_id, goal.goal_id);- assert!(!updated.continuation_suppressed);- assert_eq!(updated.tokens_used, 120);- assert_eq!(updated.time_used_seconds, 3);-}diff --git a/crates/openhuman-core/src/agent/goals/tools.rs b/crates/openhuman-core/src/agent/goals/tools.rsdeleted file mode 100644index a1662808a7..0000000000--- a/crates/openhuman-core/src/agent/goals/tools.rs+++ /dev/null@@ -1,50 +0,0 @@-//! Host wiring for tinyagents' model-facing goal controls.-//!-//! `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;-use tinyagents_graph::goals::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 = crate::storage::sessions::stores_or_ephemeral(workspace_dir).kv;- 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>- })- .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)]-#[path = "tools_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/goals/tools_tests.rs b/crates/openhuman-core/src/agent/goals/tools_tests.rsdeleted file mode 100644index 7188a585cc..0000000000--- a/crates/openhuman-core/src/agent/goals/tools_tests.rs+++ /dev/null@@ -1,51 +0,0 @@-use super::*;-use serde_json::json;-use tinytools::{ToolCallOptions, ToolRunContext};--struct ThreadContext(&'static str);--impl ToolRunContext for ThreadContext {- fn thread_id(&self) -> Option<&str> {- Some(self.0)- }-}--#[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_persists_to_the_workspace_store_and_answers_goal_and_text() {- let tmp = tempfile::tempdir().unwrap();- 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 }),- ToolCallOptions::default(),- Some(&context),- )- .await- .unwrap();- assert!(!res.is_error, "{}", res.output());- let payload: serde_json::Value = serde_json::from_str(&res.output()).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 stored = tinyagents_graph::goals::store::get(- &crate::storage::sessions::stores_or_ephemeral(tmp.path()).kv,- "thread-host-tools",- )- .await- .unwrap()- .expect("goal persisted through the workspace store");- assert_eq!(stored.objective, "land the PR");-}