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(agent): keep the close deadline through repair and billing (review)
M3gA-Mindfc51fd8828e6
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rsindex e38ce678af..4a5253326d 100644--- a/crates/openhuman-core/src/agent/session_host/driver.rs+++ b/crates/openhuman-core/src/agent/session_host/driver.rs@@ -251,6 +251,12 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {outcome.wrap_up_injected = false;}+ // When the close (and any required-output repair after it) must be+ // done by, so the turn commits before the backstop drops it.+ let close_by = request.run_context.data.turn_deadline.map(|deadline| {+ let now = Instant::now();+ now + deadline.close_budget(now)+ });let close = grounded_close::close_if_needed(&self.turn_model_source,&self.model_name,@@ -260,11 +266,7 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {&request.history,&user_message,&outcome,- request- .run_context- .data- .turn_deadline- .map(|deadline| deadline.close_budget(Instant::now())),+ close_by.map(|at| at.saturating_duration_since(Instant::now())),).await;let mut output = close@@ -310,23 +312,14 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {.breaker_halt.as_deref().is_some_and(|reason| reason.starts_with("Stopping after "));+ let time_left = close_by.map(|at| at.saturating_duration_since(Instant::now()));let required_repair = match required_output.as_ref() {- Some(contract) if classified_halt => {- if !tinyagents_harness::config::output_satisfies_contract(&output, contract) {- output.push_str("\n\n");- output.push_str(&tinyagents_harness::config::synthesize_block(contract));- if history- .last()- .is_some_and(|message| matches!(message, Message::Assistant(_)))- {- history.pop();- }- history.push(Message::assistant(output.clone()));- }+ Some(contract) if classified_halt || time_left.is_some_and(|left| left.is_zero()) => {+ append_synthesized_block(&mut output, &mut history, contract);None}Some(contract) => {- grounded_close::repair_required_output(+ let repair = grounded_close::repair_required_output(&self.turn_model_source,&self.model_name,self.temperature,@@ -338,8 +331,22 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {close.is_none() && request.run_context.data.progress.is_some(),request.run_context.data.progress.as_ref(),outcome.model_calls.saturating_add(1) as u32,- )- .await+ );+ match time_left {+ Some(left) => {+ // Bound to what is left so the turn still commits; on+ // expiry fall back to the deterministic block.+ let repaired = tokio::time::timeout(left, repair).await;+ match repaired {+ Ok(repaired) => repaired,+ Err(_) => {+ append_synthesized_block(&mut output, &mut history, contract);+ None+ }+ }+ }+ None => repair.await,+ }}None => None,};@@ -634,6 +641,28 @@ fn driver_error_with_snapshot(}}+/// Append the deterministic required-output block when `output` lacks it, and+/// make that the durable final assistant row. Used when no model repair may+/// run: a classified halt, or a turn out of time before the backstop.+fn append_synthesized_block(+ output: &mut String,+ history: &mut Vec<Message>,+ contract: &tinyagents_harness::config::RequiredOutput,+) {+ if tinyagents_harness::config::output_satisfies_contract(output, contract) {+ return;+ }+ output.push_str("\n\n");+ output.push_str(&tinyagents_harness::config::synthesize_block(contract));+ if history+ .last()+ .is_some_and(|message| matches!(message, Message::Assistant(_)))+ {+ history.pop();+ }+ history.push(Message::assistant(output.clone()));+}+#[cfg(test)]#[path = "driver_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rsindex 600d331f76..022f7d4e03 100644--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs@@ -262,10 +262,10 @@ pub(super) async fn close_if_needed(}};- let (output, usage) = within_close_budget(+ let mut usage = RepairUsage::for_model(model);+ let output = within_close_budget(budget,- model,- close_with_one_repair(model, instruction, stop_reason, ask, verify, &fallback),+ close_with_one_repair(instruction, stop_reason, ask, verify, &fallback, &mut usage),&fallback,).await;@@ -273,15 +273,14 @@ pub(super) async fn close_if_needed(}/// Run `close` within `budget`, else ship `fallback` (the deterministic summary-/// a rejected close ships). `None` (no turn deadline) waits for `close`.-/// ponytail: usage of calls finished before a timeout is dropped; thread a-/// shared `RepairUsage` through if that spend must be billed.+/// a rejected close ships). `None` (no turn deadline) waits for `close`. The+/// close records into a caller-owned `RepairUsage`, so calls that finished+/// before a timeout are still billed.async fn within_close_budget(budget: Option<std::time::Duration>,- model: &str,- close: impl std::future::Future<Output = (String, RepairUsage)>,+ close: impl std::future::Future<Output = String>,fallback: impl FnOnce() -> String,-) -> (String, RepairUsage) {+) -> String {let Some(budget) = budget else {return close.await;};@@ -293,7 +292,7 @@ async fn within_close_budget(budget_ms,"[session-runtime] grounded close ran out of the turn budget; shipping the deterministic summary");- (fallback(), RepairUsage::for_model(model))+ fallback()}}}@@ -312,20 +311,19 @@ async fn within_close_budget(/// exercised without a provider; the deterministic guard stays here, ahead of/// `verify`, because it is the one check that cannot fail open.async fn close_with_one_repair<A, AF, V, VF>(- model: &str,instruction: String,stop_reason: Option<&str>,ask: A,verify: V,fallback: impl FnOnce() -> String,-) -> (String, RepairUsage)+ usage: &mut RepairUsage,+) -> StringwhereA: Fn(String) -> AF,AF: std::future::Future<Output = (String, Option<BilledUsage>)>,V: Fn(String) -> VF,VF: std::future::Future<Output = (Option<CloseViolation>, Option<BilledUsage>)>,{- let mut usage = RepairUsage::for_model(model);let mut prompt = instruction.clone();for attempt in 0..2 {let (candidate, candidate_usage) = ask(prompt).await;@@ -343,7 +341,7 @@ whereviolation};let Some(violation) = violation else {- return (candidate, usage);+ return candidate;};if attempt > 0 {break;@@ -354,7 +352,7 @@ where);prompt = close_repair_instruction(&instruction, violation);}- (fallback(), usage)+ fallback()}async fn completion(diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rsindex 8f0d85aa6a..9c5d38a3c7 100644--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs@@ -81,11 +81,16 @@ async fn run(candidates: Vec<String>, verdicts: Vec<Option<CloseViolation>>) ->async move { (violation, None) }};- let (output, usage) =- close_with_one_repair("test-model", instruction.clone(), None, ask, verify, || {- FALLBACK.to_string()- })- .await;+ let mut usage = RepairUsage::for_model("test-model");+ let output = close_with_one_repair(+ instruction.clone(),+ None,+ ask,+ verify,+ || FALLBACK.to_string(),+ &mut usage,+ )+ .await;Shipped {output,@@ -251,30 +256,42 @@ fn a_capped_truncated_turn_gets_the_cap_checkpoint() {/// #7716: a close that never answers ships the fallback once the budget runs/// out; one that finishes in time, or runs without a deadline, ships its reply.-#[tokio::test]+/// On the paused clock the budget elapses without real time passing.+#[tokio::test(start_paused = true)]async fn close_budget_bounds_the_close_and_falls_back_on_expiry() {use std::time::Duration;let fallback = || FALLBACK.to_string();- let reply = || async {- (- CLEAN_REPLY.to_string(),- RepairUsage::for_model("test-model"),- )- };- let stalled = std::future::pending::<(String, RepairUsage)>();- let (output, usage) = within_close_budget(- Some(Duration::from_millis(20)),- "test-model",- stalled,- fallback,- )- .await;+ let stalled = std::future::pending::<String>();+ let output = within_close_budget(Some(Duration::from_secs(20)), stalled, fallback).await;assert_eq!(output, FALLBACK);- assert_eq!(usage.model_calls, 0);for budget in [Some(Duration::from_secs(60)), None] {- let (output, _) = within_close_budget(budget, "test-model", reply(), fallback).await;+ let reply = async { CLEAN_REPLY.to_string() };+ let output = within_close_budget(budget, reply, fallback).await;assert_eq!(output, CLEAN_REPLY, "budget {budget:?}");}}++/// A call that finished before the timeout is still billed: the candidate+/// came back, then its verifier stalled past the budget.+#[tokio::test(start_paused = true)]+async fn timed_out_close_keeps_the_usage_of_finished_calls() {+ let instruction = final_answer_instruction(None, false, RECORDS);+ let ask = |_prompt: String| async { (CLEAN_REPLY.to_string(), None) };+ let verify = |_candidate: String| {+ std::future::pending::<(Option<CloseViolation>, Option<BilledUsage>)>()+ };+ let fallback = || FALLBACK.to_string();+ let mut usage = RepairUsage::for_model("test-model");++ let output = within_close_budget(+ Some(std::time::Duration::from_secs(20)),+ close_with_one_repair(instruction, None, ask, verify, fallback, &mut usage),+ fallback,+ )+ .await;++ assert_eq!(output, FALLBACK);+ assert_eq!(usage.model_calls, 1, "the answered ask is recorded");+}diff --git a/crates/openhuman-core/src/agent/session_host/driver_tests.rs b/crates/openhuman-core/src/agent/session_host/driver_tests.rsindex 5d08588eb7..6f07a6f45f 100644--- a/crates/openhuman-core/src/agent/session_host/driver_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver_tests.rs@@ -268,3 +268,29 @@ fn recorded_declarations_allow_missing_executors_without_authorizing_fresh_namesassert!(error.error.to_string().contains("invented_tool"));assert!(!error.error.to_string().contains("retired_tool"));}++/// A turn out of time skips the model repair (#7716); the required block is+/// then synthesized once and becomes the durable final row.+#[test]+fn synthesized_block_is_appended_once_and_replaces_the_final_row() {+ let contract = tinyagents_harness::config::RequiredOutput {+ block_key: "result".into(),+ required_keys: vec!["status".into()],+ };+ let mut output = "Done.".to_string();+ let mut history = vec![Message::user("go"), Message::assistant("Done.")];++ append_synthesized_block(&mut output, &mut history, &contract);+ assert!(tinyagents_harness::config::output_satisfies_contract(+ &output, &contract+ ));+ assert_eq!(+ history.len(),+ 2,+ "the final row is replaced, not duplicated"+ );++ let once = output.clone();+ append_synthesized_block(&mut output, &mut history, &contract);+ assert_eq!(output, once, "a satisfied output is left alone");+}