Skip to content

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

fix(agent): handle tool output with no content field

Steven Enamakeldc527b980368
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
index 1d81261621..f0fdb86207 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
@@ -1,6 +1,7 @@
//! [`ToolOutputMiddleware`]: the `after_tool` ladder every tool result passes
-//! through before it enters the transcript — payload summarizer, TokenJuice
-//! compaction, per-tool char cap, shared byte-budget backstop, disclosure.
+//! through before it enters the transcript — TinyJuice (LLM summary, then
+//! content-aware compaction), per-tool char cap, shared byte-budget backstop,
+//! disclosure.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -18,9 +19,8 @@ use crate::agent::harness::tool_result_artifacts::{
apply_per_result_persistence, artifact_read_target, page_artifact_read, ArtifactRead,
ToolResultArtifactStore, TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,
};
-use crate::agent::tinyagents::payload_summarizer::{
- PayloadSummarizer, SummarizeOutcome, UnavailableReason,
-};
+use crate::agent::tinyagents::payload_summarizer::PayloadSummarizer;
+use crate::inference::tokenjuice::generate::GenerateTicket;
use crate::inference::tokenjuice::AgentTokenjuiceCompression;
fn estimate_output_tokens(bytes: usize) -> u64 {
@@ -93,10 +93,9 @@ pub(crate) fn is_truncation_exempt(name: &str) -> bool {
pub(crate) struct ToolOutputMiddleware {
/// Fallback per-tool-result byte cap for tools that don't declare their own.
pub(crate) budget_bytes: usize,
+ /// The model behind TinyJuice's summary stage. `None` means this agent's
+ /// results are never summarized.
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,
@@ -111,6 +110,9 @@ pub(crate) struct ToolOutputMiddleware {
/// `before_tool`, where the arguments are visible, and consumed in
/// `after_tool`, where they are not.
pub(crate) artifact_reads: Mutex<HashMap<String, ArtifactRead>>,
+ /// `summary_focus` values taken out of calls in `before_tool`, keyed by
+ /// call id, for the summary of the same call's result.
+ pub(crate) focus_by_call: Mutex<HashMap<String, String>>,
}
impl ToolOutputMiddleware {
@@ -122,6 +124,36 @@ impl ToolOutputMiddleware {
.get(name)
.and_then(|policy| policy.runtime.max_result_bytes)
}
+
+ /// Register a summary call bound to this turn, when this agent has a
+ /// summary model and the result is at least TinyJuice's threshold.
+ fn summary_ticket(
+ &self,
+ ctx: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ tool_name: &str,
+ bytes: usize,
+ ) -> Option<GenerateTicket> {
+ let summarizer = self.payload_summarizer.as_ref()?;
+ let threshold_tokens = self
+ .runtime_config
+ .as_ref()
+ .map(|config| config.context.summarizer_payload_threshold_tokens)
+ .unwrap_or_default();
+ if threshold_tokens == 0 || estimate_output_tokens(bytes) < threshold_tokens as u64 {
+ return None;
+ }
+ match summarizer.prepare(ctx) {
+ Ok(prepared) => Some(crate::inference::tokenjuice::generate::register(prepared)),
+ Err(error) => {
+ tracing::warn!(
+ tool = tool_name,
+ error = %error,
+ "[tinyagents::mw] could not prepare a summary call; compacting without one"
+ );
+ None
+ }
+ }
+ }
}
#[async_trait]
@@ -136,6 +168,19 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Too
_state: &(),
call: &mut TaToolCall,
) -> TaResult<()> {
+ // Taken out before validation and before the tool runs: it is an
+ // argument to the summary of the result, not to the tool.
+ if let Some(focus) = crate::inference::tokenjuice::focus::take_summary_focus(&mut call.arguments) {
+ tracing::debug!(
+ tool = %call.name,
+ call_id = %call.id,
+ focus_chars = focus.chars().count(),
+ "[tinyagents::mw] summary_focus captured"
+ );
+ if let Ok(mut by_call) = self.focus_by_call.lock() {
+ by_call.insert(call.id.clone(), focus);
+ }
+ }
if let Some(read) = artifact_read_target(&call.name, &call.arguments) {
tracing::debug!(
tool = %call.name,
@@ -173,6 +218,9 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Too
.ok()
.and_then(|mut reads| reads.remove(&call_id));
if let Some(read) = artifact_read {
+ if let Ok(mut by_call) = self.focus_by_call.lock() {
+ by_call.remove(&call_id);
+ }
tracing::info!(
tool = tool_name,
path = %read.path,
@@ -233,7 +281,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Too
// and prefixing afterwards also means a tool's declared cap bounds the
// tool's own output, which is what it is a contract about, rather than
// openhuman's annotation about it.
- let mut pending_notice: Option<&'static str> = None;
+ let mut pending_notice: Option<String> = None;
// The byte count a summary replaced, stated in step 5 for the same
// reason as the notice: a cap that truncates the summary must not take
// the authoritative size with it (#6283).
@@ -267,78 +315,68 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext> for Too
&& content.len() as u64 <= crate::tools::FileReadTool::MAX_FILE_SIZE_BYTES)
.then(|| content.clone());
- // A tool that declares its own cap bounds itself, and step 4 spills
- // the overflow to an artifact the model can page with `file_read`.
- // Summarizing it as well would pay a model call — at `web_fetch` sizes,
- // 20s and ~160k prompt tokens — to produce something the paging handle
- // already gives losslessly. Neither Hermes nor Codex runs a model over
- // oversized tool output; both truncate and hand back a way to read the
- // rest.
- if !compaction_exempt && tool_cap.is_none() {
- if let Some(ps) = &self.payload_summarizer {
- match ps
- .maybe_summarize_in_parent(ctx, tool_name, self.task_hint.as_deref(), &content)
- .await
- {
- Ok(SummarizeOutcome::Summarized(payload)) => {
- tracing::info!(
- tool = tool_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),
- });
- summarized_from_bytes = Some(payload.original_bytes);
- 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 = tool_name,
- bytes = content.len(),
- ?reason,
- "[tinyagents::mw] payload_summarizer unavailable; disclosing raw output"
- );
- pending_notice = Some(reason.notice());
- }
- // 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 = tool_name,
- bytes = content.len(),
- error = %error,
- "[tinyagents::mw] payload_summarizer errored; disclosing raw output"
- );
- pending_notice = Some(UnavailableReason::Failed.notice());
- }
- }
- }
-
- // 2. TokenJuice content-aware compaction. This mirrors the legacy
- // `agent_tool_exec` stage that ran after semantic summarization and
- // before the hard output caps.
- let before_tokenjuice_bytes = content.len();
- let compacted = crate::inference::tokenjuice::compact_output_with_config(
- std::mem::take(&mut content),
- tool_name,
- self.tokenjuice_compaction_enabled,
- self.tokenjuice_compression,
- self.runtime_config.as_ref(),
+ // 1+2. TinyJuice: the LLM summary stage (when this agent has a
+ // summary model), then content-aware compaction (when enabled).
+ //
+ // A tool that declares its own cap bounds itself, and step 3
+ // spills the overflow to an artifact the model can page with
+ // `file_read`. Summarizing it as well would pay a model call — at
+ // `web_fetch` sizes, 20s and ~160k prompt tokens — to produce
+ // something the paging handle already gives losslessly. The one
+ // exception is a caller that said what it needs (`summary_focus`):
+ // a summary written for that question is worth the call, because
+ // paging cannot answer it.
+ let focus = self
+ .focus_by_call
+ .lock()
+ .ok()
+ .and_then(|mut focus| focus.remove(&call_id));
+ let wants_tinyjuice =
+ self.tokenjuice_compaction_enabled || self.payload_summarizer.is_some();
+ if !compaction_exempt && wants_tinyjuice && (tool_cap.is_none() || focus.is_some()) {
+ // Bind a summary call to this turn only when the result is big
+ // enough for TinyJuice to want one; building the child context for
+ // every small result would be waste.
+ let ticket = self.summary_ticket(ctx, tool_name, content.len());
+ let before_bytes = content.len();
+ let compacted = crate::inference::tokenjuice::compact_tool_output(
+ crate::inference::tokenjuice::ToolOutputCompaction {
+ content: std::mem::take(&mut content),
+ tool_name,
+ enabled: self.tokenjuice_compaction_enabled,
+ profile: self.tokenjuice_compression,
+ runtime_config: self.runtime_config.as_ref(),
+ arguments: None,
+ focus,
+ context_token: ticket.as_ref().map(|t| t.token().to_string()),
+ scope: ctx.data.thread_id.clone(),
+ },
)
.await;
- content = compacted;
- let after_tokenjuice_bytes = content.len();
- if after_tokenjuice_bytes < before_tokenjuice_bytes {
+ drop(ticket);
+ content = compacted.text;
+ if let Some(bytes) = compacted.summarized_from_bytes {
+ tracing::info!(
+ tool = tool_name,
+ from_bytes = bytes,
+ to_bytes = content.len(),
+ "[tinyagents::mw] tinyjuice summarized tool output"
+ );
+ summarized_from_bytes = Some(bytes);
+ }
+ if let Some(notice) = compacted.notice {
+ tracing::warn!(
+ tool = tool_name,
+ bytes = content.len(),
+ "[tinyagents::mw] tinyjuice summary unavailable; disclosing raw output"
+ );
+ pending_notice = Some(notice);
+ }
+ let after_bytes = content.len();
+ if after_bytes < before_bytes {
ctx.emit(AgentEvent::Compressed {
- from_tokens: estimate_output_tokens(before_tokenjuice_bytes),
- to_tokens: estimate_output_tokens(after_tokenjuice_bytes),
+ from_tokens: estimate_output_tokens(before_bytes),
+ to_tokens: estimate_output_tokens(after_bytes),
});
}
}