The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): keep repeated-failure nudges out of durable history
M3gA-Mind03dd151bb3c6
diff --git a/crates/openhuman-core/src/agent/agent_tests.rs b/crates/openhuman-core/src/agent/agent_tests.rsindex abe6f71a5f..ee059d2070 100644--- a/crates/openhuman-core/src/agent/agent_tests.rs+++ b/crates/openhuman-core/src/agent/agent_tests.rs@@ -337,6 +337,8 @@ fn xml_tool_response(name: &str, args: &str) -> ChatResponse {#[path = "agent_memory_attribution_tests.rs"]mod agent_memory_attribution_tests;+#[path = "agent_turn_loop_nudge_tests.rs"]+mod agent_turn_loop_nudge_tests;#[path = "agent_turn_loop_packed_tool_tests.rs"]mod agent_turn_loop_packed_tool_tests;#[path = "agent_turn_loop_tests.rs"]diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_nudge_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_nudge_tests.rsnew file mode 100644index 0000000000..b34eef8639--- /dev/null+++ b/crates/openhuman-core/src/agent/agent_turn_loop_nudge_tests.rs@@ -0,0 +1,279 @@+use super::*;+use tinyinference_llm::message::Message;++// #6725: the repeated-failure breaker's corrective nudge reaches the next model+// request only. It used to be a steering `InjectMessage`, which joined the+// working transcript and was committed as durable history.++const NUDGE: &str =+ "The last call failed validation. Correct its schema or arguments once before trying again.";++/// A native-tool-calling model that replays scripted responses and records the+/// messages of every request it receives.+struct RecordingProvider {+ responses: Mutex<Vec<ChatResponse>>,+ requests: Mutex<Vec<Vec<Message>>>,+ /// Fail every call from this 0-based index on (drives the error path).+ fail_from_call: Option<usize>,+}++#[async_trait]+impl ChatModel<()> for RecordingProvider {+ fn profile(&self) -> Option<&ModelProfile> {+ static PROFILE: std::sync::LazyLock<ModelProfile> =+ std::sync::LazyLock::new(|| ModelProfile {+ provider: Some("agent-test".to_string()),+ tool_calling: true,+ parallel_tool_calls: true,+ ..ModelProfile::default()+ });+ Some(&PROFILE)+ }++ async fn invoke(+ &self,+ _state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ let index = {+ let mut requests = self.requests.lock().unwrap();+ requests.push(request.messages.clone());+ requests.len() - 1+ };+ if self.fail_from_call.is_some_and(|from| index >= from) {+ return Err(tinyinference_llm::Error::Model(+ "400 Bad Request: provider error".into(),+ ));+ }+ let response = {+ let mut guard = self.responses.lock().unwrap();+ if guard.is_empty() {+ text_response("done")+ } else {+ guard.remove(0)+ }+ };+ Ok(crate::agent::tinyagents::model::native_model_response_for_request(&response, &request))+ }+}++/// Fails with a tool-owned 422, which the breaker classifies as `validation`.+struct ValidationFailingTool(&'static str);++#[async_trait]+impl Tool for ValidationFailingTool {+ fn name(&self) -> &str {+ self.0+ }++ fn description(&self) -> &str {+ "Always fails validation"+ }++ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({"type": "object"})+ }++ async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {+ Ok(ToolResult::error(r#"{"status_code": 422}"#))+ }+}++fn call(id: &str, name: &str) -> ChatResponse {+ tool_response(vec![ToolCall {+ id: id.into(),+ name: name.into(),+ arguments: "{}".into(),+ extra_content: None,+ }])+}++fn nudge_count(messages: &[Message]) -> usize {+ messages+ .iter()+ .filter(|m| matches!(m, Message::System(_)) && m.text() == NUDGE)+ .count()+}++async fn run_turn(+ script: Vec<ChatResponse>,+ tools: Vec<Box<dyn Tool>>,+) -> (Vec<Vec<Message>>, Vec<ConversationMessage>) {+ let (requests, history, _tmp) = run_turn_failing_from(script, tools, None).await;+ (requests, history)+}++async fn run_turn_failing_from(+ script: Vec<ChatResponse>,+ tools: Vec<Box<dyn Tool>>,+ fail_from_call: Option<usize>,+) -> (+ Vec<Vec<Message>>,+ Vec<ConversationMessage>,+ tempfile::TempDir,+) {+ let provider = Arc::new(RecordingProvider {+ responses: Mutex::new(script),+ requests: Mutex::new(Vec::new()),+ fail_from_call,+ });+ let (mut agent, tmp) = build_agent_with(provider.clone(), tools, Box::new(NativeDialect));+ let outcome = agent.turn("do the thing").await;+ assert_eq!(+ outcome.is_err(),+ fail_from_call.is_some(),+ "turn outcome: {outcome:?}"+ );+ let requests = provider.requests.lock().unwrap().clone();+ (requests, agent.history(), tmp)+}++/// No system row may follow the first conversational row of committed history.+fn committed_system_rows_past_prefix(history: &[ConversationMessage]) -> Vec<String> {+ history+ .iter()+ .filter_map(|m| match m {+ ConversationMessage::Chat(chat) => Some(chat),+ _ => None,+ })+ .skip_while(|chat| chat.role == "system")+ .filter(|chat| chat.role == "system")+ .map(|chat| chat.content.clone())+ .collect()+}++#[tokio::test]+async fn validation_nudge_reaches_the_retry_but_is_not_committed() {+ let (requests, history) = run_turn(+ vec![call("tc1", "fail_a"), text_response("recovered")],+ vec![Box::new(ValidationFailingTool("fail_a"))],+ )+ .await;++ assert_eq!(requests.len(), 2, "one failing call, then the retry");+ assert!(+ matches!(requests[1].last(), Some(m @ Message::System(_)) if m.text() == NUDGE),+ "the retry request must end with the nudge, got {:?}",+ requests[1].last()+ );+ assert_eq!(nudge_count(&requests[1]), 1);+ // Fixture guard: the failed call really is in the committed turn.+ assert!(+ history.iter().any(|m| matches!(+ m,+ ConversationMessage::Chat(chat) if chat.role == "tool" && chat.content.contains("422")+ )) || history+ .iter()+ .any(|m| matches!(m, ConversationMessage::ToolResults(r) if r.iter().any(|r| r.content.contains("422")))),+ "the validation failure must be part of the committed turn"+ );+ assert_eq!(+ committed_system_rows_past_prefix(&history),+ Vec::<String>::new(),+ "the nudge must not be committed into durable history"+ );+ assert_eq!(+ committed_rows_mentioning_nudge(&history),+ Vec::<String>::new()+ );+}++#[tokio::test]+async fn a_second_validation_failure_rearms_the_nudge() {+ // Validation has a budget of one per (tool, scope): the same tool failing+ // again halts the run. A different tool's first failure is a fresh blocker+ // and must nudge again, even though the first nudge was already consumed.+ let (requests, history) = run_turn(+ vec![+ call("tc1", "fail_a"),+ call("tc2", "fail_b"),+ text_response("recovered"),+ ],+ vec![+ Box::new(ValidationFailingTool("fail_a")),+ Box::new(ValidationFailingTool("fail_b")),+ ],+ )+ .await;++ assert_eq!(requests.len(), 3);+ assert_eq!(requests.iter().map(|r| nudge_count(r)).collect::<Vec<_>>(), [0, 1, 1],+ "each failure nudges exactly the request that follows it; a consumed nudge is not carried over");+ assert!(+ matches!(requests[2].last(), Some(m @ Message::System(_)) if m.text() == NUDGE),+ "the re-armed nudge must end the request after the second failure"+ );+ assert_eq!(+ committed_system_rows_past_prefix(&history),+ Vec::<String>::new()+ );+}++/// Committed rows carrying the nudge text in any role. A failed turn renders+/// its unanswered request into the failure note as text (#6281), so a leak can+/// arrive inside an assistant row, not only as a system row.+fn committed_rows_mentioning_nudge(history: &[ConversationMessage]) -> Vec<String> {+ history+ .iter()+ .filter_map(|m| match m {+ ConversationMessage::Chat(chat) if chat.content.contains(NUDGE) => {+ Some(format!("{}: {}", chat.role, chat.content))+ }+ _ => None,+ })+ .collect()+}++/// Every persisted file under the workspace, as text.+fn persisted_text(root: &std::path::Path) -> Vec<(std::path::PathBuf, String)> {+ walkdir::WalkDir::new(root)+ .into_iter()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_type().is_file())+ .filter_map(|entry| {+ let text = std::fs::read_to_string(entry.path()).ok()?;+ Some((entry.into_path(), text))+ })+ .collect()+}++#[tokio::test]+async fn a_failed_nudged_request_does_not_persist_the_nudge() {+ // When the nudged request itself fails, the driver persists a display-only+ // failure record that renders the request's unanswered tail as text+ // (#6281). The injector runs after the snapshot middleware, so that tail+ // never holds the nudge.+ let (requests, _history, tmp) = run_turn_failing_from(+ vec![call("tc1", "fail_a")],+ vec![Box::new(ValidationFailingTool("fail_a"))],+ Some(1),+ )+ .await;++ assert_eq!(+ requests.len(),+ 2,+ "fail_a, then the nudged request that fails"+ );+ assert_eq!(+ nudge_count(&requests[1]),+ 1,+ "the nudged request reached the model"+ );+ let files = persisted_text(tmp.path());+ // Fixture guard: the failure record rendered the failing request's+ // unanswered tail, which is exactly where a leaked nudge would be written.+ assert!(+ files+ .iter()+ .any(|(_, text)| text.contains("The request that failed also carried these steps")),+ "the failure record must render the unanswered steps; files: {:?}",+ files.iter().map(|(path, _)| path).collect::<Vec<_>>()+ );+ let leaked: Vec<_> = files+ .iter()+ .filter(|(_, text)| text.contains(NUDGE))+ .map(|(path, _)| path)+ .collect();+ assert!(leaked.is_empty(), "the nudge was persisted in {leaked:?}");+}diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 57c833ab6e..0649716b48 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -347,12 +347,15 @@ pub(super) fn assemble_turn_harness(// error `REPEATED_TOOL_FAILURE_THRESHOLD` times in a row, so a deterministic// security/approval denial or terminal tool error surfaces its root cause// instead of burning the whole iteration budget (legacy ProgressGuard parity).- if let Some(handle) = &handle {- harness.push_middleware(Arc::new(middleware::RepeatedToolFailureMiddleware::new(+ let repeated_failure = handle.as_ref().map(|handle| {+ Arc::new(middleware::RepeatedToolFailureMiddleware::new(handle.clone(),REPEATED_TOOL_FAILURE_THRESHOLD,halt_summary.clone(),- )));+ ))+ });+ if let Some(mw) = &repeated_failure {+ harness.push_middleware(mw.clone());}// Policy-driven stop hooks (budget cap, thread-goal budget, ad-hoc iteration@@ -674,6 +677,12 @@ pub(super) fn assemble_turn_harness(if let Some(mw) = &repeat_progress {harness.push_middleware(Arc::new(mw.eviction_observer()));}+ // Registered after it: the breaker's corrective nudges ride the next+ // request only. Anything earlier (notably the transcript snapshot a failed+ // turn persists) must not see them, or they become durable history (#6725).+ if let Some(mw) = &repeated_failure {+ harness.push_middleware(Arc::new(mw.nudge_injector()));+ }AssembledTurnHarness {harness,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rsindex e5e4b700b8..0588f37e93 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs@@ -3,6 +3,7 @@//! OpenHuman's recoverable-failure headroom and terminal-inference fast-halt.use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};use async_trait::async_trait;@@ -14,6 +15,7 @@ use tinyagents_harness::no_progress::{};use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};use tinyinference_llm::message::Message as TaMessage;+use tinyinference_llm::model::ModelRequest;use tinyinference_llm::tool::ToolCall as TaToolCall;use tinytools::ToolResult as TaToolResult;@@ -40,12 +42,10 @@ use super::loop_guards::{/// into OpenHuman steering. It owns only the OpenHuman-side policy:////// - [`NoProgress::Continue`] — do nothing.-/// - [`NoProgress::Nudge`] — inject the crate's structured "no progress since-/// step X" corrective into the working transcript via-/// [`SteeringCommand::InjectMessage`] so the next model call sees it and-/// changes strategy *before* the same-strategy retry cap trips. (Not-/// `Redirect`: that verb is outside the Interactive steering allowlist and-/// would abort the turn — see the nudge call site.)+/// - [`NoProgress::Nudge`] — queue the crate's structured "no progress since+/// step X" corrective for the **next model request only** (see+/// [`PendingNudgeInjector`]) so the model changes strategy *before* the+/// same-strategy retry cap trips./// - [`NoProgress::Halt`] — record the crate's root-cause summary into the shared/// [`HaltSummarySlot`](crate::agent::tinyagents::HaltSummarySlot) (the turn overrides its final/// text with it) and pause the run via the shared steering handle (same@@ -82,6 +82,12 @@ pub(crate) struct RepeatedToolFailureMiddleware {/// Consecutive recoverable-looking failures with no success in between. Reset/// on any success or non-recoverable failure (mirrors the legacy guard).recoverable_consecutive: AtomicU32,+ /// Corrective nudges for the next model request, drained by+ /// [`PendingNudgeInjector`]. Never sent through steering: an injected+ /// message joins the working transcript and is committed into durable+ /// history, where it replays as a stale instruction on every later turn+ /// (#6725).+ pending_nudges: Arc<Mutex<Vec<String>>>,}impl RepeatedToolFailureMiddleware {@@ -103,9 +109,34 @@ impl RepeatedToolFailureMiddleware {target_scopes: std::sync::Mutex::new(std::collections::HashMap::new()),recoverable_sig_counts: std::sync::Mutex::new(std::collections::HashMap::new()),recoverable_consecutive: AtomicU32::new(0),+ pending_nudges: Arc::new(Mutex::new(Vec::new())),}}+ /// The request-scoped half of this breaker. Register it **last**: its+ /// `before_model` must run after the transcript snapshot (which a failed+ /// turn persists) and after every reduction step.+ pub(crate) fn nudge_injector(&self) -> PendingNudgeInjector {+ PendingNudgeInjector {+ pending: self.pending_nudges.clone(),+ }+ }++ fn queue_nudge(&self, instruction: impl Into<String>) {+ if let Ok(mut pending) = self.pending_nudges.lock() {+ pending.push(instruction.into());+ }+ }++ /// Drain the queued nudges (what the injector does before a request).+ #[cfg(test)]+ pub(crate) fn take_pending_nudges(&self) -> Vec<String> {+ self.pending_nudges+ .lock()+ .map(|mut pending| std::mem::take(&mut *pending))+ .unwrap_or_default()+ }+/// Clear the consecutive recoverable-failure streak. Called on any success or/// non-recoverable failure (the per-signature identical counts persist across/// the turn, matching the legacy guard). Idempotent.@@ -451,10 +482,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>} else {"The desktop target was not found. Rediscover the current app and window once before trying again."};- self.handle- .send(SteeringCommand::InjectMessage(TaMessage::system(- instruction,- )));+ self.queue_nudge(instruction);}// The classified budget owns this known blocker. In particular,// a different query must not reset its count or trigger a@@ -581,19 +609,10 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>hard_reject,"[tinyagents::mw] no-progress nudge — steering the model to change strategy before the retry cap");- // Inject the crate's structured corrective as a system message via- // the `InjectMessage` steering lane. This runs on *every* turn,- // including the user's live interactive turn, whose steering policy- // permits only `InjectMessage`/`Pause` — `Redirect` is Background- // (sub-agent) only, so sending it here aborted every interactive- // turn that hit the nudge with `steering command redirect is not- // permitted by the run policy` (a #4473 migration regression). The- // corrective is trusted, system-generated advisory text, so the- // `InjectMessage` lane is both permitted and semantically correct.- self.handle- .send(SteeringCommand::InjectMessage(TaMessage::system(- instruction,- )));+ // Request-scoped, not steering: no run policy can reject it (a+ // `Redirect` nudge aborted interactive turns, #4473), and it is+ // never committed into durable history (#6725).+ self.queue_nudge(instruction);}NoProgress::Halt(summary) => {// #4092: if the blocker is user-actionable (a missing connection),@@ -624,3 +643,40 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>Ok(())}}++/// Appends queued [`RepeatedToolFailureMiddleware`] nudges to the next model+/// request as system messages, then forgets them. The request is built from a+/// copy of the working transcript, so nothing it adds is ever committed.+pub(crate) struct PendingNudgeInjector {+ pending: Arc<Mutex<Vec<String>>>,+}++#[async_trait]+impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for PendingNudgeInjector {+ fn name(&self) -> &str {+ "pending_nudge_injector"+ }++ async fn before_model(+ &self,+ _ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,+ _state: &(),+ request: &mut ModelRequest,+ ) -> TaResult<()> {+ let nudges = self+ .pending+ .lock()+ .map(|mut pending| std::mem::take(&mut *pending))+ .unwrap_or_default();+ if !nudges.is_empty() {+ tracing::debug!(+ count = nudges.len(),+ "[tinyagents::mw] request-scoped nudge(s) appended to the next model request"+ );+ request+ .messages+ .extend(nudges.into_iter().map(TaMessage::system));+ }+ Ok(())+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rsindex 03e6ba2b66..ef189aab4d 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs@@ -276,9 +276,6 @@ async fn halt_on_missing_connection_asks_the_user_instead_of_reporting_back() {#[tokio::test]async fn repeated_tool_failure_nudges_change_of_strategy_before_the_halt() {- use crate::agent::tinyagents::host::steering::{openhuman_steering_handle, SteeringRunClass};- use tinyagents_harness::steering::SteeringCommandKind;-// #4089: before the same-strategy retry cap, the breaker must feed a// structured "no progress since step X" corrective back into the loop so// the model changes approach rather than retrying the identical failing@@ -303,7 +300,7 @@ async fn repeated_tool_failure_nudges_change_of_strategy_before_the_halt() {mw.after_tool(&mut ctx(), &(), &invocation("read-2", "read_file"), &mut r).await.unwrap();- let nudges = drain_nudge_messages(&handle);+ let nudges = drain_nudge_messages(&mw);assert_eq!(nudges.len(),1,@@ -319,22 +316,13 @@ async fn repeated_tool_failure_nudges_change_of_strategy_before_the_halt() {"the nudge names the failing call so the model knows what not to repeat: {nudge}");- // Regression for the #4473 crash: the nudge must ride a steering lane the- // user's *interactive* turn permits. `Redirect` is Background-only, so a- // Redirect nudge aborted interactive turns; `InjectMessage` is permitted- // on both classes. Assert the interactive policy accepts the lane we use.- let interactive = openhuman_steering_handle(SteeringRunClass::Interactive);- assert!(- interactive- .policy()- .is_allowed(SteeringCommandKind::InjectMessage),- "the no-progress nudge must use a lane the interactive turn permits"- );+ // Regression for the #4473 crash (a `Redirect` nudge was refused by the+ // interactive run policy and aborted the turn) and for #6725 (an+ // `InjectMessage` nudge was committed into durable history): the nudge+ // must not ride steering at all.assert!(- !interactive- .policy()- .is_allowed(SteeringCommandKind::Redirect),- "sanity: interactive still refuses Redirect (the lane that crashed it)"+ handle.drain().is_empty(),+ "the nudge must not be sent as a steering command");}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex 9f32511a9b..b47350c21f 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -316,18 +316,10 @@ fn drain_pause_count(handle: &SteeringHandle) -> usize {.count()}-/// Collect the nudge system-message texts drained from `handle`. The nudge-/// rides the `InjectMessage` lane (not `Redirect`) so it is permitted on the-/// user's interactive turn — see the test below.-fn drain_nudge_messages(handle: &SteeringHandle) -> Vec<String> {- handle- .drain()- .into_iter()- .filter_map(|c| match c {- SteeringCommand::InjectMessage(message) => Some(message.text()),- _ => None,- })- .collect()+/// Collect the nudge texts queued for the next model request. Nudges are+/// request-scoped (#6725): they never ride a steering command.+fn drain_nudge_messages(mw: &RepeatedToolFailureMiddleware) -> Vec<String> {+ mw.take_pending_nudges()}// ── RepeatedToolFailureMiddleware body-level ok:false (flows breaker) ────