Skip to content

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

fix(agent): keep a failed chat turn's accepted rounds and failure cause in history

M3gA-Mind5c0f70ca1dc7
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 b1e3119cd9..dcbdbc1cee 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core.rs
@@ -245,6 +245,7 @@ include!("core_turn.rs");
// calls, split by responsibility into real submodules. Their `impl Agent`
// blocks complement `turn()` above.
mod experience_context;
+mod failed_turn;
mod grounded_close;
mod harness_turn;
mod resumed_prefix;
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
new file mode 100644
index 0000000000..d705c618c7
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/failed_turn.rs
@@ -0,0 +1,159 @@
+//! Keeping what a failed chat turn did (#6281).
+
+use crate::agent::harness::session::transcript::{MessageUsage, TurnUsage};
+use crate::agent::harness::session::turn_checkpoint::{truncate_chars, CHECKPOINT_RESULT_CHARS};
+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 anyhow::Result;
+use tinyinference::message::Message;
+
+/// Leads the note a failed turn leaves in history, so the model (and a reader
+/// of the transcript) can tell it from a reply.
+const FAILED_TURN_NOTE_PREFIX: &str = "[turn failed before completion:";
+
+impl Agent {
+ /// Drive the chat turn and, if it fails, keep what it did.
+ ///
+ /// `turn()` has already pushed this turn's user message, but on `Err` the
+ /// turn body returned before anything else it produced reached `history` or
+ /// the transcript. Every follow-up ("what happened?", "try again") then ran
+ /// without the tool calls, their results, or the reason the turn failed.
+ ///
+ /// On any error from the turn body (provider, harness, tool loop, or a typed
+ /// error raised after the loop) this appends the rounds the provider had
+ /// already accepted, then a failure note, and persists the transcript, so a
+ /// warm follow-up and a cold-boot resume both see them. A turn future that is
+ /// dropped (cancelled) is not an error and records nothing here.
+ pub(super) async fn run_turn_via_tinyagents_session(
+ &mut self,
+ user_message: &str,
+ effective_model: &str,
+ temperature: f64,
+ max_iterations: usize,
+ artifact_store: Option<ToolResultArtifactStore>,
+ suppress_tools: bool,
+ ) -> Result<String> {
+ let snapshot = TranscriptSnapshotSink::default();
+ let result = Box::pin(self.run_turn_via_tinyagents_session_inner(
+ user_message,
+ effective_model,
+ temperature,
+ max_iterations,
+ artifact_store,
+ suppress_tools,
+ snapshot.clone(),
+ ))
+ .await;
+ if let Err(err) = &result {
+ let snapshot = std::mem::take(
+ &mut *snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner),
+ );
+ self.record_failed_turn(&snapshot, effective_model, err);
+ }
+ result
+ }
+
+ fn record_failed_turn(
+ &mut self,
+ snapshot: &TranscriptSnapshot,
+ effective_model: &str,
+ err: &anyhow::Error,
+ ) {
+ let (accepted, unanswered) = split_snapshot(snapshot);
+ log::warn!(
+ "[agent_loop] turn failed; recording {} accepted round message(s), {} unanswered \
+ message(s) as text, and the failure cause into history — #6281",
+ accepted.len(),
+ unanswered.len()
+ );
+ // Only rounds the provider already answered are replayed as structured
+ // messages. The newest round was carried only by the failing request, and
+ // a request rejected for malformed tool history must not be replayed, or
+ // the de-poison eviction in `web_chat::run_task` would reseed the same
+ // rejection from this transcript. That round goes into the note as text.
+ self.history
+ .extend(crate::agent::message_convert::messages_to_conversation(
+ accepted,
+ ));
+ self.history
+ .push(ConversationMessage::Chat(ChatMessage::assistant(
+ failed_turn_note(err, unanswered),
+ )));
+ self.trim_history();
+
+ 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,
+ context_window: 0,
+ cost_usd: 0.0,
+ },
+ 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));
+ }
+}
+
+/// 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!(
+ "{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)
+ )),
+ }
+ }
+ note
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
index efe4a56610..c055291cd1 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn/core/harness_turn.rs
@@ -31,7 +31,11 @@ impl Agent {
/// harness event stream via `OpenhumanEventBridge` (tinyagents harness),
/// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history
/// is trimmed to the provider's context window.
- pub(super) async fn run_turn_via_tinyagents_session(
+ ///
+ /// Called through [`Agent::run_turn_via_tinyagents_session`], which records
+ /// a failed turn from `transcript_snapshot` (#6281).
+ #[allow(clippy::too_many_arguments)]
+ pub(super) async fn run_turn_via_tinyagents_session_inner(
&mut self,
user_message: &str,
effective_model: &str,
@@ -41,6 +45,7 @@ impl Agent {
crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore,
>,
suppress_tools: bool,
+ transcript_snapshot: crate::agent::tinyagents::TranscriptSnapshotSink,
) -> Result<String> {
let turn_started = std::time::Instant::now();
// This turn's stamped user message is already the last entry in
@@ -93,6 +98,12 @@ impl Agent {
.await
.map(|prepared| prepared.messages)
.unwrap_or(messages);
+ // The rounds this run produces start after the transcript it is seeded
+ // with; a failed turn records only those (#6281).
+ transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .request_base_len = messages.len();
// Per-turn tool scope (#1725). A chat / small-talk turn runs with an
// EMPTY tool set: the provider request carries no tool schema, so the
@@ -135,9 +146,9 @@ impl Agent {
// Progressive-disclosure handoff is a sub-agent (integrations_agent)
// concern; the top-level chat turn never sets it.
handoff: None,
- // Live transcript snapshotting is a sub-agent error-recovery concern
- // (#4466); the chat path persists its transcript post-run.
- transcript_snapshot: None,
+ // The harness drops its working transcript on `Err`; the snapshot
+ // is how a failed turn still keeps the rounds it completed (#6281).
+ transcript_snapshot: Some(transcript_snapshot.clone()),
};
// Gather any sub-agent spend delegated during this turn (synchronous
@@ -201,6 +212,13 @@ impl Agent {
)
.await;
let outcome = outcome?;
+ // The run handed back its own transcript, folded into history below, so
+ // an error after this point must not replay the snapshot's rounds again.
+ transcript_snapshot
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .messages
+ .clear();
// Record whether this turn paused at the tool-call cap (vs. finishing
// naturally) BEFORE anything below can early-return, so a caller
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
new file mode 100644
index 0000000000..a5fccc0c0c
--- /dev/null
+++ b/crates/openhuman-core/src/agent/harness/session/turn_failed_turn_history_tests.rs
@@ -0,0 +1,155 @@
+use super::*;
+
+fn echo_tool_call() -> anyhow::Result<ChatResponse> {
+ Ok(ChatResponse {
+ text: Some("<tool_call>{\"name\":\"echo\",\"arguments\":{}}</tool_call>".into()),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ })
+}
+
+fn failed_turn_agent(provider: Arc<dyn ChatModel<()>>) -> Agent {
+ make_agent_with_builder(
+ provider,
+ vec![Box::new(EchoTool)],
+ vec![],
+ crate::config::AgentConfig {
+ max_tool_iterations: 5,
+ ..crate::config::AgentConfig::default()
+ },
+ crate::config::ContextConfig::default(),
+ )
+}
+
+fn tool_call_rounds(agent: &Agent) -> usize {
+ agent
+ .history
+ .iter()
+ .filter(|message| matches!(message, ConversationMessage::AssistantToolCalls { .. }))
+ .count()
+}
+
+/// #6281: a turn that fails after doing work keeps the rounds the provider
+/// accepted plus the failure cause, persists them, and the next turn sees them.
+#[tokio::test]
+async fn failed_turn_keeps_its_work_and_cause_for_the_next_turn() {
+ let provider_impl = Arc::new(SequenceProvider {
+ responses: AsyncMutex::new(vec![
+ // Call 1 answered: round 1 runs.
+ echo_tool_call(),
+ // Call 2 answered (its request carried round 1): round 2 runs.
+ echo_tool_call(),
+ // Call 3 fails; only its request carried round 2. A 400 is not
+ // retried by the harness, so the turn fails on this one response.
+ Err(anyhow::anyhow!("400 Bad Request: provider boom")),
+ // The follow-up turn.
+ Ok(ChatResponse {
+ text: Some("The last turn hit a provider error.".into()),
+ tool_calls: vec![],
+ usage: None,
+ reasoning_content: None,
+ }),
+ ]),
+ requests: AsyncMutex::new(Vec::new()),
+ tool_counts: AsyncMutex::new(Vec::new()),
+ });
+ let mut agent = failed_turn_agent(provider_impl.clone());
+
+ let err = agent
+ .turn("run the task")
+ .await
+ .expect_err("the third model call fails the turn");
+ assert!(err.to_string().contains("provider boom"), "got: {err}");
+
+ // Round 1 was in a request the provider answered, so it is replayed as
+ // structured messages. Round 2 was only in the failing request, so it must
+ // not be (a rejected request must never be replayed), and lives in the note.
+ assert_eq!(
+ tool_call_rounds(&agent),
+ 1,
+ "only the accepted round is kept as structured tool calls: {:?}",
+ agent.history
+ );
+ assert!(agent
+ .history
+ .iter()
+ .any(|message| matches!(message, ConversationMessage::ToolResults(results) if !results.is_empty())));
+ 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.starts_with("[turn failed before completion:") && note.contains("provider boom"),
+ "the note must carry the failure cause, got: {note}"
+ );
+ assert!(
+ note.contains("called `echo`"),
+ "the unanswered round must be kept as text, got: {note}"
+ );
+
+ let path = agent
+ .session_transcript_path
+ .clone()
+ .expect("a failed turn must persist its transcript");
+ let persisted = transcript::read_transcript(&path).expect("read transcript");
+ assert!(
+ persisted
+ .messages
+ .iter()
+ .any(|message| message.role == "assistant" && message.content.contains("provider boom")),
+ "the persisted transcript must carry the failure note"
+ );
+
+ agent
+ .turn("what happened?")
+ .await
+ .expect("the follow-up turn succeeds");
+ let requests = provider_impl.requests.lock().await;
+ let follow_up = requests.last().expect("follow-up request");
+ assert!(
+ follow_up
+ .iter()
+ .any(|message| message.content.starts_with("[Tool results]")),
+ "the follow-up request must carry the failed turn's tool result: {follow_up:?}"
+ );
+ assert!(
+ follow_up
+ .iter()
+ .any(|message| message.role == "assistant" && message.content.contains("provider boom")),
+ "the follow-up request must carry the failure cause: {follow_up:?}"
+ );
+}
+
+/// #6281: a turn that fails on its first model call still records why, so the
+/// history never holds two user messages in a row with no explanation between.
+#[tokio::test]
+async fn turn_failing_on_first_call_records_the_cause() {
+ let provider: Arc<dyn ChatModel<()>> = Arc::new(SequenceProvider {
+ responses: AsyncMutex::new(vec![Err(anyhow::anyhow!("400 Bad Request: provider boom"))]),
+ requests: AsyncMutex::new(Vec::new()),
+ tool_counts: AsyncMutex::new(Vec::new()),
+ });
+ let mut agent = failed_turn_agent(provider);
+
+ agent
+ .turn("run the task")
+ .await
+ .expect_err("the first model call fails the turn");
+
+ assert_eq!(tool_call_rounds(&agent), 0);
+ let tail: Vec<(String, String)> = agent
+ .history
+ .iter()
+ .rev()
+ .take(2)
+ .map(|message| match message {
+ ConversationMessage::Chat(chat) => (chat.role.clone(), chat.content.clone()),
+ other => panic!("unexpected history entry: {other:?}"),
+ })
+ .collect();
+ assert_eq!(tail[1].0, "user");
+ assert_eq!(tail[0].0, "assistant");
+ assert!(tail[0].1.contains("provider boom"), "got: {}", tail[0].1);
+ assert!(agent.session_transcript_path.is_some());
+}
diff --git a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs b/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
index 6045c92dba..b59c9b3a7a 100644
--- a/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
+++ b/crates/openhuman-core/src/agent/harness/session/turn_tests.rs
@@ -538,6 +538,8 @@ fn tool_calls_envelope(id: &str) -> String {
mod turn_auto_recall_tests;
#[path = "turn_checkpoint_and_wrapup_tests.rs"]
mod turn_checkpoint_and_wrapup_tests;
+#[path = "turn_failed_turn_history_tests.rs"]
+mod turn_failed_turn_history_tests;
#[path = "turn_final_reply_grounding_tests.rs"]
mod turn_final_reply_grounding_tests;
#[path = "turn_history_and_context_tests.rs"]
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 67b0b64289..cd1364ed60 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
@@ -242,8 +242,7 @@ pub(in super::super) async fn run_subagent_via_graph(
// worker thread. Attach a snapshot middleware that mirrors each `before_model`
// 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 =
- std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let transcript_snapshot = crate::agent::tinyagents::TranscriptSnapshotSink::default();
// A sub-agent turn runs *nested inside* the parent agent's turn (parent
// harness → spawn_subagent tool → here), so the child's full
@@ -331,7 +330,7 @@ pub(in super::super) async fn run_subagent_via_graph(
let mapped = map_tinyagents_subagent_error(err);
let recovered = transcript_snapshot
.lock()
- .map(|g| g.clone())
+ .map(|g| crate::agent::message_convert::messages_to_history(&g.messages))
.unwrap_or_default();
tracing::warn!(
agent_id,
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
index 88764b48c8..1cc9ceb184 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
@@ -60,7 +60,9 @@ pub(crate) use repeated_failure::RepeatedToolFailureMiddleware;
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, TranscriptSnapshotSink, TurnContextMiddleware};
+pub(crate) use turn_context::{
+ HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink, TurnContextMiddleware,
+};
#[cfg(test)]
#[path = "middleware_tests.rs"]
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 42c205e5d8..5d99406e35 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@ -12,7 +12,8 @@ use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::Middleware;
use tinyagents_harness::runtime::AgentHarness;
use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};
-use tinyinference::model::ModelRequest;
+use tinyinference::message::Message;
+use tinyinference::model::{ModelRequest, ModelResponse};
use crate::agent::harness::tool_result_artifacts::ToolResultArtifactStore;
use crate::agent::tinyagents::payload_summarizer::PayloadSummarizer;
@@ -58,32 +59,47 @@ pub(crate) struct TurnContextMiddleware {
/// placeholder. `None` everywhere else.
pub(crate) handoff: Option<HandoffConfig>,
/// Live transcript snapshot sink (#4466). When set, a
- /// [`TranscriptSnapshotMiddleware`] mirrors the running conversation (as
- /// openhuman [`ChatMessage`]s) into this shared buffer before every model
- /// call. Only the sub-agent path sets it, so an erroring run can persist the
- /// rounds completed before the failure (the harness drops its partial
- /// transcript on `Err`). `None` everywhere else (chat persists post-run).
+ /// [`TranscriptSnapshotMiddleware`] mirrors the running conversation into
+ /// this shared buffer before every model call, so an erroring run can still
+ /// record the rounds completed before the failure (the harness drops its
+ /// partial transcript on `Err`). Set by the sub-agent path and by the
+ /// top-level chat turn (#6281); `None` on the channel path.
pub(crate) transcript_snapshot: Option<TranscriptSnapshotSink>,
}
-/// Shared buffer a [`TranscriptSnapshotMiddleware`] mirrors the live sub-agent
+/// 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.
+ 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
+ /// exactly a request the provider accepted. Anything past it was sent only
+ /// in a request that has not been answered, which is where a provider
+ /// rejection of malformed history comes from (#6281).
+ pub(crate) accepted_len: usize,
+ /// Length of the transcript the caller seeded the run with, so the rounds
+ /// 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,
+}
+
+/// Shared buffer a [`TranscriptSnapshotMiddleware`] mirrors the live
/// conversation into, so the caller can persist completed rounds even when the
/// harness run ends in `Err` (#4466).
-pub(crate) type TranscriptSnapshotSink =
- Arc<std::sync::Mutex<Vec<crate::agent::messages::ChatMessage>>>;
+pub(crate) type TranscriptSnapshotSink = Arc<std::sync::Mutex<TranscriptSnapshot>>;
/// Observation-only middleware that snapshots the running transcript into a
/// shared [`TranscriptSnapshotSink`] before each model call (#4466).
///
/// The tinyagents harness owns the working message vector and only hands it back
-/// inside a successful `AgentRun`; on a mid-run error it is dropped. The
-/// sub-agent runner persists a per-child `session_raw` transcript so
-/// `learning/transcript_ingest` can read it — but a failed run used to persist
-/// nothing. This middleware mirrors each `before_model` request's messages
-/// (which include every prior completed assistant/tool round) into an
-/// openhuman-owned buffer, so the runner's error path can still write the rounds
-/// that completed before the failure. Converts to [`ChatMessage`] eagerly so the
-/// caller does not need access to the private `convert` module.
+/// inside a successful `AgentRun`; on a mid-run error it is dropped. This
+/// middleware mirrors each `before_model` request's messages (which include
+/// every prior completed assistant/tool round) into an openhuman-owned buffer,
+/// and marks the boundary of what the provider answered in `after_model`, so the
+/// caller's error path can still record the rounds that completed before the
+/// failure.
pub(crate) struct TranscriptSnapshotMiddleware {
sink: TranscriptSnapshotSink,
}
@@ -100,9 +116,20 @@ impl Middleware<()> for TranscriptSnapshotMiddleware {
_state: &(),
request: &mut ModelRequest,
) -> TaResult<()> {
- let history = crate::agent::message_convert::messages_to_history(&request.messages);
if let Ok(mut guard) = self.sink.lock() {
- *guard = history;
+ guard.messages = request.messages.clone();
+ }
+ Ok(())
+ }
+
+ async fn after_model(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ _response: &mut ModelResponse,
+ ) -> TaResult<()> {
+ if let Ok(mut guard) = self.sink.lock() {
+ guard.accepted_len = guard.messages.len();
}
Ok(())
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index c97184e6ac..fe3789e636 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -71,7 +71,9 @@ 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, TranscriptSnapshotSink, TurnContextMiddleware};
+pub(crate) use middleware::{
+ HandoffConfig, TranscriptSnapshot, TranscriptSnapshotSink, TurnContextMiddleware,
+};
pub(crate) use observability::SubagentScope;
pub use resolved_route::{
current_resolved_provider_route, current_route_slot, record_resolved_provider_route,