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(composio): handle missing state in contract state retrieval
Steven Enamakel2f1f8202290b
diff --git a/crates/openhuman-core/src/channels/runtime/test_support.rs b/crates/openhuman-core/src/channels/runtime/test_support.rsindex 8217dd4c4a..f859079e19 100644--- a/crates/openhuman-core/src/channels/runtime/test_support.rs+++ b/crates/openhuman-core/src/channels/runtime/test_support.rs@@ -26,7 +26,6 @@ use std::sync::{Arc, Mutex};use std::time::Duration;use tinyagents_session::transcript::TranscriptMessage;use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse};-use tinymemory_api::types::{MemoryCategory, MemoryEntry};use tinytools::{Tool, ToolResult};#[derive(Debug, Clone)]@@ -42,7 +41,6 @@ pub struct DispatchHarnessOptions {pub handler_delay_ms: u64,pub timeout_secs: u64,pub seed_history_len: usize,- pub memory_entries: Vec<TestMemoryEntry>,/// Workspace the runtime context reports; `None` falls back to the OS temp dir.////// `pub`, like every other field here, and it has to be: integration tests@@ -114,20 +112,12 @@ impl Default for DispatchHarnessOptions {handler_delay_ms: 0,timeout_secs: CHANNEL_MESSAGE_TIMEOUT_SECS,seed_history_len: 0,- memory_entries: Vec::new(),workspace_dir: None,system_prompt: HarnessSystemPrompt::default(),}}}-#[derive(Debug, Clone)]-pub struct TestMemoryEntry {- pub key: String,- pub content: String,- pub score: Option<f64>,-}-#[derive(Debug, Clone, PartialEq, Eq)]pub struct ObservedSend {pub kind: &'static str,@@ -257,122 +247,6 @@ impl ChatModel<()> for HarnessModel {}}-/// A provider whose `recall` answers with a fixed entry list regardless of-/// query.-///-/// Deliberately not [`InMemoryProvider`](crate::memory::guard::in_memory::InMemoryProvider):-/// that one substring-matches, and these harness entries are scripted to come-/// back for whatever the test sends. The point here is the channel pipeline-/// downstream of recall, not recall itself.-struct HarnessMemory {- entries: Vec<MemoryEntry>,-}--#[async_trait]-impl tinymemory_api::provider::MemoryCore for HarnessMemory {- async fn store(- &self,- _namespace: &str,- _key: &str,- _content: &str,- _category: MemoryCategory,- _session_id: Option<&str>,- _taint: tinymemory_api::types::MemoryTaint,- ) -> std::result::Result<(), tinymemory_api::error::MemoryError> {- Ok(())- }-- async fn get(- &self,- _namespace: &str,- _key: &str,- ) -> std::result::Result<Option<MemoryEntry>, tinymemory_api::error::MemoryError> {- Ok(None)- }-- async fn forget(- &self,- _namespace: &str,- _key: &str,- ) -> std::result::Result<bool, tinymemory_api::error::MemoryError> {- Ok(false)- }-- async fn list(- &self,- _namespace: Option<&str>,- _category: Option<&MemoryCategory>,- _session_id: Option<&str>,- ) -> std::result::Result<Vec<MemoryEntry>, tinymemory_api::error::MemoryError> {- Ok(Vec::new())- }-- async fn namespaces(- &self,- ) -> std::result::Result<- Vec<tinymemory_api::types::NamespaceSummary>,- tinymemory_api::error::MemoryError,- > {- Ok(Vec::new())- }-}--#[async_trait]-impl tinymemory_api::provider::MemoryRecall for HarnessMemory {- async fn recall(- &self,- _query: &str,- _limit: usize,- _opts: &tinymemory_api::recall::OwnedRecallOpts,- _scope: Option<&tinymemory_api::provider::types::SourceScope>,- ) -> std::result::Result<Vec<MemoryEntry>, tinymemory_api::error::MemoryError> {- Ok(self.entries.clone())- }-}--#[async_trait]-impl tinymemory_api::provider::MemoryPortability for HarnessMemory {- async fn export_page(- &self,- _cursor: Option<&str>,- _limit: usize,- ) -> std::result::Result<- tinymemory_api::provider::types::ExportPage,- tinymemory_api::error::MemoryError,- > {- Err(tinymemory_api::error::MemoryError::Other(anyhow::anyhow!(- "harness memory does not export"- )))- }-- async fn import_records(- &self,- _records: Vec<tinymemory_api::provider::types::ExportRecord>,- ) -> std::result::Result<- tinymemory_api::provider::types::ImportOutcome,- tinymemory_api::error::MemoryError,- > {- Err(tinymemory_api::error::MemoryError::Other(anyhow::anyhow!(- "harness memory does not import"- )))- }-}--#[async_trait]-impl tinymemory_api::provider::MemoryProvider for HarnessMemory {- fn driver_id(&self) -> &str {- "harness-memory"- }-- fn capabilities(&self) -> tinymemory_api::capabilities::Capabilities {- tinymemory_api::capabilities::Capabilities::mandatory()- }-- async fn health(&self) -> tinymemory_api::health::MemoryHealth {- tinymemory_api::health::MemoryHealth::Ready- }-}-struct HarnessTool;#[async_trait]@@ -394,20 +268,6 @@ impl Tool for HarnessTool {}}-fn memory_entry(input: TestMemoryEntry) -> MemoryEntry {- MemoryEntry {- id: input.key.clone(),- key: input.key,- content: input.content,- namespace: None,- category: MemoryCategory::Conversation,- timestamp: "now".to_string(),- session_id: None,- score: input.score,- taint: tinymemory_api::types::MemoryTaint::Internal,- }-}-/// Acquire the shared agent-handler guard. Hold the returned guard across any/// call that re-registers `AGENT_RUN_TURN_METHOD` (the harness, or/// `start_channels`) so concurrent registrations cannot race in the same@@ -556,20 +416,11 @@ pub async fn run_dispatch_harness(options: DispatchHarnessOptions) -> DispatchHachannels_by_name: Arc::new(channels_by_name),turn_model_source: Some(crate::agent::tinyagents::TurnModelSource::from_model(model)),default_provider: Arc::new("harness-provider".to_string()),- memory: crate::memory::guard::in_memory::guard_over(Arc::new(HarnessMemory {- entries: options- .memory_entries- .into_iter()- .map(memory_entry)- .collect(),- })),tools_registry: Arc::new(vec![Box::new(HarnessTool) as Box<dyn Tool>]),system_prompt: harness_system_prompt,model: Arc::new("harness-model".to_string()),temperature: 0.0,- auto_save_memory: true,max_tool_iterations: 3,- min_relevance_score: 0.2,conversation_histories: Arc::clone(&conversation_histories),turn_model_source_cache: Arc::new(Mutex::new(provider_cache)),route_overrides: Arc::new(Mutex::new(HashMap::new())),diff --git a/crates/openhuman-core/src/integrations/composio/contract/state.rs b/crates/openhuman-core/src/integrations/composio/contract/state.rsdeleted file mode 100644index 08057632b8..0000000000--- a/crates/openhuman-core/src/integrations/composio/contract/state.rs+++ /dev/null@@ -1,275 +0,0 @@-//! What a connection remembers between sync runs: a cursor, a dedup set, and-//! a daily request budget.-//!-//! One [`SyncState`] per `(toolkit, connection)` pair, persisted as JSON under-//! [`STATE_NAMESPACE`] in whatever key/value store the driver provides. It is-//! the reason a second Gmail sync does not re-ingest the first sync's messages-//! and the reason a runaway pipeline stops at five hundred requests instead of-//! exhausting a user's quota.-//!-//! # Why this is contract vocabulary rather than engine state-//!-//! Both sides read it. The module advances the cursor and records requests; the-//! host shows "synced 4 minutes ago, 312 of 500 requests used today" and, on-//! disconnect, walks the dedup set to decide what to forget. A structural twin-//! on the host side would decode today and diverge the first time a field was-//! added — and this shape is *persisted*, so a divergence is not a wire bug-//! that reconnects away, it is a stranded cursor and a re-ingested inbox.-//!-//! # What is not here-//!-//! `SyncStateStore`, and the `load` / `save` that use it. This crate publishes-//! no traits and holds no I/O (see [`crate`]); the engine crate carries the-//! trait and offers the two methods as an extension trait over the type defined-//! here. Everything below is arithmetic on a struct.-//!-//! # Durability-//!-//! [`STATE_NAMESPACE`] and the serde field names are a compatibility surface:-//! changing the namespace strands every cursor, and renaming a field silently-//! resets it to its default on the next load. The engine keeps a-//! structurally-identical copy for its own internal pipelines, persisting under-//! the same namespace with the same shape, until those pipelines retire — the-//! pin tests below are what hold the two together.--use std::collections::{HashMap, HashSet};--use chrono::Utc;-use serde::{Deserialize, Serialize};--/// The key/value namespace every persisted sync cursor lives under.-///-/// An alias for [`STATE_NAMESPACE`], kept because callers reach for one name or-/// the other depending on whether they are writing state or cleaning it up.-/// Durable: changing it strands every cursor.-pub const KV_NAMESPACE: &str = STATE_NAMESPACE;--/// Requests one connection may spend in a day before its budget is exhausted.-///-/// A backstop against a paginating pipeline that never terminates, not a-/// billing limit — the provider-reported cost is tallied separately.-pub const DEFAULT_DAILY_REQUEST_LIMIT: u32 = 500;--/// The key/value namespace every persisted sync cursor lives under.-///-/// Durable: changing it strands every cursor.-pub const STATE_NAMESPACE: &str = "composio-sync-state";--/// A per-connection, per-day request allowance.-///-/// `date` is the UTC day the counter belongs to. Every accessor compares it-/// against today and treats a stale date as a fresh allowance, so a state-/// loaded from yesterday reports a full budget without anyone having to reset-/// it — which is what makes a missed midnight rollover a non-event.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct DailyBudget {- /// The UTC day this counter belongs to, as `YYYY-MM-DD`.- pub date: String,- /// Requests spent on [`date`](Self::date).- pub requests_used: u32,- /// Allowance for one day; defaults to [`DEFAULT_DAILY_REQUEST_LIMIT`].- pub limit: u32,-}--impl Default for DailyBudget {- fn default() -> Self {- Self {- date: today(),- requests_used: 0,- limit: DEFAULT_DAILY_REQUEST_LIMIT,- }- }-}--impl DailyBudget {- /// Requests still available today.- ///- /// A counter from an earlier day reports the full limit rather than its- /// stale remainder: the rollover happens on read, so nothing has to run at- /// midnight for a budget to refresh.- pub fn remaining(&self) -> u32 {- if self.date != today() {- self.limit- } else {- self.limit.saturating_sub(self.requests_used)- }- }-- /// Whether today's allowance is spent.- pub fn is_exhausted(&self) -> bool {- self.remaining() == 0- }-- /// Charge `count` requests against today's allowance, rolling the counter- /// over first if it belongs to an earlier day.- pub fn record_requests(&mut self, count: u32) {- self.roll_over_if_stale();- self.requests_used = self.requests_used.saturating_add(count);- }-- /// Reset the counter when it belongs to an earlier day.- ///- /// Every accessor already rolls over lazily, so this exists for the one- /// caller that wants the *stored* value normalised rather than the answer:- /// a state just loaded from yesterday, so that what is written back is- /// today's row and not a stale one that later reads have to keep- /// compensating for.- pub fn roll_over_if_stale(&mut self) {- let today = today();- if self.date != today {- self.date = today;- self.requests_used = 0;- }- }-- /// Charge a single request. Shorthand for [`record_requests`](Self::record_requests).- pub fn record_request(&mut self) {- self.record_requests(1);- }-}--/// Everything one `(toolkit, connection)` pair carries between sync runs.-///-/// The two `#[serde(skip)]` fields are per-run counters rather than state: they-/// exist so a finished run can report what it spent, and persisting them would-/// make the tally cumulative, which is not what any caller reads it as.-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct SyncState {- /// Composio toolkit slug, e.g. `"gmail"`.- pub toolkit: String,- /// The connection this state belongs to.- pub connection_id: String,- /// Provider-native pagination cursor, when the provider issues one.- #[serde(default)]- pub cursor: Option<String>,- /// Upstream item ids already ingested, so a re-run does not duplicate them.- #[serde(default)]- pub synced_ids: HashSet<String>,- /// Item id to version string, for providers whose items can be edited after- /// they were first seen.- #[serde(default)]- pub item_versions: HashMap<String, String>,- /// Today's request allowance.- #[serde(default)]- pub daily_budget: DailyBudget,- /// Newest item id seen, for providers that page newest-first.- #[serde(default)]- pub last_seen_id: Option<String>,- /// When the last run finished, epoch milliseconds.- #[serde(default)]- pub last_sync_at_ms: Option<u64>,- /// Requests spent by the *current* run. Not persisted.- #[serde(skip)]- pub run_requests: u32,- /// Provider-reported cost accumulated by the *current* run. Not persisted.- #[serde(skip)]- pub run_provider_cost_usd: f64,-}--impl SyncState {- /// A fresh state for a connection that has never synced.- pub fn new(toolkit: impl Into<String>, connection_id: impl Into<String>) -> Self {- Self {- toolkit: toolkit.into(),- connection_id: connection_id.into(),- cursor: None,- synced_ids: HashSet::new(),- item_versions: HashMap::new(),- daily_budget: DailyBudget::default(),- last_seen_id: None,- last_sync_at_ms: None,- run_requests: 0,- run_provider_cost_usd: 0.0,- }- }-- /// The key/value key a state is stored under, within [`STATE_NAMESPACE`].- ///- /// Durable, like the namespace: a different separator strands every cursor.- pub fn key(toolkit: &str, connection_id: &str) -> String {- format!("{toolkit}:{connection_id}")- }-- /// Whether this item has already been ingested.- pub fn is_synced(&self, id: &str) -> bool {- self.synced_ids.contains(id)- }-- /// Record an item as ingested.- pub fn mark_synced(&mut self, id: impl Into<String>) {- self.synced_ids.insert(id.into());- }-- /// Move the pagination cursor forward.- pub fn advance_cursor(&mut self, cursor: impl Into<String>) {- self.cursor = Some(cursor.into());- }-- /// Record the newest item id this run saw.- pub fn set_last_seen_id(&mut self, id: impl Into<String>) {- self.last_seen_id = Some(id.into());- }-- /// Stamp when the run finished, epoch milliseconds.- pub fn set_last_sync_at_ms(&mut self, timestamp_ms: u64) {- self.last_sync_at_ms = Some(timestamp_ms);- }-- /// Whether today's request allowance is spent.- pub fn budget_exhausted(&self) -> bool {- self.daily_budget.is_exhausted()- }-- /// Requests still available today.- pub fn budget_remaining(&self) -> u32 {- self.daily_budget.remaining()- }-- /// Charge `count` requests against both the daily allowance and this run's- /// counter.- pub fn record_requests(&mut self, count: u32) {- self.daily_budget.record_requests(count);- self.run_requests = self.run_requests.saturating_add(count);- }-- /// Record one completed Composio action: its request attempts and the- /// provider-reported cost.- ///- /// `attempts` is floored at one — an action that reached the provider spent- /// at least one request however the caller counted its retries. A cost that- /// is negative, infinite or `NaN` is discarded rather than propagated into- /// a total someone reads as money.- pub fn record_action(&mut self, attempts: u32, cost_usd: f64) {- self.record_requests(attempts.max(1));- if cost_usd.is_finite() && cost_usd > 0.0 {- self.run_provider_cost_usd += cost_usd;- }- }-}--/// First non-empty string found at any of `paths` — dot-separated — in `item`.-///-/// Providers disagree about where an item's stable id lives (`id`, `messageId`,-/// `data.id`, …), so a pipeline hands this the candidates in priority order and-/// takes the first that is actually populated. Whitespace-only values count as-/// absent: an id of `" "` dedupes nothing and would poison the synced set.-pub fn extract_item_id(item: &serde_json::Value, paths: &[&str]) -> Option<String> {- paths.iter().find_map(|path| {- let value = path- .split('.')- .try_fold(item, |current, segment| current.get(segment))?;- value- .as_str()- .map(str::trim)- .filter(|value| !value.is_empty())- .map(str::to_owned)- })-}--fn today() -> String {- Utc::now().format("%Y-%m-%d").to_string()-}--#[cfg(test)]-#[path = "state_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/contract/state_tests.rs b/crates/openhuman-core/src/integrations/composio/contract/state_tests.rsdeleted file mode 100644index efecb95d0a..0000000000--- a/crates/openhuman-core/src/integrations/composio/contract/state_tests.rs+++ /dev/null@@ -1,194 +0,0 @@-//! Tests for the persisted sync-state shape.-//!-//! The load/save round-trip through a key/value store is tested in the engine-//! crate, next to the `SyncStateStore` trait that performs it. What is pinned-//! here is what a migration would have to care about: the namespace, the-//! serialised field set, and the day-rollover arithmetic that decides whether a-//! connection is allowed to make another request.--#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]--use super::{- extract_item_id, DailyBudget, SyncState, DEFAULT_DAILY_REQUEST_LIMIT, KV_NAMESPACE,- STATE_NAMESPACE,-};--/// The namespace is durable: every persisted Composio sync cursor lives under-/// this string, so a change strands all of them. The engine's own copy of this-/// type must agree — failing here means a coordinated migration, never a local-/// edit.-#[test]-fn the_state_namespace_is_pinned() {- assert_eq!(- STATE_NAMESPACE, "composio-sync-state",- "the Composio sync-state namespace changed; every persisted cursor is \- stored under the old value and needs migrating"- );- assert_eq!(KV_NAMESPACE, STATE_NAMESPACE);-}--/// The serialised shape is persisted and is also what the engine's copy writes.-/// Pinned so the two cannot drift silently.-#[test]-fn the_state_wire_shape_is_pinned() {- let mut state = SyncState::new("gmail", "conn-1");- state.advance_cursor("c2");- state.mark_synced("m1");- state.item_versions.insert("m1".into(), "v1".into());- state.set_last_seen_id("m1");- state.set_last_sync_at_ms(1_000);- // Written directly rather than through `record_requests`, which would roll- // the stale date forward to today and make the expectation clock-dependent.- state.daily_budget.date = "2026-01-02".into();- state.daily_budget.requests_used = 3;-- let value = serde_json::to_value(&state).expect("serialize");- assert_eq!(- value,- serde_json::json!({- "toolkit": "gmail",- "connection_id": "conn-1",- "cursor": "c2",- "synced_ids": ["m1"],- "item_versions": {"m1": "v1"},- "daily_budget": {"date": "2026-01-02", "requests_used": 3, "limit": 500},- "last_seen_id": "m1",- "last_sync_at_ms": 1000- })- );-}--#[test]-fn per_run_counters_never_reach_the_wire() {- // A persisted tally would make every subsequent run report the sum of all- // the runs before it, which is not what the audit log reads it as.- let mut state = SyncState::new("gmail", "conn-1");- state.record_action(2, 0.25);- assert_eq!(state.run_requests, 2);- assert_eq!(state.run_provider_cost_usd, 0.25);-- let value = serde_json::to_value(&state).expect("serialize");- let object = value.as_object().expect("state serialises as an object");- assert!(!object.contains_key("run_requests"));- assert!(!object.contains_key("run_provider_cost_usd"));-}--#[test]-fn the_key_is_toolkit_then_connection() {- assert_eq!(SyncState::key("gmail", "conn-1"), "gmail:conn-1");-}--#[test]-fn a_fresh_state_has_synced_nothing_and_spent_nothing() {- let state = SyncState::new("slack", "conn-2");- assert!(state.cursor.is_none());- assert!(!state.is_synced("anything"));- assert!(!state.budget_exhausted());- assert_eq!(state.budget_remaining(), DEFAULT_DAILY_REQUEST_LIMIT);- assert_eq!(state.run_requests, 0);-}--#[test]-fn a_state_missing_every_optional_field_still_decodes() {- // Only `toolkit` and `connection_id` are required; a row written by an- // older peer that never knew about `item_versions` must load rather than- // fail the whole connection.- let stored = serde_json::json!({ "toolkit": "gmail", "connection_id": "c" });- let state: SyncState = serde_json::from_value(stored).expect("deserialize");- assert!(state.cursor.is_none());- assert!(state.synced_ids.is_empty());- assert!(state.item_versions.is_empty());- assert_eq!(state.daily_budget.limit, DEFAULT_DAILY_REQUEST_LIMIT);-}--#[test]-fn a_stale_budget_reports_full_and_resets_on_the_next_charge() {- let mut budget = DailyBudget {- date: "2000-01-01".into(),- requests_used: 499,- limit: 500,- };- assert_eq!(budget.remaining(), 500);- budget.record_requests(1);- assert_eq!(budget.requests_used, 1);- assert_eq!(budget.remaining(), 499);-}--#[test]-fn an_exhausted_budget_reports_zero_remaining() {- let mut budget = DailyBudget {- limit: 2,- ..DailyBudget::default()- };- budget.record_request();- assert!(!budget.is_exhausted());- budget.record_request();- assert!(budget.is_exhausted());- assert_eq!(budget.remaining(), 0);-}--#[test]-fn charging_past_the_limit_saturates_rather_than_wrapping() {- let mut budget = DailyBudget {- limit: 1,- ..DailyBudget::default()- };- budget.record_requests(u32::MAX);- budget.record_requests(10);- assert_eq!(budget.requests_used, u32::MAX);- assert_eq!(budget.remaining(), 0);-}--#[test]-fn an_action_always_costs_at_least_one_request() {- let mut state = SyncState::new("gmail", "conn-1");- state.record_action(0, 0.0);- assert_eq!(state.run_requests, 1);- assert_eq!(state.daily_budget.requests_used, 1);-}--#[test]-fn a_nonsense_action_cost_is_discarded_rather_than_totalled() {- let mut state = SyncState::new("gmail", "conn-1");- state.record_action(1, f64::NAN);- state.record_action(1, f64::INFINITY);- state.record_action(1, -5.0);- assert_eq!(state.run_provider_cost_usd, 0.0);- state.record_action(1, 0.5);- assert_eq!(state.run_provider_cost_usd, 0.5);-}--#[test]-fn an_item_id_is_taken_from_the_first_populated_path() {- let item = serde_json::json!({ "data": { "id": "inner" }, "messageId": "outer" });- assert_eq!(- extract_item_id(&item, &["missing", "data.id", "messageId"]).as_deref(),- Some("inner")- );-}--#[test]-fn a_blank_item_id_counts_as_absent() {- // An id of `" "` dedupes nothing and would poison the synced set, so it- // must not win over a later path that is actually populated.- let item = serde_json::json!({ "id": " ", "messageId": "m-1" });- assert_eq!(- extract_item_id(&item, &["id", "messageId"]).as_deref(),- Some("m-1")- );-}--#[test]-fn a_non_string_item_id_is_skipped() {- let item = serde_json::json!({ "id": 7, "messageId": "m-1" });- assert_eq!(- extract_item_id(&item, &["id", "messageId"]).as_deref(),- Some("m-1")- );-}--#[test]-fn no_matching_path_yields_none() {- let item = serde_json::json!({ "id": "x" });- assert_eq!(extract_item_id(&item, &["nope", "also.nope"]), None);-}