Skip to content

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

fix(agent): review follow-ups for the breaker: scrub halt text, cut URL queries anywhere, clear and nudge invalid_arguments

killbill83bb3f766c23
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 228ef7588f..50cd155db3 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@ -118,6 +118,10 @@ impl RepeatedToolFailureMiddleware {
.lock()
.map(|failures| failures.clone())
.unwrap_or_default();
+ // The crate's summary quotes the last error as the tool returned it;
+ // the whole text is read by the model and persisted with the session,
+ // so it is scrubbed here, at the one place every halt passes through.
+ let summary = crate::security::scrub::sanitize_text(&summary).value;
with_failing_calls(summary, &failures)
}
@@ -235,28 +239,44 @@ fn render_call(tool: &str, arguments: &serde_json::Value) -> String {
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 without_queries = cut_url_queries(&raw);
let scrubbed = crate::security::scrub::sanitize_text(&without_queries).value;
crate::util::truncate_with_ellipsis(&scrubbed, RENDERED_CALL_CHARS).to_string()
}
+/// `text` with every URL in it cut at its query or fragment, wherever the URL
+/// sits: at the start of a word, after `url=` or a quote, inside prose or a
+/// JSON string. The URL ends at the first whitespace or closing quote, bracket
+/// or parenthesis; what follows the `?` or `#` up to that end is dropped.
+fn cut_url_queries(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut rest = text;
+ loop {
+ let Some(pos) = ["https://", "http://"]
+ .iter()
+ .filter_map(|scheme| rest.find(scheme))
+ .min()
+ else {
+ out.push_str(rest);
+ return out;
+ };
+ let (before, from_scheme) = rest.split_at(pos);
+ out.push_str(before);
+ let end = from_scheme
+ .find(|c: char| c.is_whitespace() || matches!(c, '\'' | '"' | ')' | ']' | '>' | '}'))
+ .unwrap_or(from_scheme.len());
+ let (url, tail) = from_scheme.split_at(end);
+ out.push_str(url.split(['?', '#']).next().unwrap_or(url));
+ rest = tail;
+ }
+}
+
/// `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::String(s) if s.contains("http://") || s.contains("https://") => {
+ Value::String(cut_url_queries(s))
}
Value::Array(items) => Value::Array(items.iter().map(strip_url_queries).collect()),
Value::Object(map) => Value::Object(
@@ -271,6 +291,11 @@ fn strip_url_queries(value: &serde_json::Value) -> serde_json::Value {
/// 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 {
+ // The line is read by the model and persisted with the session in a halt
+ // summary, so it is scrubbed first: a command can print a token or a
+ // user's own words on stderr.
+ let scrubbed = crate::security::scrub::sanitize_text(text).value;
+ let text = scrubbed.as_str();
let first = text
.lines()
.find(|l| !l.trim().is_empty())
@@ -690,6 +715,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"validation",
"unavailable",
"service_refused",
+ "invalid_arguments",
] {
self.classified
.clear(&ClassifiedFailure::new(class, tool_name, &scope));
@@ -721,6 +747,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"missing_window"
| "missing_app"
| "validation"
+ | "invalid_arguments"
| "uncertain_side_effect"
| "unavailable"
| "service_refused"
@@ -731,6 +758,10 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
first_error_line(&failure_text)
),
"validation" => "The last call failed validation. Correct its schema or arguments once before trying again.".to_owned(),
+ "invalid_arguments" => format!(
+ "The `{tool_name}` call was rejected before it ran: its arguments did not match the tool's schema ({}). Read the tool's parameters and correct the call; do not resend it unchanged.",
+ first_error_line(&failure_text)
+ ),
"uncertain_side_effect" => "The last command timed out and was killed; it may have partly run. Check its effect before repeating anything, then retry at most once as a smaller, bounded step (fewer items per call, a per-item timeout such as `timeout 5`, or background it and poll).".to_owned(),
"unavailable" => format!("The `{tool_name}` tool is unavailable for the rest of this run: a module it needs failed to load and will not recover until the app restarts. Do not call `{tool_name}` again; continue with your other tools."),
_ => "The desktop target was not found. Rediscover the current app and window once before trying again.".to_owned(),
@@ -864,7 +895,9 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
let same_command_again = exit_report && {
let key = format!("{tool_name}\u{1f}{arg_fp}");
let mut last = self.last_exit_report.lock().ok();
- let repeat = last.as_deref().is_some_and(|l| l.as_deref() == Some(key.as_str()));
+ let repeat = last
+ .as_deref()
+ .is_some_and(|l| l.as_deref() == Some(key.as_str()));
if let Some(slot) = last.as_mut() {
**slot = Some(key);
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs
index 9ecd17f638..45bd44fbd9 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_classified_failure_tests.rs
@@ -279,24 +279,43 @@ async fn a_refused_integration_steers_the_model_off_it_instead_of_ending_the_run
);
mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
let mut result = failing_result("web_search_tool", refused);
- mw.after_tool(&mut ctx(), &(), &invocation(id, "web_search_tool"), &mut result)
- .await
- .unwrap();
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation(id, "web_search_tool"),
+ &mut result,
+ )
+ .await
+ .unwrap();
}
};
run("ws-1", "regex chess move generator").await;
- assert_eq!(drain_pause_count(&handle), 0, "a refused connector must not halt");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "a refused connector must not halt"
+ );
assert!(slot.lock().unwrap().is_none(), "no halt summary");
let nudges = mw.take_pending_nudges();
assert_eq!(nudges.len(), 1, "{nudges:?}");
- assert!(nudges[0].contains("`web_search_tool` tool cannot be used"), "{nudges:?}");
+ assert!(
+ nudges[0].contains("`web_search_tool` tool cannot be used"),
+ "{nudges:?}"
+ );
assert!(nudges[0].contains("HTTP 401"), "{nudges:?}");
- assert!(nudges[0].contains("continue with your other tools"), "{nudges:?}");
+ assert!(
+ nudges[0].contains("continue with your other tools"),
+ "{nudges:?}"
+ );
// The model insists on the same operation: now the ledger stops it.
run("ws-2", "regex chess move generator").await;
- assert_eq!(drain_pause_count(&handle), 1, "a second refusal of the same operation halts");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "a second refusal of the same operation halts"
+ );
let summary = slot.lock().unwrap().clone().unwrap();
assert!(summary.contains("service_refused"), "{summary}");
}
@@ -315,11 +334,21 @@ async fn a_refused_platform_fetch_still_stops_on_first_failure() {
);
mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
let mut result = failing_result("web_fetch", "401 Unauthorized");
- mw.after_tool(&mut ctx(), &(), &invocation("fetch-1", "web_fetch"), &mut result)
- .await
- .unwrap();
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("fetch-1", "web_fetch"),
+ &mut result,
+ )
+ .await
+ .unwrap();
assert_eq!(drain_pause_count(&handle), 1);
- assert!(slot.lock().unwrap().clone().unwrap().contains("authentication"));
+ assert!(slot
+ .lock()
+ .unwrap()
+ .clone()
+ .unwrap()
+ .contains("authentication"));
}
/// A shell success in between clears the ledger, so a later, unrelated timeout
@@ -480,9 +509,14 @@ async fn a_missing_file_from_any_tool_is_a_correctable_call() {
);
mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
let mut result = failing_result("use_skill", error);
- mw.after_tool(&mut ctx(), &(), &invocation("skill-1", "use_skill"), &mut result)
- .await
- .unwrap();
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("skill-1", "use_skill"),
+ &mut result,
+ )
+ .await
+ .unwrap();
assert_eq!(drain_pause_count(&handle), 0, "one wrong path never halts");
assert!(slot.lock().unwrap().is_none());
}
@@ -768,11 +802,18 @@ async fn a_credentialed_endpoint_is_steered_off_then_stopped() {
FETCH_403,
)
.await;
- assert_eq!(drain_pause_count(&handle), 0, "first refusal steers, not stops");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "first refusal steers, not stops"
+ );
assert!(slot.lock().unwrap().is_none());
let nudges = mw.take_pending_nudges();
assert_eq!(nudges.len(), 1, "{nudges:?}");
- assert!(nudges[0].contains("`composio_execute` tool cannot be used"), "{nudges:?}");
+ assert!(
+ nudges[0].contains("`composio_execute` tool cannot be used"),
+ "{nudges:?}"
+ );
fail_call(
&mw,
"cred-2",
@@ -781,7 +822,11 @@ async fn a_credentialed_endpoint_is_steered_off_then_stopped() {
FETCH_403,
)
.await;
- assert_eq!(drain_pause_count(&handle), 1, "the same refused operation again stops");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "the same refused operation again stops"
+ );
let summary = slot.lock().unwrap().clone().unwrap();
assert!(summary.contains("service_refused"), "{summary}");
}
@@ -868,3 +913,53 @@ fn fetched_site_status_reads_only_the_web_fetch_error_shape() {
assert_eq!(status(text), None, "{text}");
}
}
+
+/// Schema rejections are counted per turn of trouble, not per run: a success
+/// between them restarts the count, and the first rejection comes back with a
+/// correction nudge that names the tool and quotes the rejection.
+#[tokio::test]
+async fn a_success_clears_the_invalid_arguments_count_and_a_rejection_is_nudged() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 8, slot.clone());
+ async fn reject(mw: &RepeatedToolFailureMiddleware, id: &str) {
+ let mut call = TaToolCall::new(id, "search", serde_json::json!({"query": 1}));
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result =
+ failing_result("search", "schema validation failed: query must be a string");
+ mw.after_tool(&mut ctx(), &(), &invocation(id, "search"), &mut result)
+ .await
+ .unwrap();
+ }
+ reject(&mw, "r-1").await;
+ let nudges = mw.take_pending_nudges();
+ assert!(
+ nudges
+ .iter()
+ .any(|n| n.contains("`search` call was rejected") && n.contains("schema")),
+ "a rejection is nudged with the tool's name and the rejection: {nudges:?}"
+ );
+ reject(&mw, "r-2").await;
+ reject(&mw, "r-3").await;
+ let mut ok = TaToolCall::new("ok", "search", serde_json::json!({"query": "fine"}));
+ mw.before_tool(&mut ctx(), &(), &mut ok).await.unwrap();
+ let mut success = TaToolResult::success("hits");
+ mw.after_tool(&mut ctx(), &(), &invocation("ok", "search"), &mut success)
+ .await
+ .unwrap();
+ reject(&mw, "r-4").await;
+ reject(&mw, "r-5").await;
+ reject(&mw, "r-6").await;
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "the success restarted the count: three more rejections stay inside the budget"
+ );
+ assert!(slot.lock().unwrap().is_none());
+ reject(&mw, "r-7").await;
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "the fourth since the success stops"
+ );
+}
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 aeb79a885d..dbdd04b71d 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
@@ -266,11 +266,23 @@ async fn a_success_between_failures_clears_the_listed_calls() {
let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
let report = tinytools::render_command_failure(Some(1), "", "boom");
for i in 0..2 {
- run_shell(&mw, &format!("a-{i}"), "false-a", failing_result("shell", &report)).await;
+ run_shell(
+ &mw,
+ &format!("a-{i}"),
+ "false-a",
+ failing_result("shell", &report),
+ )
+ .await;
}
run_shell(&mw, "ok", "true", TaToolResult::success("fine")).await;
for i in 0..3 {
- run_shell(&mw, &format!("b-{i}"), "false-b", failing_result("shell", &report)).await;
+ run_shell(
+ &mw,
+ &format!("b-{i}"),
+ "false-b",
+ failing_result("shell", &report),
+ )
+ .await;
}
let summary = slot
.lock()
@@ -298,7 +310,10 @@ async fn listed_calls_carry_no_query_strings_or_secrets() {
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");
+ let fake_key = format!(
+ "sk-ant-{}{}",
+ "abcdefghijklmnopqrstuvwxyz0123456789", "ABCDEF"
+ );
run_shell(
&mw,
"key-0",
@@ -360,18 +375,49 @@ async fn six_different_failing_commands_are_investigation_not_a_loop() {
let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
let attempts = [
- ("pip install fasttext", exit_report(1, "", "RuntimeError: Unsupported compiler")),
- ("pip install fasttext-wheel", exit_report(1, "", "No matching distribution")),
- ("g++ --version", exit_report(127, "", "g++: command not found")),
- ("cat /etc/os-release; which cc gcc clang", exit_report(2, "Debian 12", "")),
- ("python -c 'import setuptools.build_meta'", exit_report(1, "", "BackendUnavailable")),
- ("apt-get install -y g++", exit_report(100, "", "E: Unable to locate package")),
- ("pip download fasttext --no-deps", exit_report(1, "", "network unreachable")),
+ (
+ "pip install fasttext",
+ exit_report(1, "", "RuntimeError: Unsupported compiler"),
+ ),
+ (
+ "pip install fasttext-wheel",
+ exit_report(1, "", "No matching distribution"),
+ ),
+ (
+ "g++ --version",
+ exit_report(127, "", "g++: command not found"),
+ ),
+ (
+ "cat /etc/os-release; which cc gcc clang",
+ exit_report(2, "Debian 12", ""),
+ ),
+ (
+ "python -c 'import setuptools.build_meta'",
+ exit_report(1, "", "BackendUnavailable"),
+ ),
+ (
+ "apt-get install -y g++",
+ exit_report(100, "", "E: Unable to locate package"),
+ ),
+ (
+ "pip download fasttext --no-deps",
+ exit_report(1, "", "network unreachable"),
+ ),
];
for (i, (command, report)) in attempts.iter().enumerate() {
- run_shell(&mw, &format!("probe-{i}"), command, failing_result("shell", report)).await;
+ run_shell(
+ &mw,
+ &format!("probe-{i}"),
+ command,
+ failing_result("shell", report),
+ )
+ .await;
}
- assert_eq!(drain_pause_count(&handle), 0, "distinct failing commands never halt");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "distinct failing commands never halt"
+ );
assert!(slot.lock().unwrap().is_none(), "no halt summary");
}
@@ -385,11 +431,18 @@ async fn the_same_failing_command_three_times_still_halts() {
&mw,
&format!("same-{i}"),
"pip install fasttext",
- failing_result("shell", &exit_report(1, "", "RuntimeError: Unsupported compiler")),
+ failing_result(
+ "shell",
+ &exit_report(1, "", "RuntimeError: Unsupported compiler"),
+ ),
)
.await;
}
- assert_eq!(drain_pause_count(&handle), 1, "an identical failing command still trips the ladder");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "an identical failing command still trips the ladder"
+ );
let summary = slot.lock().unwrap().clone().unwrap();
assert!(summary.contains("pip install fasttext"), "{summary}");
}
@@ -402,10 +455,108 @@ async fn a_different_command_between_repeats_resets_the_identical_count() {
let same = || failing_result("shell", &exit_report(1, "", "boom"));
run_shell(&mw, "a-1", "make", same()).await;
run_shell(&mw, "a-2", "make", same()).await;
- run_shell(&mw, "b-1", "ls build/", failing_result("shell", &exit_report(2, "", "No such file"))).await;
+ run_shell(
+ &mw,
+ "b-1",
+ "ls build/",
+ failing_result("shell", &exit_report(2, "", "No such file")),
+ )
+ .await;
run_shell(&mw, "a-3", "make", same()).await;
run_shell(&mw, "a-4", "make", same()).await;
- assert_eq!(drain_pause_count(&handle), 0, "the streak restarted after `ls build/`");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 0,
+ "the streak restarted after `ls build/`"
+ );
run_shell(&mw, "a-5", "make", same()).await;
- assert_eq!(drain_pause_count(&handle), 1, "three identical failures in a row halt");
+ assert_eq!(
+ drain_pause_count(&handle),
+ 1,
+ "three identical failures in a row halt"
+ );
+}
+
+/// The first error line a halt summary carries is scrubbed like the rendered
+/// call: a program that prints a key on stderr does not get it persisted.
+#[tokio::test]
+async fn a_halt_summary_never_carries_a_secret_printed_on_stderr() {
+ 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 fake_key = format!(
+ "sk-ant-{}{}",
+ "abcdefghijklmnopqrstuvwxyz0123456789", "ABCDEF"
+ );
+ for i in 0..6 {
+ let id = format!("leak-{i}");
+ let mut call = TaToolCall::new(
+ &id,
+ "web_fetch",
+ json!({ "url": format!("https://example.test/q{i}") }),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result(
+ "web_fetch",
+ &format!("boom (debug header x-api-key: {fake_key}, attempt {i})"),
+ );
+ 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("abcdefghijklmnopqrstuvwxyz0123456789"),
+ "the key on stderr is scrubbed from the error line: {summary}"
+ );
+ assert!(
+ summary.contains("boom"),
+ "the error itself is still named: {summary}"
+ );
+}
+
+/// A query is cut from a URL wherever the URL sits in an argument: after
+/// `url=`, after a verb, inside prose, not only at the start of a word.
+#[tokio::test]
+async fn queries_are_cut_from_urls_anywhere_in_an_argument() {
+ 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());
+ run_shell(
+ &mw,
+ "c-0",
+ "curl url=https://example.test/a?q=zzz0 -o out",
+ failing_result("shell", "boom"),
+ )
+ .await;
+ for i in 1..6 {
+ let id = format!("f-{i}");
+ let mut call = TaToolCall::new(
+ &id,
+ "web_fetch",
+ json!({ "url": format!("https://example.test/p{i}"), "source": format!("GET https://example.test/p{i}?q=zzz{i} then parse") }),
+ );
+ 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("token=zzz"),
+ "no query survives: {summary}"
+ );
+ assert!(
+ summary.contains("https://example.test/p1") && summary.contains("then parse"),
+ "host, path and the surrounding text remain: {summary}"
+ );
}