Skip to content

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

feat(agent): attach tool calls and failure metadata to text-dialect rounds

Steven Enamakel816ef1650151
diff --git a/crates/openhuman-core/src/agent/messages.rs b/crates/openhuman-core/src/agent/messages.rs
index 87daccc16b..ea3d937981 100644
--- a/crates/openhuman-core/src/agent/messages.rs
+++ b/crates/openhuman-core/src/agent/messages.rs
@@ -14,6 +14,12 @@ const REPLAYED_METADATA_KEY: &str = "openhuman_replayed";
const WRAPPED_VALUE_KEY: &str = "openhuman_wrapped_value";
const WRAPPED_FLAG: &str = "wrapped";
+/// Durable `extra_metadata` key on a text-dialect `[Tool results]` user row:
+/// the call ids whose results in that row failed. The per-result analogue of
+/// the `tool_failure` a native `tool` row carries; written by the session codec
+/// and read by the thread transcript projection.
+pub(crate) const TOOL_RESULT_FAILURES_METADATA_KEY: &str = "openhuman_tool_failures";
+
fn would_wrap(message: &ChatMessage) -> bool {
matches!(&message.extra_metadata, Some(value) if !value.is_object())
}
diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs
index b762849a77..b9ea1695fa 100644
--- a/crates/openhuman-core/src/agent/session_host/codec.rs
+++ b/crates/openhuman-core/src/agent/session_host/codec.rs
@@ -6,7 +6,10 @@
use crate::agent::{
message_convert,
- messages::{chat_message_from_transcript, transcript_message_from_chat},
+ messages::{
+ chat_message_from_transcript, transcript_message_from_chat,
+ TOOL_RESULT_FAILURES_METADATA_KEY,
+ },
tinyagents::host::OpenHumanRunContext,
};
use tinyagents_runtime::{RuntimeError, TranscriptCodec, TranscriptTurnOptions};
@@ -14,6 +17,7 @@ use tinyagents_session::transcript::{
MessageUsage, SessionTranscript, ToolFailure, TranscriptMessage, TranscriptToolCall, TurnUsage,
};
use tinyinference_llm::message::Message;
+use tinytools_agent::dialect::parse_replayed_results;
/// Converts OpenHuman's durable transcript rows at the TinyAgents boundary.
#[derive(Default)]
@@ -51,6 +55,7 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
// keeps non-prefix messages. New messages alone receive this turn's
// request correlation id.
let mut consumed = vec![false; previous.len().min(prior.len())];
+ let mut fresh = vec![false; rows.len()];
for (next_index, next_message) in next.iter().enumerate() {
let matched = previous.iter().enumerate().take(consumed.len()).find_map(
|(previous_index, previous_message)| {
@@ -63,6 +68,7 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
consumed[previous_index] = true;
} else {
rows[next_index].request_id = options.request_id.clone();
+ fresh[next_index] = true;
}
}
// The generic inference `Message::Tool` intentionally carries only a
@@ -70,11 +76,13 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
// sidecar preserves the execution failure bit until this persistence
// boundary, so resumed transcript rows retain the same failure status
// the live tool timeline observed.
- let failures = options
+ let sidecar = options
.context
.session_sidecar
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clone();
+ let failures = sidecar
.tool_outcomes
.iter()
.filter(|outcome| !outcome.success)
@@ -88,6 +96,12 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
});
}
}
+ attach_text_dialect_rounds(
+ &mut rows,
+ &fresh,
+ &sidecar.tool_outcomes,
+ sidecar.resolved_route.as_ref(),
+ );
Ok(rows)
}
@@ -164,17 +178,129 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
},
ts: chrono::Utc::now().to_rfc3339(),
reasoning_content: None,
- tool_calls: sidecar
- .tool_outcomes
- .iter()
- .map(|outcome| TranscriptToolCall {
- id: outcome.call_id.clone(),
- name: outcome.name.clone(),
- arguments: outcome.arguments.to_string(),
- extra_content: None,
- })
- .collect(),
+ // The writer attaches this record to the turn's *final* assistant
+ // row. A call belongs to the row that issued it — the native
+ // envelope, or `attach_text_dialect_rounds` for a text dialect —
+ // so listing the turn's calls here filed every one of them under
+ // the answer that followed their results, and the projection
+ // reported them as never settled.
+ tool_calls: Vec::new(),
iteration: sidecar.model_calls.min(u32::MAX as usize) as u32,
}))
}
}
+
+/// Give each text-dialect tool round's calls to the assistant row that issued
+/// them, and record which of its results failed.
+///
+/// A native round is persisted as a `{content, tool_calls}` envelope followed
+/// by `tool` rows, so its calls and failure bits already sit on the right rows.
+/// A text dialect (`xml`, `pformat`, code) persists its replay form instead: the
+/// issuing assistant row holds only prose, and every result of the round is
+/// folded into one `[Tool results]` user row. Neither shape can say which calls
+/// were made or which of them failed, so this reads the round's call ids back
+/// out of that results row and takes names, arguments and outcomes from the
+/// turn sidecar:
+///
+/// - the issuing row (the fresh assistant row directly before the results row)
+/// gets a provenance-only [`TurnUsage`] — zero spend, since the turn's spend
+/// is recorded once on its final row — whose `tool_calls` are this round's;
+/// - the results row gets the ids of its failed results under
+/// [`TOOL_RESULT_FAILURES_METADATA_KEY`], the per-result analogue of a native
+/// `tool` row's `tool_failure`.
+///
+/// Rows carried over from a previous turn are left untouched.
+fn attach_text_dialect_rounds(
+ rows: &mut [TranscriptMessage],
+ fresh: &[bool],
+ outcomes: &[crate::agent::tinyagents::ToolCallOutcome],
+ route: Option<&tinyinference_llm::model::ResolvedModelRoute>,
+) {
+ let mut iteration = 0u32;
+ for index in 0..rows.len() {
+ if !fresh[index] {
+ continue;
+ }
+ if rows[index].role == "assistant" {
+ iteration = iteration.saturating_add(1);
+ continue;
+ }
+ if rows[index].role != "user" {
+ continue;
+ }
+ let Some(results) = parse_replayed_results(&rows[index].content) else {
+ continue;
+ };
+ let outcome_for = |id: &str| outcomes.iter().find(|outcome| outcome.call_id == id);
+
+ let failed: Vec<serde_json::Value> = results
+ .iter()
+ .filter(|result| outcome_for(&result.tool_call_id).is_some_and(|o| !o.success))
+ .map(|result| serde_json::Value::String(result.tool_call_id.clone()))
+ .collect();
+ if !failed.is_empty() {
+ match rows[index].extra_metadata.get_or_insert_with(|| {
+ serde_json::Value::Object(serde_json::Map::new())
+ }) {
+ serde_json::Value::Object(map) => {
+ map.insert(
+ TOOL_RESULT_FAILURES_METADATA_KEY.to_string(),
+ serde_json::Value::Array(failed),
+ );
+ }
+ _ => log::warn!(
+ "[session_host][codec] text-dialect results row has non-object metadata; \
+ failure status not recorded"
+ ),
+ }
+ }
+
+ let Some(issuer) = index.checked_sub(1) else {
+ continue;
+ };
+ if !fresh[issuer] || rows[issuer].role != "assistant" || rows[issuer].turn_usage.is_some()
+ {
+ continue;
+ }
+ let calls: Vec<TranscriptToolCall> = results
+ .iter()
+ .filter_map(|result| outcome_for(&result.tool_call_id))
+ .map(|outcome| TranscriptToolCall {
+ id: outcome.call_id.clone(),
+ name: outcome.name.clone(),
+ arguments: outcome.arguments.to_string(),
+ extra_content: None,
+ })
+ .collect();
+ log::debug!(
+ "[session_host][codec] text-dialect round iteration={iteration} results={} \
+ attached_calls={} failed={}",
+ results.len(),
+ calls.len(),
+ rows[index]
+ .extra_metadata
+ .as_ref()
+ .and_then(|meta| meta.get(TOOL_RESULT_FAILURES_METADATA_KEY))
+ .and_then(serde_json::Value::as_array)
+ .map_or(0, Vec::len)
+ );
+ if calls.is_empty() {
+ continue;
+ }
+ rows[issuer].turn_usage = Some(TurnUsage {
+ provider: route.map(|route| route.provider.clone()).unwrap_or_default(),
+ model: route.map(|route| route.model.clone()).unwrap_or_default(),
+ usage: MessageUsage {
+ input: 0,
+ output: 0,
+ cached_input: 0,
+ context_window: 0,
+ cost_usd: 0.0,
+ },
+ ts: chrono::Utc::now().to_rfc3339(),
+ reasoning_content: None,
+ tool_calls: calls,
+ iteration,
+ });
+ }
+}