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(context): summarize before blanking, and only blank under real pressure
sanil-23d7762ed99e64
diff --git a/src/openhuman/agent/tinyagents/middleware_part_01.rs b/src/openhuman/agent/tinyagents/middleware_part_01.rsindex 132aabe5af..027fc5d327 100644--- a/src/openhuman/agent/tinyagents/middleware_part_01.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_01.rs@@ -10,7 +10,7 @@ use tinyagents_harness::context::RunContext;use tinyagents_harness::events::AgentEvent;use tinyinference::message::{ContentBlock, Message as TaMessage};use tinyagents_harness::middleware::{- AgentRun, BudgetTracker, ContextualToolSelectionMiddleware, MicrocompactMiddleware, Middleware,+ AgentRun, BudgetTracker, ContextualToolSelectionMiddleware, Middleware,MiddlewareToolOutcome, ToolAllowlistMiddleware, ToolHandler, ToolMiddleware,};use tinyinference::model::{ModelRequest, ModelResponse, PromptSegment, SegmentRole};@@ -290,16 +290,14 @@ impl TurnContextMiddleware {if let Some(sink) = self.transcript_snapshot {harness.push_middleware(Arc::new(TranscriptSnapshotMiddleware { sink }));}- if self.microcompact_keep_recent > 0 {- // Crate middleware (upstreamed from the in-house copy). Constructed- // with OpenHuman's model-facing placeholder so behavior is- // byte-identical to the deleted local version. Events stay off (the- // default) to preserve the prior silent-rewrite behavior.- harness.push_middleware(Arc::new(MicrocompactMiddleware::new(- self.microcompact_keep_recent,- CLEARED_PLACEHOLDER,- )));- }+ // Microcompact is NOT registered here any more (issue #6014). It used to+ // be, which put its `before_model` ahead of the summarization step the+ // caller installs later — so by the time the task-aware summarizer ran,+ // every tool body past `keep_recent` had already been replaced with+ // `CLEARED_PLACEHOLDER` and it was summarizing placeholders. The one+ // component able to preserve those results in condensed form never saw+ // them. The caller now sites it AFTER compression, so the ladder reads+ // summarize → blank → evict. See `assemble_turn_harness`.// REVERSE-ORDER RULE (issue #4464): the crate runs `after_tool` hooks in// REVERSE registration order (`MiddlewareStack::run_after_tool` iterates// `self.middlewares.iter().rev()`, tinyagents src/harness/middleware/mod.rs).diff --git a/src/openhuman/agent/tinyagents/middleware_part_05.rs b/src/openhuman/agent/tinyagents/middleware_part_05.rsindex ef4145bda3..49f1f3fe23 100644--- a/src/openhuman/agent/tinyagents/middleware_part_05.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_05.rs@@ -548,6 +548,9 @@ impl Middleware<()> for ImageAwareMessageTrimMiddleware {pub(crate) struct FinalCallWrapUpMiddleware {/// The synthetic user turn appended on the final call.instruction: &'static str,+ /// Every tool call's captured outcome, so the concluding call can be given+ /// back the results microcompact blanked (see `before_model`).+ outcomes: crate::openhuman::agent::tinyagents::ToolOutcomeSink,/// Set when the injection fires, so the caller can report the turn as/// capped. Necessary because this turn now ends *naturally* — the model/// returns text and requests no tools, which is the loop's ordinary@@ -557,9 +560,13 @@ pub(crate) struct FinalCallWrapUpMiddleware {}impl FinalCallWrapUpMiddleware {- pub(crate) fn new(instruction: &'static str) -> Self {+ pub(crate) fn new(+ instruction: &'static str,+ outcomes: crate::openhuman::agent::tinyagents::ToolOutcomeSink,+ ) -> Self {Self {instruction,+ outcomes,fired: Arc::new(std::sync::atomic::AtomicBool::new(false)),}}@@ -602,6 +609,81 @@ impl Middleware<()> for FinalCallWrapUpMiddleware {);request.tools.clear();request.tool_choice = tinyinference::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.+ let restored = match self.outcomes.lock() {+ Ok(outcomes) => {+ let mut restored = 0usize;+ for message in request.messages.iter_mut() {+ let TaMessage::Tool(tool) = message else {+ continue;+ };+ if tool.content.iter().any(|block| !matches!(block, ContentBlock::Text(_))) {+ continue;+ }+ let body: String = tool+ .content+ .iter()+ .filter_map(|block| match block {+ ContentBlock::Text(text) => Some(text.as_str()),+ _ => None,+ })+ .collect();+ if body.trim() != CLEARED_PLACEHOLDER {+ continue;+ }+ let Some(outcome) = self_outcome_for(&outcomes, &tool.tool_call_id) else {+ continue;+ };+ if outcome.trim().is_empty() {+ continue;+ }+ tool.content = vec![ContentBlock::Text(outcome)];+ restored += 1;+ }+ restored+ }+ Err(_) => {+ tracing::warn!(+ "[tinyagents::mw] tool-outcome sink poisoned; concluding without restoring \+ cleared tool results"+ );+ 0+ }+ };+ if restored > 0 {+ tracing::info!(+ restored,+ "[tinyagents::mw] restored cleared tool results for the concluding call"+ );+ }request.messages.push(TaMessage::user(self.instruction.to_string()));@@ -610,3 +692,17 @@ impl Middleware<()> for FinalCallWrapUpMiddleware {Ok(())}}++/// The captured content for one tool call id, if the sink holds it.+///+/// A free function so the borrow of the locked sink stays scoped to the lookup+/// rather than being held across the mutation of `request.messages`.+fn self_outcome_for(+ outcomes: &[crate::openhuman::agent::tinyagents::ToolCallOutcome],+ call_id: &str,+) -> Option<String> {+ outcomes+ .iter()+ .find(|outcome| outcome.call_id == call_id)+ .map(|outcome| outcome.content.clone())+}diff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_01_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_01_tests.rsindex f40e635a51..b03e0e7543 100644--- a/src/openhuman/agent/tinyagents/middleware_tests_part_01_tests.rs+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_01_tests.rs@@ -1,4 +1,8 @@+// Imported here rather than in `middleware_part_01.rs` since #6014: the+// production install site moved to `assemble_turn_harness` (which names it+// fully-qualified), so the module itself no longer references the type.use super::*;+use tinyagents_harness::middleware::MicrocompactMiddleware;// #4462: image-aware token estimation. A base64 image marker must be priced// at the flat IMAGE_MARKER_TOKEN_COST, not chars/4 of its payload — otherwisediff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rsindex 5921aa3109..21265eba78 100644--- a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs@@ -127,3 +127,136 @@ async fn embedder_tool_hooks_post_use_without_pre_call_falls_back_to_null() {assert_eq!(post[0].1, serde_json::Value::Null);assert_eq!(post[0].2, Some(true));}++// ── FinalCallWrapUpMiddleware (issue #6014) ──────────────────────────────────++fn sink_with(entries: &[(&str, &str)]) -> crate::openhuman::agent::tinyagents::ToolOutcomeSink {+ std::sync::Arc::new(std::sync::Mutex::new(+ entries+ .iter()+ .map(+ |(id, content)| crate::openhuman::agent::tinyagents::ToolCallOutcome {+ call_id: (*id).to_string(),+ name: "fetch".to_string(),+ success: true,+ content: (*content).to_string(),+ },+ )+ .collect(),+ ))+}++/// A run with calls left is untouched: no instruction, and the tool belt intact.+#[tokio::test]+async fn wrap_up_leaves_a_call_with_budget_remaining_alone() {+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]));+ let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(5), ());+ ctx.limits.record_model_call().unwrap();+ let mut request = ModelRequest {+ messages: vec![TaMessage::user("hi")],+ tools: vec![ToolSchema::new("echo", "echo", serde_json::json!({}))],+ ..Default::default()+ };++ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();++ assert_eq!(+ request.messages.len(),+ 1,+ "no instruction should be appended"+ );+ assert_eq!(request.tools.len(), 1, "the belt must stay intact mid-turn");+}++/// On the last permitted call the tools are withdrawn — structurally, not by+/// asking — and the wrap-up instruction is appended as the final turn.+#[tokio::test]+async fn wrap_up_withdraws_tools_and_appends_the_instruction_on_the_last_call() {+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]));+ let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());+ ctx.limits.record_model_call().unwrap();+ ctx.limits.record_model_call().unwrap(); // now the final call+ let mut request = ModelRequest {+ messages: vec![TaMessage::user("hi")],+ tools: vec![ToolSchema::new("echo", "echo", serde_json::json!({}))],+ tool_choice: tinyinference::model::ToolChoice::Required,+ ..Default::default()+ };++ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();++ assert!(+ request.tools.is_empty(),+ "tools must be withdrawn, not discouraged"+ );+ assert!(+ matches!(request.tool_choice, tinyinference::model::ToolChoice::None),+ "a Required choice with no tools is a provider 400"+ );+ assert_eq!(+ request.messages.last().map(|m| m.text()),+ Some("CONCLUDE NOW".to_string()),+ "the instruction must be the final turn of the request"+ );+ assert!(mw.fired().load(std::sync::atomic::Ordering::SeqCst));+}++/// The concluding call gets back the results microcompact blanked — otherwise+/// it is asked to report findings it cannot read, which is the same+/// empty-handed answer the whole mechanism exists to prevent.+#[tokio::test]+async fn wrap_up_restores_tool_results_microcompact_cleared() {+ let mw = FinalCallWrapUpMiddleware::new(+ "CONCLUDE NOW",+ sink_with(&[+ ("call-old", "issue #41: auth bypass"),+ ("call-new", "issue #42: leak"),+ ]),+ );+ let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());+ ctx.limits.record_model_call().unwrap();+ ctx.limits.record_model_call().unwrap();+ let mut request = ModelRequest {+ messages: vec![+ // The shape microcompact leaves behind: an older result blanked to+ // the placeholder, a recent one kept verbatim.+ TaMessage::tool("call-old", CLEARED_PLACEHOLDER),+ TaMessage::tool("call-new", "issue #42: leak"),+ ],+ ..Default::default()+ };++ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();++ let bodies: Vec<String> = request.messages.iter().map(|m| m.text()).collect();+ assert!(+ bodies.iter().any(|b| b.contains("issue #41: auth bypass")),+ "the cleared result should be restored from the capture sink: {bodies:?}"+ );+ assert!(+ !bodies.iter().any(|b| b.trim() == CLEARED_PLACEHOLDER),+ "no placeholder should survive into the concluding call: {bodies:?}"+ );+}++/// A result the model legitimately saw in full is never rewritten, even when+/// the sink holds a different (e.g. later-truncated) copy for that id.+#[tokio::test]+async fn wrap_up_does_not_rewrite_a_result_that_was_never_cleared() {+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[("call-1", "FROM SINK")]));+ let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());+ ctx.limits.record_model_call().unwrap();+ ctx.limits.record_model_call().unwrap();+ let mut request = ModelRequest {+ messages: vec![TaMessage::tool("call-1", "IN THE TRANSCRIPT")],+ ..Default::default()+ };++ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();++ assert_eq!(+ request.messages[0].text(),+ "IN THE TRANSCRIPT",+ "only a placeholder body may be replaced"+ );+}diff --git a/src/openhuman/agent/tinyagents/mod_part_04.rs b/src/openhuman/agent/tinyagents/mod_part_04.rsindex a64e90f0e2..df273dcb56 100644--- a/src/openhuman/agent/tinyagents/mod_part_04.rs+++ b/src/openhuman/agent/tinyagents/mod_part_04.rs@@ -131,6 +131,9 @@ fn assemble_turn_harness(// Capture context settings before `install` consumes `context_mw`.let autocompact_enabled = context_mw.autocompact_enabled;+ // Captured for the same reason `autocompact_enabled` is — `install` consumes+ // `context_mw` — and used to site microcompact below, after compression.+ let microcompact_keep_recent = context_mw.microcompact_keep_recent;let tool_result_artifact_index = context_mw.artifact_store.as_ref()@@ -207,36 +210,6 @@ fn assemble_turn_harness()));}}- // Issue #6014: make the last permitted model call the turn's conclusion,- // rather than leaving the answer to an extra out-of-band call after the loop- // has exited. Registered late so its `before_model` runs after the context- // middlewares have shaped the transcript — the instruction it appends is the- // final turn of the request and must not be what a trim evicts.- //- // **Top-level turns only**, the same cut `CapPauser`'s dispatch guard takes- // and for a related reason: a sub-agent reaching its own model-call cap is a- // routine outcome rather than a user-visible dead end. It summarises and- // hands the result back to its parent as a tool result, the parent keeps- // going, and `subagent_runner` already owns that checkpoint (including its- // own deterministic fallback). The problem this fixes — a person left with a- // status line where an answer should be — is a property of the turn that- // answers a human.- //- // Withholding it also leaves the child's budget arithmetic alone. The- // conclusion costs one model call, so installing this would silently convert- // a delegated run's N tool rounds into N-1; that is a fine trade to make- // once, deliberately, at the top level, and not one to impose on every child- // as a side effect.- let wrap_up_mw = (pause_at_cap && subagent_scope.is_none()).then(|| {- Arc::new(middleware::FinalCallWrapUpMiddleware::new(- crate::openhuman::agent::harness::session::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,- ))- });- let wrap_up_fired = wrap_up_mw.as_ref().map(|mw| mw.fired());- if let Some(mw) = wrap_up_mw {- harness.push_middleware(mw);- }-let early_exit_set: HashSet<&str> = early_exit_tools.iter().copied().collect();// One hook per run, shared by every early-exit adapter (records the first// early-exit and pauses). Requires the steering handle.@@ -519,7 +492,6 @@ fn assemble_turn_harness(harness.push_middleware(Arc::new(middleware::CostBudgetMiddleware::with_shadow(shadow_budget_tracker,)));-// Autocompaction parity: when the provider's context window is known, install// the two-stage context-management step (issue #4249).//@@ -575,6 +547,83 @@ fn assemble_turn_harness(// restores all three: image markers priced at a flat cost, the// proportional reply reserve, system messages always kept in place, and a// grep-able warn with drop/token counts on any eviction.+ }++ // ── The context ladder, cheapest sufficient step first (issue #6014) ──────+ //+ // `before_model` runs in registration order, so what follows IS the order+ // these fire in, and each step only matters when the one above it was not+ // enough:+ //+ // 1. compression (above) — at 90% of the window, fold the older slice+ // into one task-aware summary that preserves its results.+ // 2. microcompact — if still over, blank older tool bodies outright.+ // 3. the wrap-up — on a capped turn's final call, undo (2) for the one+ // call that has to report everything, then ask for the conclusion.+ // 4. trim — if still over, evict oldest whole messages.+ //+ // The order used to be 2 -> 1 -> 4, because `context_mw.install` registered+ // microcompact: the summarizer was handed a transcript whose tool bodies+ // were already `CLEARED_PLACEHOLDER` and asked, by its own prompt, for "key+ // results/outputs" it could no longer see. Nothing recovered them.+ if microcompact_keep_recent > 0 {+ // The token-budget gate the crate added for this and this call site+ // never used (`with_token_budget`, tinyhumansai/openhuman#4755).+ // Constructed bare, microcompact blanks on EVERY call once past+ // `keep_recent` — not only under context pressure — so a turn that made+ // ten tool calls composed its answer from the last five results with the+ // rest blanked, while sitting well inside a window with room for all+ // ten. That is not a capped-turn problem: it is every turn.+ //+ // The budget matches the trim's input allowance, which is what puts+ // microcompact strictly behind compression: the summarizer fires first,+ // and blanking happens only if the transcript is STILL over afterwards.+ //+ // With no advertised window there is no budget to size and nothing else+ // bounding the transcript, so the legacy always-blank behaviour stays as+ // the sole backstop against unbounded growth.+ let microcompact = tinyagents_harness::middleware::MicrocompactMiddleware::new(+ microcompact_keep_recent,+ crate::openhuman::agent::context::CLEARED_PLACEHOLDER,+ );+ let microcompact = match context_window.filter(|w| *w > 0) {+ Some(window) => {+ microcompact.with_token_budget(middleware::legacy_max_input_tokens(window).max(1))+ }+ None => microcompact,+ };+ harness.push_middleware(Arc::new(microcompact));+ }++ // Issue #6014: make the last permitted model call the turn's conclusion,+ // rather than leaving the answer to an extra out-of-band call after the loop+ // has exited.+ //+ // **Top-level turns only**, the same cut `CapPauser`'s dispatch guard takes.+ // A sub-agent reaching its own model-call cap is a routine outcome rather+ // than a user-visible dead end: it summarises, hands the result back to its+ // parent as a tool result, the parent keeps going, and `subagent_runner`+ // already owns that checkpoint. The harm this fixes — a person left with a+ // status line where an answer should be — belongs to the turn that answers a+ // human. Withholding it also leaves a child's budget arithmetic alone: the+ // conclusion costs a model call, and turning every delegated run's N tool+ // rounds into N-1 is not a trade to impose as a side effect.+ let wrap_up_mw = (pause_at_cap && subagent_scope.is_none()).then(|| {+ Arc::new(middleware::FinalCallWrapUpMiddleware::new(+ crate::openhuman::agent::harness::session::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,+ tool_outcome_sink.clone(),+ ))+ });+ let wrap_up_fired = wrap_up_mw.as_ref().map(|mw| mw.fired());+ if let Some(mw) = wrap_up_mw {+ harness.push_middleware(mw);+ }++ if let Some(window) = context_window.filter(|w| *w > 0) {+ // Deterministic hard-cap trim (issue #4462), last in the ladder: it drops+ // whole messages, so it runs only once summarizing and blanking have both+ // failed to fit the window. See `ImageAwareMessageTrimMiddleware` for the+ // three legacy guards it restores over the crate trim.harness.push_middleware(Arc::new(middleware::ImageAwareMessageTrimMiddleware::for_context_window(window),));