Skip to content

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

fix(agent): disclose a failed summarization instead of passing a raw dump

M3gA-Mind0959a50cef65
diff --git a/src/openhuman/agent/tinyagents/middleware.rs b/src/openhuman/agent/tinyagents/middleware.rs
index 1869efa980..3a101fc55e 100644
--- a/src/openhuman/agent/tinyagents/middleware.rs
+++ b/src/openhuman/agent/tinyagents/middleware.rs
@@ -49,7 +49,9 @@ use crate::openhuman::agent::context::CLEARED_PLACEHOLDER;
use crate::openhuman::agent::harness::tool_result_artifacts::{
apply_per_result_persistence, ToolResultArtifactStore, TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,
};
-use crate::openhuman::agent::tinyagents::payload_summarizer::PayloadSummarizer;
+use crate::openhuman::agent::tinyagents::payload_summarizer::{
+ PayloadSummarizer, SummarizeOutcome, UnavailableReason,
+};
use crate::openhuman::inference::tokenjuice::AgentTokenjuiceCompression;
use crate::openhuman::security::approval::{
redact_args, summarize_action, ApprovalGate, ExecutionOutcome, GateOutcome,
@@ -710,24 +712,59 @@ impl Middleware<()> for ToolOutputMiddleware {
// 1. Semantic summarization (progressive disclosure) — swap the raw
// payload for a compressed summary when the summarizer opts in.
- // Failures never break the tool call (the trait swallows them).
+ // Failures never break the tool call, but they are no longer
+ // silent: when summarization does not happen the model is told so
+ // in the payload itself. This used to be
+ // `if let Ok(Some(payload)) = …`, which discarded `Err(_)` and
+ // `Ok(None)` identically — so a failed summarization reached the
+ // model as an unannounced raw dump and it re-called the same tool.
if !compaction_exempt {
if let Some(ps) = &self.payload_summarizer {
- if let Ok(Some(payload)) = ps
+ match ps
.maybe_summarize_in_parent(ctx, &result.name, None, &result.content)
.await
{
- tracing::info!(
- tool = %result.name,
- from_bytes = payload.original_bytes,
- to_bytes = payload.summary_bytes,
- "[tinyagents::mw] payload_summarizer compressed tool output"
- );
- ctx.emit(AgentEvent::Compressed {
- from_tokens: estimate_output_tokens(payload.original_bytes),
- to_tokens: estimate_output_tokens(payload.summary_bytes),
- });
- result.content = payload.summary;
+ Ok(SummarizeOutcome::Summarized(payload)) => {
+ tracing::info!(
+ tool = %result.name,
+ from_bytes = payload.original_bytes,
+ to_bytes = payload.summary_bytes,
+ "[tinyagents::mw] payload_summarizer compressed tool output"
+ );
+ ctx.emit(AgentEvent::Compressed {
+ from_tokens: estimate_output_tokens(payload.original_bytes),
+ to_tokens: estimate_output_tokens(payload.summary_bytes),
+ });
+ result.content = payload.summary;
+ }
+ // The payload was fine as it was. Say nothing: a notice on
+ // every small tool result would be pure noise.
+ Ok(SummarizeOutcome::NotNeeded) => {}
+ Ok(SummarizeOutcome::Unavailable(reason)) => {
+ tracing::warn!(
+ tool = %result.name,
+ bytes = result.content.len(),
+ ?reason,
+ "[tinyagents::mw] payload_summarizer unavailable; disclosing raw output"
+ );
+ result.content = format!("{}\n\n{}", reason.notice(), result.content);
+ }
+ // Reserved for fatal misconfiguration. Previously
+ // indistinguishable from "nothing to do"; the model is now
+ // told the output is raw for the same reason as above.
+ Err(error) => {
+ tracing::warn!(
+ tool = %result.name,
+ bytes = result.content.len(),
+ error = %error,
+ "[tinyagents::mw] payload_summarizer errored; disclosing raw output"
+ );
+ result.content = format!(
+ "{}\n\n{}",
+ UnavailableReason::Failed.notice(),
+ result.content
+ );
+ }
}
}
@@ -3113,6 +3150,134 @@ mod tests {
RunContext::new(RunConfig::new("mw-test"), ())
}
+ // ── payload_summarizer disclosure (#5722) ──────────────────────
+ //
+ // The behaviour these pin: when summarization does not happen, the model
+ // must be able to see that from the payload. Previously every one of
+ // these cases produced byte-identical content to a successful
+ // pass-through, so the model could not tell a raw dump from a normal
+ // result and re-called the same tool.
+
+ struct StubSummarizer(std::sync::Mutex<Option<anyhow::Result<SummarizeOutcome>>>);
+
+ impl StubSummarizer {
+ fn ok(outcome: SummarizeOutcome) -> Arc<Self> {
+ Arc::new(Self(std::sync::Mutex::new(Some(Ok(outcome)))))
+ }
+ }
+
+ #[async_trait]
+ impl PayloadSummarizer for StubSummarizer {
+ async fn maybe_summarize_in_parent(
+ &self,
+ _parent_ctx: &RunContext<()>,
+ _tool_name: &str,
+ _parent_task_hint: Option<&str>,
+ _raw: &str,
+ ) -> anyhow::Result<SummarizeOutcome> {
+ self.0
+ .lock()
+ .expect("stub outcome lock")
+ .take()
+ .expect("stub summarizer called more than once")
+ }
+ }
+
+ fn summarizer_mw(ps: Arc<dyn PayloadSummarizer>) -> ToolOutputMiddleware {
+ ToolOutputMiddleware {
+ // Large enough that the byte-budget backstop never fires, so these
+ // tests observe the summarizer stage alone.
+ budget_bytes: 10_000_000,
+ payload_summarizer: Some(ps),
+ artifact_store: None,
+ tokenjuice_compaction_enabled: false,
+ tokenjuice_compression:
+ crate::openhuman::inference::tokenjuice::AgentTokenjuiceCompression::Off,
+ tool_policies: HashMap::new(),
+ }
+ }
+
+ #[tokio::test]
+ async fn unavailable_summarization_is_disclosed_in_the_payload() {
+ let mw = summarizer_mw(StubSummarizer::ok(SummarizeOutcome::Unavailable(
+ UnavailableReason::Failed,
+ )));
+ let mut ctx = ctx();
+ let mut result = tool_result("test_tool", "RAW-TOOL-OUTPUT");
+
+ mw.after_tool(&mut ctx, &(), &mut result)
+ .await
+ .expect("after_tool should not fail");
+
+ assert!(
+ result
+ .content
+ .starts_with(UnavailableReason::Failed.notice()),
+ "the notice must be a PREFIX — the downstream per-tool cap keeps the \
+ head, so an appended notice is the first thing truncated away; got: {}",
+ result.content
+ );
+ assert!(
+ result.content.contains("RAW-TOOL-OUTPUT"),
+ "disclosure must not cost the payload: {}",
+ result.content
+ );
+ }
+
+ #[tokio::test]
+ async fn a_payload_that_needed_nothing_is_left_completely_alone() {
+ // The other half of the contract. If every result carried a notice the
+ // marker would be noise and the model would learn to ignore it.
+ let mw = summarizer_mw(StubSummarizer::ok(SummarizeOutcome::NotNeeded));
+ let mut ctx = ctx();
+ let mut result = tool_result("test_tool", "RAW-TOOL-OUTPUT");
+
+ mw.after_tool(&mut ctx, &(), &mut result)
+ .await
+ .expect("after_tool should not fail");
+
+ assert_eq!(
+ result.content, "RAW-TOOL-OUTPUT",
+ "a below-threshold payload must be byte-identical"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_summarizer_error_is_disclosed_rather_than_swallowed() {
+ // `Err` used to be discarded by the same `if let Ok(Some(..))` that
+ // discarded `None`, so a fatal misconfiguration was indistinguishable
+ // from "nothing to do".
+ struct ErroringSummarizer;
+ #[async_trait]
+ impl PayloadSummarizer for ErroringSummarizer {
+ async fn maybe_summarize_in_parent(
+ &self,
+ _parent_ctx: &RunContext<()>,
+ _tool_name: &str,
+ _parent_task_hint: Option<&str>,
+ _raw: &str,
+ ) -> anyhow::Result<SummarizeOutcome> {
+ Err(anyhow::anyhow!("summarizer misconfigured"))
+ }
+ }
+
+ let mw = summarizer_mw(Arc::new(ErroringSummarizer));
+ let mut ctx = ctx();
+ let mut result = tool_result("test_tool", "RAW-TOOL-OUTPUT");
+
+ mw.after_tool(&mut ctx, &(), &mut result)
+ .await
+ .expect("a summarizer error must never break the tool call");
+
+ assert!(
+ result
+ .content
+ .starts_with(UnavailableReason::Failed.notice()),
+ "an errored summarizer must be disclosed too; got: {}",
+ result.content
+ );
+ }
+
#[tokio::test]
async fn prompt_cache_segments_fingerprint_full_tool_schema() {
let mw = PromptCacheSegmentMiddleware;
diff --git a/src/openhuman/agent/tinyagents/payload_summarizer.rs b/src/openhuman/agent/tinyagents/payload_summarizer.rs
index 1f44614041..ad077f3077 100644
--- a/src/openhuman/agent/tinyagents/payload_summarizer.rs
+++ b/src/openhuman/agent/tinyagents/payload_summarizer.rs
@@ -24,8 +24,8 @@
//!
//! ## Trigger conditions
//!
-//! [`PayloadSummarizer::maybe_summarize_in_parent`] returns `Ok(None)` (i.e.
-//! pass-through, do nothing) when:
+//! [`PayloadSummarizer::maybe_summarize_in_parent`] leaves the raw payload in
+//! place when:
//!
//! * The raw payload is below
//! [`SubagentPayloadSummarizer::threshold_tokens`] (config default 4 000
@@ -65,11 +65,10 @@ use crate::openhuman::agent::harness::definition::{AgentDefinition, PromptSource
use crate::openhuman::agent::harness::fork_context::{current_parent, ParentExecutionContext};
use crate::openhuman::agent::harness::subagent_runner;
-/// Outcome returned by [`PayloadSummarizer::maybe_summarize_in_parent`].
+/// A successful compression, carried by [`SummarizeOutcome::Summarized`].
///
-/// `Ok(None)` means the caller should keep the raw payload unchanged.
-/// `Ok(Some(...))` means the caller should replace the raw payload with
-/// [`SummarizedPayload::summary`] before appending it to agent history.
+/// The caller replaces the raw payload with [`SummarizedPayload::summary`]
+/// before appending it to agent history.
#[derive(Debug, Clone)]
pub struct SummarizedPayload {
/// The compressed summary text. Replaces the raw tool output.
@@ -80,6 +79,69 @@ pub struct SummarizedPayload {
pub summary_bytes: usize,
}
+/// Why a payload reached agent history without being summarized.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UnavailableReason {
+ /// Larger than `summarizer_max_payload_tokens`, so summarization was never
+ /// attempted and the payload will be truncated downstream.
+ PayloadTooLarge,
+ /// The failure circuit breaker is open for the rest of this session.
+ Disabled,
+ /// The summarizer sub-agent ran and did not produce a usable summary.
+ Failed,
+}
+
+impl UnavailableReason {
+ /// The model-facing notice for this reason.
+ ///
+ /// **Prefixed** to the tool result, never appended: the downstream
+ /// per-tool char cap keeps the head (`content.chars().take(cap)`), so an
+ /// appended notice is the first thing truncation removes.
+ ///
+ /// Every variant ends by saying a retry is pointless. Without that, the
+ /// model's reasonable response to a truncated dump is to call the same
+ /// tool again — the silent re-dispatch loop that reads to a user as a
+ /// hang.
+ #[must_use]
+ pub fn notice(self) -> &'static str {
+ match self {
+ Self::PayloadTooLarge => concat!(
+ "[openhuman: summarization unavailable — this output exceeds the summarizer's ",
+ "size cap, so the raw output follows and may be truncated. ",
+ "Re-running this tool will return the same result.]"
+ ),
+ Self::Disabled => concat!(
+ "[openhuman: summarization unavailable — it is switched off for this session ",
+ "after repeated failures, so the raw output follows. ",
+ "Re-running this tool will return the same result.]"
+ ),
+ Self::Failed => concat!(
+ "[openhuman: summarization unavailable — the summarizer did not return a usable ",
+ "summary, so the raw output follows. ",
+ "Re-running this tool will return the same result.]"
+ ),
+ }
+ }
+}
+
+/// What one summarization attempt concluded.
+///
+/// Replaces a bare `Option<SummarizedPayload>`, in which `None` meant both
+/// "nothing to do" and "this failed". That conflation was the defect: the one
+/// production caller could not tell the two apart, so a failed summarization
+/// entered agent history looking like ordinary tool output.
+#[derive(Debug, Clone)]
+pub enum SummarizeOutcome {
+ /// Replace the raw payload with this summary.
+ Summarized(SummarizedPayload),
+ /// The payload did not need summarizing. Keep it and say nothing — a
+ /// notice here would be noise on every small tool result.
+ NotNeeded,
+ /// The raw payload is what the model will see. Keep it, and prefix
+ /// [`UnavailableReason::notice`] so the model knows why.
+ Unavailable(UnavailableReason),
+}
+
/// Trait for anything that can compress a tool result before it enters
/// agent history. Implementations decide the threshold, the dispatch
/// mechanism, and the failure policy.
@@ -87,21 +149,23 @@ pub struct SummarizedPayload {
pub trait PayloadSummarizer: Send + Sync {
/// TinyAgents parent-context-aware entry point.
///
- /// Returns `Ok(None)` if the payload should be kept as-is, or
- /// `Ok(Some(...))` if the caller should swap it for the
- /// compressed [`SummarizedPayload::summary`].
+ /// See [`SummarizeOutcome`]. The three states are deliberately distinct:
+ /// a caller must be able to tell "this payload was fine as it was" from
+ /// "summarization did not happen", because only the second needs to be
+ /// disclosed to the model.
///
- /// Errors are intentionally swallowed by the default implementation
- /// — a failed summarization should never break a tool call. The
- /// trait still returns `Result` so future implementations can
- /// surface fatal misconfigurations.
+ /// A failed summarization should still never break a tool call, so
+ /// implementations report failure as
+ /// [`SummarizeOutcome::Unavailable`] rather than `Err`. `Err` remains for
+ /// fatal misconfiguration, and the caller now handles it rather than
+ /// pattern-matching it away.
async fn maybe_summarize_in_parent(
&self,
parent_ctx: &RunContext<()>,
tool_name: &str,
parent_task_hint: Option<&str>,
raw: &str,
- ) -> Result<Option<SummarizedPayload>>;
+ ) -> Result<SummarizeOutcome>;
}
/// Default implementation that dispatches the `summarizer` through
@@ -200,7 +264,7 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {
tool_name: &str,
parent_task_hint: Option<&str>,
raw: &str,
- ) -> Result<Option<SummarizedPayload>> {
+ ) -> Result<SummarizeOutcome> {
let tokens = estimate_tokens(raw);
// ── 1. Pass-through checks ─────────────────────────────────────
@@ -212,7 +276,9 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {
threshold = self.threshold_tokens,
"[payload_summarizer] below threshold, passing through"
);
- return Ok(None);
+ // The only genuinely uneventful exit: the payload was fine as it
+ // was, so the model is told nothing.
+ return Ok(SummarizeOutcome::NotNeeded);
}
if tokens > self.max_payload_tokens {
warn!(
@@ -222,7 +288,9 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {
max = self.max_payload_tokens,
"[payload_summarizer] payload exceeds max cap, skipping summarization (will be truncated downstream)"
);
- return Ok(None);
+ return Ok(SummarizeOutcome::Unavailable(
+ UnavailableReason::PayloadTooLarge,
+ ));
}
if self.breaker_tripped() {
warn!(
@@ -231,7 +299,7 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {
bytes = raw.len(),
"[payload_summarizer] circuit breaker tripped, skipping summarization"
);
- return Ok(None);
+ return Ok(SummarizeOutcome::Unavailable(UnavailableReason::Disabled));
}
info!(
@@ -395,7 +463,7 @@ impl SubagentPayloadSummarizer {
raw: &str,
started: std::time::Instant,
outcome: Result<String>,
- ) -> Result<Option<SummarizedPayload>> {
+ ) -> Result<SummarizeOutcome> {
match outcome {
Ok(output) => {
let summary = output.trim().to_string();
@@ -405,7 +473,7 @@ impl SubagentPayloadSummarizer {
"[payload_summarizer] summarizer returned empty response, falling through"
);
self.record_failure();
- return Ok(None);
+ return Ok(SummarizeOutcome::Unavailable(UnavailableReason::Failed));
}
if summary.len() >= raw.len() {
warn!(
@@ -415,7 +483,7 @@ impl SubagentPayloadSummarizer {
"[payload_summarizer] summary not smaller than raw payload, falling through"
);
self.record_failure();
- return Ok(None);
+ return Ok(SummarizeOutcome::Unavailable(UnavailableReason::Failed));
}
self.record_success();
let summary_bytes = summary.len();
@@ -433,7 +501,7 @@ impl SubagentPayloadSummarizer {
elapsed_ms = started.elapsed().as_millis() as u64,
"[payload_summarizer] compressed successfully"
);
- Ok(Some(SummarizedPayload {
+ Ok(SummarizeOutcome::Summarized(SummarizedPayload {
summary,
original_bytes,
summary_bytes,
@@ -446,7 +514,7 @@ impl SubagentPayloadSummarizer {
"[payload_summarizer] sub-agent dispatch failed, falling through to raw payload"
);
self.record_failure();
- Ok(None)
+ Ok(SummarizeOutcome::Unavailable(UnavailableReason::Failed))
}
}
}
@@ -531,7 +599,7 @@ mod tests {
}
#[tokio::test]
- async fn maybe_summarize_returns_none_below_threshold() {
+ async fn below_threshold_is_not_needed_not_unavailable() {
let summarizer = SubagentPayloadSummarizer::new(
dummy_definition(),
TEST_THRESHOLD_TOKENS,
@@ -544,13 +612,14 @@ mod tests {
.await
.expect("below-threshold check should not error");
assert!(
- outcome.is_none(),
- "~256-token payload below 500k threshold should be passed through"
+ matches!(outcome, SummarizeOutcome::NotNeeded),
+ "a payload below the threshold needed nothing, so the model must be \
+ told nothing; got {outcome:?}"
);
}
#[tokio::test]
- async fn maybe_summarize_returns_none_above_max_cap() {
+ async fn above_max_cap_is_disclosed_as_unavailable() {
let summarizer = SubagentPayloadSummarizer::new(
dummy_definition(),
TEST_THRESHOLD_TOKENS,
@@ -562,14 +631,22 @@ mod tests {
.maybe_summarize_in_parent(&dummy_parent_ctx(), "test_tool", None, &raw)
.await
.expect("above-cap check should not error");
+ // The regression guard. This used to be `outcome.is_none()`, the same
+ // value the below-threshold case returns — which is exactly how a
+ // payload that will be truncated downstream reached the model looking
+ // like ordinary output.
assert!(
- outcome.is_none(),
- "~2.36M-token payload above 2M cap should be passed through (truncation handles it downstream)"
+ matches!(
+ outcome,
+ SummarizeOutcome::Unavailable(UnavailableReason::PayloadTooLarge)
+ ),
+ "a payload over the cap is not summarized and will be truncated, so \
+ it must be disclosed, not passed through silently; got {outcome:?}"
);
}
#[tokio::test]
- async fn maybe_summarize_returns_none_when_breaker_tripped() {
+ async fn tripped_breaker_is_disclosed_as_unavailable() {
let summarizer = SubagentPayloadSummarizer::new(
dummy_definition(),
TEST_THRESHOLD_TOKENS,
@@ -589,11 +666,54 @@ mod tests {
.await
.expect("breaker check should not error");
assert!(
- outcome.is_none(),
- "tripped breaker must short-circuit before any sub-agent dispatch"
+ matches!(
+ outcome,
+ SummarizeOutcome::Unavailable(UnavailableReason::Disabled)
+ ),
+ "a tripped breaker must short-circuit before any dispatch AND be \
+ disclosed — it is the case that repeats most often, because the \
+ breaker is rebuilt per session build; got {outcome:?}"
);
}
+ #[test]
+ fn every_unavailable_notice_tells_the_model_a_retry_is_pointless() {
+ // The whole point of the notice. A model handed a truncated dump with
+ // no explanation does the reasonable thing and calls the same tool
+ // again, which is the re-dispatch loop a user perceives as a hang.
+ for reason in [
+ UnavailableReason::PayloadTooLarge,
+ UnavailableReason::Disabled,
+ UnavailableReason::Failed,
+ ] {
+ let notice = reason.notice();
+ assert!(
+ notice.contains("Re-running this tool will return the same result."),
+ "{reason:?} must tell the model not to retry: {notice}"
+ );
+ assert!(
+ notice.starts_with("[openhuman: summarization unavailable"),
+ "{reason:?} must be greppable and self-identifying: {notice}"
+ );
+ }
+ }
+
+ #[test]
+ fn the_three_notices_are_distinct() {
+ // Three different situations; a reader (human or model) should be able
+ // to tell which one happened.
+ let all = [
+ UnavailableReason::PayloadTooLarge.notice(),
+ UnavailableReason::Disabled.notice(),
+ UnavailableReason::Failed.notice(),
+ ];
+ for (i, a) in all.iter().enumerate() {
+ for b in all.iter().skip(i + 1) {
+ assert_ne!(a, b, "each reason needs its own notice");
+ }
+ }
+ }
+
#[test]
fn build_summarizer_prompt_includes_tool_name_and_hint() {
let prompt = build_summarizer_prompt(