The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): reuse identical payload summaries, pass the user's goal, state the real size (#6283)
M3gA-Mind63355da7a5e3
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.rsindex 4921821c3b..883abec709 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@@ -123,6 +123,9 @@ impl Agent {let context_mw = crate::agent::tinyagents::TurnContextMiddleware {tool_result_budget_bytes: self.context.tool_result_budget_bytes(),payload_summarizer: self.payload_summarizer.clone(),+ // The raw user message (the date-stamped copy lives in history):+ // what the summarizer should keep facts for (#6283).+ task_hint: Some(user_message.to_string()),artifact_store,tokenjuice_compaction_enabled: self.context.compaction_enabled(),tokenjuice_compression: self.tokenjuice_compression,diff --git a/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.md b/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.mdindex 7d0f0cb07c..155c1a4745 100644--- a/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.md+++ b/crates/openhuman-core/src/agent/registry/agents/summarizer/prompt.md@@ -46,11 +46,10 @@ Structure:- ...(Only include this section if the payload contained IDs/URLs/hashes. Skip otherwise.)--## Original size-<original_bytes> bytes → summary of <this note>```+Do not state the payload's size and do not add an "Original size" section: the runtime appends the exact byte count after your note. The input tells you how many bytes the payload has and that all of it is between the markers, so never describe it as truncated unless the payload text itself says it was cut.+## Edge cases- If the payload is already short, produce a short summary. Don't pad.diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rsindex 591b64644f..461ebcfbfd 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs@@ -92,6 +92,9 @@ pub(crate) struct ToolOutputMiddleware {/// Fallback per-tool-result byte cap for tools that don't declare their own.pub(crate) budget_bytes: usize,pub(crate) payload_summarizer: Option<Arc<dyn PayloadSummarizer>>,+ /// What the user asked for this turn, handed to the payload summarizer so+ /// it keeps the facts that matter to the task. `None` off the chat path.+ pub(crate) task_hint: Option<String>,pub(crate) artifact_store: Option<ToolResultArtifactStore>,pub(crate) tokenjuice_compaction_enabled: bool,pub(crate) tokenjuice_compression: AgentTokenjuiceCompression,@@ -180,7 +183,12 @@ impl Middleware<()> for ToolOutputMiddleware {if !compaction_exempt {if let Some(ps) = &self.payload_summarizer {match ps- .maybe_summarize_in_parent(ctx, &result.name, None, &result.content)+ .maybe_summarize_in_parent(+ ctx,+ &result.name,+ self.task_hint.as_deref(),+ &result.content,+ ).await{Ok(SummarizeOutcome::Summarized(payload)) => {diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rsindex 42c205e5d8..da5175cdcf 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs@@ -35,6 +35,9 @@ pub(crate) struct TurnContextMiddleware {pub(crate) tool_result_budget_bytes: usize,/// Optional semantic tool-output summarizer (progressive disclosure).pub(crate) payload_summarizer: Option<Arc<dyn PayloadSummarizer>>,+ /// The user's request for this turn, passed to the payload summarizer as+ /// its task hint. `None` when the turn has no user message to offer.+ pub(crate) task_hint: Option<String>,/// Optional action-workspace artifact sink for oversized tool results.pub(crate) artifact_store: Option<ToolResultArtifactStore>,/// Whether TokenJuice content-aware compaction runs before output caps.@@ -125,6 +128,7 @@ impl TurnContextMiddleware {Self {tool_result_budget_bytes: DEFAULT_TOOL_RESULT_BUDGET_BYTES,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,@@ -188,6 +192,7 @@ impl TurnContextMiddleware {harness.push_middleware(Arc::new(ToolOutputMiddleware {budget_bytes: self.tool_result_budget_bytes,payload_summarizer: self.payload_summarizer,+ task_hint: self.task_hint,artifact_store: self.artifact_store,tokenjuice_compaction_enabled: self.tokenjuice_compaction_enabled,tokenjuice_compression: self.tokenjuice_compression,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex 97920b1431..b68545a7d1 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -76,6 +76,7 @@ fn summarizer_mw(ps: Arc<dyn PayloadSummarizer>) -> ToolOutputMiddleware {// tests observe the summarizer stage alone.budget_bytes: 10_000_000,payload_summarizer: Some(ps),+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Off,@@ -168,6 +169,7 @@ fn compaction_enabled_mw() -> ToolOutputMiddleware {ToolOutputMiddleware {budget_bytes: 1_000_000,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: true,tokenjuice_compression: AgentTokenjuiceCompression::Full,@@ -215,6 +217,7 @@ fn truncation_probe_mw() -> ToolOutputMiddleware {ToolOutputMiddleware {budget_bytes: DEFAULT_TOOL_RESULT_BUDGET_BYTES,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rsindex 2017585b16..426b38ea66 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs@@ -311,6 +311,7 @@ async fn tool_output_truncates_over_the_flat_budget() {let mw = ToolOutputMiddleware {budget_bytes: 100,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,@@ -332,6 +333,7 @@ async fn tool_output_leaves_small_results_untouched() {let mw = ToolOutputMiddleware {budget_bytes: 1_000,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,@@ -362,6 +364,7 @@ fn tool_char_cap_reads_the_tools_own_declared_cap() {let mw = ToolOutputMiddleware {budget_bytes: 1_000,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,@@ -404,6 +407,7 @@ async fn an_unavailable_notice_survives_a_tool_cap_shorter_than_itself() {payload_summarizer: Some(StubSummarizer::ok(SummarizeOutcome::Unavailable(UnavailableReason::Failed,))),+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Off,@@ -458,6 +462,7 @@ async fn tool_output_honors_a_tools_own_cap() {let mw = ToolOutputMiddleware {budget_bytes: 100_000,payload_summarizer: None,+ task_hint: None,artifact_store: None,tokenjuice_compaction_enabled: false,tokenjuice_compression: AgentTokenjuiceCompression::Off,@@ -638,3 +643,38 @@ async fn get_tool_contract_is_compaction_exempt() {"get_tool_contract's response must not be tokenjuice-tabulated");}++/// #6283: the summarizer used to be called with a hard-coded `None` hint, so+/// it compressed every payload blind to what the user asked for.+#[tokio::test]+async fn the_turns_task_hint_reaches_the_payload_summarizer() {+ struct HintRecorder(std::sync::Mutex<Option<Option<String>>>);+ #[async_trait]+ impl PayloadSummarizer for HintRecorder {+ 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("recorder lock") = Some(parent_task_hint.map(str::to_owned));+ Ok(SummarizeOutcome::NotNeeded)+ }+ }++ let recorder = Arc::new(HintRecorder(std::sync::Mutex::new(None)));+ let mut mw = summarizer_mw(recorder.clone());+ mw.task_hint = Some("find the release notes for v2".to_string());+ let mut result = tool_result("use_skill", "RAW-TOOL-OUTPUT");++ mw.after_tool(&mut ctx(), &(), &mut result)+ .await+ .expect("after_tool should not fail");++ assert_eq!(+ recorder.0.lock().expect("recorder lock").clone(),+ Some(Some("find the release notes for v2".to_string())),+ "the turn's task hint must be handed to the payload summarizer"+ );+}diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rsindex 08b398af76..e71071854e 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer.rs@@ -54,8 +54,9 @@use anyhow::{anyhow, Result};use async_trait::async_trait;-use std::collections::HashSet;-use std::sync::{Arc, Mutex};+use sha2::{Digest, Sha256};+use std::collections::{HashMap, HashSet, VecDeque};+use std::sync::{Arc, LazyLock, Mutex};use tinyagents_harness::context::RunContext;use tinyagents_harness::runtime::{AgentHarness, InvalidArgsPolicy, RunPolicy, UnknownToolPolicy};use tinyagents_harness::subagent::SubAgent;@@ -318,6 +319,22 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {UnavailableReason::PayloadTooLarge,));}+ // Checked before the breaker: a summary we already have costs nothing,+ // so a broken summarizer is no reason to withhold it.+ let cache_key = summary_cache_key(tool_name, parent_task_hint, raw);+ if let Some(summary) = cached_summary(&cache_key) {+ info!(+ tool = tool_name,+ bytes = raw.len(),+ summary_bytes = summary.len(),+ "[payload_summarizer] reusing the summary of an identical payload"+ );+ return Ok(SummarizeOutcome::Summarized(SummarizedPayload {+ summary_bytes: summary.len(),+ summary,+ original_bytes: raw.len(),+ }));+ }if self.breaker_tripped() {warn!(tool = tool_name,@@ -341,7 +358,7 @@ impl PayloadSummarizer for SubagentPayloadSummarizer {let outcome = self.invoke_tinyagents_summarizer_in_parent(parent_ctx, prompt).await;- self.handle_summarizer_result(tool_name, raw, started, outcome)+ self.handle_summarizer_result(tool_name, raw, started, outcome, cache_key)}}@@ -487,10 +504,11 @@ impl SubagentPayloadSummarizer {raw: &str,started: std::time::Instant,outcome: Result<String>,+ cache_key: SummaryCacheKey,) -> Result<SummarizeOutcome> {match outcome {Ok(output) => {- let summary = output.trim().to_string();+ let summary = output.trim();if summary.is_empty() {warn!(tool = tool_name,@@ -499,6 +517,14 @@ impl SubagentPayloadSummarizer {self.record_failure();return Ok(SummarizeOutcome::Unavailable(UnavailableReason::Failed));}+ // The size is the runtime's to state, not the model's. The model+ // was never told it and estimated it instead — live summaries+ // reported "~9,000 bytes (truncated payload)" for a complete+ // 119,796-byte input, and the orchestrator reasoned from that.+ let summary = format!(+ "{summary}\n\n## Original size\n{} bytes of tool output, complete, summarized into this note.",+ raw.len()+ );if summary.len() >= raw.len() {warn!(tool = tool_name,@@ -525,6 +551,7 @@ impl SubagentPayloadSummarizer {elapsed_ms = started.elapsed().as_millis() as u64,"[payload_summarizer] compressed successfully");+ remember_summary(cache_key, summary.clone());Ok(SummarizeOutcome::Summarized(SummarizedPayload {summary,original_bytes,@@ -552,20 +579,95 @@ fn estimate_tokens(text: &str) -> usize {text.len().div_ceil(4)}+/// Identity of one summarization: thread, tool, task hint and payload bytes.+type SummaryCacheKey = [u8; 32];++/// How many summaries the process keeps. Oldest out first.+// ponytail: FIFO eviction, move to LRU if hit rates on long threads show it matters.+const SUMMARY_CACHE_ENTRIES: usize = 64;++/// Summaries already produced, reused when the same tool returns the same+/// payload for the same task in the same thread.+///+/// Process-wide rather than a field: a `SubagentPayloadSummarizer` is built per+/// turn (`AgentBuilder`), so a per-instance cache would die before the repeat+/// it exists for — in a live session one 119,796-byte payload was summarized+/// five times across four turns at ~40-60 s each.+static SUMMARY_CACHE: LazyLock<Mutex<SummaryCache>> = LazyLock::new(Default::default);++#[derive(Default)]+struct SummaryCache {+ entries: HashMap<SummaryCacheKey, String>,+ order: VecDeque<SummaryCacheKey>,+}++/// Key a summary by everything that shapes it. The thread scopes reuse to a+/// conversation; the hint is included because a summary written for one goal+/// can drop exactly the facts another goal needs. Fields are length-prefixed+/// so no two different tuples hash the same byte stream.+fn summary_cache_key(+ tool_name: &str,+ parent_task_hint: Option<&str>,+ raw: &str,+) -> SummaryCacheKey {+ let thread = super::thread_context::current_thread_id().unwrap_or_default();+ let mut hasher = Sha256::new();+ for part in [+ thread.as_str(),+ tool_name,+ parent_task_hint.unwrap_or(""),+ raw,+ ] {+ hasher.update((part.len() as u64).to_le_bytes());+ hasher.update(part.as_bytes());+ }+ hasher.finalize().into()+}++fn cached_summary(key: &SummaryCacheKey) -> Option<String> {+ SUMMARY_CACHE.lock().ok()?.entries.get(key).cloned()+}++fn remember_summary(key: SummaryCacheKey, summary: String) {+ let Ok(mut cache) = SUMMARY_CACHE.lock() else {+ return;+ };+ if cache.entries.insert(key, summary).is_none() {+ cache.order.push_back(key);+ }+ while cache.order.len() > SUMMARY_CACHE_ENTRIES {+ if let Some(oldest) = cache.order.pop_front() {+ cache.entries.remove(&oldest);+ }+ }+}++/// Upper bound on the task hint carried into the prompt. It is the user's+/// message for the turn, which can be a pasted document; the summarizer needs+/// the intent, not the whole thing.+const TASK_HINT_MAX_CHARS: usize = 2_000;+/// Build the user-message prompt fed into the summarizer sub-agent.////// Wraps the raw payload in `--- BEGIN ---` / `--- END ---` markers so/// the sub-agent can unambiguously distinguish the payload boundary/// from other prompt scaffolding. The tool name and optional parent/// task hint are surfaced before the payload so the summarizer can-/// prioritize facts relevant to the parent's intent.+/// prioritize facts relevant to the parent's intent, and the exact byte+/// count is stated so the model never has to guess the payload's size or+/// whether it was cut.fn build_summarizer_prompt(tool_name: &str, parent_task_hint: Option<&str>, raw: &str) -> String {let hint_line = parent_task_hint- .map(|h| format!("Parent task hint: {}\n\n", h))+ .map(str::trim)+ .filter(|h| !h.is_empty())+ .map(|h| {+ let clipped: String = h.chars().take(TASK_HINT_MAX_CHARS).collect();+ format!("Parent task hint: {clipped}\n\n")+ }).unwrap_or_default();format!(- "Tool name: {}\n\n{}Raw tool output (summarize per the extraction contract in your system prompt):\n\n--- BEGIN ---\n{}\n--- END ---",- tool_name, hint_line, raw+ "Tool name: {tool_name}\n\n{hint_line}Raw tool output: {} bytes, complete, all of it between the markers below (summarize per the extraction contract in your system prompt):\n\n--- BEGIN ---\n{raw}\n--- END ---",+ raw.len())}diff --git a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rsindex 425ed22aee..a3d013b9c0 100644--- a/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/payload_summarizer_tests.rs@@ -209,3 +209,99 @@ fn record_success_resets_breaker() {summarizer.record_failure();assert!(!summarizer.breaker_tripped());}++// ── summary reuse and the real payload size (#6283) ─────────────────────++fn low_threshold_summarizer() -> SubagentPayloadSummarizer {+ SubagentPayloadSummarizer::new(dummy_definition(), 1, TEST_MAX_TOKENS)+}++#[tokio::test]+async fn an_identical_payload_reuses_the_earlier_summary_instead_of_dispatching() {+ let raw = "identical payload for the reuse test ".repeat(64);+ let hint = Some("reuse-test goal");+ remember_summary(+ summary_cache_key("reuse_tool", hint, &raw),+ "CACHED SUMMARY".to_string(),+ );++ // No parent execution context is installed, so a real dispatch fails and+ // reports `Unavailable`; only reuse can produce a summary here.+ let outcome = low_threshold_summarizer()+ .maybe_summarize_in_parent(&dummy_parent_ctx(), "reuse_tool", hint, &raw)+ .await+ .expect("summarization never errors here");++ match outcome {+ SummarizeOutcome::Summarized(payload) => {+ assert_eq!(payload.summary, "CACHED SUMMARY");+ assert_eq!(payload.original_bytes, raw.len());+ }+ other => panic!(+ "an identical payload must reuse the stored summary instead of dispatching \+ the summarizer again; got {other:?}"+ ),+ }+}++#[tokio::test]+async fn a_summary_written_for_another_goal_is_not_reused() {+ let raw = "payload shared across two goals ".repeat(64);+ remember_summary(+ summary_cache_key("goal_tool", Some("goal A"), &raw),+ "SUMMARY FOR GOAL A".to_string(),+ );++ let outcome = low_threshold_summarizer()+ .maybe_summarize_in_parent(&dummy_parent_ctx(), "goal_tool", Some("goal B"), &raw)+ .await+ .expect("summarization never errors here");++ assert!(+ !matches!(outcome, SummarizeOutcome::Summarized(_)),+ "a summary shaped for one goal must not be served for another; got {outcome:?}"+ );+}++#[test]+fn a_successful_summary_is_remembered_and_states_the_real_size() {+ let summarizer = low_threshold_summarizer();+ let raw = "x".repeat(50_000);+ let key = summary_cache_key("size_tool", Some("size goal"), &raw);++ let outcome = summarizer+ .handle_summarizer_result(+ "size_tool",+ &raw,+ std::time::Instant::now(),+ Ok("model note: original was ~9,000 bytes (truncated payload)".to_string()),+ key,+ )+ .expect("a usable summary is not an error");++ let SummarizeOutcome::Summarized(payload) = outcome else {+ panic!("a non-empty, smaller summary must be accepted");+ };+ assert!(+ payload+ .summary+ .contains("50000 bytes of tool output, complete"),+ "the size the orchestrator reads must come from the real byte count, got: {}",+ payload.summary+ );+ assert_eq!(+ cached_summary(&key).as_deref(),+ Some(payload.summary.as_str()),+ "a successful summary must be stored for reuse"+ );+}++#[test]+fn build_summarizer_prompt_states_the_real_byte_count() {+ let raw = "abc".repeat(1_000);+ let prompt = build_summarizer_prompt("size_tool", None, &raw);+ assert!(+ prompt.contains("Raw tool output: 3000 bytes, complete"),+ "the summarizer must be told the payload's exact size, got: {prompt}"+ );+}