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
refactor(tinyagents): consolidate memory and hook tests, remove stale repeat-progress and wrap-up te
Steven Enamakel7bc7222e2da6
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex 70f2f6298d..affb7c1c15 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -6,8 +6,9 @@ use std::sync::Arc;use tinyagents_harness::cache::InMemoryResponseCache;use tinyagents_harness::middleware::{- plan_mode_middleware, BudgetLimits, BudgetMiddleware, ContextCompressionMiddleware,- PromptCacheGuardMiddleware, RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,+ plan_mode_middleware, ArgRecoveryMiddleware, BudgetLimits, BudgetMiddleware,+ ContextCompressionMiddleware, PromptCacheGuardMiddleware, RepeatProgressMiddleware,+ RunModeHandle, ToolPolicyMiddleware as TaToolPolicyMiddleware,};use tinyagents_harness::runtime::AgentHarness;use tinyagents_harness::steering::SteeringHandle;@@ -655,9 +656,7 @@ pub(super) fn assemble_turn_harness(// required-field schema is left untouched so the crate's// `InvalidArgsPolicy::ReturnToolError` admission path reports the original// validation error. It never reaches approval/policy wrappers or the tool.- harness.push_middleware(Arc::new(ArgRecoveryMiddleware::new(- tool_sets.clone(),- )));+ harness.push_middleware(Arc::new(ArgRecoveryMiddleware::new(tool_sets.clone())));// Bare packed-tool routing (`before_tool`, #6276): a call that names a// withheld packed tool directly becomes the `use_skill` call that reachesdiff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rsindex cb0b628611..1a764bd5d8 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs@@ -147,9 +147,7 @@ pub(super) fn install_context_ladder(crate::agent::context::CLEARED_PLACEHOLDER,);let microcompact = match context_window.filter(|w| *w > 0) {- Some(window) => {- microcompact.with_token_budget(legacy_max_input_tokens(window).max(1))- }+ Some(window) => microcompact.with_token_budget(legacy_max_input_tokens(window).max(1)),None => microcompact,};// Emit `AgentEvent::Compressed` when a body is cleared. Off by default —diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rsindex ef189aab4d..803d7d2212 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs@@ -515,72 +515,6 @@ async fn existing_error_is_some_behavior_is_unchanged_by_body_level_check() {);}-#[tokio::test]-async fn successful_repeat_tracker_halt_maps_to_summary_and_pause() {- let handle = SteeringHandle::allow_all();- let summary = std::sync::Arc::new(std::sync::Mutex::new(None));- let mw = RepeatProgressMiddleware::new(handle.clone(), summary.clone());-- for _ in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), "ok", None).await;- assert_eq!(drain_pause_count(&handle), 0);- }- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), "ok", None).await;-- assert_eq!(drain_pause_count(&handle), 1);- assert!(- summary- .lock()- .unwrap()- .as_deref()- .is_some_and(|text| text.contains("successful tool-call batch")),- "crate halt summary should be preserved for the host turn result"- );-}--#[tokio::test]-async fn successful_repeat_tracker_resets_failed_and_exempt_batches() {- let handle = SteeringHandle::allow_all();- let mw = RepeatProgressMiddleware::new(- handle.clone(),- std::sync::Arc::new(std::sync::Mutex::new(None)),- );-- // Distinct outputs keep the run-wide recurrence ledger out of this test: it- // pins the adjacent-batch streak, which a failure resets.- for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {- let output = format!("before-{i}");- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), &output, None).await;- }- run_successful_repeat_cycle(- &mw,- "lookup",- json!({"id": 1}),- "ok",- Some("temporary failure"),- )- .await;- for i in 0..DEFAULT_REPEAT_CALL_THRESHOLD - 1 {- let output = format!("after-{i}");- run_successful_repeat_cycle(&mw, "lookup", json!({"id": 1}), &output, None).await;- }- assert_eq!(- drain_pause_count(&handle),- 0,- "a failed batch resets the successful-repeat streak"- );-- for _ in 0..DEFAULT_REPEAT_OUTPUT_THRESHOLD + 1 {- run_successful_repeat_cycle(&mw, "wait_subagent", json!({"task_id": "t"}), "ok", None)- .await;- }- assert_eq!(- drain_pause_count(&handle),- 0,- "polling tools remain exempt from successful-repeat halts"- );-}-#[tokio::test]async fn memory_write_without_index_read_gets_a_corrective_note() {let mw = MemoryProtocolMiddleware::new();diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_memory_and_hooks_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_memory_and_hooks_tests.rsnew file mode 100644index 0000000000..91a4837977--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_memory_and_hooks_tests.rs@@ -0,0 +1,132 @@+use super::*;++#[tokio::test]+async fn failed_memory_write_does_not_advance_the_protocol() {+ let mw = MemoryProtocolMiddleware::new();+ let failed = run_cycle(+ &mw,+ "memory_store",+ json!({}),+ "disk full",+ Some("disk full"),+ )+ .await;+ // A failed write is not annotated and leaves nothing pending, so a later+ // run-end sweep must not warn about a stale index.+ assert!(!result_text(&failed).contains(MEMORY_PROTOCOL_MARKER));+ let mut run = AgentRun::new();+ // after_agent is a no-op warn path; it must not error.+ mw.after_agent(&mut ctx(), &(), &mut run).await.unwrap();+}++#[tokio::test]+async fn second_write_without_an_update_flags_index_drift() {+ let mw = MemoryProtocolMiddleware::new();+ run_cycle(&mw, "memory_recall", json!({}), "checked", None).await;+ let first = run_cycle(&mw, "memory_store", json!({}), "a", None).await;+ assert!(!result_text(&first).contains("drifting"));++ // No update_memory_md between the two writes → the index is drifting.+ let second = run_cycle(&mw, "memory_store", json!({}), "b", None).await;+ assert!(+ result_text(&second).contains("drifting"),+ "a second unsynced write should flag index drift: {}",+ result_text(&second)+ );+}++#[tokio::test]+async fn embedder_tool_hooks_post_use_replays_the_normalized_pre_call_arguments() {+ let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let mw = embedder_hook_mw(pre.clone(), post.clone(), false);++ let mut call = TaToolCall {+ id: "call-1".into(),+ name: "lookup".into(),+ arguments: json!({"id": 42}),+ invalid: None,+ };+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();++ let mut result = TaToolResult::success("found");+ mw.after_tool(+ &mut ctx(),+ &(),+ &invocation("call-1", "lookup"),+ &mut result,+ )+ .await+ .unwrap();++ assert_eq!(pre.lock().unwrap().len(), 1, "one pre-use notification");+ let post = post.lock().unwrap();+ assert_eq!(post.len(), 1, "one post-use notification");+ let (tool, arguments, success, duration) = &post[0];+ assert_eq!(tool, "lookup");+ assert_eq!(+ *arguments,+ json!({"id": 42}),+ "post-use context must preserve the normalized pre-call arguments, not Null"+ );+ assert_eq!(*success, Some(true));+ assert_eq!(+ *duration, None,+ "canonical ToolResult carries no elapsed field"+ );+}++#[tokio::test]+async fn embedder_tool_hooks_veto_denies_the_call_and_skips_post_use() {+ let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let mw = embedder_hook_mw(pre.clone(), post.clone(), true);++ let mut call = TaToolCall {+ id: "call-2".into(),+ name: "rm".into(),+ arguments: json!({"path": "/"}),+ invalid: None,+ };+ let error = mw+ .before_tool(&mut ctx(), &(), &mut call)+ .await+ .unwrap_err();+ assert!(+ error.to_string().contains("vetoed"),+ "veto must surface as a tool error: {error}"+ );+ // The call was vetoed — no post-use event, and no cache entry leaks.+ assert_eq!(pre.lock().unwrap().len(), 1, "pre-use hook still observed");+ assert!(+ post.lock().unwrap().is_empty(),+ "no post-use for a vetoed call"+ );+ assert!(+ mw.arguments_by_call_id.lock().unwrap().is_empty(),+ "a vetoed call must not leave a cached argument entry"+ );+}++#[tokio::test]+async fn embedder_tool_hooks_post_use_without_pre_call_falls_back_to_null() {+ let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let mw = embedder_hook_mw(pre.clone(), post.clone(), false);++ // A result with no matching `before_tool` (defensive path) must not panic+ // and falls back to `Null`, the pre-fix behaviour.+ let mut result = TaToolResult::success("found");+ mw.after_tool(+ &mut ctx(),+ &(),+ &invocation("orphan", "lookup"),+ &mut result,+ )+ .await+ .unwrap();+ let post = post.lock().unwrap();+ assert_eq!(post.len(), 1);+ assert_eq!(post[0].1, serde_json::Value::Null);+ assert_eq!(post[0].2, Some(true));+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex b47350c21f..3b014bc168 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -1,6 +1,4 @@use super::approval::approval_tool_name;-use super::artifact_index_toc::NO_WINDOW_ALLOWANCE;-use super::message_trim::{estimate_message_tokens, estimate_text_tokens, IMAGE_MARKER_TOKEN_COST};use super::repeated_failure::{is_body_level_failure, user_actionable_escalation};use super::tool_output::{is_compaction_exempt, is_truncation_exempt, COMPACTION_EXEMPT_TOOLS, SAMPLING_TOOLS,@@ -335,49 +333,6 @@ fn body_failure_result(name: &str, extra: serde_json::Value) -> TaToolResult {tool_result(name, &serde_json::to_string_pretty(&body).unwrap())}-// ── RepeatProgressMiddleware / crate SuccessfulRepeatTracker ───────────--fn repeated_success_response(tool: &str, args: serde_json::Value) -> ModelResponse {- ModelResponse {- message: tinyinference_llm::message::AssistantMessage {- id: None,- content: vec![ContentBlock::Text("working".to_string())],- tool_calls: vec![TaToolCall::new("repeat-1", tool, args)],- usage: None,- origin: None,- },- usage: None,- finish_reason: Some("tool_calls".to_string()),- raw: None,- resolved_model: None,- continue_turn: None,- served_from_cache: false,- correlation: None,- resolved_route: None,- }-}--async fn run_successful_repeat_cycle(- mw: &RepeatProgressMiddleware,- tool: &str,- args: serde_json::Value,- output: &str,- error: Option<&str>,-) {- let mut response = repeated_success_response(tool, args);- mw.after_model(&mut ctx(), &(), &mut response)- .await- .unwrap();- let mut result = match error {- Some(error) => TaToolResult::error(error),- None => tool_result(tool, output),- };- let invocation = ToolInvocationIdentity::new("repeat-1", tool);- mw.after_tool(&mut ctx(), &(), &invocation, &mut result)- .await- .unwrap();-}-// ── MemoryProtocolMiddleware (issue #4116) ──────────────────────────────use crate::agent::harness::memory_protocol::MEMORY_PROTOCOL_MARKER;@@ -478,8 +433,6 @@ mod classified_failure_tests;mod loop_guard_tests;#[path = "middleware_prompt_cache_tests.rs"]mod prompt_cache_tests;-#[path = "middleware_repeat_progress_tests.rs"]-mod repeat_progress_tests;#[path = "middleware_research_budget_tests.rs"]mod research_budget_tests;@@ -490,7 +443,5 @@ mod tool_output_artifact_tests;mod tool_output_tests;#[path = "middleware_tool_policy_tests.rs"]mod tool_policy_tests;-#[path = "middleware_wrap_up_final_write_tests.rs"]-mod wrap_up_final_write_tests;-#[path = "middleware_wrap_up_toc_tests.rs"]-mod wrap_up_toc_tests;+#[path = "middleware_memory_and_hooks_tests.rs"]+mod memory_and_hooks_tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rsindex d5809cbe66..afad24af16 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tool_output_tests.rs@@ -6,46 +6,6 @@ use super::*;use tinyagents_harness::middleware::MicrocompactMiddleware;use tinytools::{ToolRuntime, ToolTimeout};-// #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 — otherwise-// one image reads as millions of tokens and the trimmer evicts everything,-// including the system prompt.--#[test]-fn estimate_text_tokens_markerless_is_chars_over_four() {- assert_eq!(estimate_text_tokens(&"a".repeat(40)), (40 + 3) / 4);- assert_eq!(estimate_text_tokens(""), 0);-}--#[test]-fn estimate_text_tokens_prices_image_marker_flat_not_by_length() {- let huge = "x".repeat(40_000);- let text = format!("[IMAGE:{huge}]");- let tokens = estimate_text_tokens(&text);- // chars/4 of the payload would be ~10_000; the flat price is 1_200.- assert!(- tokens >= IMAGE_MARKER_TOKEN_COST,- "at least the flat image cost: {tokens}"- );- assert!(- tokens < 2_000,- "image priced flat, not by base64 length: {tokens}"- );-}--#[test]-fn estimate_text_tokens_charges_each_image_marker_once() {- let tokens = estimate_text_tokens("[IMAGE:aaaa] and [IMAGE:bbbb]");- assert!(- tokens >= 2 * IMAGE_MARKER_TOKEN_COST,- "two images each priced: {tokens}"- );- assert!(- tokens < 2 * IMAGE_MARKER_TOKEN_COST + 100,- "no runaway from the surrounding text: {tokens}"- );-}-#[tokio::test]async fn unavailable_summarization_is_disclosed_in_the_payload() {use crate::inference::tokenjuice::module_stub::FAILED_NOTICE;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rsdeleted file mode 100644index d0eb588255..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/middleware_wrap_up_toc_tests.rs+++ /dev/null@@ -1,341 +0,0 @@-use super::*;--#[tokio::test]-async fn failed_memory_write_does_not_advance_the_protocol() {- let mw = MemoryProtocolMiddleware::new();- let failed = run_cycle(- &mw,- "memory_store",- json!({}),- "disk full",- Some("disk full"),- )- .await;- // A failed write is not annotated and leaves nothing pending, so a later- // run-end sweep must not warn about a stale index.- assert!(!result_text(&failed).contains(MEMORY_PROTOCOL_MARKER));- let mut run = AgentRun::new();- // after_agent is a no-op warn path; it must not error.- mw.after_agent(&mut ctx(), &(), &mut run).await.unwrap();-}--#[tokio::test]-async fn second_write_without_an_update_flags_index_drift() {- let mw = MemoryProtocolMiddleware::new();- run_cycle(&mw, "memory_recall", json!({}), "checked", None).await;- let first = run_cycle(&mw, "memory_store", json!({}), "a", None).await;- assert!(!result_text(&first).contains("drifting"));-- // No update_memory_md between the two writes → the index is drifting.- let second = run_cycle(&mw, "memory_store", json!({}), "b", None).await;- assert!(- result_text(&second).contains("drifting"),- "a second unsynced write should flag index drift: {}",- result_text(&second)- );-}--#[tokio::test]-async fn embedder_tool_hooks_post_use_replays_the_normalized_pre_call_arguments() {- let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let mw = embedder_hook_mw(pre.clone(), post.clone(), false);-- let mut call = TaToolCall {- id: "call-1".into(),- name: "lookup".into(),- arguments: json!({"id": 42}),- invalid: None,- };- mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();-- let mut result = TaToolResult::success("found");- mw.after_tool(- &mut ctx(),- &(),- &invocation("call-1", "lookup"),- &mut result,- )- .await- .unwrap();-- assert_eq!(pre.lock().unwrap().len(), 1, "one pre-use notification");- let post = post.lock().unwrap();- assert_eq!(post.len(), 1, "one post-use notification");- let (tool, arguments, success, duration) = &post[0];- assert_eq!(tool, "lookup");- assert_eq!(- *arguments,- json!({"id": 42}),- "post-use context must preserve the normalized pre-call arguments, not Null"- );- assert_eq!(*success, Some(true));- assert_eq!(- *duration, None,- "canonical ToolResult carries no elapsed field"- );-}--#[tokio::test]-async fn embedder_tool_hooks_veto_denies_the_call_and_skips_post_use() {- let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let mw = embedder_hook_mw(pre.clone(), post.clone(), true);-- let mut call = TaToolCall {- id: "call-2".into(),- name: "rm".into(),- arguments: json!({"path": "/"}),- invalid: None,- };- let error = mw- .before_tool(&mut ctx(), &(), &mut call)- .await- .unwrap_err();- assert!(- error.to_string().contains("vetoed"),- "veto must surface as a tool error: {error}"- );- // The call was vetoed — no post-use event, and no cache entry leaks.- assert_eq!(pre.lock().unwrap().len(), 1, "pre-use hook still observed");- assert!(- post.lock().unwrap().is_empty(),- "no post-use for a vetoed call"- );- assert!(- mw.arguments_by_call_id.lock().unwrap().is_empty(),- "a vetoed call must not leave a cached argument entry"- );-}--#[tokio::test]-async fn embedder_tool_hooks_post_use_without_pre_call_falls_back_to_null() {- let pre = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let post = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let mw = embedder_hook_mw(pre.clone(), post.clone(), false);-- // A result with no matching `before_tool` (defensive path) must not panic- // and falls back to `Null`, the pre-fix behaviour.- let mut result = TaToolResult::success("found");- mw.after_tool(- &mut ctx(),- &(),- &invocation("orphan", "lookup"),- &mut result,- )- .await- .unwrap();- let post = post.lock().unwrap();- assert_eq!(post.len(), 1);- 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::agent::tinyagents::ToolOutcomeSink {- std::sync::Arc::new(std::sync::Mutex::new(- entries- .iter()- .map(|(id, content)| crate::agent::tinyagents::ToolCallOutcome {- call_id: (*id).to_string(),- name: "fetch".to_string(),- arguments: serde_json::Value::Null,- success: true,- content: (*content).to_string(),- duration_ms: 0,- })- .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", "WRITE NOW", sink_with(&[]), 0);- let mut ctx = RunContext::new(- RunConfig::new("mw-test").with_max_model_calls(5),- crate::agent::tinyagents::host::OpenHumanRunContext::new(),- );- 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", "WRITE NOW", sink_with(&[]), 0);- let mut ctx = RunContext::new(- RunConfig::new("mw-test").with_max_model_calls(2),- crate::agent::tinyagents::host::OpenHumanRunContext::new(),- );- 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_llm::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_llm::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",- "WRITE NOW",- sink_with(&[- ("call-old", "issue #41: auth bypass"),- ("call-new", "issue #42: leak"),- ]),- // Unbounded: this case is about restoring what was cleared, not about- // the budget that stops it (covered by its own test below).- 0,- );- let mut ctx = RunContext::new(- RunConfig::new("mw-test").with_max_model_calls(2),- crate::agent::tinyagents::host::OpenHumanRunContext::new(),- );- 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",- "WRITE NOW",- sink_with(&[("call-1", "FROM SINK")]),- 0,- );- let mut ctx = RunContext::new(- RunConfig::new("mw-test").with_max_model_calls(2),- crate::agent::tinyagents::host::OpenHumanRunContext::new(),- );- 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"- );-}--// ── ArtifactIndexTocMiddleware (issue #6014) ─────────────────────────────────--async fn ctx_with_artifacts(- entries: &[(&str, &str, &str, u64)],-) -> RunContext<crate::agent::tinyagents::host::OpenHumanRunContext> {- 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<crate::agent::tinyagents::host::OpenHumanRunContext> {- use tinyagents_harness::store::StoreRegistry;- let index = std::sync::Arc::new(- crate::agent::harness::tool_result_artifacts::ToolResultArtifactIndexStore::new(),- );- for (call_id, tool, path, bytes) in entries {- let mut fields = serde_json::Map::new();- fields.insert("tool".to_string(), (*tool).into());- fields.insert("call_id".to_string(), (*call_id).into());- fields.insert("artifact_path".to_string(), (*path).into());- fields.insert(- "original_bytes".to_string(),- serde_json::Value::from(*bytes),- );- tinyagents_harness::store::Store::put(- index.as_ref(),- "tool_results",- call_id,- fields.into(),- )- .await- .unwrap();- }- let mut registry = StoreRegistry::new();- registry.register(- crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE,- index,- );- RunContext::new(- config,- crate::agent::tinyagents::host::OpenHumanRunContext::new(),- )- .with_stores(registry)-}--/// Nothing offloaded → no message. The contents list must not spend context-/// saying that there is nothing to point at.--#[path = "middleware_wrap_up_toc_budget_tests.rs"]-mod budget_tests;