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(tinyagents): count each middleware's fixed text against its own share\n\nBoth consumers of the split allowance added text no share accounted for. The\ncontents list seeded `used` at zero and counted only rows, then prepended a\nparagraph of header and appended the omitted-count line. The wrap-up filled its\nbudget to the boundary and then pushed its instruction unconditionally.\n\nRestoration filling to the boundary is what makes this bite: a fixed addition\nafter it is exactly the overshoot the budget exists to prevent. With a window\nthe trim middleware then evicts oldest non-system messages — including results\njust restored, the eviction bounded restoration was there to avoid. Without a\nwindow nothing trims and the request simply exceeds the allowance. The effect\nis largest on a small window, where the share floors at 64 tokens and the\nheader alone is comparable.\n\nEach middleware now seeds `used` with its own fixed text, so its share bounds\nits whole contribution rather than the variable part. Reserving the overhead\nfrom the total before splitting would double-count it, since neither share is\nspent anywhere but inside its own middleware.\n\n`FOOTER_ALLOWANCE` stands in for the omitted-count line, which cannot be\nmeasured before the cap decides how many rows were dropped.\n\nAdds `both_middlewares_together_stay_inside_the_no_window_allowance`, which\nruns both in registration order against one request and asserts the combined\ntotal — the bound that actually matters — plus that each contributed, so it\ncannot pass vacuously. The two existing caps now assert the nominal share\ninstead of a loose multiple of it.\n\nReported by CodeRabbit on #6068.\n\n
sanil-23656a6bdec494
diff --git a/src/openhuman/agent/tinyagents/middleware_part_06.rs b/src/openhuman/agent/tinyagents/middleware_part_06.rsindex 2b83092286..b79f78bfe5 100644--- a/src/openhuman/agent/tinyagents/middleware_part_06.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_06.rs@@ -171,11 +171,17 @@ impl Middleware<()> for FinalCallWrapUpMiddleware {// before the request is built), and the earliest ones are most likely// already reflected in the compression summary above.let budget = self.input_budget;+ // Seeded with the instruction this middleware appends unconditionally+ // below, not just with what the request already holds (CodeRabbit on+ // #6068). Restoration fills the budget to its boundary, so an+ // unaccounted fixed addition after it is exactly the overshoot the+ // budget exists to prevent.let mut used: u64 = request.messages.iter().map(estimate_message_tokens)- .sum();+ .sum::<u64>()+ .saturating_add(estimate_text_tokens(self.instruction));let restored = match self.outcomes.lock() {Ok(outcomes) => {let mut restored = 0usize;@@ -293,6 +299,10 @@ const NO_WINDOW_ALLOWANCE: u64 = 5_120;/// read as "unbounded".const TOC_ALLOWANCE_MIN: u64 = 64;+/// Reserved for the omitted-count line, which cannot be measured before the+/// row cap decides how many rows were dropped. One short sentence.+const FOOTER_ALLOWANCE: u64 = 48;+/// Split a turn's input allowance between the two things that add to the/// request: the artifact contents list and the wrap-up's result restoration.///@@ -442,12 +452,26 @@ impl Middleware<()> for ArtifactIndexTocMiddleware {// silently ending, so the model knows more exist — the same disclosure// rule the rest of this ladder follows, and the reason the artifacts are// findable at all.+ let header = format!(+ "## Stored results from this turn\n\n\+ {total} tool result(s) were too large to keep inline and were written to disk. The \+ text you saw for them is a preview; the full content is at the path below and can be \+ read with the file-reading tool when you need detail the preview does not carry.\n\n"+ );if self.input_budget > 0 {// Already this middleware's share of the turn's allowance — the// split happens once, at the install site, so the two things that// add to the request cannot each spend the whole of it.let cap = self.input_budget.max(1);- let mut used: u64 = 0;+ // Seeded with the fixed text, so the cap bounds the whole message+ // rather than the rows alone (CodeRabbit on #6068). The header is a+ // paragraph; against the 64-token floor a small window gets, it is+ // comparable to the rows it introduces. `FOOTER_ALLOWANCE` stands in+ // for the omitted-count line, which cannot be measured before the+ // count is known — it is one short sentence, and reserving it when+ // nothing is omitted only spends a row.+ let mut used: u64 =+ estimate_text_tokens(&header).saturating_add(FOOTER_ALLOWANCE);let mut kept = 0usize;for row in &rows {used = used.saturating_add(estimate_text_tokens(row));@@ -466,11 +490,7 @@ impl Middleware<()> for ArtifactIndexTocMiddleware {"[tinyagents::mw] rendering the persisted-artifact contents list");request.messages.push(TaMessage::system(format!(- "## Stored results from this turn\n\n\- {count} tool result(s) were too large to keep inline and were written to disk. The \- text you saw for them is a preview; the full content is at the path below and can be \- read with the file-reading tool when you need detail the preview does not carry.\n\n\- {}{}",+ "{header}{}{}",rows.join("\n"),if omitted > 0 {format!(diff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rsindex 7266cd8654..35d2f5b2f0 100644--- a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs@@ -268,6 +268,13 @@ async fn wrap_up_does_not_rewrite_a_result_that_was_never_cleared() {// ── ArtifactIndexTocMiddleware (issue #6014) ─────────────────────────────────async fn ctx_with_artifacts(entries: &[(&str, &str, &str, u64)]) -> RunContext<()> {+ ctx_with_artifacts_and_config(entries, RunConfig::new("mw-test")).await+}++async fn ctx_with_artifacts_and_config(+ entries: &[(&str, &str, &str, u64)],+ config: RunConfig,+) -> RunContext<()> {use tinyagents_harness::store::StoreRegistry;let index = std::sync::Arc::new(crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore::new(@@ -296,7 +303,7 @@ async fn ctx_with_artifacts(entries: &[(&str, &str, &str, u64)]) -> RunContext<(crate::openhuman::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,index,);- RunContext::new(RunConfig::new("mw-test"), ()).with_stores(registry)+ RunContext::new(config, ()).with_stores(registry)}/// Nothing offloaded → no message. The contents list must not spend context@@ -477,9 +484,13 @@ async fn toc_is_capped_and_reports_what_it_omitted() {text.contains("not listed here"),"an omitted count must be disclosed, not silently dropped: {text}");+ // The nominal share, not a loose multiple of it: the cap now seeds `used`+ // with the header and the reserved footer, so it bounds the whole message+ // rather than the rows alone (CodeRabbit on #6068).assert!(- estimate_text_tokens(&text) < 400,- "the list must stay inside the share it was given (200, plus the header)"+ estimate_text_tokens(&text) <= 200,+ "the list must stay inside the share it was given: {}",+ estimate_text_tokens(&text));}@@ -546,8 +557,8 @@ async fn the_contents_list_stays_bounded_when_no_window_is_advertised() {"an omitted count must be disclosed, not silently dropped: {text}");assert!(- estimate_text_tokens(&text) < 1_024,- "the no-window fallback must bound the list: {}",+ estimate_text_tokens(&text) <= split_input_allowance(0).0,+ "the no-window fallback must bound the whole list message: {}",estimate_text_tokens(&text));}@@ -596,3 +607,78 @@ async fn wrap_up_restoration_stays_bounded_when_no_window_is_advertised() {"some restored, not all 40 — got {restored}");}++/// The two consumers share one allowance, so the bound that matters is the one+/// on the request they *both* wrote to (CodeRabbit on #6068). Runs them in+/// registration order — wrap-up, then contents list — on the no-window path,+/// where nothing downstream would trim what they overshoot by.+#[tokio::test]+async fn both_middlewares_together_stay_inside_the_no_window_allowance() {+ let big = "x".repeat(8_000);+ let outcomes: Vec<(String, String)> = (0..40)+ .map(|i| (format!("call-{i}"), big.clone()))+ .collect();+ let borrowed: Vec<(&str, &str)> = outcomes+ .iter()+ .map(|(a, b)| (a.as_str(), b.as_str()))+ .collect();+ let artifacts: Vec<(String, String, String, u64)> = (0..400)+ .map(|i| {+ (+ format!("call-{i}"),+ "file_read".to_string(),+ format!("outputs/a-fairly-long-artifact-path-{i}.json"),+ 1_000,+ )+ })+ .collect();+ let artifact_refs: Vec<(&str, &str, &str, u64)> = artifacts+ .iter()+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))+ .collect();++ let mut ctx = ctx_with_artifacts_and_config(+ &artifact_refs,+ RunConfig::new("mw-test").with_max_model_calls(2),+ )+ .await;+ ctx.limits.record_model_call().unwrap();+ ctx.limits.record_model_call().unwrap();++ let (toc_allowance, restore_allowance) = split_input_allowance(0);+ let mut request = ModelRequest {+ messages: borrowed+ .iter()+ .map(|(id, _)| TaMessage::tool(*id, CLEARED_PLACEHOLDER))+ .collect(),+ ..Default::default()+ };++ // Registration order at the install site: wrap-up first, contents list after.+ FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&borrowed), restore_allowance)+ .before_model(&mut ctx, &(), &mut request)+ .await+ .unwrap();+ ArtifactIndexTocMiddleware::new(toc_allowance)+ .before_model(&mut ctx, &(), &mut request)+ .await+ .unwrap();++ let used: u64 = request.messages.iter().map(estimate_message_tokens).sum();+ assert!(+ used <= NO_WINDOW_ALLOWANCE,+ "the combined request must stay inside the shared allowance: {used} > {NO_WINDOW_ALLOWANCE}"+ );+ // Both actually contributed — otherwise the bound is met vacuously.+ assert!(+ request.messages.iter().any(|m| m.text().starts_with("xxx")),+ "the wrap-up restored nothing, so the bound proves nothing"+ );+ assert!(+ request+ .messages+ .iter()+ .any(|m| m.text().contains("Stored results from this turn")),+ "the contents list is absent, so the bound proves nothing"+ );+}