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
feat(tinyagents): add budget, compaction, and loop-guard middleware
Steven Enamakel2be6a9a7410e
diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge.rsdeleted file mode 100644index 68be5d5d8c..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/budget_charge.rs+++ /dev/null@@ -1,129 +0,0 @@-//! Normalize measured gateway charges before the shared budget settles calls.--use std::sync::Arc;--use async_trait::async_trait;-use tinyinference_llm::model::{- ChatModel, InputModality, InputSource, ModelProfile, ModelRequest, ModelResponse, ModelStream,- ModelStreamItem,-};-use tinyinference_llm::usage::ChargedAmount;--pub(super) struct GatewayChargeModel {- inner: Arc<dyn ChatModel<()>>,-}--impl GatewayChargeModel {- pub(super) fn new(inner: Arc<dyn ChatModel<()>>) -> Self {- Self { inner }- }-}--fn rounded_micros(micros: Option<f64>) -> Option<ChargedAmount> {- micros- .filter(|amount| amount.is_finite() && *amount >= 0.0 && *amount < i64::MAX as f64)- .map(|amount| ChargedAmount::usd_micros(amount.ceil() as i64))-}--fn normalize_charge(response: &mut ModelResponse) {- let Some(usage) = response.usage.as_mut() else {- // Missing usage must retain conservative token and charge reservations.- tracing::trace!(- source = "missing_usage",- charge_known = false,- "budget_charge_normalized"- );- return;- };- let Some(raw) = response.raw.as_ref() else {- tracing::trace!(- source = "typed_usage",- charge_known = usage- .charged_amount- .is_some_and(|charge| charge.micros >= 0),- "budget_charge_normalized"- );- return;- };- let (source, charge) =- if let Some(managed) = raw.pointer("/openhuman_usage_meta/charged_amount_usd") {- (- "managed_backend",- rounded_micros(managed.as_f64().map(|amount| amount * 1_000_000.0)),- )- } else if let Some(buyer) = raw.pointer("/usage/buyer_cost_micro") {- let charge = if let Some(micros) = buyer.as_i64() {- (micros >= 0).then_some(ChargedAmount::usd_micros(micros))- } else {- rounded_micros(buyer.as_f64())- };- ("gateway_buyer", charge)- } else if let Some(cost) = raw.pointer("/usage/cost") {- (- "provider_cost",- rounded_micros(cost.as_f64().map(|amount| amount * 1_000_000.0)),- )- } else {- tracing::trace!(- source = "typed_usage",- charge_known = usage- .charged_amount- .is_some_and(|charge| charge.micros >= 0),- "budget_charge_normalized"- );- return;- };- // Presence selects the authoritative billing source, including known zero- // and malformed values. Invalid billing remains unknown; fractional units- // round up. The ledger never substitutes a provider estimate for host or- // buyer billing, and no locally calculated price enters settlement.- usage.charged_amount = charge;- tracing::trace!(- source,- charge_known = charge.is_some(),- "budget_charge_normalized"- );-}--#[async_trait]-impl ChatModel<()> for GatewayChargeModel {- fn profile(&self) -> Option<&ModelProfile> {- self.inner.profile()- }-- fn supports_input(&self, modality: InputModality, mime: &str, source: InputSource) -> bool {- self.inner.supports_input(modality, mime, source)- }-- fn cache_identity(&self) -> Option<String> {- self.inner.cache_identity()- }-- async fn invoke(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- let mut response = self.inner.invoke(state, request).await?;- normalize_charge(&mut response);- Ok(response)- }-- async fn stream(- &self,- state: &(),- request: ModelRequest,- ) -> tinyinference_llm::Result<ModelStream> {- let stream = self.inner.stream(state, request).await?;- Ok(stream.map_items(|mut item| {- if let ModelStreamItem::Completed(response) = &mut item {- normalize_charge(response);- }- item- }))- }-}--#[cfg(test)]-#[path = "budget_charge_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs b/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rsdeleted file mode 100644index b8b32e3a6a..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/budget_charge_tests.rs+++ /dev/null@@ -1,157 +0,0 @@-//! Host charge normalization preserves streaming settlement and unknown usage.--use super::*;-use futures::StreamExt;-use tinyinference_llm::usage::Usage;--struct StreamingFixture;--#[async_trait]-impl ChatModel<()> for StreamingFixture {- fn supports_input(&self, modality: InputModality, mime: &str, source: InputSource) -> bool {- modality == InputModality::Image && mime == "image/png" && source == InputSource::Url- }-- fn cache_identity(&self) -> Option<String> {- Some("fixture-identity".to_owned())- }-- async fn invoke(&self, _: &(), _: ModelRequest) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse {- usage: Some(Usage::new(10, 5)),- raw: Some(serde_json::json!({"usage": {"buyer_cost_micro": 10}})),- ..ModelResponse::assistant("done")- })- }-}--#[tokio::test]-async fn streaming_gateway_charge_settles_and_releases_the_reservation() {- use tinyinference_llm::model::budget::{Budget, BudgetedModel, CallBudget, SpendLimits};- let budget = Budget::new(SpendLimits {- tokens: None,- cost_micros: Some(150),- });- let model = BudgetedModel::new(- Arc::new(GatewayChargeModel::new(Arc::new(StreamingFixture))),- budget.clone(),- CallBudget {- input_tokens: 1_000,- output_tokens: 5,- cost_micros: 100,- },- );- for expected_cost in [10, 20] {- let mut stream = model.stream(&(), ModelRequest::default()).await.unwrap();- let mut completed = false;- while let Some(item) = stream.next().await {- if let ModelStreamItem::Completed(response) = item {- assert_eq!(response.usage.unwrap().charged_amount.unwrap().micros, 10);- completed = true;- }- }- assert!(completed);- assert_eq!(budget.snapshot().spent.cost_micros, expected_cost);- }-}--#[test]-fn absent_raw_charge_preserves_typed_charge_and_absent_usage_stays_unknown() {- let mut response = ModelResponse {- usage: Some(Usage {- charged_amount: Some(ChargedAmount::usd_micros(12)),- ..Usage::new(10, 5)- }),- raw: Some(serde_json::json!({"usage": {}})),- ..ModelResponse::assistant("done")- };- normalize_charge(&mut response);- assert_eq!(response.usage.unwrap().charged_amount.unwrap().micros, 12);- response.usage = None;- response.raw = Some(serde_json::json!({"usage": {"buyer_cost_micro": 10}}));- normalize_charge(&mut response);- assert!(response.usage.is_none());-}--#[test]-fn integer_buyer_charge_does_not_lose_fixed_point_precision() {- let amount = 9_007_199_254_740_993_i64;- let mut response = ModelResponse {- usage: Some(Usage::new(10, 5)),- raw: Some(serde_json::json!({"usage": {"buyer_cost_micro": amount}})),- ..ModelResponse::assistant("done")- };- normalize_charge(&mut response);- assert_eq!(- response.usage.unwrap().charged_amount.unwrap().micros,- amount- );-}--#[test]-fn charge_adapter_preserves_transport_and_cache_identity() {- let model = GatewayChargeModel::new(Arc::new(StreamingFixture));- assert!(model.profile().is_none());- assert!(model.supports_input(InputModality::Image, "image/png", InputSource::Url));- assert!(!model.supports_input(InputModality::Audio, "audio/wav", InputSource::Url));- assert_eq!(model.cache_identity().as_deref(), Some("fixture-identity"));-}--#[test]-fn invalid_gateway_amount_discards_a_typed_charge_but_absent_metadata_preserves_it() {- let mut response = ModelResponse {- usage: Some(Usage {- charged_amount: Some(ChargedAmount::usd_micros(12)),- ..Usage::new(10, 5)- }),- ..ModelResponse::assistant("done")- };- normalize_charge(&mut response);- assert_eq!(response.usage.unwrap().charged_amount.unwrap().micros, 12);- response.raw = Some(serde_json::json!({"usage": {"buyer_cost_micro": -0.5, "cost": 0}}));- normalize_charge(&mut response);- assert!(response.usage.unwrap().charged_amount.is_none());-}--#[test]-fn authoritative_billing_source_presence_prevents_unknown_charge_refunds() {- for raw in [- serde_json::json!({"usage": {"buyer_cost_micro": null, "cost": 0}}),- serde_json::json!({"usage": {"buyer_cost_micro": "invalid", "cost": 0}}),- serde_json::json!({"usage": {"cost": "invalid"}}),- ] {- let mut response = ModelResponse {- usage: Some(Usage {- charged_amount: Some(ChargedAmount::usd_micros(12)),- ..Usage::new(10, 5)- }),- raw: Some(raw.clone()),- ..ModelResponse::assistant("done")- };- normalize_charge(&mut response);- assert!(response.usage.unwrap().charged_amount.is_none(), "{raw}");- }-}--#[test]-fn managed_backend_charge_precedes_generic_provider_billing() {- for (reported, expected) in [(0.0000064, Some(7)), (0.0, Some(0)), (-1.0, None)] {- let mut response = ModelResponse {- usage: Some(Usage::new(10, 5)),- raw: Some(serde_json::json!({- "openhuman_usage_meta": {"charged_amount_usd": reported},- "usage": {"buyer_cost_micro": 42, "cost": 1}- })),- ..ModelResponse::assistant("done")- };- normalize_charge(&mut response);- assert_eq!(- response- .usage- .unwrap()- .charged_amount- .map(|charge| charge.micros),- expected- );- }-}diff --git a/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rs b/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rsdeleted file mode 100644index c4a05030a8..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/compaction_carry.rs+++ /dev/null@@ -1,121 +0,0 @@-//! Carrying a turn's context compaction into the history the session persists.-//!-//! The harness compacts by folding older messages into a checkpoint inside the-//! run (`ContextCompressionMiddleware`) and reports the folded transcript on-//! `AgentRun::compacted_history`. The session driver, though, does not persist-//! the harness transcript verbatim: it rebuilds the turn's history from the-//! request plus the post-processed conversation (grounded close, required-//! output repair). So the fold is carried as *what* replaced the old messages-//! (the checkpoint) and *how much* of the tail survived (`kept_tail`-//! non-system messages), and re-applied to that rebuilt history.-//!-//! Persisting the compacted history makes the next turn start from the-//! checkpoint instead of re-reading and re-summarizing everything this turn-//! already folded. The runtime session sees a history that no longer extends-//! the persisted one, so it seals the current transcript generation and opens-//! the next: the full conversation stays on disk.--use tinyagents_harness::summarization::{find_safe_cutoff_point, is_checkpoint};-use tinyinference_llm::message::Message;--/// A turn's compaction, in a form that can be re-applied to the history the-/// session driver assembles.-#[derive(Debug, Clone, PartialEq)]-pub(crate) struct CompactionCarry {- /// The checkpoint message standing in for the folded history.- pub checkpoint: Message,- /// How many trailing non-system messages stay verbatim after it.- pub kept_tail: usize,-}--impl CompactionCarry {- /// The carry for a run's `compacted_history` (`None` when the run did not- /// compact, or the history carries no checkpoint).- pub(crate) fn from_compacted_history(compacted: &[Message]) -> Option<Self> {- let at = compacted.iter().position(is_checkpoint)?;- let kept_tail = compacted[at + 1..]- .iter()- .filter(|message| !matches!(message, Message::System(_)))- .count();- Some(Self {- checkpoint: compacted[at].clone(),- kept_tail,- })- }-- /// `history` with everything before its last `kept_tail` non-system- /// messages folded into the checkpoint.- ///- /// Leading system messages stay first and the checkpoint follows them.- /// System messages inside the folded range (mid-conversation notes) are- /// kept; earlier checkpoints are dropped, since this one supersedes them.- /// The cut is moved, if needed, so the kept tail never opens with a tool- /// result whose call was folded. A history with nothing before the kept- /// tail is returned unchanged.- pub(crate) fn apply(&self, history: Vec<Message>) -> Vec<Message> {- let lead = history- .iter()- .take_while(|message| matches!(message, Message::System(_)) && !is_checkpoint(message))- .count();- let body = &history[lead..];- let non_system: Vec<usize> = body- .iter()- .enumerate()- .filter(|(_, message)| !matches!(message, Message::System(_)))- .map(|(index, _)| index)- .collect();- if self.kept_tail >= non_system.len() {- tracing::debug!(- kept_tail = self.kept_tail,- messages = non_system.len(),- "[compaction_carry] nothing to fold; persisting the history unchanged"- );- return history;- }- let requested = non_system[non_system.len() - self.kept_tail];- let cut = find_safe_cutoff_point(body, requested);- if cut != requested {- tracing::debug!(- requested,- cut,- "[compaction_carry] moved the cut to keep tool calls paired"- );- }-- let mut compacted = Vec::with_capacity(lead + 1 + body.len() - cut);- compacted.extend(history[..lead].iter().cloned());- compacted.push(self.checkpoint.clone());- compacted.extend(- body[..cut]- .iter()- .filter(|message| matches!(message, Message::System(_)) && !is_checkpoint(message))- .cloned(),- );- compacted.extend(- body[cut..]- .iter()- .filter(|message| !is_checkpoint(message))- .cloned(),- );- tracing::info!(- full = history.len(),- compacted = compacted.len(),- kept_tail = self.kept_tail,- "[compaction_carry] persisting the compacted history"- );- compacted- }-}--/// The text of the latest real user message in `history`, skipping-/// compaction checkpoints (which are user-role but not the user's words).-pub(crate) fn last_user_message(history: &[Message]) -> Option<&Message> {- history- .iter()- .rev()- .find(|message| matches!(message, Message::User(_)) && !is_checkpoint(message))-}--#[cfg(test)]-#[path = "compaction_carry_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs b/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rsdeleted file mode 100644index aa30b40c3d..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs+++ /dev/null@@ -1,141 +0,0 @@-use super::*;-use tinyagents_harness::summarization::{checkpoint_message, SummaryPlacement};-use tinyinference_llm::tool::ToolCall;--fn checkpoint(body: &str) -> Message {- checkpoint_message(SummaryPlacement::User, body)-}--fn call(id: &str) -> Message {- let mut message = Message::assistant("");- if let Message::Assistant(assistant) = &mut message {- assistant- .tool_calls- .push(ToolCall::new(id, "read", serde_json::json!({})));- }- message-}--#[test]-fn reads_the_checkpoint_and_the_kept_tail() {- let compacted = vec![- Message::system("sys"),- checkpoint("summary"),- call("c3"),- Message::tool("c3", "out"),- Message::assistant("done"),- ];- let carry = CompactionCarry::from_compacted_history(&compacted).expect("carry");- assert_eq!(carry.checkpoint, checkpoint("summary"));- assert_eq!(carry.kept_tail, 3);- assert!(CompactionCarry::from_compacted_history(&[Message::user("hi")]).is_none());-}--#[test]-fn folds_everything_before_the_kept_tail() {- let carry = CompactionCarry {- checkpoint: checkpoint("summary"),- kept_tail: 3,- };- let history = vec![- Message::system("sys"),- Message::user("task"),- call("c1"),- Message::tool("c1", "one"),- call("c2"),- Message::tool("c2", "two"),- Message::assistant("done"),- ];- let compacted = carry.apply(history);- assert_eq!(- compacted,- vec![- Message::system("sys"),- checkpoint("summary"),- call("c2"),- Message::tool("c2", "two"),- Message::assistant("done"),- ]- );-}--#[test]-fn never_opens_the_kept_tail_with_an_orphan_tool_result() {- // Two kept non-system messages would start at c2's result; the cut moves- // back to include the call.- let carry = CompactionCarry {- checkpoint: checkpoint("summary"),- kept_tail: 2,- };- let history = vec![- Message::user("task"),- call("c2"),- Message::tool("c2", "two"),- Message::assistant("done"),- ];- let compacted = carry.apply(history);- assert_eq!(- compacted,- vec![- checkpoint("summary"),- call("c2"),- Message::tool("c2", "two"),- Message::assistant("done"),- ]- );-}--#[test]-fn replaces_an_older_checkpoint_and_keeps_mid_conversation_system_notes() {- let carry = CompactionCarry {- checkpoint: checkpoint("new"),- kept_tail: 1,- };- let history = vec![- Message::system("sys"),- checkpoint("old"),- Message::user("task"),- Message::system("note"),- Message::assistant("done"),- ];- let compacted = carry.apply(history);- assert_eq!(- compacted,- vec![- Message::system("sys"),- checkpoint("new"),- Message::system("note"),- Message::assistant("done"),- ]- );-}--#[test]-fn a_history_shorter_than_the_tail_is_unchanged() {- let carry = CompactionCarry {- checkpoint: checkpoint("summary"),- kept_tail: 5,- };- let history = vec![Message::system("sys"), Message::user("hi")];- assert_eq!(carry.apply(history.clone()), history);-}--#[test]-fn the_last_user_message_skips_checkpoints() {- let history = vec![Message::user("real"), checkpoint("summary"), call("c1")];- assert_eq!(last_user_message(&history), Some(&Message::user("real")));- assert_eq!(last_user_message(&[checkpoint("only")]), None);-}--#[test]-fn a_checkpoint_survives_the_session_transcript_round_trip() {- // The driver hands persisted history to the harness through the native- // transcript form; the checkpoint must still read as one on the far side,- // or the next turn would summarize it as raw history.- let original = checkpoint("## Goal\nship it");- let native = tinyagents_runtime::transcript::message_to_native_transcript(&original)- .expect("user rows convert");- let back = crate::agent::message_convert::chat_message_to_message(&native);- assert!(is_checkpoint(&back), "{back:?}");- assert_eq!(back.text(), original.text());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/call_effect.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/call_effect.rsdeleted file mode 100644index be59ea0c16..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/call_effect.rs+++ /dev/null@@ -1,285 +0,0 @@-//! Whether a tool call can change anything outside the conversation, read-//! from the tool's own declarations where it makes them.-//!-//! The failure breaker needs this to decide what a timeout means. A read that-//! timed out can simply be retried; an action that timed out may already have-//! happened, so retrying it can repeat an effect the agent cannot observe. It-//! used to answer from a five-name allowlist, so `use_skill` →-//! `composio_list_tools` and every other read outside that list halted the-//! turn on its first timeout.-//!-//! Sources, strongest first:-//!-//! 1. [`tinytools::Tool::external_effect_with_args`]: the approval gate's own-//! signal for an outbound message, payment, or remote write. Always wins.-//! 2. A classified [`tinytools::ToolPolicy`] declaring `read_only`, or a write,-//! destructive, install, or payment side effect.-//! 3. The operation verb in the tool's name (or, for a dispatcher, its-//! target's): a documented list in [`name_effect`]. A mutating verb wins-//! over a reading one, so `list_and_send` is an action.-//! 4. [`tinytools::Tool::permission_level_with_args`] at `ReadOnly` or below,-//! when the name carries no verb either way.-//!-//! Anything left over is [`CallEffect::Unknown`], which the breaker treats as-//! side-effecting.--use std::collections::HashMap;-use std::sync::Arc;--use serde_json::Value;-use tinytools::{PermissionLevel, Tool};--/// What a failed call may have done to the world.-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(crate) enum CallEffect {- /// Reads, lists, searches: safe to retry.- ReadOnly,- /// May have changed state outside the conversation.- SideEffecting,- /// Nothing says either way; treated as side-effecting.- #[default]- Unknown,-}--/// What a registered tool declares about one call.-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(crate) struct ToolEffectFacts {- /// From a classified `ToolPolicy`, when its side effects decide the- /// question (`None` for an unclassified tool, or one declaring only- /// network access).- pub(crate) classified: Option<CallEffect>,- /// `external_effect_with_args`: the approval gate's signal.- pub(crate) external: bool,- /// `permission_level_with_args` above `ReadOnly`.- pub(crate) elevated: bool,-}--/// Looks up the declarations of a registered tool by name, for these args.-pub(crate) type ToolFactsLookup =- Arc<dyn Fn(&str, &Value) -> Option<ToolEffectFacts> + Send + Sync>;--/// The facts `tool` declares for a call with `args`.-pub(crate) fn facts_for_tool(tool: &dyn Tool, args: &Value) -> ToolEffectFacts {- let policy = tool.policy();- let effects = &policy.side_effects;- let classified = if !policy.classified {- None- } else if effects.read_only {- Some(CallEffect::ReadOnly)- } else if effects.writes_files- || effects.installs_dependencies- || effects.destructive- || effects.payment- {- Some(CallEffect::SideEffecting)- } else {- None- };- ToolEffectFacts {- classified,- external: tool.external_effect_with_args(args),- elevated: tool.permission_level_with_args(args) > PermissionLevel::ReadOnly,- }-}--/// A lookup over the turn's registered tool sets.-pub(crate) fn tool_sets_lookup(tool_sets: Vec<Arc<Vec<Box<dyn Tool>>>>) -> ToolFactsLookup {- let mut index: HashMap<String, (usize, usize)> = HashMap::new();- for (set_idx, set) in tool_sets.iter().enumerate() {- for (tool_idx, tool) in set.iter().enumerate() {- index- .entry(tool.name().to_string())- .or_insert((set_idx, tool_idx));- }- }- Arc::new(move |name: &str, args: &Value| {- let (set_idx, tool_idx) = *index.get(name)?;- let tool = tool_sets.get(set_idx)?.get(tool_idx)?;- Some(facts_for_tool(tool.as_ref(), args))- })-}--/// The tool a dispatcher call actually reaches.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) struct DispatchTarget<'a> {- /// The skill (tool pack) named by the call, when the dispatcher has one.- pub(crate) skill: Option<&'a str>,- /// The target tool or action name.- pub(crate) tool: &'a str,- /// The arguments passed through to the target.- pub(crate) args: Option<&'a Value>,-}--/// The connector dispatcher whose `tool` argument is a Composio action slug.-const COMPOSIO_EXECUTE: &str = "composio_execute";--/// The target of a dispatcher tool call: `use_skill` (`skill`, `tool`,-/// `args`) or `composio_execute` (`tool`, `arguments`). `None` for any other-/// tool, or when the call names no target.-pub(crate) fn dispatch_target<'a>(tool: &str, args: &'a Value) -> Option<DispatchTarget<'a>> {- let (args_field, skill) = if tool == tinyagents_harness::tool::packs::USE_SKILL {- ("args", args.get("skill").and_then(Value::as_str))- } else if tool == COMPOSIO_EXECUTE {- ("arguments", None)- } else {- return None;- };- let target = args- .get("tool")- .and_then(Value::as_str)- .map(str::trim)- .filter(|name| !name.is_empty())?;- Some(DispatchTarget {- skill: skill.map(str::trim).filter(|s| !s.is_empty()),- tool: target,- args: args.get(args_field),- })-}--/// Operation verbs that read without changing anything.-const READING_VERBS: &[&str] = &[- "browse", "cat", "check", "count", "describe", "dig", "fetch", "find", "get", "grep", "info",- "inspect", "list", "lookup", "ls", "peek", "poll", "preview", "query", "read", "recall",- "retrieve", "search", "show", "stat", "status", "view", "whois",-];--/// Operation verbs that change state. One of these anywhere in the name makes-/// the call an action, even beside a reading verb.-const MUTATING_VERBS: &[&str] = &[- "add",- "apply",- "approve",- "archive",- "authorize",- "book",- "bridge",- "buy",- "cancel",- "clear",- "close",- "commit",- "connect",- "copy",- "create",- "delete",- "deploy",- "disable",- "disconnect",- "edit",- "enable",- "exec",- "execute",- "follow",- "forward",- "insert",- "install",- "invite",- "kill",- "like",- "mark",- "merge",- "mint",- "modify",- "move",- "open",- "patch",- "pay",- "post",- "publish",- "purchase",- "push",- "put",- "remove",- "rename",- "replace",- "reply",- "reset",- "restart",- "run",- "save",- "schedule",- "send",- "set",- "share",- "sign",- "star",- "start",- "stop",- "store",- "submit",- "swap",- "transfer",- "trash",- "uninstall",- "update",- "upload",- "upsert",- "write",-];--/// The effect the operation verbs in `name` imply: `Unknown` when it carries-/// none. Names are split on anything that is not a letter or digit, so-/// `composio_list_tools` and `GMAIL_FETCH_EMAILS` both read as reads.-pub(crate) fn name_effect(name: &str) -> CallEffect {- let mut reads = false;- for token in name- .split(|c: char| !c.is_ascii_alphanumeric())- .filter(|t| !t.is_empty())- {- let token = token.to_ascii_lowercase();- if MUTATING_VERBS.contains(&token.as_str()) {- return CallEffect::SideEffecting;- }- reads |= READING_VERBS.contains(&token.as_str());- }- if reads {- CallEffect::ReadOnly- } else {- CallEffect::Unknown- }-}--/// The effect of one tool (not a dispatcher) from its facts and its name.-fn leaf_effect(facts: Option<ToolEffectFacts>, name: &str) -> CallEffect {- if let Some(facts) = facts {- if facts.external {- return CallEffect::SideEffecting;- }- if let Some(classified) = facts.classified {- return classified;- }- }- match name_effect(name) {- CallEffect::Unknown => match facts {- Some(facts) if !facts.elevated => CallEffect::ReadOnly,- _ => CallEffect::Unknown,- },- known => known,- }-}--/// What a call to `tool` with `args` may have done. `lookup` supplies the-/// registered tools' declarations; without it only names are read.-///-/// A dispatcher is judged by its target, unless the dispatcher itself already-/// declares an external effect for these arguments (`composio_execute` does-/// for a mutating action slug).-pub(crate) fn call_effect(- lookup: Option<&ToolFactsLookup>,- tool: &str,- args: &Value,-) -> CallEffect {- let facts = lookup.and_then(|lookup| lookup(tool, args));- let Some(target) = dispatch_target(tool, args) else {- return leaf_effect(facts, tool);- };- if facts.is_some_and(|f| f.external || f.classified == Some(CallEffect::SideEffecting)) {- return CallEffect::SideEffecting;- }- let inner_args = target.args.unwrap_or(&Value::Null);- let inner_facts = lookup.and_then(|lookup| lookup(target.tool, inner_args));- // A target the lookup does not know (a Composio slug, a packed tool) is- // judged by its name alone: being reached through a read-only-declared- // dispatcher says nothing about it.- leaf_effect(inner_facts, target.tool)-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rsdeleted file mode 100644index 6e734e9b8f..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/loop_guards.rs+++ /dev/null@@ -1,39 +0,0 @@-//! Loop-guard thresholds and the repeat-call exemption shared by the-//! repeated-failure and repeat-progress breakers (issue #4463), ported verbatim-//! from the deleted `agent/harness/tool_loop.rs`. The halt-summary wording and-//! the terminal-inference recogniser live in the host copy table-//! (`inference::failure_copy`); the recoverable-failure marker list in-//! `tinyinference_llm::failure`.--// ── Loop-guard restorations (issue #4463) ────────────────────────────────────-//-// The TinyAgents migration dropped several loop breakers that the crate does not-// replace (verified against `harness::no_progress`, which tracks *failures*-// only): the recoverable-failure headroom, the terminal delegated-inference-// fast-halt (#3104), the policy-denied fast-trip, and the successful-repeat /-// identical-output guards (#4088 / #4095). These helpers + the-// [`RepeatProgressMiddleware`] below restore that behaviour seam-side, ported-// verbatim from the deleted `agent/harness/tool_loop.rs` thresholds/wording so-// the guards read identically to the legacy loop.--/// Recoverable/transient failures get more identical-retry headroom than the-/// deterministic default: a flaky network call or a timeout can succeed on a-/// later attempt once the model adapts (longer timeout, smaller batch, retry).-/// Mirrors the legacy `RECOVERABLE_REPEAT_FAILURE_THRESHOLD`.-pub(crate) const RECOVERABLE_REPEAT_FAILURE_THRESHOLD: u32 = 8;-/// Recoverable failures also get a larger *consecutive* (varied-args) no-progress-/// headroom before the breaker halts. Mirrors the legacy-/// `RECOVERABLE_NO_PROGRESS_FAILURE_THRESHOLD`.-pub(crate) const RECOVERABLE_NO_PROGRESS_FAILURE_THRESHOLD: u32 = 12;--/// Tools whose contract is to be re-invoked with identical arguments, so an-/// identical repeat is legitimate progress — not a no-progress loop. Today this-/// is `wait_subagent`, which polls a running async sub-agent and explicitly tells-/// the model to "call wait_subagent again" when a `timeout_secs` window elapses-/// while the sub-agent is still running. Without this exemption a task that-/// outlives two wait windows would have its third identical `wait_subagent`-/// halted by the no-progress breakers before it could collect the eventual-/// result. Ported from legacy `tool_loop::is_repeat_call_exempt` (Codex P1 on #4230).-pub(crate) fn is_repeat_call_exempt(tool: &str) -> bool {- matches!(tool, "wait_subagent")-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop.rsdeleted file mode 100644index cb8e8d5b9c..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop.rs+++ /dev/null@@ -1,116 +0,0 @@-//! Telling a repeat loop apart from a real blocker when the failure breaker-//! stops a run.-//!-//! The repeat guard (`RepeatProgressMiddleware`) answers a call that would-//! only return a result the model already holds with a refusal, and the call-//! never runs. A refused call is neither progress nor a failure, so it leaves-//! the classified ledger untouched. When a model keeps re-issuing one batch-//! of reads, one of them through a mistyped path, the guard refuses the-//! repeated reads and the mistyped read fails again with nothing in between-//! to clear its `not_found` count: the ledger stops the turn, and the user is-//! told "something this needs could not be found" when the turn was stuck-//! repeating itself. [`RepeatLoopWitness`] records what is needed to say so-//! instead.--use std::collections::HashSet;-use std::hash::{Hash, Hasher};-use std::sync::atomic::{AtomicUsize, Ordering};-use std::sync::Mutex;--/// Most failed-call signatures remembered in one run.-const MAX_FAILED_CALLS: usize = 256;--/// Classified-failure classes whose stop is relabelled when it comes from a-/// repeat loop: wrong calls the model could have corrected or dropped. A-/// security or credential refusal, an uncertain side effect, an unavailable-/// service or a transient failure keeps its own wording.-const CORRECTABLE_CLASSES: &[&str] = &[- "not_found",- "missing_window",- "missing_app",- "validation",- "invalid_arguments",- "task_failed",-];--/// Whether a classified stop of `class` may be explained by a repeat loop.-pub(super) fn is_correctable_class(class: &str) -> bool {- CORRECTABLE_CLASSES.contains(&class)-}--/// What the failure breaker has seen of the repeat guard and of repeated-/// failing calls in the current run.-#[derive(Default)]-pub(super) struct RepeatLoopWitness {- /// `tool\u{1f}argument-fingerprint\u{1f}outcome-hash` of every failure so- /// far.- failed_calls: Mutex<HashSet<String>>,- /// Calls the repeat guard refused since the last successful call.- refusals_since_progress: AtomicUsize,-}--impl RepeatLoopWitness {- /// A call ran and succeeded: the run is no longer only repeating itself.- pub(super) fn record_success(&self) {- self.refusals_since_progress.store(0, Ordering::SeqCst);- }-- /// The repeat guard refused a call. Returns the refusals since the last- /// success, this one included.- pub(super) fn record_refusal(&self) -> usize {- self.refusals_since_progress.fetch_add(1, Ordering::SeqCst) + 1- }-- /// Calls the repeat guard refused since the last success.- pub(super) fn refusals(&self) -> usize {- self.refusals_since_progress.load(Ordering::SeqCst)- }-- /// A call failed with `failure_text`. Returns whether the same tool- /// already failed with the same arguments and the same outcome earlier- /// in this run (an identical re-issue). The outcome is compared with its- /// volatile spans (timestamps, durations, request ids) normalised away; a- /// retry that fails differently (a task that got further, a different- /// error) is new evidence, not a repeat.- pub(super) fn record_failure(- &self,- tool: &str,- arg_fingerprint: &str,- failure_text: &str,- ) -> bool {- let mut hasher = std::collections::hash_map::DefaultHasher::new();- tinyagents_harness::no_progress::normalize_volatile(failure_text).hash(&mut hasher);- let key = format!("{tool}\u{1f}{arg_fingerprint}\u{1f}{:x}", hasher.finish());- let Ok(mut failed) = self.failed_calls.lock() else {- return false;- };- if failed.contains(&key) {- return true;- }- if failed.len() < MAX_FAILED_CALLS {- failed.insert(key);- }- false- }-}--/// The stop note for a run stopped while it re-issued calls it already had-/// results for. `error_line` is the failing call's scrubbed first error line.-///-/// It names the repeating as the cause (the note maps to the-/// "kept repeating the same step" reason, see-/// `session_host::stop_summary::StopReasonKind::from_stop_note`) and still-/// tells the model which call failed and how.-pub(super) fn repeat_loop_halt_summary(tool: &str, refusals: usize, error_line: &str) -> String {- format!(- "Stopping: the run kept re-issuing tool calls it already had results for — the repeat \- guard refused {refusals} identical successful call(s) — and `{tool}` was re-run with \- identical arguments and failed the same way again. Re-running steps adds no new \- information. Last error:\n{error_line}\n\nUse the results already in the conversation, \- correct the failing call, or report back instead of repeating it."- )-}--#[cfg(test)]-#[path = "repeat_loop_stop_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop_tests.rsdeleted file mode 100644index a38c898281..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeat_loop_stop_tests.rs+++ /dev/null@@ -1,69 +0,0 @@-use super::*;-use crate::agent::session_host::stop_summary::StopReasonKind;--#[test]-fn only_an_identical_re_issue_counts_as_a_repeated_failure() {- let witness = RepeatLoopWitness::default();- assert!(!witness.record_failure("file_read", "a", "No such file"));- assert!(!witness.record_failure("file_read", "b", "No such file"));- assert!(!witness.record_failure("grep", "a", "No such file"));- assert!(witness.record_failure("file_read", "a", "No such file"));-}--#[test]-fn a_retry_that_fails_differently_is_not_a_repeat() {- let witness = RepeatLoopWitness::default();- assert!(!witness.record_failure("browser_task", "a", "Task ended at step 2"));- assert!(!witness.record_failure("browser_task", "a", "Task ended at step 5"));- // Only volatile spans differ: still the same outcome.- assert!(!witness.record_failure("fetch", "u", "timed out after 31s"));- assert!(witness.record_failure("fetch", "u", "timed out after 47s"));-}--#[test]-fn a_success_clears_the_refusal_count() {- let witness = RepeatLoopWitness::default();- assert_eq!(witness.record_refusal(), 1);- assert_eq!(witness.record_refusal(), 2);- witness.record_success();- assert_eq!(witness.refusals(), 0);-}--#[test]-fn security_and_side_effect_classes_keep_their_own_wording() {- for class in [- "not_found",- "missing_window",- "validation",- "invalid_arguments",- ] {- assert!(is_correctable_class(class), "{class}");- }- for class in [- "policy",- "blocked_by_policy",- "authentication",- "permission",- "uncertain_side_effect",- "transient",- "unavailable",- ] {- assert!(!is_correctable_class(class), "{class}");- }-}--#[test]-fn the_repeat_loop_note_reads_as_a_repeating_step() {- let note = repeat_loop_halt_summary(- "file_read",- 2,- "Failed to resolve path 'src/lbi.rs': No such file or directory (os error 2)",- );- assert_eq!(- StopReasonKind::from_stop_note(¬e),- StopReasonKind::RepeatingStep,- "{note}"- );- let stop = crate::agent::turn_stop::TurnStop::breaker(¬e);- assert_eq!(stop.failure_class.as_deref(), Some("repeating_step"));-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rsdeleted file mode 100644index a563b3401e..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/research_budget.rs+++ /dev/null@@ -1,159 +0,0 @@-//! Bound direct web research so a run that keeps finding more leads still answers.-//!-//! Only web access is bounded. Once the budget is spent the web tools leave the-//! request and the run carries on with the rest; the turn is forced to answer-//! only when no other tool remains (#6959).--use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};--use async_trait::async_trait;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::{Middleware, ToolInvocationIdentity};-use tinyinference_llm::message::Message;-use tinyinference_llm::model::{ModelRequest, ToolChoice};-use tinytools::ToolResult;--use crate::agent::tinyagents::host::OpenHumanRunContext;--/// Direct web reads allowed before the web tools are withdrawn.-/// This bounds the master agent's exploratory search while leaving room to read-/// primary sources; broad research belongs in one deep `web_answer_tool` call or-/// a batched `web_contents_tool` read, each of which counts once.-pub(super) const DIRECT_WEB_READ_LIMIT: usize = 8;--/// The instruction appended when the budget is spent and no non-web tool-/// remains, so every tool is withdrawn. It says outright that tools are gone-/// and a call will not run: told only to "answer", a native model with a-/// transcript full of tool calls and no tool channel writes its next call as-/// plain-text markup (DeepSeek V4's-/// `<|DSML|invoke …>`), which then stood as the turn's answer. Replaying a-/// bench request that hit this budget, the old wording leaked a call 6 times in-/// 8 and this wording 0 times in 8. The harness also withholds and re-prompts-/// any call that still arrives (tinyagents `TextRecovery::withholding`).-pub(crate) const RESEARCH_CLOSE_INSTRUCTION: &str = "The direct web research budget for this turn is exhausted, and tools are no longer available for this reply: any tool call you write now will not run. Answer the user's latest request now in plain text, using only the results already available. State any remaining uncertainty. Do not search again, repeat a page fetch, or merely describe what you plan to read.";--/// The instruction appended when the budget is spent but the run still has-/// non-web tools: only web access is exhausted, not the task (#6959).-pub(crate) const WEB_BUDGET_EXHAUSTED_INSTRUCTION: &str = "The direct web research budget for this turn is exhausted, so the web tools have been removed. Continue the task with your remaining tools, using the web results already available. Do not try to search or fetch pages again.";--/// Consecutive failed web calls after which web access looks blocked.-const BLOCKED_AFTER_FAILURES: usize = 2;--/// The one-time note sent after [`BLOCKED_AFTER_FAILURES`] failed web calls in a-/// row (a blocked network, an offline sandbox).-pub(crate) const WEB_BLOCKED_NOTE: &str = "Web access looks blocked: the last web calls failed. Do not keep retrying web tools; continue the task with your other tools and the information already available.";--/// The direct web-read tools this budget governs: the `web_search` family-/// (`tools::user_filter`) plus `web_fetch`.-fn is_web_research_tool(name: &str) -> bool {- matches!(- name,- "web_search_tool" | "web_answer_tool" | "web_contents_tool" | "web_fetch"- )-}--#[derive(Default)]-pub(crate) struct ResearchBudgetMiddleware {- /// Successful web reads. A failed call read nothing and is not counted.- completed_reads: AtomicUsize,- /// Failed web calls since the last successful one.- consecutive_failures: AtomicUsize,- /// Set once the blocked note is due; cleared when it is sent.- blocked_note_pending: AtomicBool,- /// Whether the blocked note was already queued this run.- blocked_note_sent: AtomicBool,-}--impl ResearchBudgetMiddleware {- pub(crate) fn new() -> Self {- Self::default()- }-}--#[async_trait]-impl Middleware<(), OpenHumanRunContext> for ResearchBudgetMiddleware {- fn name(&self) -> &str {- "research_budget"- }-- async fn after_tool(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- invocation: &ToolInvocationIdentity,- result: &mut ToolResult,- ) -> TaResult<()> {- let tool = invocation.tool_name();- if !is_web_research_tool(tool) {- return Ok(());- }- if !result.is_error {- self.consecutive_failures.store(0, Ordering::Relaxed);- self.completed_reads.fetch_add(1, Ordering::Relaxed);- return Ok(());- }- let failures = self.consecutive_failures.fetch_add(1, Ordering::Relaxed) + 1;- tracing::debug!(- tool,- consecutive_failures = failures,- "[tinyagents::mw] research_budget: failed web call not counted against the budget"- );- if failures >= BLOCKED_AFTER_FAILURES- && !self.blocked_note_sent.swap(true, Ordering::Relaxed)- {- tracing::info!(- consecutive_failures = failures,- "[tinyagents::mw] research_budget: web access looks blocked; queueing one-time note"- );- self.blocked_note_pending.store(true, Ordering::Relaxed);- }- Ok(())- }-- async fn before_model(- &self,- _ctx: &mut RunContext<OpenHumanRunContext>,- _state: &(),- request: &mut ModelRequest,- ) -> TaResult<()> {- let reads = self.completed_reads.load(Ordering::Relaxed);- if reads < DIRECT_WEB_READ_LIMIT {- if self.blocked_note_pending.swap(false, Ordering::Relaxed) {- request- .messages- .push(Message::user(WEB_BLOCKED_NOTE.to_string()));- }- return Ok(());- }- // The budget note supersedes a pending blocked note: the web tools are- // gone either way.- self.blocked_note_pending.store(false, Ordering::Relaxed);- request- .tools- .retain(|tool| !is_web_research_tool(&tool.name));- if request.tools.is_empty() {- tracing::info!(- web_reads = reads,- "[tinyagents::mw] research_budget: budget reached and no non-web tool remains; concluding turn"- );- request.tool_choice = ToolChoice::None;- request- .messages- .push(Message::user(RESEARCH_CLOSE_INSTRUCTION.to_string()));- return Ok(());- }- tracing::info!(- web_reads = reads,- remaining_tools = request.tools.len(),- "[tinyagents::mw] research_budget: budget reached; withdrawing web tools only"- );- if matches!(&request.tool_choice, ToolChoice::Tool(name) if is_web_research_tool(name)) {- request.tool_choice = ToolChoice::Auto;- }- request- .messages- .push(Message::user(WEB_BUDGET_EXHAUSTED_INSTRUCTION.to_string()));- Ok(())- }-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget.rsdeleted file mode 100644index 4779f90f2f..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget.rs+++ /dev/null@@ -1,253 +0,0 @@-//! Keep a `shell` command's deadline inside the turn's wall-clock budget-//! (#6953).-//!-//! `timeout_secs` accepts up to an hour, and an omitted value runs unbounded,-//! with no regard for how much of the turn is left. When the turn's deadline-//! arrives mid-command the harness kills the whole turn, and the user gets no-//! answer. On Terminal-Bench a model started `timeout 600 …` three minutes-//! before the ceiling and the turn died in it.-//!-//! [`ShellTurnBudget`] clamps the deadline in `before_tool` to what the turn-//! has left minus [`SHELL_TIMEOUT_RESERVE`], so the command ends while there is-//! still time for a model call to answer. The model is told when it happens:-//!-//! - a requested `timeout_secs` that was reduced is always reported-//! (`[timeout_secs reduced from 660s to 170s: only 260s of the turn budget-//! remain]`), because the model chose that number;-//! - a deadline set on a command that asked for none is reported only if it-//! fired. Otherwise it changed nothing the model could see.-//!-//! Two middlewares share the state: [`ShellTimeoutClampMiddleware`] must run-//! after argument recovery so it edits real object arguments, and-//! [`ShellTimeoutNoteMiddleware`] must be registered early so its `after_tool`-//! runs after the output caps and the note survives them.--use std::collections::HashMap;-use std::sync::{Arc, Mutex};-use std::time::Duration;--use async_trait::async_trait;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::Result as TaResult;-use tinyagents_harness::middleware::{- Middleware, ToolInvocationIdentity, TurnClock, TurnClockMiddleware,-};-use tinyagents_harness::runtime::AgentHarness;--use crate::agent::tinyagents::host::OpenHumanRunContext;-use tinyinference_llm::tool::ToolCall;-use tinytools::ToolResult;--/// Time kept back from a shell command for the model to read its result and-/// answer.-pub(crate) const SHELL_TIMEOUT_RESERVE: Duration = Duration::from_secs(90);--/// The tool whose deadline this governs.-const SHELL_TOOL: &str = "shell";--/// The shell result prefix when its own `timeout_secs` killed the command.-const SHELL_TIMED_OUT: &str = "Command timed out after";--/// One clamp applied to a shell call.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(crate) struct ShellTimeoutClamp {- /// The model's `timeout_secs`, or `None` when it asked for no deadline.- pub requested: Option<u64>,- /// The deadline the command runs under.- pub clamped_secs: u64,- /// Turn budget left when the call started.- pub remaining_secs: u64,-}--impl ShellTimeoutClamp {- /// The line appended to the call's result.- pub(crate) fn note(&self) -> String {- let (clamped, remaining) = (self.clamped_secs, self.remaining_secs);- match self.requested {- Some(requested) => format!(- "[timeout_secs reduced from {requested}s to {clamped}s: only {remaining}s of the turn budget remain]"- ),- None => format!(- "[timeout_secs set to {clamped}s: only {remaining}s of the turn budget remain]"- ),- }- }-}--/// The deadline a shell call may have with `remaining` turn budget left, or-/// `None` when `requested` already fits.-///-/// The cap is what is left minus [`SHELL_TIMEOUT_RESERVE`]. When less than-/// twice the reserve is left, it is half of what is left, so the command and-/// the answer split it. It is never below one second, because `0` means-/// unbounded to the shell. A missing or `0` request is unbounded and always-/// exceeds the cap.-pub(crate) fn clamp_shell_timeout(- requested: Option<u64>,- remaining: Duration,-) -> Option<ShellTimeoutClamp> {- let requested = requested.filter(|secs| *secs > 0);- let cap = remaining- .saturating_sub(SHELL_TIMEOUT_RESERVE)- .max(remaining / 2)- .as_secs()- .clamp(1, tinytools_std::timeout::MAX_TIMEOUT_SECS);- if requested.is_some_and(|secs| secs <= cap) {- return None;- }- Some(ShellTimeoutClamp {- requested,- clamped_secs: cap,- remaining_secs: remaining.as_secs(),- })-}--/// Shared state: the turn's budget and the clamps waiting to be reported,-/// keyed by call id.-pub(crate) struct ShellTurnBudget {- /// The harness policy's wall-clock budget for the turn (see- /// [`TurnClock::of`]).- budget: Option<Duration>,- pending: Mutex<HashMap<String, ShellTimeoutClamp>>,-}--impl ShellTurnBudget {- pub(crate) fn new(budget: Option<Duration>) -> Arc<Self> {- Arc::new(Self {- budget,- pending: Mutex::default(),- })- }-- /// The `before_tool` half, which rewrites the call's `timeout_secs`.- pub(crate) fn clamp(self: &Arc<Self>) -> ShellTimeoutClampMiddleware {- ShellTimeoutClampMiddleware(Arc::clone(self))- }-- /// The `after_tool` half, which reports a clamp on the call's result.- pub(crate) fn notes(self: &Arc<Self>) -> ShellTimeoutNoteMiddleware {- ShellTimeoutNoteMiddleware(Arc::clone(self))- }-- fn pending(&self) -> std::sync::MutexGuard<'_, HashMap<String, ShellTimeoutClamp>> {- self.pending- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- }-}--/// Clamps a `shell` call's `timeout_secs` to the turn's remainder.-pub(crate) struct ShellTimeoutClampMiddleware(Arc<ShellTurnBudget>);--#[async_trait]-impl<C: Send + Sync> Middleware<(), C> for ShellTimeoutClampMiddleware {- fn name(&self) -> &str {- "shell_turn_budget"- }-- async fn before_tool(- &self,- ctx: &mut RunContext<C>,- _state: &(),- call: &mut ToolCall,- ) -> TaResult<()> {- if call.name != SHELL_TOOL {- return Ok(());- }- let Some(clock) = TurnClock::of(ctx, self.0.budget) else {- return Ok(());- };- let Some(arguments) = call.arguments.as_object_mut() else {- return Ok(());- };- let requested = match arguments.get("timeout_secs") {- Some(value) => {- let Some(requested) = value.as_u64() else {- // A malformed explicit value belongs to shell's existing- // schema/argument validation path; do not silently fix it.- return Ok(());- };- Some(requested)- }- None => None,- };- let Some(clamp) = clamp_shell_timeout(requested, clock.remaining()) else {- return Ok(());- };- tracing::debug!(- run_id = %ctx.run_id(),- call_id = %call.id,- requested_secs = ?clamp.requested,- clamped_secs = clamp.clamped_secs,- remaining_secs = clamp.remaining_secs,- "[tinyagents::mw] shell_turn_budget: clamping shell timeout_secs to the turn remainder"- );- arguments.insert("timeout_secs".to_string(), clamp.clamped_secs.into());- self.0.pending().insert(call.id.clone(), clamp);- Ok(())- }-}--/// Reports a clamp on the clamped call's result.-pub(crate) struct ShellTimeoutNoteMiddleware(Arc<ShellTurnBudget>);--#[async_trait]-impl<C: Send + Sync> Middleware<(), C> for ShellTimeoutNoteMiddleware {- fn name(&self) -> &str {- "shell_turn_budget_note"- }-- async fn after_tool(- &self,- _ctx: &mut RunContext<C>,- _state: &(),- invocation: &ToolInvocationIdentity,- result: &mut ToolResult,- ) -> TaResult<()> {- let Some(clamp) = self.0.pending().remove(invocation.call_id().as_str()) else {- return Ok(());- };- let fired = result.is_error && super::tool_result_text(result).starts_with(SHELL_TIMED_OUT);- if clamp.requested.is_none() && !fired {- return Ok(());- }- tracing::debug!(- call_id = %invocation.call_id(),- fired,- "[tinyagents::mw] shell_turn_budget: reporting the clamped timeout to the model"- );- super::append_tool_result_text(result, format!("\n{}", clamp.note()));- Ok(())- }-}--/// Install the turn's time notes and return the shell budget whose-/// [`clamp`](ShellTurnBudget::clamp) the caller pushes after argument recovery.-///-/// Pushes [`TurnClockMiddleware`] (`[turn budget: …]` once per tenth of the-/// budget past half) and [`ShellTurnBudget::notes`]. Call it before the-/// repeat-progress guard: `after_tool` runs in reverse registration order, so-/// these notes are appended after every output cap (they survive truncation)-/// and after the guard has fingerprinted the result (a changing note does not-/// make two identical results look different).-pub(crate) fn install_time_notes(- harness: &mut AgentHarness<(), OpenHumanRunContext>,-) -> Arc<ShellTurnBudget> {- let budget = harness- .policy()- .limits- .max_wall_clock_ms- .map(Duration::from_millis);- tracing::debug!(- budget_ms = ?budget.map(|b| b.as_millis() as u64),- "[tinyagents::mw] installing turn clock and shell turn-budget notes"- );- harness.push_middleware(Arc::new(TurnClockMiddleware::new(budget)));- let shell = ShellTurnBudget::new(budget);- harness.push_middleware(Arc::new(shell.notes()));- shell-}--#[cfg(test)]-#[path = "shell_turn_budget_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget_tests.rsdeleted file mode 100644index f4fbf74ab5..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/shell_turn_budget_tests.rs+++ /dev/null@@ -1,189 +0,0 @@-use super::*;-use serde_json::json;-use tinyagents_harness::context::RunConfig;-use tinyagents_harness::middleware::ToolInvocationIdentity;--const SECS: fn(u64) -> Duration = Duration::from_secs;--#[test]-fn a_timeout_past_the_turn_remainder_is_reduced_to_leave_a_reserve() {- let clamp = clamp_shell_timeout(Some(660), SECS(260)).expect("660s does not fit in 260s");- assert_eq!(clamp.requested, Some(660));- assert_eq!(clamp.clamped_secs, 170);- assert_eq!(- clamp.note(),- "[timeout_secs reduced from 660s to 170s: only 260s of the turn budget remain]"- );-}--#[test]-fn a_timeout_that_fits_is_left_alone() {- assert_eq!(clamp_shell_timeout(Some(100), SECS(260)), None);- assert_eq!(clamp_shell_timeout(Some(170), SECS(260)), None);-}--#[test]-fn an_unbounded_command_gets_the_turn_remainder_as_its_deadline() {- for requested in [None, Some(0)] {- let clamp = clamp_shell_timeout(requested, SECS(3_600)).expect("unbounded is clamped");- assert_eq!(clamp.requested, None);- assert_eq!(clamp.clamped_secs, 3_510);- assert_eq!(- clamp.note(),- "[timeout_secs set to 3510s: only 3600s of the turn budget remain]"- );- }-}--#[test]-fn injected_timeout_never_exceeds_the_shell_schema_maximum() {- let clamp = clamp_shell_timeout(None, SECS(7_200)).expect("unbounded is clamped");- assert_eq!(clamp.clamped_secs, tinytools_std::timeout::MAX_TIMEOUT_SECS);-}--#[test]-fn near_the_deadline_the_command_gets_half_of_what_is_left() {- // Less than twice the reserve left: the reserve would eat everything, so- // the command and the answer split what remains.- assert_eq!(- clamp_shell_timeout(Some(600), SECS(100))- .unwrap()- .clamped_secs,- 50- );- assert_eq!(- clamp_shell_timeout(Some(600), Duration::ZERO)- .unwrap()- .clamped_secs,- 1,- "never zero, which the shell reads as unbounded"- );-}--fn shell_call(arguments: serde_json::Value) -> ToolCall {- ToolCall::new("call-1", "shell", arguments)-}--/// A context whose 1 ms budget is already spent, so the clamp fires without-/// depending on scheduling.-fn spent_context() -> RunContext<()> {- let ctx = RunContext::new(RunConfig::new("r").with_timeout_ms(1), ());- std::thread::sleep(Duration::from_millis(5));- ctx-}--async fn before(budget: &Arc<ShellTurnBudget>, ctx: &mut RunContext<()>, call: &mut ToolCall) {- Middleware::<(), ()>::before_tool(&budget.clamp(), ctx, &(), call)- .await- .expect("before_tool succeeds");-}--async fn after(budget: &Arc<ShellTurnBudget>, ctx: &mut RunContext<()>, result: &mut ToolResult) {- let identity = ToolInvocationIdentity::new("call-1", "shell");- Middleware::<(), ()>::after_tool(&budget.notes(), ctx, &(), &identity, result)- .await- .expect("after_tool succeeds");-}--#[tokio::test]-async fn a_late_shell_call_is_clamped_and_told_why() {- let budget = ShellTurnBudget::new(None);- let mut ctx = spent_context();- let mut call = shell_call(json!({"command": "make", "timeout_secs": 660}));- before(&budget, &mut ctx, &mut call).await;- assert_eq!(call.arguments["timeout_secs"], json!(1));- assert_eq!(call.arguments["command"], json!("make"));-- let mut result = ToolResult::success("built");- after(&budget, &mut ctx, &mut result).await;- let out = result.output();- assert!(out.starts_with("built"), "{out}");- assert!(- out.contains("[timeout_secs reduced from 660s to 1s: only 0s of the turn budget remain]"),- "{out}"- );-- let mut next = ToolResult::success("again");- after(&budget, &mut ctx, &mut next).await;- assert_eq!(next.output(), "again", "a clamp is reported once");-}--#[tokio::test]-async fn an_injected_deadline_is_reported_only_when_it_fires() {- let budget = ShellTurnBudget::new(None);- let mut ctx = spent_context();-- let mut call = shell_call(json!({"command": "ls"}));- before(&budget, &mut ctx, &mut call).await;- assert_eq!(call.arguments["timeout_secs"], json!(1));- let mut quick = ToolResult::success("listing");- after(&budget, &mut ctx, &mut quick).await;- assert_eq!(quick.output(), "listing");-- let mut call = shell_call(json!({"command": "sleep 100"}));- before(&budget, &mut ctx, &mut call).await;- let mut killed = ToolResult::error(- "Command timed out after 1s and was killed: the shell tool's timeout_secs limit fired.",- );- after(&budget, &mut ctx, &mut killed).await;- assert!(- killed.output().contains("[timeout_secs set to 1s:"),- "{}",- killed.output()- );-}--#[tokio::test]-async fn other_tools_and_early_calls_are_untouched() {- let budget = ShellTurnBudget::new(None);- let mut ctx = spent_context();- let mut other = ToolCall::new("call-1", "file_read", json!({"path": "a"}));- before(&budget, &mut ctx, &mut other).await;- assert_eq!(other.arguments, json!({"path": "a"}));-- let roomy = ShellTurnBudget::new(Some(SECS(3_600)));- let mut ctx = RunContext::new(RunConfig::new("r"), ());- let mut call = shell_call(json!({"command": "make", "timeout_secs": 600}));- before(&roomy, &mut ctx, &mut call).await;- assert_eq!(call.arguments["timeout_secs"], json!(600));-}--#[tokio::test]-async fn a_turn_without_a_deadline_is_untouched() {- let budget = ShellTurnBudget::new(None);- let mut ctx = RunContext::new(RunConfig::new("r"), ());- let mut call = shell_call(json!({"command": "make"}));- before(&budget, &mut ctx, &mut call).await;- assert_eq!(call.arguments, json!({"command": "make"}));-}--#[tokio::test]-async fn malformed_explicit_timeout_is_left_for_argument_validation() {- let budget = ShellTurnBudget::new(None);- let mut ctx = spent_context();-- for value in [json!("5"), json!(-1), json!(null)] {- let mut call = shell_call(json!({"command": "make", "timeout_secs": value}));- let original = call.arguments.clone();- before(&budget, &mut ctx, &mut call).await;- assert_eq!(call.arguments, original);- }-}--#[test]-fn installing_reads_the_turn_ceiling_from_the_harness_policy() {- let mut harness: AgentHarness<(), OpenHumanRunContext> = AgentHarness::new();- let mut policy = harness.policy().clone();- policy.limits.max_wall_clock_ms = Some(120_000);- harness.with_policy(policy);- let before = harness.middleware().len();-- let shell = install_time_notes(&mut harness);-- assert_eq!(shell.budget, Some(SECS(120)));- assert_eq!(- harness.middleware().len(),- before + 2,- "the turn clock and the shell notes are both installed"- );-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/stop_latch.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/stop_latch.rsdeleted file mode 100644index c771b44c90..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/stop_latch.rs+++ /dev/null@@ -1,207 +0,0 @@-//! [`StopLatch`]: how the failure breaker records why it stopped a run.-//!-//! The stop-note slot ([`HaltSummarySlot`]) is shared by the failure breaker,-//! the repeat guard (`RepeatProgressMiddleware`) and the stop hooks, and the-//! user-facing stop summary is derived from whatever note it holds when the-//! run ends (`session_host::stop_summary`). A stop only takes effect at the-//! top of the next iteration, so every remaining result of the batch still-//! reaches the breakers after one of them stopped the run. The first breaker-//! to stop the run is its cause, so no breaker replaces a note already there-//! (the repeat guard follows the same contract in `tinyagents`). The failure-//! breaker used to overwrite it: the repeat guard stopping a run while-//! admitting a batch of re-reads, then a mistyped path in that batch failing-//! again, was summarised as "something this needs could not be found".-//!-//! The latch also relabels a classified stop that a repeat loop produced (see-//! [`super::repeat_loop_stop`]), and takes the relabel back when the rest of-//! the batch shows progress.--use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::Mutex;--use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};--use super::repeat_loop_stop::{is_correctable_class, repeat_loop_halt_summary, RepeatLoopWitness};-use crate::agent::tinyagents::HaltSummarySlot;--/// The failure breaker's side of the shared stop-note slot.-pub(super) struct StopLatch {- handle: SteeringHandle,- slot: HaltSummarySlot,- /// The note this breaker latched in the current run.- own: Mutex<Option<String>>,- /// Repeat-guard refusals and repeated failing calls in the current run.- witness: RepeatLoopWitness,- /// `(tool, error line)` of a latched classified stop on an identical- /// re-issue that no refusal has explained yet. A refusal later in the- /// same batch relabels the stop as a repeat loop.- candidate: Mutex<Option<(String, String)>>,- /// The classified note a repeat-loop relabel replaced. A success later in- /// the batch shows progress and puts it back.- relabelled_from: Mutex<Option<String>>,- /// Whether a call in the current model response's tool batch succeeded.- /// A batch that produced anything new is never relabelled as a repeat- /// loop, whatever order its results fold back in.- batch_progress: AtomicBool,-}--impl StopLatch {- /// A latch that pauses runs through `handle` and records notes in `slot`.- pub(super) fn new(handle: SteeringHandle, slot: HaltSummarySlot) -> Self {- Self {- handle,- slot,- own: Mutex::default(),- witness: RepeatLoopWitness::default(),- candidate: Mutex::default(),- relabelled_from: Mutex::default(),- batch_progress: AtomicBool::new(false),- }- }-- /// What has been seen of the repeat guard and of repeated failures.- pub(super) fn witness(&self) -> &RepeatLoopWitness {- &self.witness- }-- /// Stop the run, recording `summary` as its stop note unless another- /// breaker already stopped it. The pause is sent either way; it is- /// idempotent. Returns whether `summary` became the stop note.- pub(super) fn halt(&self, summary: String) -> bool {- let latched = match self.slot.lock() {- Ok(mut slot) => match slot.as_deref() {- Some(existing) => {- tracing::debug!(- existing = %crate::util::truncate_with_ellipsis(existing, 80),- "[tinyagents::mw] run already stopped by an earlier breaker; keeping its stop note"- );- false- }- None => {- *slot = Some(summary.clone());- if let Ok(mut own) = self.own.lock() {- *own = Some(summary);- }- true- }- },- Err(_) => false,- };- self.handle.send(SteeringCommand::Pause);- latched- }-- /// Stop the run for an exhausted classified-failure budget.- ///- /// When the failing call is an identical re-issue (`repeated`) of a- /// correctable class and the repeat guard has refused calls since the- /// last success, the run was looping, and the note says so. With no- /// refusal yet, a refusal later in the batch can still relabel it- /// ([`Self::record_refusal`]).- pub(super) fn halt_classified(- &self,- summary: String,- class: &str,- tool: &str,- repeated: bool,- error_line: impl FnOnce() -> String,- ) {- if !(repeated && is_correctable_class(class)) {- self.halt(summary);- return;- }- let error_line = error_line();- // Only the stop that owns the note may be relabelled: a second stop- // in the batch must not lend it its tool and error.- if !self.halt(summary) {- return;- }- match self.witness.refusals() {- 0 => {- if let Ok(mut candidate) = self.candidate.lock() {- *candidate = Some((tool.to_owned(), error_line));- }- }- refusals => self.relabel(repeat_loop_halt_summary(tool, refusals, &error_line)),- }- }-- /// The repeat guard refused a call. Relabels this breaker's classified- /// stop as a repeat loop if it is waiting for that evidence.- pub(super) fn record_refusal(&self) {- let refusals = self.witness.record_refusal();- let Some((tool, error_line)) = self.candidate.lock().ok().and_then(|mut c| c.take()) else {- return;- };- self.relabel(repeat_loop_halt_summary(&tool, refusals, &error_line));- }-- /// A call ran and succeeded. The run made progress, so neither the- /// refusals around it nor a stop latched earlier in its batch can be- /// explained as a repeat loop: a pending relabel is dropped and a relabel- /// already made is taken back.- pub(super) fn record_success(&self) {- self.batch_progress.store(true, Ordering::SeqCst);- self.witness.record_success();- if let Ok(mut candidate) = self.candidate.lock() {- *candidate = None;- }- let original = self.relabelled_from.lock().ok().and_then(|mut r| r.take());- if let Some(original) = original {- tracing::debug!(- "[tinyagents::mw] a success followed a repeat-loop stop; restoring the classified stop note"- );- self.replace_own_note(original);- }- }-- /// A model response asked for a new tool batch: nothing in it has- /// succeeded yet.- pub(super) fn start_batch(&self) {- self.batch_progress.store(false, Ordering::SeqCst);- }-- /// End of a run: forget its latch state.- pub(super) fn finish_run(&self) {- for state in [&self.own, &self.relabelled_from] {- if let Ok(mut state) = state.lock() {- *state = None;- }- }- if let Ok(mut candidate) = self.candidate.lock() {- *candidate = None;- }- }-- /// Replace this breaker's latched note with the repeat-loop `summary`,- /// keeping the classified note so progress can restore it.- fn relabel(&self, summary: String) {- if self.batch_progress.load(Ordering::SeqCst) {- tracing::debug!(- "[tinyagents::mw] the stop's batch made progress; keeping the classified stop note"- );- return;- }- if let Some(original) = self.replace_own_note(summary) {- tracing::debug!(- "[tinyagents::mw] classified stop came from a repeat loop; relabelled its stop note"- );- if let Ok(mut relabelled_from) = self.relabelled_from.lock() {- relabelled_from.get_or_insert(original);- }- }- }-- /// Swap `summary` in for this breaker's note, if that note is still the- /// run's stop note. Returns the note it replaced.- fn replace_own_note(&self, summary: String) -> Option<String> {- let (Ok(mut slot), Ok(mut own)) = (self.slot.lock(), self.own.lock()) else {- return None;- };- if own.is_none() || *slot != *own {- return None;- }- *slot = Some(summary.clone());- own.replace(summary)- }-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rsdeleted file mode 100644index 99c2f654cb..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rs+++ /dev/null@@ -1,485 +0,0 @@-//! A named output file that was never written, caught before the turn ends.-//!-//! # Why this exists-//!-//! The turn already carries four rungs that *tell* the model to produce its-//! deliverable: the budget notice part-way through, the penultimate call's-//! narrowed writer belt, the concluding call's instruction, and the-//! requirements check. Every one of them is advice, and the orchestrator-//! prompt's rule ("when the request names an output file, that file is the-//! deliverable") is advice too. None of them observes whether anything was-//! written, so a turn that ignores all five ends with a careful account of-//! work nobody can use.-//!-//! That is not hypothetical. One run reconstructed a transcript, catalogued-//! eleven variants and resolved the domain it was asked for, listed the output-//! file in its own answer as "still outstanding", and ended the turn. Every-//! check that read the file failed on the file's absence rather than on-//! anything it contained; an earlier run of the same request, which wrote a-//! partly-filled file, was scored on its contents.-//!-//! # How a path is identified without parsing the request-//!-//! The obvious objection to reading paths out of a request is telling an-//! output from an input: a request routinely names both. Grammar ("write to"-//! versus "read from") would be the fragile way to decide.-//!-//! The existence check decides it instead, for free. A path the request names-//! as an input is already on disk, so it is never reported. A path that the-//! request names and that nothing has created is, by construction, either a-//! deliverable that was skipped or a path the request mentioned in passing —-//! and the cost of the second case is one advisory sentence.--use std::collections::{HashMap, HashSet};-use std::sync::{Arc, Mutex};--use async_trait::async_trait;-use tinyagents_harness::context::RunContext;-use tinyagents_harness::error::{Result, TinyAgentsError};-use tinyagents_harness::middleware::library::TurnClock;-use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::middleware::ToolInvocationIdentity;-use tinyagents_harness::runtime::AgentHarness;-use tinyagents_harness::tinyinference_llm::message::Message;-use tinyagents_harness::tinyinference_llm::model::{ModelRequest, ModelResponse};-use tinytools::{ToolContent, ToolResult as TaToolResult};--use crate::agent::session_host::turn_checkpoint::wrap_harness_instruction;--/// Leave the model room to act on the notice. Below this the turn cannot both-/// write a file and answer, so the notice would only cost a call.-const MIN_REMAINING_MODEL_CALLS: usize = 3;--/// How many candidates one request may contribute. A request naming more-/// absolute paths than this is describing a tree, not a deliverable, and-/// statting an unbounded list on the concluding call is not worth it.-const MAX_CANDIDATES: usize = 8;--/// Longest plausible path. Anything longer is prose that happens to contain-/// slashes.-const MAX_PATH_CHARS: usize = 200;--/// Characters that continue a path token. Everything else — whitespace,-/// quotes, backticks, brackets, commas — ends it.-fn is_path_char(c: char) -> bool {- c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | '+' | '@' | '%')-}--/// Whether `segment` ends in a file extension: a dot followed by 1-8-/// alphanumerics, and not the whole segment (so a dotfile is not an-/// extension).-fn has_extension(segment: &str) -> bool {- match segment.rsplit_once('.') {- Some((stem, ext)) => {- !stem.is_empty()- && (1..=8).contains(&ext.len())- && ext.chars().all(|c| c.is_ascii_alphanumeric())- }- None => false,- }-}--/// Absolute paths with a file extension that `text` names, in order, deduped-/// and capped at [`MAX_CANDIDATES`].-///-/// Absolute only: a relative token in prose ("see config/settings.yml") is far-/// more often a reference than a deliverable, and a relative path cannot be-/// resolved without assuming the turn's working directory. An extension is-/// required for the same reason — it is what separates a file the request asks-/// for from a directory or a sentence fragment. Both limits mean this reports-/// nothing rather than guessing when a request is written loosely.-pub(crate) fn candidate_paths(text: &str) -> Vec<String> {- let mut seen = HashSet::new();- let mut out = Vec::new();- let bytes: Vec<char> = text.chars().collect();- let mut index = 0;- while index < bytes.len() {- if bytes[index] != '/' {- index += 1;- continue;- }- // A path starts at a `/` that does not continue a token (so `a/b` in- // prose is not read as rooted at `/b`), and not at the `//` of a URL- // (`https://host/report.pdf` is not a local file).- if index > 0 && (is_path_char(bytes[index - 1]) || bytes[index - 1] == ':') {- index += 1;- continue;- }- if bytes.get(index + 1) == Some(&'/') {- index += 1;- continue;- }- let start = index;- while index < bytes.len() && is_path_char(bytes[index]) {- index += 1;- }- let token: String = bytes[start..index].iter().collect();- let token = token.trim_end_matches(['.', '-', '_', '+']);- if token.len() < 3 || token.len() > MAX_PATH_CHARS {- continue;- }- // `..` is never statted: a request that needs traversal to name its- // own output is not a case this should act on.- if token.contains("..") {- continue;- }- let mut segments = token.split('/').filter(|s| !s.is_empty());- let Some(first) = segments.next() else {- continue;- };- let Some(last) = token.rsplit('/').next() else {- continue;- };- // At least two segments: `/report.json` at the filesystem root is far- // more likely a stray token than a deliverable.- if first == last || !has_extension(last) {- continue;- }- if seen.insert(token.to_string()) {- out.push(token.to_string());- if out.len() >= MAX_CANDIDATES {- break;- }- }- }- out-}--/// The notice, naming every candidate that does not exist.-pub(crate) fn notice(missing: &[String]) -> String {- let list = missing- .iter()- .map(|path| format!("`{path}`"))- .collect::<Vec<_>>()- .join(", ");- let (subject, verb) = if missing.len() == 1 {- ("a file", "does not exist")- } else {- ("files", "do not exist")- };- wrap_harness_instruction(&format!(- "The request names {subject} that {verb} here: {list}. If that is the file this turn \- was asked to produce, nothing has been written there and none of this turn's work \- is available to whoever asked for it: write it now with whatever you have \- established, even where fields are incomplete or provisional, and then answer. A \- file holding the parts you are sure of is worth more than a description of what it \- would have contained; mark anything provisional inside it, or say in your reply what \- is still missing. If the path refers to a file that lives elsewhere (another \- machine, a container, a service), say so and answer as before."- ))-}--/// Per-run state: the candidates read off the request, and whether the notice-/// has already been given.-#[derive(Default)]-struct RunState {- candidates: Option<Vec<String>>,- fired: bool,- /// The half-time note (a requested path still absent at 50% of the- /// clock) has been appended to a tool result.- half_noted: bool,- /// The late note (80% of the clock: stop exploring, measure every stated- /// limit) has been appended.- late_noted: bool,-}--/// Share of the turn's wall clock after which a requested path that still-/// does not exist is pointed out on the next tool result.-const HALF_TIME_BAND: u32 = 5;-/// Share of the turn's wall clock after which exploring stops being worth-/// it and the note says so.-const LATE_BAND: u32 = 8;--/// The note for a requested path still absent at half-time. The deliverable-/// written now and improved in place beats one written in the last minute:-/// one run spent eight of its nine minutes probing an input format, wrote-/// the program at minute fourteen of fifteen, and had no time left to make-/// it meet the size limit the request stated.-fn half_time_note(missing: &[String], clock: &TurnClock) -> String {- let list = missing- .iter()- .map(|path| format!("`{path}`"))- .collect::<Vec<_>>()- .join(", ");- wrap_harness_instruction(&format!(- "Half the turn's budget is gone ({} left) and nothing exists here yet at {list}. If \- that is the file this turn was asked to produce, write it now from what you have \- established, even if provisional, then improve it in place; measure every limit the \- request states against it as you go. Exploring further before it exists risks \- ending with nothing to judge. If the path refers to a file that lives elsewhere \- (another machine, a container, a service), say so in your answer.",- clock_text(clock.remaining())- ))-}--/// The note at 80% of the clock, whether or not the deliverable exists.-fn late_note(clock: &TurnClock) -> String {- wrap_harness_instruction(&format!(- "{} of the turn's budget left. Stop exploring: make what exists meet every limit, \- format and interface the request names, measure each one through the exact interface \- it will be judged by, and finish. A result that meets the stated limits beats a better \- one that is not written.",- clock_text(clock.remaining())- ))-}--/// `1m 30s`-style rendering of what is left on the clock.-fn clock_text(d: std::time::Duration) -> String {- let secs = d.as_secs();- if secs >= 60 {- format!("{}m {:02}s", secs / 60, secs % 60)- } else {- format!("{secs}s")- }-}--/// Appends `note` after the result's own content, in the plain blocks and in-/// the markdown rendering, the way the harness's own clock note is appended.-fn append_note(result: &mut TaToolResult, note: &str) {- result.content.push(ToolContent::Text {- text: format!("\n{note}"),- });- if let Some(markdown) = result.markdown_formatted.as_mut() {- markdown.push('\n');- markdown.push_str(note);- }-}--/// Holds a turn's first final answer once, when the request named an output-/// file that nothing has created. See the module docs.-pub(crate) struct UnmetDeliverableMiddleware {- runs: Mutex<HashMap<u64, RunState>>,- /// The turn\'s wall-clock budget, handed over at construction like the- /// other time-note middlewares: the run context does not carry it.- budget: Option<std::time::Duration>,-}--impl UnmetDeliverableMiddleware {- pub(crate) fn new(budget: Option<std::time::Duration>) -> Self {- Self {- runs: Mutex::default(),- budget,- }- }-- /// Which of `candidates` are not regular files (a directory written at a- /// `.csv` path is as unmet as nothing at all). Existence only: nothing is- /// opened or read, and the paths echoed back are the ones the request- /// already carried.- fn missing(candidates: &[String]) -> Vec<String> {- candidates- .iter()- .filter(|path| !std::path::Path::new(path.as_str()).is_file())- .cloned()- .collect()- }-- /// Why this response must not be held, or `None` when it may be.- fn skip_reason<C>(ctx: &RunContext<C>, response: &ModelResponse) -> Option<&'static str> {- if !response.tool_calls().is_empty() {- return Some("not_final");- }- if response.text().trim().is_empty() {- return Some("empty_answer");- }- if response.finish_reason.as_deref() == Some("length") {- return Some("truncated");- }- if response.continue_turn.is_some() {- return Some("already_continued");- }- if ctx.limits.remaining_model_calls() < MIN_REMAINING_MODEL_CALLS {- return Some("model_call_budget");- }- None- }-}--#[async_trait]-impl<C: Send + Sync> Middleware<(), C> for UnmetDeliverableMiddleware {- fn name(&self) -> &str {- "unmet_deliverable"- }-- async fn before_model(- &self,- ctx: &mut RunContext<C>,- _state: &(),- request: &mut ModelRequest,- ) -> Result<()> {- let Ok(mut runs) = self.runs.lock() else {- return Ok(());- };- let run = runs.entry(ctx.instance_id()).or_default();- if run.candidates.is_some() {- return Ok(());- }- // The request is the current turn's user message: the last user- // message on the first call, since the thread's history rides ahead- // of it and the harness's own user-role injections are wrapped as- // instructions and arrive on later calls.- let text = request- .messages- .iter()- .rev()- .find(|message| {- matches!(message, Message::User(_))- && !message.text().contains("<harness_instruction>")- })- .map(Message::text)- .unwrap_or_default();- run.candidates = Some(candidate_paths(&text));- Ok(())- }-- /// The clock-driven rungs: at half-time a requested path that still does- /// not exist is pointed out on the tool result the model is about to- /// read, and at 80% the note says to stop exploring and meet the stated- /// limits. Each note is appended once per run.- async fn after_tool(- &self,- ctx: &mut RunContext<C>,- _state: &(),- _invocation: &ToolInvocationIdentity,- result: &mut TaToolResult,- ) -> Result<()> {- let Some(clock) = TurnClock::of(ctx, self.budget) else {- return Ok(());- };- let Some(band) = clock.band() else {- return Ok(());- };- let (candidates, half_noted, late_noted) = {- let Ok(runs) = self.runs.lock() else {- return Ok(());- };- match runs.get(&ctx.instance_id()) {- Some(run) => (- run.candidates.clone().unwrap_or_default(),- run.half_noted,- run.late_noted,- ),- None => return Ok(()),- }- };- if band >= LATE_BAND && !late_noted {- // The late note supersedes the half-time one: a run whose first- // observation is already past 80% must not get the half-time- // note on its next tool result.- if let Ok(mut runs) = self.runs.lock() {- let run = runs.entry(ctx.instance_id()).or_default();- run.late_noted = true;- run.half_noted = true;- }- tracing::debug!(- band,- "[unmet_deliverable] late note: stop exploring, meet the stated limits"- );- append_note(result, &late_note(&clock));- return Ok(());- }- if (HALF_TIME_BAND..LATE_BAND).contains(&band) && !half_noted {- let missing = Self::missing(&candidates);- if let Ok(mut runs) = self.runs.lock() {- runs.entry(ctx.instance_id()).or_default().half_noted = true;- }- if !missing.is_empty() {- tracing::debug!(- band,- missing = missing.len(),- "[unmet_deliverable] half-time note: requested paths still absent"- );- append_note(result, &half_time_note(&missing, &clock));- }- }- Ok(())- }-- async fn after_model(- &self,- ctx: &mut RunContext<C>,- _state: &(),- response: &mut ModelResponse,- ) -> Result<()> {- let candidates = {- let Ok(runs) = self.runs.lock() else {- return Ok(());- };- match runs.get(&ctx.instance_id()) {- Some(run) if !run.fired => run.candidates.clone().unwrap_or_default(),- _ => return Ok(()),- }- };- if candidates.is_empty() {- return Ok(());- }- if let Some(reason) = Self::skip_reason(ctx, response) {- tracing::debug!(reason, "[unmet_deliverable] not holding this answer");- return Ok(());- }- let missing = Self::missing(&candidates);- if missing.is_empty() {- return Ok(());- }- if let Ok(mut runs) = self.runs.lock() {- runs.entry(ctx.instance_id()).or_default().fired = true;- }- tracing::debug!(- missing = missing.len(),- "[unmet_deliverable] holding the answer: a named output file was never written"- );- response.continue_turn = Some(notice(&missing));- Ok(())- }-- /// The turn is over: drop its state, whether it ended with an answer or an- /// error, so nothing is kept for a run that will not be seen again.- async fn after_agent(- &self,- ctx: &mut RunContext<C>,- _state: &(),- _run: &mut tinyagents_harness::middleware::AgentRun,- ) -> Result<()> {- if let Ok(mut runs) = self.runs.lock() {- runs.remove(&ctx.instance_id());- }- Ok(())- }-- async fn on_error(&self, ctx: &mut RunContext<C>, _error: &TinyAgentsError) -> Result<()> {- if let Ok(mut runs) = self.runs.lock() {- runs.remove(&ctx.instance_id());- }- Ok(())- }-}--/// Install the check on `harness` on the same scope as the requirements check-/// (`verify_before_finish::applies`): root orchestrator turns only, since a-/// sub-agent answers to its parent and the parent's own request is the one-/// that names a file. The policy-level wall clock is handed over because the-/// middleware cannot read `RunPolicy` from the run context.-pub(crate) fn install<C: Send + Sync + 'static>(- harness: &mut AgentHarness<(), C>,- is_subagent: bool,- agent_definition_id: Option<&str>,-) {- if !crate::agent::tinyagents::verify_before_finish::applies(is_subagent, agent_definition_id) {- tracing::debug!(- is_subagent,- agent = agent_definition_id.unwrap_or("<none>"),- "[unmet_deliverable] not installed for this turn"- );- return;- }- let turn_budget = harness- .policy()- .limits- .max_wall_clock_ms- .map(std::time::Duration::from_millis);- harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new(turn_budget)));-}--#[cfg(test)]-#[path = "unmet_deliverable_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rsdeleted file mode 100644index b79377d50d..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rs+++ /dev/null@@ -1,492 +0,0 @@-use super::*;--use std::sync::Arc;--use tinyagents_harness::context::{RunConfig, RunContext};-use tinyagents_harness::limits::RunLimits;-use tinyagents_harness::middleware::Middleware;-use tinyagents_harness::runtime::{AgentHarness, RunPolicy};-use tinyagents_harness::testkit::{FakeTool, ScriptedModel};-use tinyagents_harness::tinyinference_llm::model::ModelRequest;-use tinyagents_harness::tinyinference_llm::tool::ToolCall;--/// The real request this middleware was built for names three inputs and one-/// output. Extraction deliberately cannot tell them apart -- that is the-/// existence check's job -- so it must return all four.-const ATRX_REQUEST: &str = "Catalogue all coding variants present in the mutated ATRX \- transcripts at /app/data/mutated-transcripts.txt relative to the wild-type NM_000489.6 \- reference (encoded by /app/data/genomic-locus.fa and the CDS information at \- /app/data/CDS-information.txt). Write the final results to \- /app/output/mutation.report.json as a single JSON object.";--#[test]-fn extraction_returns_every_named_file_input_and_output_alike() {- assert_eq!(- candidate_paths(ATRX_REQUEST),- vec![- "/app/data/mutated-transcripts.txt",- "/app/data/genomic-locus.fa",- "/app/data/CDS-information.txt",- "/app/output/mutation.report.json",- ]- );-}--/// The design claim: separating a deliverable from an input needs no grammar,-/// because an input is on disk and a skipped deliverable is not.-#[test]-fn existence_alone_separates_a_skipped_deliverable_from_the_inputs() {- let dir = std::env::temp_dir().join(format!("oh-unmet-{}", std::process::id()));- std::fs::create_dir_all(&dir).expect("temp dir");- let input = dir.join("given.txt");- std::fs::write(&input, b"provided").expect("write input");- let output = dir.join("report.json");- let _ = std::fs::remove_file(&output);-- let candidates = vec![- input.to_string_lossy().to_string(),- output.to_string_lossy().to_string(),- ];- assert_eq!(- UnmetDeliverableMiddleware::missing(&candidates),- vec![output.to_string_lossy().to_string()],- "the input must not be reported; only the path nothing created"- );-- // Once written, even empty, it stops being reported: this middleware- // checks existence, never contents.- std::fs::write(&output, b"{}").expect("write output");- assert!(UnmetDeliverableMiddleware::missing(&candidates).is_empty());- let _ = std::fs::remove_dir_all(&dir);-}--#[test]-fn only_absolute_paths_carrying_a_file_extension_are_candidates() {- for rejected in [- "see config/settings.yml for the rest", // relative: a reference, not a deliverable- "write it under /app/output/", // a directory, no extension- "results go in /report.json", // single segment at the root- "read /app/../etc/passwd", // traversal is never statted- "the ratio is 3/4.5 overall", // arithmetic, not a path- "fetch https://example.com/report.pdf", // a URL, not a local file- "see http://host:8080/a/b.csv and //cdn/x.js", // scheme-less `//` too- ] {- assert!(- candidate_paths(rejected).is_empty(),- "must not treat {rejected:?} as a deliverable: {:?}",- candidate_paths(rejected)- );- }-}--#[test]-fn a_path_is_recognised_through_the_punctuation_a_request_wraps_it_in() {- for (text, expected) in [- ("write to `/app/out/r.json`.", "/app/out/r.json"),- ("write to \"/app/out/r.json\",", "/app/out/r.json"),- ("write to (/app/out/r.json)", "/app/out/r.json"),- ("write to /app/out/r.json.", "/app/out/r.json"),- ("write to </app/out/r.json>", "/app/out/r.json"),- ] {- assert_eq!(candidate_paths(text), vec![expected], "for {text:?}");- }-}--#[test]-fn a_repeated_path_is_reported_once_and_a_long_list_is_bounded() {- let twice = "first /a/b/c.json then /a/b/c.json again";- assert_eq!(candidate_paths(twice), vec!["/a/b/c.json"]);-- let many = (0..20)- .map(|i| format!("/dir/file{i}.json"))- .collect::<Vec<_>>()- .join(" ");- assert_eq!(candidate_paths(&many).len(), MAX_CANDIDATES);-}--#[test]-fn the_notice_names_the_paths_and_asks_for_a_partial_file() {- let one = notice(&["/app/output/r.json".to_string()]);- assert!(one.contains("<harness_instruction>"));- assert!(one.contains("a file that does not exist here"));- assert!(one.contains("lives elsewhere"));- assert!(one.contains("`/app/output/r.json`"));- assert!(one.contains("even where fields are incomplete or provisional"));-- let two = notice(&["/a/x.json".to_string(), "/b/y.csv".to_string()]);- assert!(two.contains("files that do not exist here"));- assert!(two.contains("`/a/x.json`, `/b/y.csv`"));-}--fn tool_round(id: &str, name: &str) -> tinyagents_harness::tinyinference_llm::model::ModelResponse {- let mut response =- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(String::new());- response.message.content = Vec::new();- response.message.tool_calls = vec![ToolCall::new(id, name, serde_json::json!({}))];- response.finish_reason = Some("tool_calls".to_string());- response-}--/// Drive a run whose request names a path that does not exist. The notice has-/// to reach the model, leave it free to call tools, and let its second answer-/// stand -- and it must not be given twice.-#[tokio::test]-async fn an_unwritten_deliverable_holds_the_answer_once_and_permits_a_fix() {- let missing = std::env::temp_dir().join(format!("oh-unmet-run-{}.json", std::process::id()));- let _ = std::fs::remove_file(&missing);- let request = format!("Do the work and write it to {}", missing.display());-- let mut harness: AgentHarness<()> = AgentHarness::new();- harness.register_model(- "mock",- Arc::new(ScriptedModel::new(vec![- tool_round("c0", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "here is what I found".to_string(),- ),- tool_round("c1", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "written and answered".to_string(),- ),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "must not be reached".to_string(),- ),- ])),- );- harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- harness.with_policy(RunPolicy {- limits: RunLimits::default()- .with_max_model_calls(20)- .with_max_tool_calls(20),- ..RunPolicy::default()- });- harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new(None)));-- let run = harness- .invoke_default(&(), vec![Message::user(request)])- .await- .expect("run succeeds");-- assert_eq!(run.text().as_deref(), Some("written and answered"));- let notices = run- .messages- .iter()- .filter(|m| matches!(m, Message::User(_)) && m.text().contains("does not exist"))- .count();- assert_eq!(- notices, 1,- "the notice must be given once, not every answer"- );-}--/// A request that names nothing, or names only files that exist, must cost the-/// turn nothing: the first answer stands.-#[tokio::test]-async fn a_request_naming_no_missing_file_is_left_alone() {- let mut harness: AgentHarness<()> = AgentHarness::new();- harness.register_model(- "mock",- Arc::new(ScriptedModel::new(vec![- tool_round("c0", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "done".to_string(),- ),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "must not be reached".to_string(),- ),- ])),- );- harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- harness.with_policy(RunPolicy {- limits: RunLimits::default().with_max_model_calls(20),- ..RunPolicy::default()- });- harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new(None)));-- let run = harness- .invoke_default(&(), vec![Message::user("summarise the situation for me")])- .await- .expect("run succeeds");- assert_eq!(run.text().as_deref(), Some("done"));-}--/// `install` puts the check on a root orchestrator turn with the policy's wall-/// clock, and on nothing else: a sub-agent's answer goes to its parent.-#[tokio::test]-async fn install_covers_root_orchestrator_turns_only() {- let missing =- std::env::temp_dir().join(format!("oh-unmet-install-{}.json", std::process::id()));- let _ = std::fs::remove_file(&missing);- let request = format!("Do the work and write it to {}", missing.display());- let script = || {- Arc::new(ScriptedModel::new(vec![- tool_round("c0", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "here is what I found".to_string(),- ),- tool_round("c1", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "written and answered".to_string(),- ),- ]))- };- let policy = || RunPolicy {- limits: RunLimits::default()- .with_max_model_calls(20)- .with_max_tool_calls(20)- .with_max_wall_clock_ms(Some(600_000)),- ..RunPolicy::default()- };-- let mut root: AgentHarness<()> = AgentHarness::new();- root.register_model("mock", script());- root.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- root.with_policy(policy());- install(&mut root, false, Some("orchestrator"));- let run = root- .invoke_default(&(), vec![Message::user(request.clone())])- .await- .expect("run succeeds");- assert_eq!(- run.text().as_deref(),- Some("written and answered"),- "a root orchestrator turn is held for the file it never wrote"- );-- let mut sub: AgentHarness<()> = AgentHarness::new();- sub.register_model("mock", script());- sub.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- sub.with_policy(policy());- install(&mut sub, true, Some("orchestrator"));- let run = sub- .invoke_default(&(), vec![Message::user(request)])- .await- .expect("run succeeds");- assert_eq!(- run.text().as_deref(),- Some("here is what I found"),- "a sub-agent turn is not checked"- );-}--/// The candidates come from the current turn's request, not from an earlier-/// turn of the thread that rides ahead of it in the harness input, and not-/// from a wrapped harness instruction.-#[tokio::test]-async fn candidates_come_from_the_current_turns_request() {- let old = std::env::temp_dir().join(format!("oh-unmet-old-{}.json", std::process::id()));- let new = std::env::temp_dir().join(format!("oh-unmet-new-{}.json", std::process::id()));- let _ = std::fs::remove_file(&old);- let _ = std::fs::remove_file(&new);- let mut harness: AgentHarness<()> = AgentHarness::new();- harness.register_model(- "mock",- Arc::new(ScriptedModel::new(vec![- tool_round("c0", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "first answer".to_string(),- ),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "second answer".to_string(),- ),- ])),- );- harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- harness.with_policy(RunPolicy {- limits: RunLimits::default()- .with_max_model_calls(20)- .with_max_tool_calls(20),- ..RunPolicy::default()- });- harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new(None)));- let run = harness- .invoke_default(- &(),- vec![- Message::user(format!("earlier turn: write {}", old.display())),- Message::assistant("done earlier"),- Message::user(format!("now write {}", new.display())),- ],- )- .await- .expect("run succeeds");- let notice = run- .messages- .iter()- .filter(|m| matches!(m, Message::User(_)) && m.text().contains("does not exist"))- .map(|m| m.text())- .collect::<Vec<_>>();- assert_eq!(notice.len(), 1, "held once for the current request");- assert!(- notice[0].contains(&new.display().to_string()),- "names the current turn's path"- );- assert!(- !notice[0].contains(&old.display().to_string()),- "not the earlier turn's path"- );- assert_eq!(run.text().as_deref(), Some("second answer"));-}--fn result_text(result: &TaToolResult) -> String {- result- .content- .iter()- .filter_map(|block| match block {- ToolContent::Text { text } => Some(text.as_str()),- _ => None,- })- .collect()-}--/// The two clock-driven notes ride a tool result once each: the half-time-/// note names the path still absent at 50% of the budget, the late note at-/// 80% says to stop exploring, and neither repeats in a later band. A-/// directory at the path counts as absent: the deliverable is a file.-#[tokio::test]-async fn the_half_time_and_late_notes_ride_a_tool_result_once_each() {- let missing = std::env::temp_dir().join(format!("oh-unmet-clock-{}.csv", std::process::id()));- let _ = std::fs::remove_dir_all(&missing);- std::fs::create_dir_all(&missing).expect("a directory at the csv path");- // A 4 s budget: the sleeps land a full band away from each threshold,- // so a second of scheduler slop cannot move a call across one.- let middleware = UnmetDeliverableMiddleware::new(Some(std::time::Duration::from_millis(4_000)));- let mut ctx = RunContext::new(RunConfig::new("clock"), ());- let mut request = ModelRequest {- messages: vec![Message::user(format!(- "do the work and write {}",- missing.display()- ))],- ..ModelRequest::default()- };- Middleware::<(), ()>::before_model(&middleware, &mut ctx, &(), &mut request)- .await- .expect("before_model");- async fn run(middleware: &UnmetDeliverableMiddleware, ctx: &mut RunContext<()>) -> String {- let identity = tinyagents_harness::middleware::ToolInvocationIdentity::new("c0", "shell");- let mut result = TaToolResult::success("output");- Middleware::<(), ()>::after_tool(middleware, ctx, &(), &identity, &mut result)- .await- .expect("after_tool");- result_text(&result)- }-- assert_eq!(- run(&middleware, &mut ctx).await,- "output",- "nothing before half-time"- );-- std::thread::sleep(std::time::Duration::from_millis(2_200));- let half = run(&middleware, &mut ctx).await;- assert!(half.contains("Half the turn's budget is gone"), "{half:?}");- assert!(- half.contains(&missing.display().to_string()),- "names the absent path"- );- assert_eq!(- run(&middleware, &mut ctx).await,- "output",- "the half-time note is given once"- );-- std::thread::sleep(std::time::Duration::from_millis(1_300));- let late = run(&middleware, &mut ctx).await;- assert!(late.contains("Stop exploring"), "{late:?}");- assert!(- !late.contains("Half the turn's budget"),- "the late note stands alone"- );- assert_eq!(- run(&middleware, &mut ctx).await,- "output",- "the late note is given once"- );- let _ = std::fs::remove_dir_all(&missing);-}--/// A directory at a path that names a file is not the deliverable.-#[test]-fn a_directory_at_the_path_is_still_missing() {- let dir = std::env::temp_dir().join(format!("oh-unmet-dir-{}.json", std::process::id()));- let _ = std::fs::remove_dir_all(&dir);- std::fs::create_dir_all(&dir).expect("dir");- let candidates = vec![dir.to_string_lossy().to_string()];- assert_eq!(UnmetDeliverableMiddleware::missing(&candidates), candidates);- let _ = std::fs::remove_dir_all(&dir);-}--/// A run whose first tool result arrives past 80% gets the late note and-/// never the half-time one: the later rung supersedes the earlier.-#[tokio::test]-async fn a_late_first_observation_skips_the_half_time_note() {- let missing = std::env::temp_dir().join(format!("oh-unmet-late-{}.csv", std::process::id()));- let _ = std::fs::remove_file(&missing);- let middleware = UnmetDeliverableMiddleware::new(Some(std::time::Duration::from_millis(1)));- let mut ctx = RunContext::new(RunConfig::new("late-first"), ());- let mut request = ModelRequest {- messages: vec![Message::user(format!("write {}", missing.display()))],- ..ModelRequest::default()- };- Middleware::<(), ()>::before_model(&middleware, &mut ctx, &(), &mut request)- .await- .expect("before_model");- std::thread::sleep(std::time::Duration::from_millis(5));- let identity = tinyagents_harness::middleware::ToolInvocationIdentity::new("c0", "shell");- let mut first = TaToolResult::success("output");- Middleware::<(), ()>::after_tool(&middleware, &mut ctx, &(), &identity, &mut first)- .await- .expect("after_tool");- assert!(result_text(&first).contains("Stop exploring"));- let mut second = TaToolResult::success("output");- Middleware::<(), ()>::after_tool(&middleware, &mut ctx, &(), &identity, &mut second)- .await- .expect("after_tool");- assert_eq!(- result_text(&second),- "output",- "no half-time note after the late one"- );-}--/// The turn's state is dropped when the run ends, so a long-lived harness-/// keeps nothing for runs it will not see again.-#[tokio::test]-async fn the_runs_state_is_dropped_when_the_turn_ends() {- let missing = std::env::temp_dir().join(format!("oh-unmet-drop-{}.json", std::process::id()));- let _ = std::fs::remove_file(&missing);- let middleware = Arc::new(UnmetDeliverableMiddleware::new(None));- let mut harness: AgentHarness<()> = AgentHarness::new();- harness.register_model(- "mock",- Arc::new(ScriptedModel::new(vec![- tool_round("c0", "writer"),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "first answer".to_string(),- ),- tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(- "second answer".to_string(),- ),- ])),- );- harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));- harness.with_policy(RunPolicy {- limits: RunLimits::default()- .with_max_model_calls(20)- .with_max_tool_calls(20),- ..RunPolicy::default()- });- harness.push_middleware(Arc::clone(&middleware) as Arc<dyn Middleware<(), ()>>);- let run = harness- .invoke_default(- &(),- vec![Message::user(format!("write {}", missing.display()))],- )- .await- .expect("run succeeds");- assert_eq!(run.text().as_deref(), Some("second answer"));- assert!(- middleware.runs.lock().expect("lock").is_empty(),- "the finished run leaves no state behind"- );-}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rsdeleted file mode 100644index 13a2a0f0ef..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware_research_budget_tests.rs+++ /dev/null@@ -1,236 +0,0 @@-use super::*;--/// Every direct web-read tool the budget governs.-const WEB_TOOLS: [&str; 4] = [- "web_search_tool",- "web_answer_tool",- "web_contents_tool",- "web_fetch",-];--fn request_with_tools(names: &[&str]) -> ModelRequest {- ModelRequest {- tools: names- .iter()- .map(|name| ToolSchema::new(*name, "tool", json!({})))- .collect(),- ..ModelRequest::new(vec![TaMessage::user(- "Find more information about Jev from TypeSafe".to_string(),- )])- }-}--fn research_request() -> ModelRequest {- request_with_tools(&["web_search_tool"])-}--/// A coding turn: web tools beside the local tools that do the actual work.-fn coding_request() -> ModelRequest {- let mut names = WEB_TOOLS.to_vec();- names.extend(["shell", "apply_patch"]);- request_with_tools(&names)-}--fn tool_names(request: &ModelRequest) -> Vec<&str> {- request- .tools- .iter()- .map(|tool| tool.name.as_str())- .collect()-}--async fn record_reads(- mw: &ResearchBudgetMiddleware,- run: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- reads: usize,-) {- for i in 0..reads {- let name = WEB_TOOLS[i % WEB_TOOLS.len()];- mw.after_tool(- run,- &(),- &invocation(format!("web-{i}"), name),- &mut tool_result(name, "Jev is TypeSafe's System One model"),- )- .await- .unwrap();- }-}--async fn record_failed_read(- mw: &ResearchBudgetMiddleware,- run: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,- call_id: &str,-) {- mw.after_tool(- run,- &(),- &invocation(call_id, "web_fetch"),- &mut failing_result("web_fetch", "Request failed: connection refused"),- )- .await- .unwrap();-}--/// A run with nothing but web tools still concludes once the budget is spent:-/// there is nothing left to continue the task with.-#[tokio::test]-async fn web_only_research_concludes_after_eight_reads() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- record_reads(&mw, &mut run, research_budget::DIRECT_WEB_READ_LIMIT - 1).await;- let mut request = research_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.tools.len(), 1);-- record_reads(&mw, &mut run, 1).await;- let mut request = research_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert!(request.tools.is_empty());- assert_eq!(- request.tool_choice,- tinyinference_llm::model::ToolChoice::None- );- assert!(request.messages.last().unwrap().text().contains("Answer"));-}--/// With the tools withdrawn, the instruction must say that a tool call will-/// not run: without it DeepSeek V4 wrote its next call as plain-text markup-/// that stood as the answer.-#[tokio::test]-async fn the_concluding_instruction_says_tools_are_gone() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- record_reads(&mw, &mut run, research_budget::DIRECT_WEB_READ_LIMIT).await;- let mut request = research_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- let instruction = request.messages.last().unwrap().text();- assert_eq!(instruction, research_budget::RESEARCH_CLOSE_INSTRUCTION);- assert!(instruction.contains("tools are no longer available"));- assert!(instruction.contains("will not run"));- assert!(instruction.contains("plain text"));-}--/// #6959: a spent web budget withdraws only the web tools. A coding turn keeps-/// `shell` and `apply_patch` and is told to carry on with them, rather than-/// being forced to answer before any edit is made.-#[tokio::test]-async fn a_spent_web_budget_keeps_the_non_web_tools() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- record_reads(&mw, &mut run, research_budget::DIRECT_WEB_READ_LIMIT).await;-- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(tool_names(&request), vec!["shell", "apply_patch"]);- assert_eq!(- request.tool_choice,- tinyinference_llm::model::ToolChoice::Auto- );- let instruction = request.messages.last().unwrap().text();- assert_eq!(- instruction,- research_budget::WEB_BUDGET_EXHAUSTED_INSTRUCTION- );- assert!(instruction.contains("remaining tools"));-- // Every later request of the turn stays narrowed the same way.- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(tool_names(&request), vec!["shell", "apply_patch"]);-}--/// A tool choice pinned to a web tool cannot survive that tool's removal.-#[tokio::test]-async fn a_spent_web_budget_releases_a_choice_pinned_to_a_web_tool() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- record_reads(&mw, &mut run, research_budget::DIRECT_WEB_READ_LIMIT).await;-- let mut request = coding_request();- request.tool_choice = tinyinference_llm::model::ToolChoice::Tool("web_fetch".into());- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(- request.tool_choice,- tinyinference_llm::model::ToolChoice::Auto- );-}--/// #6959: a failed web call (a blocked network, an offline sandbox) read-/// nothing, so it must not spend the budget.-#[tokio::test]-async fn failed_web_reads_do_not_spend_the_budget() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- for i in 0..research_budget::DIRECT_WEB_READ_LIMIT * 2 {- record_failed_read(&mw, &mut run, &format!("fail-{i}")).await;- }- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.tools.len(), WEB_TOOLS.len() + 2);- assert_ne!(- request.messages.last().unwrap().text(),- research_budget::WEB_BUDGET_EXHAUSTED_INSTRUCTION- );-}--/// Two web failures in a row get one note that web access looks blocked, on-/// the next request only.-#[tokio::test]-async fn consecutive_failed_web_reads_note_that_web_access_looks_blocked_once() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();-- record_failed_read(&mw, &mut run, "fail-0").await;- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.messages.len(), 1, "one failure is not a pattern");-- record_failed_read(&mw, &mut run, "fail-1").await;- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(- request.messages.last().unwrap().text(),- research_budget::WEB_BLOCKED_NOTE- );- assert_eq!(request.tools.len(), WEB_TOOLS.len() + 2);-- record_failed_read(&mw, &mut run, "fail-2").await;- record_failed_read(&mw, &mut run, "fail-3").await;- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.messages.len(), 1, "the note is sent once per run");-}--/// A successful read in between breaks the run of failures.-#[tokio::test]-async fn a_successful_read_resets_the_failure_streak() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- record_failed_read(&mw, &mut run, "fail-0").await;- record_reads(&mw, &mut run, 1).await;- record_failed_read(&mw, &mut run, "fail-1").await;-- let mut request = coding_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.messages.len(), 1);-}--#[tokio::test]-async fn unrelated_tools_do_not_spend_the_web_research_budget() {- let mw = ResearchBudgetMiddleware::new();- let mut run = ctx();- for i in 0..10 {- mw.after_tool(- &mut run,- &(),- &invocation(format!("file-{i}"), "file_read"),- &mut tool_result("file_read", "content"),- )- .await- .unwrap();- }- let mut request = research_request();- mw.before_model(&mut run, &(), &mut request).await.unwrap();- assert_eq!(request.tools.len(), 1);-}