Skip to content

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

fix(agent): keep the latest round and the durable seed when a run fails

M3gA-Mindc1c6f6433e95
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
index f44cbe4423..9242883742 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
@@ -164,3 +164,56 @@ async fn turn_failing_on_first_call_records_the_cause() {
assert!(tail[0].1.contains("provider boom"), "got: {}", tail[0].1);
assert!(agent.session_transcript_path.is_some());
}
+
+/// #6281 review: an error in the tool stage, after a model response and before
+/// the next model request, still records that response's tool calls.
+#[tokio::test]
+async fn tool_stage_failure_keeps_the_latest_response() {
+ // One response asking for more tool calls than the turn's tool-call cap
+ // (eight per allowed model call): admission of the call past the cap fails
+ // the run in the tool stage, before any further model request.
+ let calls: String = (0..9)
+ .map(|n| {
+ format!("<tool_call>{{\"name\":\"echo\",\"arguments\":{{\"n\":{n}}}}}</tool_call>")
+ })
+ .collect();
+ let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
+ responses: AsyncMutex::new(vec![Ok(ChatResponse {
+ text: Some(calls),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ })]),
+ requests: AsyncMutex::new(Vec::new()),
+ tool_counts: AsyncMutex::new(Vec::new()),
+ });
+ let mut agent = make_agent_with_builder(
+ provider,
+ vec![Box::new(EchoTool)],
+ vec![],
+ crate::config::AgentConfig {
+ max_tool_iterations: 1,
+ ..crate::config::AgentConfig::default()
+ },
+ crate::config::ContextConfig::default(),
+ );
+
+ let err = agent
+ .turn("run the task")
+ .await
+ .expect_err("the call past the tool-call cap fails the turn");
+
+ let note = match agent.history.last() {
+ Some(ConversationMessage::Chat(chat)) if chat.role == "assistant" => chat.content.clone(),
+ other => panic!("a failed turn must end history on its failure note, got: {other:?}"),
+ };
+ assert!(
+ note.contains("called `echo`"),
+ "the response the tool stage failed on must be kept as text ({err}), got: {note}"
+ );
+ assert_eq!(
+ tool_call_rounds(&agent),
+ 0,
+ "a response no provider has seen again is never replayed as structured tool calls"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
index 338f3b2ec1..904cb6ecb7 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/dispatch.rs
@@ -334,15 +334,18 @@ pub(in super::super) async fn run_subagent_via_graph(
// error. Previously the `?`-return skipped both persistence steps, so
// a failed run left no transcript and an empty worker thread.
let mapped = map_tinyagents_subagent_error(err);
- // Persist only what a provider accepted as structured history: a
- // request rejected for malformed tool history must not be replayed by
- // a resumed sub-agent. The unanswered suffix rides the failure marker
- // as text (#6281).
+ // Persist the caller's original history plus only what a provider
+ // accepted as structured messages: a request rejected for malformed
+ // tool history must not be replayed by a resumed sub-agent, and the
+ // snapshot's own seed is the provider-bound copy with rehydrated
+ // images. The unanswered suffix rides the failure marker as text
+ // (#6281).
let (recovered, unanswered_steps, recovered_usage) = {
let snapshot = transcript_snapshot
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
- let end = snapshot.accepted_end();
+ let (recovered, unanswered) =
+ super::transcript::failed_run_history(history.as_slice(), &snapshot);
let usage = AggregatedUsage {
input_tokens: snapshot.input_tokens,
output_tokens: snapshot.output_tokens,
@@ -354,11 +357,7 @@ pub(in super::super) async fn run_subagent_via_graph(
snapshot.cached_input_tokens,
),
};
- (
- crate::agent::message_convert::messages_to_history(&snapshot.messages[..end]),
- crate::agent::tinyagents::render_unanswered_steps(&snapshot.messages[end..]),
- usage,
- )
+ (recovered, unanswered, usage)
};
tracing::warn!(
agent_id,
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
index 42166c16c0..1b2fb6dbe2 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph/transcript.rs
@@ -7,6 +7,34 @@ use crate::agent::messages::ChatMessage;
use super::dispatch::AggregatedUsage;
use super::worker_mirror::mirror_worker_thread_from_history;
+/// The history a failed sub-agent run persists, plus the unanswered steps as
+/// text (#6281).
+///
+/// Starts from the caller's original `history`, not the snapshot's seeded
+/// prefix: that prefix is the provider-bound `dispatch_history`, which carries
+/// rehydrated image data where the durable history keeps its placeholders. Only
+/// the rounds a provider accepted follow it as structured messages. An empty
+/// snapshot (the run failed before its first model call) recovers nothing, as
+/// before.
+pub(super) fn failed_run_history(
+ original: &[ChatMessage],
+ snapshot: &crate::agent::tinyagents::TranscriptSnapshot,
+) -> (Vec<ChatMessage>, Option<String>) {
+ if snapshot.messages.is_empty() {
+ return (Vec::new(), None);
+ }
+ let base = snapshot.request_base_len.min(snapshot.messages.len());
+ let end = snapshot.accepted_end();
+ let mut recovered = original.to_vec();
+ recovered.extend(crate::agent::message_convert::messages_to_history(
+ &snapshot.messages[base..end],
+ ));
+ (
+ recovered,
+ crate::agent::tinyagents::render_unanswered_steps(&snapshot.messages[end..]),
+ )
+}
+
/// Persist a sub-agent turn's raw transcript to `session_raw`, mirroring the
/// removed `SubagentObserver::persist_transcript`: `agent_type:"subagent"`, the
/// `task_id`, and the provider/model + usage carried on the last assistant
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_failed_run_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_failed_run_tests.rs
index f4649789d3..332b8f4477 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_failed_run_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_failed_run_tests.rs
@@ -102,3 +102,60 @@ async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
"the marker carries the cause and the unanswered round as text, got: {marker}"
);
}
+
+/// #6281 review: a failed run recovers the caller's original history, not the
+/// provider-bound seed the snapshot started from (which carries rehydrated image
+/// data for a vision run).
+#[test]
+fn failed_run_history_keeps_the_original_seed_not_the_provider_bound_one() {
+ use crate::agent::tinyagents::TranscriptSnapshot;
+ use tinyinference::message::Message;
+
+ let original = vec![ChatMessage::user("describe [IMAGE:attachment-1]")];
+ let snapshot = TranscriptSnapshot {
+ messages: vec![
+ // The provider-bound seed: the placeholder expanded to image data.
+ Message::user("describe data:image/png;base64,AAAA"),
+ // Round 0, answered by the next request.
+ Message::Assistant(
+ tool_response("call-0", "echo", serde_json::json!({ "msg": "round-0" })).message,
+ ),
+ Message::tool("call-0", "echoed:round-0"),
+ // Round 1, carried only by the failing request.
+ Message::Assistant(
+ tool_response("call-1", "echo", serde_json::json!({ "msg": "round-1" })).message,
+ ),
+ Message::tool("call-1", "echoed:round-1"),
+ ],
+ accepted_len: 3,
+ request_base_len: 1,
+ ..TranscriptSnapshot::default()
+ };
+
+ let (recovered, unanswered) =
+ super::super::transcript::failed_run_history(&original, &snapshot);
+
+ assert_eq!(
+ recovered.first().map(|message| message.content.as_str()),
+ Some("describe [IMAGE:attachment-1]"),
+ "the durable placeholder must be kept: {recovered:?}"
+ );
+ assert!(
+ !recovered
+ .iter()
+ .any(|message| message.content.contains("base64")),
+ "provider-bound image data must not be persisted: {recovered:?}"
+ );
+ assert_eq!(
+ recovered
+ .iter()
+ .filter(|message| message.role == "tool")
+ .count(),
+ 1,
+ "only the accepted round follows the seed: {recovered:?}"
+ );
+ assert!(
+ unanswered.is_some_and(|steps| steps.contains("round-1")),
+ "the unanswered round is kept as text"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
index 34334cafa2..368e422b7a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -70,8 +70,9 @@ pub(crate) struct TurnContextMiddleware {
/// What a [`TranscriptSnapshotMiddleware`] has seen of a live run.
#[derive(Default)]
pub(crate) struct TranscriptSnapshot {
- /// The transcript of the most recent model request: the run's input plus
- /// every assistant/tool round completed before that call.
+ /// The transcript of the most recent model request (the run's input plus
+ /// every round completed before that call), followed by the response and
+ /// tool results produced since, so an error in a later stage still has them.
pub(crate) messages: Vec<Message>,
/// Length of the most recent request the provider **answered**. The loop
/// only appends to its working transcript, so `messages[..accepted_len]` is
@@ -161,6 +162,23 @@ impl Middleware<()> for TranscriptSnapshotMiddleware {
"openhuman.transcript_snapshot"
}
+ async fn after_tool(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ result: &mut TaToolResult,
+ ) -> TaResult<()> {
+ // A tool result reaches a provider only with the next request, so it
+ // also sits past `accepted_len` until that request is answered.
+ if let Ok(mut guard) = self.sink.lock() {
+ guard.messages.push(Message::tool(
+ result.call_id.clone(),
+ result.content.clone(),
+ ));
+ }
+ Ok(())
+ }
+
async fn before_model(
&self,
_ctx: &mut RunContext<()>,
@@ -181,6 +199,12 @@ impl Middleware<()> for TranscriptSnapshotMiddleware {
) -> TaResult<()> {
if let Ok(mut guard) = self.sink.lock() {
guard.accepted_len = guard.messages.len();
+ // The response has not been sent back to a provider yet, so it sits
+ // past `accepted_len`; an error before the next request still keeps
+ // it, as text.
+ guard
+ .messages
+ .push(Message::Assistant(response.message.clone()));
// A cache replay consumed no provider tokens.
if let Some(usage) = response
.usage