Skip to content

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

refactor(middleware): extract outcome restoration into a shared method

Steven Enamakelf8327b6b4b3f
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
index d7d353f8aa..1deccc5719 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/final_call_wrap_up.rs
@@ -122,90 +122,23 @@ impl FinalCallWrapUpMiddleware {
pub(crate) fn fired(&self) -> Arc<std::sync::atomic::AtomicBool> {
self.fired.clone()
}
-}
-#[async_trait]
-impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for FinalCallWrapUpMiddleware
-{
- fn name(&self) -> &str {
- "final_call_wrap_up"
- }
-
- async fn before_model(
- &self,
- ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- _state: &(),
- request: &mut ModelRequest,
- ) -> TaResult<()> {
- if ctx.limits.remaining_model_calls() > 0 {
- return Ok(());
- }
- // A budget of one call would make the very first call the concluding
- // one, so the turn could never run a tool at all. That is a
- // misconfiguration rather than a cap being reached, and silently
- // answering it with a "you have run out of tool calls" instruction
- // would misreport it — leave such a run alone.
- if ctx.limits.limits().max_model_calls <= 1 {
- return Ok(());
- }
- tracing::info!(
- model_calls = ctx.limits.model_calls(),
- max_model_calls = ctx.limits.limits().max_model_calls,
- tools_withdrawn = request.tools.len(),
- "[tinyagents::mw] final permitted model call — withdrawing tools and asking for the \
- turn's conclusion"
- );
- request.tools.clear();
- request.tool_choice = tinyinference_llm::model::ToolChoice::None;
- // Give the concluding call back the results microcompact blanked.
- //
- // `MicrocompactMiddleware` replaces every tool-result body past the
- // most recent `keep_recent` (5, by default) with `CLEARED_PLACEHOLDER`,
- // and — constructed without a token budget — it does so on every call,
- // not only under context pressure. That is right for an intermediate
- // call, which needs recent context to choose the next tool and nothing
- // more. It is exactly wrong for this one: a turn that spent 24 rounds
- // gathering would be asked to report its findings with 19 rounds of
- // them replaced by "[Old tool result content cleared]", which is the
- // same empty-handed answer this whole mechanism exists to prevent,
- // arrived at from the other direction.
- //
- // Restored from the captured outcomes rather than by exempting the
- // turn from microcompact, because the blanking has already happened by
- // the time this runs (registration order: microcompact is installed by
- // `context_mw.install`, this middleware immediately after it) and
- // because the sink is the honest source — it holds each result as it
- // entered the transcript, after the per-result byte cap.
- //
- // Only a body that IS the placeholder is replaced, so a result the
- // model legitimately saw in full is never rewritten.
- //
- // This deliberately runs BEFORE the compression and trim middlewares,
- // which are installed after it: restoring can make the request large,
- // and those two are what bound it. The resulting degradation ladder is
- // the one this call wants — everything when it fits, an LLM summary of
- // the older slice when it does not, and oldest-first eviction only in
- // extremis. What it never does again is silently blank the middle.
- // Restore newest-first, and only while the request still fits.
- //
- // CodeRabbit on #6068: restoration runs AFTER `ContextCompressionMiddleware`
- // and before `ImageAwareMessageTrimMiddleware`, so an unbounded restore can
- // push the request over the window and the trim then evicts whole
- // messages — which is strictly more destructive than the blanking being
- // undone, and can discard the very results just restored.
- //
- // The review suggested a compression phase after restoration. That is a
- // second summarizer model call on the one call already about to produce
- // the conclusion, and it is avoidable: the overflow is preventable
- // rather than repairable. Restoring under the same budget the trim
- // enforces means the trim never has cause to fire, so nothing is
- // evicted and nothing needs re-summarising.
- //
- // Newest-first because recency is relevance here: the last rounds'
- // results are the ones the model has not seen (the cap is checked
- // before the request is built), and the earliest ones are most likely
- // already reflected in the compression summary above.
+ /// Give a concluding-or-persisting call back the tool results microcompact
+ /// blanked, newest-first and only while the request still fits.
+ ///
+ /// Shared by both of this middleware's calls, because both need the same
+ /// thing for the same reason: the content the turn gathered. The final call
+ /// needs it to *report* findings, and the penultimate one needs it to
+ /// *write them into a file* — and a turn asked to produce an artifact from
+ /// nineteen rounds of "[Old tool result content cleared]" produces the same
+ /// empty-handed result from either direction.
+ ///
+ /// `instruction` is the text the caller will append afterwards; it is
+ /// seeded into the token accounting here rather than counted later, because
+ /// restoration fills the budget to its boundary and an unaccounted fixed
+ /// addition after it is exactly the overshoot the budget exists to prevent
+ /// (CodeRabbit on #6068).
+ fn restore_cleared_outcomes(&self, request: &mut ModelRequest, instruction: &str) -> usize {
let budget = self.input_budget;
// Seeded with the instruction this middleware appends unconditionally
// below, not just with what the request already holds (CodeRabbit on
@@ -217,7 +150,7 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
.iter()
.map(estimate_message_tokens)
.sum::<u64>()
- .saturating_add(estimate_text_tokens(self.instruction));
+ .saturating_add(estimate_text_tokens(instruction));
let restored = match self.outcomes.lock() {
Ok(outcomes) => {
let mut restored = 0usize;
@@ -292,6 +225,94 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
"[tinyagents::mw] restored cleared tool results for the concluding call"
);
}
+ restored
+ }
+
+}
+
+#[async_trait]
+impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
+ for FinalCallWrapUpMiddleware
+{
+ fn name(&self) -> &str {
+ "final_call_wrap_up"
+ }
+
+ async fn before_model(
+ &self,
+ ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
+ _state: &(),
+ request: &mut ModelRequest,
+ ) -> TaResult<()> {
+ if ctx.limits.remaining_model_calls() > 0 {
+ return Ok(());
+ }
+ // A budget of one call would make the very first call the concluding
+ // one, so the turn could never run a tool at all. That is a
+ // misconfiguration rather than a cap being reached, and silently
+ // answering it with a "you have run out of tool calls" instruction
+ // would misreport it — leave such a run alone.
+ if ctx.limits.limits().max_model_calls <= 1 {
+ return Ok(());
+ }
+ tracing::info!(
+ model_calls = ctx.limits.model_calls(),
+ max_model_calls = ctx.limits.limits().max_model_calls,
+ tools_withdrawn = request.tools.len(),
+ "[tinyagents::mw] final permitted model call — withdrawing tools and asking for the \
+ turn's conclusion"
+ );
+ request.tools.clear();
+ request.tool_choice = tinyinference_llm::model::ToolChoice::None;
+ // Give the concluding call back the results microcompact blanked.
+ //
+ // `MicrocompactMiddleware` replaces every tool-result body past the
+ // most recent `keep_recent` (5, by default) with `CLEARED_PLACEHOLDER`,
+ // and — constructed without a token budget — it does so on every call,
+ // not only under context pressure. That is right for an intermediate
+ // call, which needs recent context to choose the next tool and nothing
+ // more. It is exactly wrong for this one: a turn that spent 24 rounds
+ // gathering would be asked to report its findings with 19 rounds of
+ // them replaced by "[Old tool result content cleared]", which is the
+ // same empty-handed answer this whole mechanism exists to prevent,
+ // arrived at from the other direction.
+ //
+ // Restored from the captured outcomes rather than by exempting the
+ // turn from microcompact, because the blanking has already happened by
+ // the time this runs (registration order: microcompact is installed by
+ // `context_mw.install`, this middleware immediately after it) and
+ // because the sink is the honest source — it holds each result as it
+ // entered the transcript, after the per-result byte cap.
+ //
+ // Only a body that IS the placeholder is replaced, so a result the
+ // model legitimately saw in full is never rewritten.
+ //
+ // This deliberately runs BEFORE the compression and trim middlewares,
+ // which are installed after it: restoring can make the request large,
+ // and those two are what bound it. The resulting degradation ladder is
+ // the one this call wants — everything when it fits, an LLM summary of
+ // the older slice when it does not, and oldest-first eviction only in
+ // extremis. What it never does again is silently blank the middle.
+ // Restore newest-first, and only while the request still fits.
+ //
+ // CodeRabbit on #6068: restoration runs AFTER `ContextCompressionMiddleware`
+ // and before `ImageAwareMessageTrimMiddleware`, so an unbounded restore can
+ // push the request over the window and the trim then evicts whole
+ // messages — which is strictly more destructive than the blanking being
+ // undone, and can discard the very results just restored.
+ //
+ // The review suggested a compression phase after restoration. That is a
+ // second summarizer model call on the one call already about to produce
+ // the conclusion, and it is avoidable: the overflow is preventable
+ // rather than repairable. Restoring under the same budget the trim
+ // enforces means the trim never has cause to fire, so nothing is
+ // evicted and nothing needs re-summarising.
+ //
+ // Newest-first because recency is relevance here: the last rounds'
+ // results are the ones the model has not seen (the cap is checked
+ // before the request is built), and the earliest ones are most likely
+ // already reflected in the compression summary above.
+ self.restore_cleared_outcomes(request, self.instruction);
request
.messages
.push(TaMessage::user(self.instruction.to_string()));