Skip to content

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

fix(agent): record answered-call usage and split sub-agent failures at the accepted boundary

M3gA-Minde3bae2c12cb6
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
index 121b189520..c4ab25ccd5 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
@@ -5,7 +5,9 @@ use crate::agent::harness::session::turn_checkpoint::{truncate_chars, CHECKPOINT
use crate::agent::harness::session::types::Agent;
use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
use crate::agent::messages::{ChatMessage, ConversationMessage};
-use crate::agent::tinyagents::{TranscriptSnapshot, TranscriptSnapshotSink};
+use crate::agent::tinyagents::{
+ render_unanswered_steps, TranscriptSnapshot, TranscriptSnapshotSink,
+};
use anyhow::Result;
use tinyinference::message::Message;
@@ -63,7 +65,10 @@ impl Agent {
effective_model: &str,
err: &anyhow::Error,
) {
- let (accepted, unanswered) = split_snapshot(snapshot);
+ let base = snapshot.request_base_len.min(snapshot.messages.len());
+ let accepted_end = snapshot.accepted_end();
+ let accepted = &snapshot.messages[base..accepted_end];
+ let unanswered = &snapshot.messages[accepted_end..];
log::warn!(
"[agent_loop] turn failed; recording {} accepted round message(s), {} unanswered \
message(s) as text, and the failure cause into history session_id={} \
@@ -91,75 +96,56 @@ impl Agent {
)));
self.trim_history();
+ // The calls the provider answered were billed even though the turn
+ // failed. Their spend already reached the cost tracker live (the event
+ // bridge records usage per call); the transcript records the same totals
+ // instead of zeros.
+ let (input, output, cached) = (
+ snapshot.input_tokens,
+ snapshot.output_tokens,
+ snapshot.cached_input_tokens,
+ );
+ let cost_usd = crate::platform::cost::catalog::estimate_cost_usd(
+ effective_model,
+ input,
+ output,
+ cached,
+ );
let persisted = self.tool_dispatcher.to_provider_messages(&self.history);
- // A failed run reports no usage; record zeros, but keep the provider and
- // model so the transcript meta stays attributable.
let turn_usage = TurnUsage {
provider: self.event_channel().to_string(),
model: effective_model.to_string(),
usage: MessageUsage {
- input: 0,
- output: 0,
- cached_input: 0,
+ input,
+ output,
+ cached_input: cached,
context_window: 0,
- cost_usd: 0.0,
+ cost_usd,
},
ts: chrono::Utc::now().to_rfc3339(),
reasoning_content: None,
tool_calls: Vec::new(),
iteration: 0,
};
- self.persist_session_transcript(&persisted, 0, 0, 0, 0.0, Some(&turn_usage));
+ self.persist_session_transcript(
+ &persisted,
+ input,
+ output,
+ cached,
+ cost_usd,
+ Some(&turn_usage),
+ );
}
}
-/// Split a snapshot into this run's rounds the provider answered and the ones
-/// only the failing (unanswered) request carried.
-fn split_snapshot(snapshot: &TranscriptSnapshot) -> (&[Message], &[Message]) {
- let len = snapshot.messages.len();
- let base = snapshot.request_base_len.min(len);
- let accepted_end = snapshot.accepted_len.clamp(base, len);
- (
- &snapshot.messages[base..accepted_end],
- &snapshot.messages[accepted_end..],
- )
-}
-
/// The failure cause, plus the unanswered steps rendered as text.
fn failed_turn_note(err: &anyhow::Error, unanswered: &[Message]) -> String {
- let mut note = format!(
+ let cause = format!(
"{FAILED_TURN_NOTE_PREFIX} {}]",
truncate_chars(&err.to_string(), CHECKPOINT_RESULT_CHARS)
);
- if unanswered.is_empty() {
- return note;
- }
- note.push_str("\n\nThe request that failed also carried these steps, recorded here as text:\n");
- for msg in unanswered {
- match msg {
- Message::Assistant(assistant) if !assistant.tool_calls.is_empty() => {
- for call in &assistant.tool_calls {
- let call = crate::agent::message_convert::ta_call_to_oh_call(call);
- note.push_str(&format!(
- "- called `{}` with {}\n",
- call.name,
- truncate_chars(&call.arguments, CHECKPOINT_RESULT_CHARS)
- ));
- }
- }
- Message::Tool(_) => note.push_str(&format!(
- "- tool result: {}\n",
- truncate_chars(&msg.text(), CHECKPOINT_RESULT_CHARS)
- )),
- Message::Assistant(_) => note.push_str(&format!(
- "- assistant: {}\n",
- truncate_chars(&msg.text(), CHECKPOINT_RESULT_CHARS)
- )),
- Message::User(_) | Message::System(_) => note.push_str(&format!(
- "- message: {}\n",
- truncate_chars(&msg.text(), CHECKPOINT_RESULT_CHARS)
- )),
- }
+ match render_unanswered_steps(unanswered) {
+ Some(steps) => format!("{cause}\n\n{steps}"),
+ None => cause,
}
- note
}
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 a5fccc0c0c..f44cbe4423 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
@@ -4,7 +4,11 @@ fn echo_tool_call() -> anyhow::Result<ChatResponse> {
Ok(ChatResponse {
text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
tool_calls: vec![],
- usage: None,
+ usage: Some(UsageInfo {
+ input_tokens: 100,
+ output_tokens: 7,
+ ..UsageInfo::default()
+ }),
reasoning_content: None,
})
}
@@ -100,6 +104,13 @@ async fn failed_turn_keeps_its_work_and_cause_for_the_next_turn() {
.any(|message| message.role == "assistant" && message.content.contains("provider boom")),
"the persisted transcript must carry the failure note"
);
+ // Both answered calls reported usage before the failure; the failed turn
+ // records it rather than zeros.
+ assert_eq!(
+ (persisted.meta.input_tokens, persisted.meta.output_tokens),
+ (200, 14),
+ "the failed turn must record the usage of its answered calls"
+ );
agent
.turn("what happened?")
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 cd1364ed60..338f3b2ec1 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
@@ -243,6 +243,12 @@ pub(in super::super) async fn run_subagent_via_graph(
// request's transcript here, so the error path below can still persist the
// rounds that completed before the failure.
let transcript_snapshot = crate::agent::tinyagents::TranscriptSnapshotSink::default();
+ // The seeded history is always kept; only rounds past it are split into
+ // accepted and unanswered on failure (#6281).
+ transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .request_base_len = dispatch_history.len();
// A sub-agent turn runs *nested inside* the parent agent's turn (parent
// harness → spawn_subagent tool → here), so the child's full
@@ -328,15 +334,38 @@ 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);
- let recovered = transcript_snapshot
- .lock()
- .map(|g| crate::agent::message_convert::messages_to_history(&g.messages))
- .unwrap_or_default();
+ // 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).
+ 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 usage = AggregatedUsage {
+ input_tokens: snapshot.input_tokens,
+ output_tokens: snapshot.output_tokens,
+ cached_input_tokens: snapshot.cached_input_tokens,
+ charged_amount_usd: crate::platform::cost::catalog::estimate_cost_usd(
+ model,
+ snapshot.input_tokens,
+ snapshot.output_tokens,
+ snapshot.cached_input_tokens,
+ ),
+ };
+ (
+ crate::agent::message_convert::messages_to_history(&snapshot.messages[..end]),
+ crate::agent::tinyagents::render_unanswered_steps(&snapshot.messages[end..]),
+ usage,
+ )
+ };
tracing::warn!(
agent_id,
task_id,
error = %mapped,
recovered_rounds = recovered.len(),
+ unanswered_steps = unanswered_steps.is_some(),
"[subagent_runner:graph] sub-agent run errored; persisting recovered transcript before returning (#4466)"
);
super::transcript::persist_failed_run(
@@ -347,6 +376,8 @@ pub(in super::super) async fn run_subagent_via_graph(
provider_label,
model,
&recovered,
+ &recovered_usage,
+ unanswered_steps.as_deref(),
context_window.unwrap_or(0),
if native_tools { "native" } else { "xml" },
worker_thread_id.as_deref(),
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 eaa35e7d15..42166c16c0 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
@@ -84,9 +84,11 @@ pub(super) fn persist_subagent_transcript(
/// transcript-snapshot middleware captured before the harness error to
/// `session_raw` (so `learning/transcript_ingest` can still ingest a failed run,
/// not skip an absent file), mirror those rounds onto the worker thread, and
-/// append a trailing failure marker so the record is self-describing. Usage is
-/// zeroed — the harness reported no totals on the error path — and the iteration
-/// count is the number of completed rounds recovered.
+/// append a trailing failure marker so the record is self-describing. `recovered`
+/// holds only what a provider accepted; steps only the failing request carried
+/// arrive as `unanswered_steps` text and are appended to the marker (#6281).
+/// `usage` is what the answered calls reported, and the iteration count is the
+/// number of completed rounds recovered.
#[allow(clippy::too_many_arguments)]
pub(super) fn persist_failed_run(
workspace_dir: &std::path::Path,
@@ -96,18 +98,20 @@ pub(super) fn persist_failed_run(
provider_label: &str,
model: &str,
recovered: &[ChatMessage],
+ usage: &AggregatedUsage,
+ unanswered_steps: Option<&str>,
context_window: u64,
dispatcher: &str,
worker_thread_id: Option<&str>,
error: &SubagentRunError,
) {
- let marker = format!("[subagent run failed before completion: {error}]");
+ let marker = match unanswered_steps {
+ Some(steps) => format!("[subagent run failed before completion: {error}]\n\n{steps}"),
+ None => format!("[subagent run failed before completion: {error}]"),
+ };
let mut history = recovered.to_vec();
history.push(ChatMessage::assistant(marker.clone()));
- // A failed run has no usage totals; record zeros so the transcript is still a
- // valid, ingestable `session_raw` record with the failure surfaced.
- let usage = AggregatedUsage::default();
persist_subagent_transcript(
workspace_dir,
transcript_stem,
@@ -116,7 +120,7 @@ pub(super) fn persist_failed_run(
provider_label,
model,
&history,
- &usage,
+ usage,
context_window,
dispatcher,
recovered.len() as u32,
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
new file mode 100644
index 0000000000..f4649789d3
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_failed_run_tests.rs
@@ -0,0 +1,104 @@
+use super::*;
+
+/// Answers two tool rounds, then rejects the third request with a 400 (which the
+/// harness does not retry).
+struct FailsOnThirdCallProvider {
+ calls: AtomicUsize,
+}
+#[async_trait]
+impl ChatModel<()> for FailsOnThirdCallProvider {
+ fn profile(&self) -> Option<&ModelProfile> {
+ Some(native_tool_profile())
+ }
+
+ async fn invoke(
+ &self,
+ _state: &(),
+ _request: ModelRequest,
+ ) -> tinyinference::Result<ModelResponse> {
+ let n = self.calls.fetch_add(1, Ordering::SeqCst);
+ if n < 2 {
+ Ok(tool_response(
+ &format!("call-{n}"),
+ "echo",
+ serde_json::json!({ "msg": format!("round-{n}") }),
+ ))
+ } else {
+ Err(tinyinference::Error::Model(
+ "400 Bad Request: provider boom".to_string(),
+ ))
+ }
+ }
+}
+
+/// #6281: a failed sub-agent run persists only the round a provider accepted as
+/// structured history; the round only the rejected request carried goes into the
+/// failure marker as text, so a resumed sub-agent cannot replay it.
+#[tokio::test]
+async fn failed_subagent_run_keeps_its_unanswered_round_out_of_history() {
+ let provider = Arc::new(FailsOnThirdCallProvider {
+ calls: AtomicUsize::new(0),
+ });
+ let parent_tools: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![Box::new(EchoTool)]);
+ let mut allowed = HashSet::new();
+ allowed.insert("echo".to_string());
+ let mut history = vec![ChatMessage::user("please echo twice")];
+ let workspace = tempfile::TempDir::new().expect("temp workspace");
+ let stem = "root-session__failed_run";
+
+ let result = run_subagent_via_graph(
+ crate::agent::tinyagents::TurnModelSource::from_model(provider),
+ "mock-model",
+ 0.0,
+ &mut history,
+ parent_tools,
+ vec![],
+ vec![],
+ allowed,
+ 10,
+ None,
+ None,
+ "researcher",
+ "task-failed",
+ false,
+ None,
+ workspace.path().to_path_buf(),
+ None,
+ 1024,
+ false,
+ stem,
+ "mock-channel",
+ None,
+ AgentTokenjuiceCompression::Off,
+ None,
+ )
+ .await;
+ assert!(result.is_err(), "the rejected third call fails the run");
+
+ use crate::agent::harness::session::transcript;
+ let path =
+ transcript::resolve_keyed_transcript_path(workspace.path(), stem).expect("transcript path");
+ let persisted = transcript::read_transcript(&path).expect("failed run transcript");
+ let tool_rows: Vec<&str> = persisted
+ .messages
+ .iter()
+ .filter(|message| message.role == "tool")
+ .map(|message| message.content.as_str())
+ .collect();
+ assert_eq!(
+ tool_rows.len(),
+ 1,
+ "only the accepted round is persisted as a tool row: {tool_rows:?}"
+ );
+ assert!(
+ tool_rows[0].contains("echoed:round-0"),
+ "got: {tool_rows:?}"
+ );
+ let marker = &persisted.messages.last().expect("failure marker").content;
+ assert!(
+ marker.starts_with("[subagent run failed before completion:")
+ && marker.contains("provider boom")
+ && marker.contains("round-1"),
+ "the marker carries the cause and the unanswered round as text, got: {marker}"
+ );
+}
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
index fd0148e925..665a16f767 100644
--- a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/graph_tests.rs
@@ -77,6 +77,9 @@ impl ChatModel<()> for TwoStepProvider {
}
}
+#[path = "graph_failed_run_tests.rs"]
+mod graph_failed_run_tests;
+
#[tokio::test]
async fn subagent_runs_through_the_graph_engine_with_real_tools() {
let provider = Arc::new(TwoStepProvider {
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
index 1cc9ceb184..642ea72f74 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
@@ -61,7 +61,8 @@ pub(crate) use tool_exposure::OpenHumanToolExposureShadowMiddleware;
pub(crate) use tool_outcome_capture::ToolOutcomeCaptureMiddleware;
pub(crate) use tool_policy::ToolPolicyMiddleware;
pub(crate) use turn_context::{
- HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink, TurnContextMiddleware,
+ render_unanswered_steps, HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink,
+ TurnContextMiddleware,
};
#[cfg(test)]
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 5d99406e35..34334cafa2 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -83,6 +83,57 @@ pub(crate) struct TranscriptSnapshot {
/// this run produced start at `messages[request_base_len..]`. Set by the
/// caller; `0` when the caller does not need the split.
pub(crate) request_base_len: usize,
+ /// Usage the provider reported for the calls it answered (cache replays
+ /// excluded), so a run that fails still accounts for what it spent.
+ pub(crate) input_tokens: u64,
+ pub(crate) output_tokens: u64,
+ pub(crate) cached_input_tokens: u64,
+}
+
+/// Display cap for one unanswered step in a failure note, matching the cap
+/// checkpoint's per-result slice.
+const UNANSWERED_STEP_CHARS: usize = 800;
+
+impl TranscriptSnapshot {
+ /// End of the prefix the provider accepted: never before the seeded input,
+ /// never past the snapshot.
+ pub(crate) fn accepted_end(&self) -> usize {
+ let len = self.messages.len();
+ self.accepted_len.clamp(self.request_base_len.min(len), len)
+ }
+}
+
+/// Render the messages only an unanswered request carried as plain text for a
+/// failure note, or `None` when there are none. Text cannot be replayed as a
+/// malformed tool sequence, so it is safe to persist where structured messages
+/// from a rejected request are not (#6281).
+pub(crate) fn render_unanswered_steps(messages: &[Message]) -> Option<String> {
+ if messages.is_empty() {
+ return None;
+ }
+ let clip = |text: &str| crate::util::truncate_with_ellipsis(text.trim(), UNANSWERED_STEP_CHARS);
+ let mut out =
+ String::from("The request that failed also carried these steps, recorded here as text:\n");
+ for msg in messages {
+ match msg {
+ Message::Assistant(assistant) if !assistant.tool_calls.is_empty() => {
+ for call in &assistant.tool_calls {
+ let call = crate::agent::message_convert::ta_call_to_oh_call(call);
+ out.push_str(&format!(
+ "- called `{}` with {}\n",
+ call.name,
+ clip(&call.arguments)
+ ));
+ }
+ }
+ Message::Tool(_) => out.push_str(&format!("- tool result: {}\n", clip(&msg.text()))),
+ Message::Assistant(_) => out.push_str(&format!("- assistant: {}\n", clip(&msg.text()))),
+ Message::User(_) | Message::System(_) => {
+ out.push_str(&format!("- message: {}\n", clip(&msg.text())))
+ }
+ }
+ }
+ Some(out)
}
/// Shared buffer a [`TranscriptSnapshotMiddleware`] mirrors the live
@@ -126,10 +177,20 @@ impl Middleware<()> for TranscriptSnapshotMiddleware {
&self,
_ctx: &mut RunContext<()>,
_state: &(),
- _response: &mut ModelResponse,
+ response: &mut ModelResponse,
) -> TaResult<()> {
if let Ok(mut guard) = self.sink.lock() {
guard.accepted_len = guard.messages.len();
+ // A cache replay consumed no provider tokens.
+ if let Some(usage) = response
+ .usage
+ .as_ref()
+ .filter(|_| !response.served_from_cache)
+ {
+ guard.input_tokens += usage.input_tokens;
+ guard.output_tokens += usage.output_tokens;
+ guard.cached_input_tokens += usage.cache_read_tokens;
+ }
}
Ok(())
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index fe3789e636..3a753900d3 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -72,7 +72,8 @@ pub(crate) use crate::agent::message_convert::{reasoning_from_content, ta_call_t
#[allow(unused_imports)] // Wired into the recall/retrieval facade in workstream 09.2.
pub(crate) use embeddings::ProviderEmbeddingModel;
pub(crate) use middleware::{
- HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink, TurnContextMiddleware,
+ render_unanswered_steps, HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink,
+ TurnContextMiddleware,
};
pub(crate) use observability::SubagentScope;
pub use resolved_route::{