Skip to content

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

Merge remote-tracking branch 'upstream/main' into life-scenarios-cache

Steven Enamakel25e2f42e1d54
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
index 585e77dff4,7e9e9e1d9f..c1b03d86b4
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output.rs
@@@ -142,11 -115,13 +146,18 @@@ 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>>,
+ /// Tools whose schema carries TinyJuice's `summary_focus` property. Only
+ /// their calls lose the argument; any other tool with a parameter of the
+ /// same name (an MCP server's, say) keeps it.
+ pub(crate) summary_focus_tools: HashSet<String>,
+ /// Calls that asked `web_fetch` for the raw body, keyed by call id. Filled
+ /// in `before_tool`, where the arguments are visible, and consumed in
+ /// `after_tool`, where they are not — the same seam `artifact_reads` uses,
+ /// and for the same reason. See [`is_raw_fetch`].
+ pub(crate) raw_fetches: Mutex<std::collections::HashSet<String>>,
}
impl ToolOutputMiddleware {
@@@ -320,120 -330,85 +383,103 @@@ impl Middleware<(), crate::agent::tinya
&& 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() {
- // 1. TokenJuice content-aware compaction — the cheap, deterministic
- // step, and so the one that runs first.
- //
- // It used to run *after* the summarizer, mirroring the legacy
- // `agent_tool_exec` order. That made it dead weight on the only
- // axis that costs anything: compaction never got to shrink the
- // payload an LLM was about to read, it only ever re-compacted a
- // summary the summarizer had already shrunk. The expensive stage
- // paid full price for the raw bytes and the cheap stage tidied
- // the leftovers.
- //
- // Ordered this way, a payload TokenJuice can bring under
- // `threshold_tokens` skips the summarizer model call entirely —
- // `maybe_summarize_in_parent` reads `content` *after* this stage
- // and answers `NotNeeded`. Same ladder discipline as the context
- // ladder's "cheapest sufficient step first" (#6014).
- //
- // This is only sound because TokenJuice's transforms are
- // representation changes an LLM can still read (tabulating a
- // uniform object-array into a `[json table: …]` marker), not
- // erasure. The context ladder's own ordering bug is the
- // counter-example to respect: microcompact *blanks* tool bodies
- // to `CLEARED_PLACEHOLDER`, so running it before summarization
- // asked the summarizer for "key results" it could no longer see.
- // Any future TokenJuice profile that drops content outright
- // rather than re-encoding it belongs behind the summarizer
- // again.
- //
- // Compaction is off by default (`[context].compaction_enabled`
- // is `false` and the router lives behind the TinyBus module
- // boundary), so on a default install
- // `compact_output_with_config` returns `content` untouched and
- // this stage changes nothing. The ordering matters for installs
- // that turn it on.
- 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()) {
++ // A `raw: true` `web_fetch` is excluded outright, `summary_focus`
++ // or not: it asked for the body *as sent*, which switches off the
++ // HTML→Markdown conversion, so the payload is unconverted markup
++ // and a summary of it is an uncached model call spent paraphrasing
++ // minified JS. One observed such fetch cost 44,561 prompt tokens —
++ // over half that turn's summarizer budget — to re-describe a page
++ // the same turn had already read as clean Markdown. Step 3 still
++ // bounds it and spills the rest to an artifact, which hands back
++ // the real markup losslessly and for no model call. See
++ // [`is_raw_fetch`].
++ if raw_fetch {
++ tracing::info!(
++ tool = tool_name,
++ bytes = content.len(),
++ "[tinyagents::mw] raw fetch: skipping the tinyjuice summary, \
++ capping and spilling to an artifact instead"
++ );
++ }
++ if !raw_fetch && !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, unprepared) = match self.summary_ticket(ctx, tool_name, &content) {
+ Some(Ok(ticket)) => (Some(ticket), false),
+ Some(Err(())) => (None, true),
+ None => (None, false),
+ };
+ // Summary reuse and the failure breaker are per scope. A turn
+ // with no thread still gets one for the life of this run, rather
+ // than a fresh one per call that never reuses or trips.
+ let scope = ctx
+ .data
+ .thread_id
+ .clone()
+ .unwrap_or_else(|| format!("run-{}", ctx.instance_id()));
+ let before_bytes = content.len();
+ let before_tokens = estimate_output_tokens(&content);
+ 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: Some(scope),
+ },
)
.await;
- content = compacted;
- let after_tokenjuice_bytes = content.len();
- if after_tokenjuice_bytes < before_tokenjuice_bytes {
- ctx.emit(AgentEvent::Compressed {
- from_tokens: estimate_output_tokens(before_tokenjuice_bytes),
- to_tokens: estimate_output_tokens(after_tokenjuice_bytes),
- });
- }
-
- // 2. Semantic summarization, on whatever step 1 left behind —
- // unless the caller asked for the raw body, see `is_raw_fetch`.
- if raw_fetch {
+ 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);
+ }
+ let notice = compacted
+ .notice
+ .or_else(|| unprepared.then(crate::inference::tokenjuice::summary_failed_notice));
+ if let Some(notice) = notice {
+ tracing::warn!(
tool = tool_name,
bytes = content.len(),
- "[tinyagents::mw] raw fetch: skipping payload summarizer, \
- capping and spilling to an artifact instead"
+ "[tinyagents::mw] tinyjuice summary unavailable; disclosing raw output"
);
+ pending_notice = Some(notice);
}
- if let Some(ps) = (!raw_fetch).then_some(self.payload_summarizer.as_ref()).flatten() {
- 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());
- }
- }
+ let after_bytes = content.len();
+ if after_bytes < before_bytes {
+ ctx.emit(AgentEvent::Compressed {
+ from_tokens: before_tokens,
+ to_tokens: estimate_output_tokens(&content),
+ });
}
}
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs
index e8add63d19,e7e377f5db..ee2aa5079a
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/tool_output_tests.rs
@@@ -24,7 -23,8 +23,9 @@@ async fn same_tool_calls_persist_artifa
runtime_config: None,
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
};
let mut ctx = context();
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
index 46438aeb88,d8d1db4b3f..d42cd3a0e8
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/turn_context.rs
@@@ -434,7 -430,8 +430,9 @@@ impl TurnContextMiddleware
runtime_config: self.runtime_config,
tool_policies,
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools,
+ raw_fetches: Default::default(),
}));
}
// Push the handoff LAST (so its `after_tool` runs FIRST): it observes the
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
index e8331a4321,be7963e3a0..04292b6619
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
@@@ -83,17 -95,18 +95,19 @@@ fn summarizing_config() -> Arc<crate::c
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.
+ // tests observe the summary 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,
- runtime_config: None,
+ tokenjuice_compression: crate::inference::tokenjuice::AgentTokenjuiceCompression::Full,
+ runtime_config: Some(summarizing_config()),
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ // `web_fetch` declares `summary_focus` in production.
+ summary_focus_tools: ["web_fetch".to_string()].into(),
+ raw_fetches: Default::default(),
}
}
@@@ -192,7 -218,8 +219,9 @@@ fn compaction_enabled_mw() -> ToolOutpu
runtime_config: None,
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
}
}
@@@ -242,7 -268,8 +270,9 @@@ fn truncation_probe_mw() -> ToolOutputM
runtime_config: None,
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
}
}
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs
index e763b4fda7,4b33f81f58..6c8b583e35
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_artifact_tests.rs
@@@ -19,11 -18,12 +18,13 @@@ fn artifact_mw
),
),
tokenjuice_compaction_enabled: false,
- tokenjuice_compression: AgentTokenjuiceCompression::Off,
- runtime_config: None,
+ tokenjuice_compression: AgentTokenjuiceCompression::Full,
+ runtime_config: Some(summarizing_config()),
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
}
}
diff --cc crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
index a4a19ad731,448dd8f95f..0b7ea7cd7a
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs
@@@ -461,7 -466,8 +466,9 @@@ async fn tool_output_truncates_over_the
runtime_config: None,
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
};
let mut result = tool_result("echo", &"x".repeat(5_000));
mw.after_tool(
@@@ -495,7 -500,8 +501,9 @@@ async fn tool_output_leaves_small_resul
runtime_config: None,
tool_policies: HashMap::new(),
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
};
let mut result = tool_result("echo", "tiny");
mw.after_tool(
@@@ -536,7 -541,8 +543,9 @@@ fn tool_char_cap_reads_the_tools_own_de
runtime_config: None,
tool_policies,
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
};
// Tool declares its own char cap → surfaced for the per-tool truncation.
assert_eq!(mw.tool_char_cap("big"), Some(10));
@@@ -637,7 -673,8 +676,9 @@@ async fn tool_output_honors_a_tools_own
runtime_config: None,
tool_policies,
artifact_reads: Default::default(),
+ focus_by_call: Default::default(),
+ summary_focus_tools: Default::default(),
+ raw_fetches: Default::default(),
};
let mut result = tool_result("capped", &"y".repeat(500));
mw.after_tool(