Skip to content

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

refactor(agent): delegate transcript conversion to tinyagents-runtime

Steven Enamakel27b3566fac02
diff --git a/crates/openhuman-core/src/agent/attachments/mod_tests.rs b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
index 75092e9063..498362977d 100644
--- a/crates/openhuman-core/src/agent/attachments/mod_tests.rs
+++ b/crates/openhuman-core/src/agent/attachments/mod_tests.rs
@@ -376,7 +376,7 @@ async fn explicit_workspace_wins_over_config_action_dir() {
fn enriched_plain_turn_reloads_with_identical_text_blocks() {
use tinyinference_llm::message::Message;
let enriched = enrich_input(Message::user("caption"), "caption", "context\ncaption");
- let row = crate::agent::message_convert::message_to_native_chat_message(&enriched).unwrap();
+ let row = tinyagents_runtime::transcript::message_to_native_transcript(&enriched).unwrap();
let replayed = crate::agent::message_convert::chat_message_to_message(&row);
assert_eq!(replayed, enriched);
}
diff --git a/crates/openhuman-core/src/agent/message_convert.rs b/crates/openhuman-core/src/agent/message_convert.rs
index b178702bb1..4fd8ab9d27 100644
--- a/crates/openhuman-core/src/agent/message_convert.rs
+++ b/crates/openhuman-core/src/agent/message_convert.rs
@@ -17,17 +17,18 @@
//! agent-loop while callers keep speaking the row vocabulary.
use tinyinference_llm::message::{
- AssistantMessage, ContentBlock, ImageRef, MediaRef, Message, SystemMessage, ToolMessage,
- UserMessage,
+ ContentBlock, ImageRef, MediaRef, Message, UserMessage,
};
use tinyinference_llm::tool::ToolCall as TaToolCall;
use tinytools_agent::dialect::{
DialectMessage, DialectResponse, DialectRole, ToolDialect, ToolResultEntry, TranscriptEntry,
};
-use crate::agent::attachments::codec::{media_from_part, part_from_media};
use crate::inference::provider::ChatResponse;
-use tinyagents_session::transcript::{TranscriptMessage, TranscriptPart, TranscriptToolCall};
+use tinyagents_session::transcript::TranscriptMessage;
+use tinyagents_runtime::transcript::reasoning_from_content;
+#[cfg(test)]
+use tinyagents_runtime::transcript::{REASONING_EXT_KEY, reasoning_content_block, message_to_flat_transcript as message_to_chat_message, message_to_native_transcript as message_to_native_chat_message};
/// Convert the host provider response at its boundary into the canonical
/// dialect input. The dialect crate owns all parsing after this field-wise map.
@@ -78,150 +79,15 @@ fn dialect_message_to_row(message: DialectMessage) -> TranscriptMessage {
row
}
-/// Key under which a thinking model's `reasoning_content` is echoed through
-/// openhuman [`TranscriptMessage::extra_metadata`]. New harness transcripts carry
-/// reasoning as [`ContentBlock::Thinking`]; legacy persisted transcripts may
-/// still have the same key inside [`ContentBlock::ProviderExtension`].
-pub(crate) const REASONING_EXT_KEY: &str = "reasoning_content";
-
-/// Build the [`ContentBlock`] that carries a response's `reasoning_content` on
-/// an assistant message, if any.
-pub(crate) fn reasoning_content_block(reasoning: Option<&str>) -> Option<ContentBlock> {
- let reasoning = reasoning?;
- // Store verbatim (only gate on non-empty after a trim): thinking-mode
- // providers validate the prior reasoning block byte-for-byte on a resumed
- // multi-turn request, so trimming boundary whitespace could break replay.
- (!reasoning.trim().is_empty()).then(|| ContentBlock::Thinking {
- text: reasoning.to_string(),
- signature: None,
- })
-}
-
-/// Separator between distinct thinking blocks joined by
-/// [`reasoning_from_content`].
-const REASONING_BLOCK_SEPARATOR: &str = "\n\n";
-
-/// Recover `reasoning_content` from an assistant message's content blocks.
-///
-/// A message can carry several thinking blocks (interleaved thinking emits one
-/// per reasoning span). All of them are kept, in order, joined by a blank
-/// line — keeping only the first silently dropped every later span from the
-/// persisted transcript and the reasoning shown for that step.
-pub(crate) fn reasoning_from_content(content: &[ContentBlock]) -> Option<String> {
- let mut parts: Vec<String> = content
- .iter()
- .filter_map(|block| match block {
- ContentBlock::Thinking { text, .. } => Some(text.clone()),
- ContentBlock::ProviderExtension(value) => value
- .get(REASONING_EXT_KEY)
- .and_then(serde_json::Value::as_str)
- .map(str::to_string),
- _ => None,
- })
- .filter(|text| !text.trim().is_empty())
- .collect();
- // A legacy row can carry the same reasoning both as a thinking block and
- // under the provider-extension key; do not render it twice.
- parts.dedup();
- match parts.len() {
- 0 => None,
- 1 => parts.into_iter().next(),
- _ => Some(parts.join(REASONING_BLOCK_SEPARATOR)),
- }
-}
-
-/// The `extra_metadata` an assistant [`TranscriptMessage`] should carry so
-/// `reasoning_content` replays on the next provider request.
-fn reasoning_extra_metadata(content: &[ContentBlock]) -> Option<serde_json::Value> {
- reasoning_from_content(content)
- .map(|reasoning| serde_json::json!({ REASONING_EXT_KEY: reasoning }))
-}
-
-/// Convert one transcript row into a harness [`Message`].
-///
-/// Role strings map onto the typed arms: an assistant row's `tool_calls` become
-/// [`AssistantMessage::tool_calls`], a tool row's `tool_call_id` becomes
-/// [`ToolMessage::tool_call_id`] (falling back to the row id, then an empty id
-/// for a bare tool message), and a user row's `parts` become text and
-/// [`ContentBlock::Image`] blocks in order. Keeping the calls on the assistant
-/// message is what stops the harness re-sending orphan `tool` messages, which
-/// native providers reject (`assistant message with 'tool_calls' must be
-/// followed by tool messages`).
+/// Lift typed rows through the owner contract, retaining the product legacy-marker adapter.
pub(crate) fn chat_message_to_message(msg: &TranscriptMessage) -> Message {
- let text = msg.content.clone();
- match msg.role.as_str() {
- "system" => Message::System(SystemMessage {
- content: vec![ContentBlock::Text(text)],
- sections: Default::default(),
- tools_added: Vec::new(),
- tools_removed: Vec::new(),
- }),
- "assistant" => {
- // Restore any `reasoning_content` stashed on the persisted message so a
- // multi-turn thinking-mode conversation replays it verbatim (see
- // [`reasoning_content_block`]).
- let reasoning = msg
- .extra_metadata
- .as_ref()
- .and_then(|meta| meta.get(REASONING_EXT_KEY))
- .and_then(serde_json::Value::as_str);
- let mut content = vec![ContentBlock::Text(text)];
- content.extend(reasoning_content_block(reasoning));
- Message::Assistant(AssistantMessage {
- id: msg.id.clone(),
- content,
- tool_calls: msg.tool_calls.iter().map(row_call_to_ta_call).collect(),
- usage: None,
- origin: None,
- })
+ let mut message = tinyagents_runtime::transcript::transcript_to_message(msg);
+ if msg.parts.is_none() {
+ if let Message::User(user) = &mut message {
+ user.content = user_content_blocks(msg.content.clone());
}
- "tool" => Message::Tool(ToolMessage {
- tool_call_id: msg
- .tool_call_id
- .clone()
- .or_else(|| msg.id.clone())
- .unwrap_or_default(),
- content: vec![ContentBlock::Text(text)],
- trusted_verbatim: false,
- artifact: None,
- }),
- // "user" and any unrecognized role default to a user turn — the safest
- // mapping for a free-form inbound message.
- _ => Message::User(UserMessage {
- content: match msg.parts.as_deref() {
- Some(parts) => user_blocks_from_parts(parts),
- None => user_content_blocks(text),
- },
- }),
- }
-}
-
-/// The content blocks of a user row's typed `parts`, in source order.
-fn user_blocks_from_parts(parts: &[TranscriptPart]) -> Vec<ContentBlock> {
- let blocks: Vec<ContentBlock> = parts
- .iter()
- .map(|part| match part {
- TranscriptPart::Text { text } => ContentBlock::Text(text.clone()),
- TranscriptPart::Image { url } => ContentBlock::Image(ImageRef {
- url: url.clone(),
- mime_type: data_uri_mime(url),
- }),
- TranscriptPart::Audio { source, mime_type } => {
- ContentBlock::Audio(media_from_part(source, mime_type))
- }
- TranscriptPart::Video { source, mime_type } => {
- ContentBlock::Video(media_from_part(source, mime_type))
- }
- TranscriptPart::Document { source, mime_type } => {
- ContentBlock::Document(media_from_part(source, mime_type))
- }
- })
- .collect();
- if blocks.is_empty() {
- vec![ContentBlock::Text(String::new())]
- } else {
- blocks
}
+ message
}
/// A user [`Message`] from the text a person (or a channel) sent: each
@@ -423,141 +289,14 @@ fn data_uri_mime(reference: &str) -> Option<String> {
/// Rebuild a harness [`TaToolCall`] from a row's [`TranscriptToolCall`] (whose
/// `arguments` is the serialized JSON string the provider emitted).
-fn row_call_to_ta_call(call: &TranscriptToolCall) -> TaToolCall {
- TaToolCall {
- id: call.id.clone(),
- name: call.name.clone(),
- arguments: serde_json::from_str(&call.arguments).unwrap_or(serde_json::Value::Null),
- invalid: None,
- }
-}
-
-/// A harness [`TaToolCall`] as a row's [`TranscriptToolCall`].
-fn ta_call_to_row_call(call: &TaToolCall) -> TranscriptToolCall {
- TranscriptToolCall {
- id: call.id.clone(),
- name: call.name.clone(),
- arguments: call.arguments.to_string(),
- extra_content: None,
- }
-}
-
/// Convert a seed history into the harness `input` transcript.
pub(crate) fn history_to_messages(history: &[TranscriptMessage]) -> Vec<Message> {
history.iter().map(chat_message_to_message).collect()
}
-/// Convert a harness [`Message`] back into a flat [`TranscriptMessage`] row.
-///
-/// Assistant tool calls are flattened to their text (the loop already executed
-/// them and appended `Tool` result messages), and a tool message preserves its
-/// correlation id on [`TranscriptMessage::id`] so downstream persistence keeps it.
-///
-/// Returns `None` for [`Message::Custom`]: that variant is a host-side
-/// out-of-band record (compaction marker, label, audit note) that the harness
-/// never sends to a provider, and a flat history *is* provider input, so
-/// carrying it across would leak it into the next request.
-pub(crate) fn message_to_chat_message(msg: &Message) -> Option<TranscriptMessage> {
- Some(match msg {
- Message::System(_) => TranscriptMessage::system(msg.text()),
- Message::User(_) => TranscriptMessage::user(msg.text()),
- Message::Assistant(a) => {
- let mut cm = TranscriptMessage::assistant(msg.text());
- cm.extra_metadata = reasoning_extra_metadata(&a.content);
- cm
- }
- Message::Tool(t) => {
- let mut cm = TranscriptMessage::tool(msg.text());
- cm.id = Some(t.tool_call_id.clone());
- cm
- }
- Message::Custom(c) => {
- log::trace!("[message_convert] dropping custom message kind={}", c.kind);
- return None;
- }
- })
-}
-
-/// Convert a harness transcript back into flat history rows.
-///
-/// [`Message::Custom`] records are dropped; see [`message_to_chat_message`].
+/// Project provider-facing flat history through the owner contract.
pub(crate) fn messages_to_history(messages: &[Message]) -> Vec<TranscriptMessage> {
- messages
- .iter()
- .filter_map(message_to_chat_message)
- .collect()
-}
-
-/// Convert one harness [`Message`] into a typed row for a **native**
-/// tool-calling provider request, preserving the structure the provider needs
-/// to round-trip a tool round: an assistant turn that made tool calls keeps
-/// them in `tool_calls`, a tool result keeps its `tool_call_id`, and a user turn
-/// with pictures keeps its text and image blocks as ordered `parts`. Without
-/// this the provider sees an assistant with no `tool_calls` followed by an
-/// orphan tool message and drops the round — breaking multi-turn native tool
-/// calling (e.g. the orchestrator's `spawn_parallel_agents` → synthesis hop) —
-/// and a native-tool provider silently loses every pasted image.
-///
-/// Returns `None` for [`Message::Custom`]: that variant is a host-side
-/// out-of-band record (compaction marker, label, audit note) that the harness
-/// never sends to a provider, so it must not leak into the next request.
-pub(crate) fn message_to_native_chat_message(msg: &Message) -> Option<TranscriptMessage> {
- Some(match msg {
- Message::System(_) => TranscriptMessage::system(msg.text()),
- Message::User(user) => user_row(msg, user),
- Message::Assistant(a) => {
- let mut cm = TranscriptMessage::assistant_with_calls(
- msg.text(),
- a.tool_calls.iter().map(ta_call_to_row_call).collect(),
- );
- cm.extra_metadata = reasoning_extra_metadata(&a.content);
- cm
- }
- Message::Tool(t) => {
- let mut cm = TranscriptMessage::tool_result(t.tool_call_id.clone(), msg.text());
- cm.id = Some(t.tool_call_id.clone());
- cm
- }
- Message::Custom(c) => {
- log::trace!("[message_convert] dropping custom message kind={}", c.kind);
- return None;
- }
- })
-}
-
-/// The row of a user message: its text, plus ordered parts when it carries an
-/// image. Json / provider-extension blocks carry no user-visible text, so they
-/// are dropped, as [`Message::text`] drops them.
-fn user_row(msg: &Message, user: &UserMessage) -> TranscriptMessage {
- let has_image = user.content.iter().any(|block| {
- matches!(
- block,
- ContentBlock::Image(_)
- | ContentBlock::Audio(_)
- | ContentBlock::Video(_)
- | ContentBlock::Document(_)
- )
- });
- if !has_image {
- return TranscriptMessage::user(msg.text());
- }
- TranscriptMessage::user_with_parts(
- user.content
- .iter()
- .filter_map(|block| match block {
- ContentBlock::Text(text) if !text.is_empty() => {
- Some(TranscriptPart::Text { text: text.clone() })
- }
- ContentBlock::Image(image) => Some(TranscriptPart::Image {
- url: image.url.clone(),
- }),
- ContentBlock::Audio(media) => part_from_media(media, "audio"),
- ContentBlock::Video(media) => part_from_media(media, "video"),
- ContentBlock::Document(media) => part_from_media(media, "document"),
- _ => None,
- })
- .collect(),
- )
+ messages.iter().filter_map(tinyagents_runtime::transcript::message_to_flat_transcript).collect()
}
/// Convert a harness transcript into typed dialect entries, preserving
diff --git a/crates/openhuman-core/src/agent/session_host/codec.rs b/crates/openhuman-core/src/agent/session_host/codec.rs
index 4ee4f276af..5a80421e67 100644
--- a/crates/openhuman-core/src/agent/session_host/codec.rs
+++ b/crates/openhuman-core/src/agent/session_host/codec.rs
@@ -32,7 +32,7 @@ impl TranscriptCodec<OpenHumanRunContext> for OpenHumanTranscriptCodec {
) -> Result<Vec<TranscriptMessage>, RuntimeError> {
let mut rows = next
.iter()
- .filter_map(message_convert::message_to_native_chat_message)
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
.collect::<Vec<_>>();
// `Message` intentionally cannot represent all durable transcript
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rs
index e9742efdd9..17e506cfcc 100644
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@ -143,7 +143,7 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
let mut messages: Vec<TranscriptMessage> = request
.history
.iter()
- .filter_map(crate::agent::message_convert::message_to_native_chat_message)
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
.collect();
if crate::agent::multimodal::has_image_placeholders(&messages) {
messages = crate::agent::multimodal::rehydrate_image_placeholders(&messages);
diff --git a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
index 3006362fd8..6a29a78de1 100644
--- a/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
+++ b/crates/openhuman-core/src/agent/subagent_host/lifecycle.rs
@@ -472,7 +472,7 @@ impl SubagentPlanner<crate::agent::tinyagents::host::OpenHumanRunContext, HostRe
options.initial_history = Some(
history
.iter()
- .filter_map(crate::agent::message_convert::message_to_native_chat_message)
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
.collect(),
);
history
@@ -1018,7 +1018,7 @@ impl tinyagents_orchestration::subagent::SubagentPersistence for OpenHumanPersis
.outcome
.history
.iter()
- .filter_map(crate::agent::message_convert::message_to_native_chat_message)
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
.collect(),
question: paused.reason.clone(),
options: None,
@@ -1184,7 +1184,7 @@ fn outcome_to_host(
final_history: outcome
.history
.iter()
- .filter_map(crate::agent::message_convert::message_to_native_chat_message)
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
.collect(),
usage: SubagentUsage {
input_tokens: outcome.usage.usage.input_tokens,
diff --git a/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs b/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs
index 822647f087..aa30b40c3d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/compaction_carry_tests.rs
@@ -133,7 +133,7 @@ fn a_checkpoint_survives_the_session_transcript_round_trip() {
// transcript form; the checkpoint must still read as one on the far side,
// or the next turn would summarize it as raw history.
let original = checkpoint("## Goal\nship it");
- let native = crate::agent::message_convert::message_to_native_chat_message(&original)
+ let native = tinyagents_runtime::transcript::message_to_native_transcript(&original)
.expect("user rows convert");
let back = crate::agent::message_convert::chat_message_to_message(&native);
assert!(is_checkpoint(&back), "{back:?}");
diff --git a/crates/openhuman-core/src/agent/tinyagents/model.rs b/crates/openhuman-core/src/agent/tinyagents/model.rs
index 230037fe07..13b6205373 100644
--- a/crates/openhuman-core/src/agent/tinyagents/model.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/model.rs
@@ -107,7 +107,7 @@ fn response_to_model_response(
// reply. Preserve it as a typed thinking block so it stays out of
// `Message::text()` but survives persistence and the next turn's request,
// where thinking-mode providers require it back.
- if let Some(block) = crate::agent::message_convert::reasoning_content_block(
+ if let Some(block) = tinyagents_runtime::transcript::reasoning_content_block(
response.reasoning_content.as_deref(),
) {
content.push(block);