Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): list the calls a no-progress halt counted, not only the last error

killbillf800f38b237f
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
index ad2f7aa505..8072a3dc47 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@ -92,9 +92,31 @@ pub(crate) struct RepeatedToolFailureMiddleware {
/// history, where it replays as a stale instruction on every later turn
/// (#6725).
pending_nudges: Arc<Mutex<Vec<String>>>,
+ /// call_id → a one-line rendering of the call (a shell command verbatim,
+ /// any other tool's arguments as compact JSON), captured in `before_tool`
+ /// so a halt can say what was tried and not only how the last attempt
+ /// ended.
+ recent_calls: std::sync::Mutex<std::collections::HashMap<String, String>>,
+ /// The consecutive failures the ladder is counting, oldest first, each as
+ /// its rendered call and first error line. Any success clears it. A halt
+ /// summary carrying only the last error left the failing commands
+ /// unrecoverable: one run was stopped after six different submissions and
+ /// kept no record of what any of them sent.
+ recent_failures: std::sync::Mutex<std::collections::VecDeque<String>>,
}
impl RepeatedToolFailureMiddleware {
+ /// `summary` with the calls the ladder counted appended (see
+ /// [`with_failing_calls`]).
+ fn halt_with(&self, summary: String) -> String {
+ let failures = self
+ .recent_failures
+ .lock()
+ .map(|failures| failures.clone())
+ .unwrap_or_default();
+ with_failing_calls(summary, &failures)
+ }
+
/// Build the breaker. `identical_threshold` (the identical-signature retry
/// ceiling) is handed straight to [`NoProgressTracker::new`], which clamps it
/// so a nudge always precedes a halt (a single failure is never a loop).
@@ -108,6 +130,8 @@ impl RepeatedToolFailureMiddleware {
halt_summary,
tracker: NoProgressTracker::new(identical_threshold),
classified: ClassifiedFailureTracker::default(),
+ recent_calls: std::sync::Mutex::default(),
+ recent_failures: std::sync::Mutex::default(),
step: AtomicUsize::new(0),
arg_sigs: std::sync::Mutex::new(std::collections::HashMap::new()),
target_scopes: std::sync::Mutex::new(std::collections::HashMap::new()),
@@ -188,6 +212,91 @@ impl RepeatedToolFailureMiddleware {
}
}
+/// Longest rendering of one call kept for a halt summary.
+const RENDERED_CALL_CHARS: usize = 200;
+/// How many consecutive failures a halt summary lists.
+const RENDERED_FAILURES: usize = 8;
+
+/// One line naming what a call did, safe for a halt summary the model reads
+/// and the session persists: a `command` argument verbatim (the shell tools),
+/// anything else as compact JSON. Secrets are redacted the way the approval
+/// card redacts them, every URL loses its query and fragment (a fetch is
+/// identified by host and path; a query can carry a token or a user's words),
+/// API-key shapes in free text are scrubbed, and the result is
+/// whitespace-collapsed and bounded so a heredoc or payload cannot swamp it.
+fn render_call(tool: &str, arguments: &serde_json::Value) -> String {
+ let raw = match arguments.get("command").and_then(serde_json::Value::as_str) {
+ Some(command) => command.to_owned(),
+ None if arguments.is_null() => tool.to_owned(),
+ None => strip_url_queries(&crate::security::approval::redact_args(arguments)).to_string(),
+ };
+ let without_queries = raw
+ .split_whitespace()
+ .map(|word| {
+ let core = word.trim_start_matches(['\'', '"', '(', '<']);
+ if core.starts_with("http://") || core.starts_with("https://") {
+ word.split(['?', '#']).next().unwrap_or(word).to_owned()
+ } else {
+ word.to_owned()
+ }
+ })
+ .collect::<Vec<_>>()
+ .join(" ");
+ let scrubbed = crate::security::scrub::sanitize_text(&without_queries).value;
+ crate::util::truncate_with_ellipsis(&scrubbed, RENDERED_CALL_CHARS).to_string()
+}
+
+/// `value` with every URL-shaped string cut at its query or fragment.
+fn strip_url_queries(value: &serde_json::Value) -> serde_json::Value {
+ use serde_json::Value;
+ match value {
+ Value::String(s) if s.starts_with("http://") || s.starts_with("https://") => {
+ Value::String(s.split(['?', '#']).next().unwrap_or(s).to_owned())
+ }
+ Value::Array(items) => Value::Array(items.iter().map(strip_url_queries).collect()),
+ Value::Object(map) => Value::Object(
+ map.iter()
+ .map(|(k, v)| (k.clone(), strip_url_queries(v)))
+ .collect(),
+ ),
+ other => other.clone(),
+ }
+}
+
+/// The first line of a failure, plus the first stderr line when the text is a
+/// command exit report -- that is where a program's own reason tends to be.
+fn first_error_line(text: &str) -> String {
+ let first = text
+ .lines()
+ .find(|l| !l.trim().is_empty())
+ .unwrap_or("")
+ .trim();
+ let stderr = text
+ .split_once("[stderr]\n")
+ .and_then(|(_, tail)| tail.lines().find(|l| !l.trim().is_empty()))
+ .map(str::trim)
+ .filter(|l| !l.is_empty() && *l != first);
+ let line = match stderr {
+ Some(err) => format!("{first} — {err}"),
+ None => first.to_owned(),
+ };
+ line.chars().take(RENDERED_CALL_CHARS).collect()
+}
+
+/// `summary` with the consecutive failing calls appended, oldest first, so the
+/// report says what was tried and not only how the last attempt ended.
+fn with_failing_calls(summary: String, failures: &std::collections::VecDeque<String>) -> String {
+ if failures.is_empty() {
+ return summary;
+ }
+ let mut out = summary;
+ out.push_str("\n\nFailing calls, oldest first:");
+ for (i, failure) in failures.iter().enumerate() {
+ out.push_str(&format!("\n{}. {failure}", i + 1));
+ }
+ out
+}
+
/// A stable, bounded fingerprint of a tool call's arguments for the identical-
/// repeat signature (hashed so a huge payload doesn't bloat the map/comparison).
fn args_fingerprint(arguments: &serde_json::Value) -> String {
@@ -463,6 +572,9 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
if let Ok(mut scopes) = self.target_scopes.lock() {
scopes.insert(call.id.clone(), failure_scope(&call.name, &call.arguments));
}
+ if let Ok(mut calls) = self.recent_calls.lock() {
+ calls.insert(call.id.clone(), render_call(&call.name, &call.arguments));
+ }
Ok(())
}
@@ -517,6 +629,28 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
};
let heuristic_failure_text = heuristic_text(tool_name, &failure_text);
+ // What this call was, for a halt summary; the consecutive-failure list
+ // mirrors the ladder: it grows on every failure and empties on any success.
+ let rendered = self
+ .recent_calls
+ .lock()
+ .ok()
+ .and_then(|mut calls| calls.remove(&invocation.call_id().to_string()))
+ .unwrap_or_else(|| tool_name.to_owned());
+ if let Ok(mut failures) = self.recent_failures.lock() {
+ if result.is_error || body_level_failure {
+ failures.push_back(format!(
+ "`{tool_name}`: {rendered} → {}",
+ first_error_line(&failure_text)
+ ));
+ while failures.len() > RENDERED_FAILURES {
+ failures.pop_front();
+ }
+ } else {
+ failures.clear();
+ }
+ }
+
if !result.is_error && !body_level_failure {
// Only a successful observation against this operation and scope
// demonstrates that its blocker changed. Unrelated successes do not.
@@ -553,7 +687,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
summary.push_str(" The action may already have happened; reconcile its external state before any retry.");
}
if let Ok(mut slot) = self.halt_summary.lock() {
- *slot = Some(summary);
+ *slot = Some(self.halt_with(summary));
}
self.handle.send(SteeringCommand::Pause);
self.tracker.reset();
@@ -606,11 +740,11 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"[tinyagents::mw] terminal delegated-inference failure — halting on first occurrence with root cause"
);
if let Ok(mut slot) = self.halt_summary.lock() {
- *slot = Some(terminal_inference_halt_summary(
+ *slot = Some(self.halt_with(terminal_inference_halt_summary(
kind,
tool_name,
&failure_text,
- ));
+ )));
}
self.handle.send(SteeringCommand::Pause);
self.tracker.reset();
@@ -671,7 +805,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"[tinyagents::mw] recoverable-failure headroom exhausted — halting run so the root cause surfaces"
);
if let Ok(mut slot) = self.halt_summary.lock() {
- *slot = Some(summary);
+ *slot = Some(self.halt_with(summary));
}
self.handle.send(SteeringCommand::Pause);
self.reset_recoverable_streak();
@@ -737,7 +871,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"[tinyagents::mw] repeated tool failure — halting run so the root cause surfaces"
);
if let Ok(mut slot) = self.halt_summary.lock() {
- *slot = Some(summary);
+ *slot = Some(self.halt_with(summary));
}
// Pause at the top of the next iteration (before the next model
// call), matching the stop-hook / cap pause path. Reset so a
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs
index 5483d66390..f8869c6d27 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs
@@ -210,3 +210,147 @@ async fn a_repeat_guard_result_never_feeds_the_failure_ladder() {
assert_eq!(drain_pause_count(&handle), 0);
assert!(slot.lock().unwrap().is_none());
}
+
+/// A halt that names only the last error leaves the failing commands
+/// unrecoverable: one run was stopped after six different submissions and kept
+/// no record of what any of them sent. The summary must list the calls it
+/// counted, oldest first, each with its own error.
+#[tokio::test]
+async fn a_no_progress_halt_lists_the_calls_it_counted() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ let report =
+ tinytools::render_command_failure(Some(1), "", "Expecting value: line 1 column 1 (char 0)");
+ for i in 0..6 {
+ run_shell(
+ &mw,
+ &format!("post-{i}"),
+ &format!("python3 submit.py --claim CLM-26{i:02}"),
+ failing_result("shell", &report),
+ )
+ .await;
+ }
+ let summary = slot
+ .lock()
+ .unwrap()
+ .clone()
+ .expect("six different failing calls halt the run");
+ assert!(
+ summary.contains("Failing calls, oldest first:"),
+ "{summary}"
+ );
+ assert!(
+ summary.contains("1. `shell`: python3 submit.py --claim CLM-2600"),
+ "the oldest counted call is listed first: {summary}"
+ );
+ assert!(
+ summary.contains("6. `shell`: python3 submit.py --claim CLM-2605"),
+ "the call that tripped the halt is listed last: {summary}"
+ );
+ assert!(
+ summary.matches("Expecting value").count() >= 6,
+ "each entry carries the program's own error line: {summary}"
+ );
+}
+
+/// A success empties the list: only the failures the ladder is still counting
+/// belong in a halt, and a long list of stale ones would misdirect the reader.
+#[tokio::test]
+async fn a_success_between_failures_clears_the_listed_calls() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ let report = tinytools::render_command_failure(Some(1), "", "boom");
+ for i in 0..3 {
+ run_shell(
+ &mw,
+ &format!("a-{i}"),
+ &format!("false-a-{i}"),
+ failing_result("shell", &report),
+ )
+ .await;
+ }
+ run_shell(&mw, "ok", "true", TaToolResult::success("fine")).await;
+ for i in 0..6 {
+ run_shell(
+ &mw,
+ &format!("b-{i}"),
+ &format!("false-b-{i}"),
+ failing_result("shell", &report),
+ )
+ .await;
+ }
+ let summary = slot
+ .lock()
+ .unwrap()
+ .clone()
+ .expect("halts on the second streak");
+ assert!(
+ !summary.contains("false-a-"),
+ "the pre-success streak is gone: {summary}"
+ );
+ assert!(
+ summary.contains("false-b-0") && summary.contains("false-b-5"),
+ "{summary}"
+ );
+}
+
+/// The listed calls are read by the model and persisted with the session, so
+/// they carry what identifies a call and nothing that should not travel: a
+/// URL's query (which can hold a token or the user's own words) and API-key
+/// shapes in a command are both gone, while host, path and command remain.
+#[tokio::test]
+async fn listed_calls_carry_no_query_strings_or_secrets() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ // Built here, not written as a literal: a key-shaped literal in source
+ // trips secret scanners, and the scrubber only sees the runtime string.
+ let fake_key = format!("sk-ant-{}{}", "abcdefghijklmnopqrstuvwxyz0123456789", "ABCDEF");
+ run_shell(
+ &mw,
+ "key-0",
+ &format!("curl -H 'x-api-key: {fake_key}' https://api.example.test/v1/run?debug=1"),
+ failing_result("shell", "boom"),
+ )
+ .await;
+ for i in 1..6 {
+ let id = format!("fetch-{i}");
+ let mut call = TaToolCall::new(
+ &id,
+ "web_fetch",
+ json!({ "url": format!("https://example.test/p{i}?token=abc{i}") }),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result("web_fetch", "boom");
+ mw.after_tool(&mut ctx(), &(), &invocation(&id, "web_fetch"), &mut result)
+ .await
+ .unwrap();
+ }
+ let summary = slot
+ .lock()
+ .unwrap()
+ .clone()
+ .expect("six varied failures halt");
+ assert!(
+ summary.contains("https://example.test/p1"),
+ "host and path kept: {summary}"
+ );
+ assert!(
+ !summary.contains("token=abc"),
+ "query strings dropped: {summary}"
+ );
+ assert!(
+ !summary.contains("?debug=1"),
+ "query dropped inside a command too: {summary}"
+ );
+ assert!(
+ !summary.contains("abcdefghijklmnopqrstuvwxyz0123456789"),
+ "key scrubbed: {summary}"
+ );
+ assert!(
+ summary.contains("curl -H"),
+ "the command itself is still named: {summary}"
+ );
+}