Skip to content

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

fix(harness): match tool outcomes by occurrence and word breaker halts neutrally

M3gA-Mind74ca95cab2b6
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core.rs b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
index 442aa141a8..b1e3119cd9 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
@@ -15,6 +15,35 @@ use crate::memory::MemoryCategory;
use anyhow::Result;
use std::hash::{Hash, Hasher};
+/// The outcome captured for one assistant tool call, matched by call id, tool
+/// name **and occurrence**.
+///
+/// Prompt-guided (XML / P-Format) calls carry no provider id, so every model
+/// response synthesizes `call_0`, `call_1`, … afresh (`tinyagents::model`), and a
+/// turn with several tool rounds repeats the same ids. A first-match lookup gave
+/// every later round the first round's result, so a turn's records could hide its
+/// latest failure (Codex review on #6289). The n-th call under an `(id, name)`
+/// takes the n-th outcome recorded under it: rounds run in order and ids are
+/// unique within a round, so parallel execution inside a round cannot reorder
+/// them. Keying on the name as well stops an unknown-tool call, which never
+/// reaches the capture sink, from consuming a later round's real outcome.
+fn nth_call_outcome<'a>(
+ tool_outcomes: &'a [crate::agent::tinyagents::ToolCallOutcome],
+ seen: &mut std::collections::HashMap<(String, String), usize>,
+ call_id: &str,
+ name: &str,
+) -> Option<&'a crate::agent::tinyagents::ToolCallOutcome> {
+ let occurrence = seen
+ .entry((call_id.to_string(), name.to_string()))
+ .or_insert(0);
+ let outcome = tool_outcomes
+ .iter()
+ .filter(|o| o.call_id == call_id && o.name == name)
+ .nth(*occurrence);
+ *occurrence += 1;
+ outcome
+}
+
/// Flatten the assistant tool calls a turn produced into [`ToolCallRecord`]s for
/// post-turn hooks + the deterministic cap checkpoint. Per-call success +
/// sanitized output summary are recovered from the turn's captured
@@ -26,10 +55,11 @@ fn tool_records_from_conversation(
tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
) -> Vec<hooks::ToolCallRecord> {
let mut records = Vec::new();
+ let mut seen = std::collections::HashMap::new();
for msg in conversation {
if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
for call in tool_calls {
- let outcome = tool_outcomes.iter().find(|o| o.call_id == call.id);
+ let outcome = nth_call_outcome(tool_outcomes, &mut seen, &call.id, &call.name);
// Default a MISSING outcome to `false` (#4467, item 7): a call
// with no captured outcome is a hallucinated/unknown tool the
// crate recovered via `ReturnToolError` without running
@@ -69,10 +99,11 @@ fn checkpoint_results_from_conversation(
tool_outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
) -> Vec<super::super::turn_checkpoint::CheckpointToolResult> {
let mut results = Vec::new();
+ let mut seen = std::collections::HashMap::new();
for msg in conversation {
if let ConversationMessage::AssistantToolCalls { tool_calls, .. } = msg {
for call in tool_calls {
- let outcome = tool_outcomes.iter().find(|o| o.call_id == call.id);
+ let outcome = nth_call_outcome(tool_outcomes, &mut seen, &call.id, &call.name);
// Same missing-outcome rule as `tool_records_from_conversation`:
// a call the crate recovered without running `after_tool` never
// reached the capture sink, so it is reported as failed rather
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
index 08e1374061..2d3e9d6f1d 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint.rs
@@ -284,8 +284,10 @@ pub(super) fn final_answer_instruction(stop_reason: Option<&str>, records: &str)
let mut out = String::new();
if let Some(reason) = stop_reason {
out.push_str(
- "The harness stopped this turn early after tool failures. Its stop note is written for \
- you, not for the user, so explain it in your own words rather than repeating it:\n\
+ "The harness stopped this turn early because its tool calls stopped making progress: they \
+ kept failing, or kept repeating the same step. Its stop note is written for you, not for \
+ the user, so explain it in your own words rather than repeating it, and describe each \
+ call as the tool records show it:\n\
<stop_note>\n",
);
out.push_str(reason.trim());
@@ -354,7 +356,7 @@ pub(super) fn parse_close_verdict(text: &str) -> CloseVerdict {
"REJECT" => Some(CloseVerdict::Reject),
_ => None,
})
- .last()
+ .next_back()
.unwrap_or(CloseVerdict::Unclear)
}
@@ -370,6 +372,9 @@ pub(super) fn parse_close_verdict(text: &str) -> CloseVerdict {
/// be reduced to the word "failed". When the breaker halted the run (issue
/// #6279) its stop note is quoted too, because it names the rung that tripped
/// and, for a missing connection or exhausted credits, what the user must do.
+/// The lead does not say the calls failed: `RepeatProgressMiddleware` halts
+/// through the same slot when identical calls keep *succeeding*, and the
+/// records below carry each call's real status.
pub(super) fn build_deterministic_final_summary(
results: &[CheckpointToolResult],
stop_reason: Option<&str>,
@@ -380,8 +385,8 @@ pub(super) fn build_deterministic_final_summary(
let mut out = match stop_reason {
Some(reason) => {
let mut lead = String::from(
- "I stopped this turn early because my tool calls kept failing, so I could not \
- finish the request.\n\n**Why I stopped**\n",
+ "I stopped this turn early because my tool calls were not making progress, so I \
+ could not finish the request.\n\n**Why I stopped**\n",
);
for line in reason.trim().lines() {
lead.push_str("> ");
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs
index dca8a4429b..9d846a6de6 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_checkpoint_tests.rs
@@ -176,6 +176,28 @@ fn the_final_summary_of_a_halted_turn_keeps_the_stop_note_and_the_records() {
);
}
+/// The breaker also halts a run whose identical calls keep succeeding
+/// (`RepeatProgressMiddleware`). The fallback must not call those calls failed
+/// when its own records show them `ok` (Codex review on #6289).
+#[test]
+fn the_final_summary_of_a_successful_repeat_halt_does_not_claim_failure() {
+ let out = build_deterministic_final_summary(
+ &[result("list_items", true, "3 items")],
+ Some(
+ "Stopping: the same successful tool-call batch was issued 3 times in a row with \
+ identical arguments and no new information.",
+ ),
+ );
+ assert!(
+ !out.to_lowercase().contains("fail"),
+ "a halt over successful calls must not be described as failing: {out}"
+ );
+ assert!(
+ out.contains("`list_items` — ok"),
+ "records keep their status: {out}"
+ );
+}
+
/// The wrap-up is grounded in the records it is handed, and only a halted run
/// passes a stop note.
#[test]
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs
index 7259743e72..a9f6f3cbd8 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_final_reply_grounding_tests.rs
@@ -32,6 +32,37 @@ impl Tool for FailingInstallTool {
}
}
+/// Succeeds on its first call and fails on every later one, so each tool round's
+/// record is distinguishable from the others.
+struct TwoRoundInstallTool {
+ calls: AtomicUsize,
+}
+
+#[async_trait]
+impl Tool for TwoRoundInstallTool {
+ fn name(&self) -> &str {
+ "install_item"
+ }
+
+ fn description(&self) -> &str {
+ "install an item"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type":"object"})
+ }
+
+ async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
+ if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
+ Ok(ToolResult::success(
+ "round one: found the demo item in the catalog",
+ ))
+ } else {
+ Ok(ToolResult::error(INSTALL_FAILURE))
+ }
+ }
+}
+
fn respond(text: &str) -> anyhow::Result<ChatResponse> {
Ok(ChatResponse {
text: Some(text.into()),
@@ -48,10 +79,13 @@ fn scripted(responses: Vec<anyhow::Result<ChatResponse>>) -> Arc<SequenceProvide
}
/// Run one turn against `provider`, returning the reply and everything streamed.
-async fn run_turn(provider: Arc<SequenceProvider>) -> (Agent, String, String) {
+async fn run_turn(
+ provider: Arc<SequenceProvider>,
+ tools: Vec<Box<dyn Tool>>,
+) -> (Agent, String, String) {
let mut agent = make_agent_with_builder(
provider,
- vec![Box::new(FailingInstallTool)],
+ tools,
vec![],
crate::config::AgentConfig {
max_tool_iterations: 8,
@@ -95,7 +129,8 @@ async fn an_intent_only_close_is_rejected_and_replaced_by_the_tool_records() {
respond("REJECT"),
]);
- let (agent, reply, streamed) = run_turn(recorded.clone()).await;
+ let (agent, reply, streamed) =
+ run_turn(recorded.clone(), vec![Box::new(FailingInstallTool)]).await;
assert!(
!reply.contains(NARRATION),
@@ -146,7 +181,7 @@ async fn an_accepted_close_is_streamed_and_kept() {
respond("ACCEPT"),
]);
- let (agent, reply, streamed) = run_turn(recorded).await;
+ let (agent, reply, streamed) = run_turn(recorded, vec![Box::new(FailingInstallTool)]).await;
assert_eq!(reply, CLOSE, "an accepted close is the reply");
assert!(
@@ -170,7 +205,7 @@ async fn a_breaker_halt_is_closed_for_the_user_instead_of_showing_the_stop_note(
respond("ACCEPT"),
]);
- let (agent, reply, _) = run_turn(recorded.clone()).await;
+ let (agent, reply, _) = run_turn(recorded.clone(), vec![Box::new(FailingInstallTool)]).await;
assert!(
!reply.contains("instead of retrying") && !reply.starts_with("Stopping:"),
@@ -195,3 +230,41 @@ async fn a_breaker_halt_is_closed_for_the_user_instead_of_showing_the_stop_note(
"the wrap-up must receive the stop note and the records as input, got: {wrap_up}"
);
}
+
+/// XML-dialect calls carry no provider id, so both rounds' calls are `call_0`.
+/// Each round must still be recorded with its own result: the second round's
+/// failure is why the request was not done, and a first-match lookup replaced it
+/// with the first round's success (Codex review on #6289).
+#[tokio::test]
+async fn each_tool_round_is_recorded_with_its_own_result() {
+ let recorded = scripted(vec![
+ respond(INSTALL_CALL),
+ respond(INSTALL_CALL),
+ respond(""),
+ respond("I'll look into the demo item."),
+ respond("REJECT"),
+ ]);
+
+ let (_, reply, _) = run_turn(
+ recorded.clone(),
+ vec![Box::new(TwoRoundInstallTool {
+ calls: AtomicUsize::new(0),
+ })],
+ )
+ .await;
+
+ assert!(
+ reply.contains("round one: found the demo item in the catalog"),
+ "the first round keeps its own result, got: {reply}"
+ );
+ assert!(
+ reply.contains("View it at https://example.test/demo"),
+ "the second round must be recorded with its own failure, not the first round's result, got: {reply}"
+ );
+ let requests = recorded.requests.lock().await;
+ let wrap_up = &requests[3].last().expect("wrap-up instruction").content;
+ assert!(
+ wrap_up.contains(INSTALL_FAILURE),
+ "the wrap-up records must carry the second round's failure, got: {wrap_up}"
+ );
+}