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(session_host): delegate grounded close to tinyagents
Steven Enamakelf03e03e4d3a1
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 ba4d089221..7d3d991c05 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@@ -8,7 +8,7 @@use tinyagents_runtime::transcript::message_to_native_transcript as message_to_native_chat_message;use tinyagents_session::transcript::TranscriptMessage;-use tinyinference_llm::model::ModelResponse;+use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse, ModelStream};use tinytools_agent::dialect::ToolDialect;use tinyagents_harness::middleware::wrap_harness_instruction;@@ -76,6 +76,42 @@ impl RepairUsage {}}+/// Resolve OpenHuman's selected summarizer per close request and forward that+/// request unchanged. TinyAgents owns streaming, validation and repair.+struct SummarizerSourceModel<'a> {+ source: &'a TurnModelSource,+ model: &'a str,+ temperature: f64,+ thread_id: Option<&'a str>,+}++#[async_trait::async_trait]+impl ChatModel<()> for SummarizerSourceModel<'_> {+ async fn invoke(+ &self,+ state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelResponse> {+ let model = self+ .source+ .build_summarizer(self.model, self.temperature, self.thread_id)+ .map_err(|error| tinyinference_llm::Error::Model(error.to_string()))?;+ model.invoke(state, request).await+ }++ async fn stream(+ &self,+ state: &(),+ request: ModelRequest,+ ) -> tinyinference_llm::Result<ModelStream> {+ let model = self+ .source+ .build_summarizer(self.model, self.temperature, self.thread_id)+ .map_err(|error| tinyinference_llm::Error::Model(error.to_string()))?;+ model.stream(state, request).await+ }+}+/// A repaired terminal reply and the extra provider usage it incurred.pub(super) struct GroundedClose {pub(super) output: String,@@ -135,11 +171,16 @@ pub(super) async fn repair_required_output(minimum_harness_phrase_chars: 24,on_call_completed: Some(&mut on_call_completed),},- fallback_placement:- tinyagents_harness::close::RequiredOutputFallbackPlacement::Prepend,+ fallback_placement: tinyagents_harness::close::RequiredOutputFallbackPlacement::Prepend,+ };+ let model_client = SummarizerSourceModel {+ source,+ model,+ temperature,+ thread_id,};let repaired = tinyagents_harness::close::repair_required_output_with_repair_options(- &*source.build_summarizer(model, temperature, thread_id).ok()?,+ &model_client,&(),dispatcher,tinyagents_harness::close::RequiredOutputRepairConfig {@@ -228,9 +269,9 @@ pub(super) async fn close_if_needed(let records = results_from_tool_outcomes(&outcome.tool_outcomes);let rendered = render_tool_results(&records, turn_checkpoint::GROUNDING_TOTAL_CHARS);let instruction = close_instruction(outcome, needs_cap_close, &rendered);+ let stop_reason = outcome.breaker_halt.as_deref();let harness_needles = harness_instruction_needles(stop_reason);let harness_phrases: Vec<&str> = harness_needles.iter().map(String::as_str).collect();- let stop_reason = outcome.breaker_halt.as_deref();let fallback = || {if needs_cap_close {build_deterministic_checkpoint(&records, outcome.model_calls)@@ -240,16 +281,11 @@ pub(super) async fn close_if_needed(};let mut usage = RepairUsage::for_model(model);- let model_client = match source.build_summarizer(model, temperature, thread_id) {- Ok(model_client) => model_client,- Err(error) => {- tracing::debug!(%error, "[session-runtime] close model unavailable");- usage.record(None, true);- return Some(GroundedClose {- output: fallback(),- usage,- });- }+ let model_client = SummarizerSourceModel {+ source,+ model,+ temperature,+ thread_id,};let mut on_call_completed = |kind, response: Option<&ModelResponse>| {usage.record_close_call(kind, response);@@ -262,7 +298,7 @@ pub(super) async fn close_if_needed(on_call_completed: Some(&mut on_call_completed),};let output = tinyagents_harness::close::grounded_close_with_options(- model_client.as_ref(),+ &model_client,&(),dispatcher,tinyagents_harness::close::GroundedCloseConfig {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 4aa846a50b..7ce125051e 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@@ -1,11 +1,8 @@-use std::cell::RefCell;-use super::*;-use crate::agent::session_host::turn_checkpoint::FINAL_ANSWER_INSTRUCTION;+use std::sync::Arc;const RECORDS: &str = "\n- `list_directory` — ok\n > three crates\n";const CLEAN_REPLY: &str = "The workspace holds three crates; the build is green.";-const FALLBACK: &str = "deterministic fallback";#[test]fn classified_halt_returns_partial_work_without_provider_usage() {@@ -48,156 +45,130 @@ fn classified_halt_returns_partial_work_without_provider_usage() {assert!(close.output.contains("403 Forbidden"), "{}", close.output);}-/// A candidate carrying a verbatim span of the directive it was just handed —-/// the shape this guard exists for, spliced from the constant so a reword-/// cannot leave this fixture quoting text nobody is given.-fn leaking_reply() -> String {- let quoted = FINAL_ANSWER_INSTRUCTION- .split('.')- .next()- .expect("the instruction opens with a sentence")- .trim();- format!("{quoted}. Anyway: the workspace holds three crates.")-}+/// The host adapter delegates generation and verification to TinyAgents while+/// retaining its selected model, temperature, output cap and billing gauge.+#[tokio::test]+async fn grounded_close_uses_the_selected_model_and_keeps_verifier_out_of_context_gauge() {+ use tinyagents_harness::testkit::ScriptedModel;+ use tinyinference_llm::usage::Usage;-/// Drive [`close_with_one_repair`] over a scripted sequence of candidates,-/// returning the shipped message, the prompts each attempt was given, the-/// candidates that reached the verifier, and the usage recorded.-async fn run(candidates: Vec<String>, verdicts: Vec<Option<CloseViolation>>) -> Shipped {- let instruction = final_answer_instruction(None, false, RECORDS);- let prompts = RefCell::new(Vec::<String>::new());- let verified = RefCell::new(Vec::<String>::new());- let remaining = RefCell::new(candidates);- let remaining_verdicts = RefCell::new(verdicts);+ let generation = tinyinference_llm::model::ModelResponse::assistant(CLEAN_REPLY)+ .with_usage(Usage::new(90, 12));+ let verification =+ tinyinference_llm::model::ModelResponse::assistant("ACCEPT").with_usage(Usage::new(7, 2));+ let scripted = Arc::new(ScriptedModel::new(vec![generation, verification]));+ let source = TurnModelSource::from_model(scripted.clone());+ let mut outcome = blank_outcome(false);+ outcome.tool_outcomes = vec![tinyagents_harness::turn_outcome::ToolCallOutcome {+ call_id: "call-1".into(),+ name: "list_directory".into(),+ arguments: serde_json::Value::Null,+ success: true,+ content: "three crates".into(),+ duration_ms: 0,+ }];- let ask = |prompt: String| {- prompts.borrow_mut().push(prompt);- let candidate = remaining.borrow_mut().remove(0);- async move { (candidate, None) }- };- let verify = |candidate: String| {- verified.borrow_mut().push(candidate);- let violation = remaining_verdicts.borrow_mut().remove(0);- async move { (violation, None) }- };-- let mut usage = RepairUsage::for_model("test-model");- let output = close_with_one_repair(- instruction.clone(),+ let closed = close_if_needed(+ &source,+ "host-selected-model",+ 0.37,+ None,+ &tinytools_agent::dialect::NativeDialect,+ &[],+ "Summarize the workspace.",+ &outcome,None,- ask,- verify,- || FALLBACK.to_string(),- &mut usage,)- .await;+ .await+ .expect("blank terminal reply needs a close");- Shipped {- output,- instruction,- prompts: prompts.into_inner(),- verified: verified.into_inner(),- model_calls: usage.model_calls,+ assert_eq!(closed.output, CLEAN_REPLY);+ assert_eq!(closed.usage.model_calls, 2);+ assert_eq!(closed.usage.input_tokens, 97);+ assert_eq!(closed.usage.output_tokens, 14);+ assert_eq!(closed.usage.last_call_input_tokens, 90);+ assert_eq!(closed.usage.last_call_output_tokens, 12);+ let requests = scripted.requests();+ assert_eq!(requests.len(), 2);+ for request in requests {+ assert_eq!(request.model.as_deref(), Some("host-selected-model"));+ assert_eq!(request.temperature, Some(0.37));+ assert_eq!(request.max_tokens, Some(AGENT_TURN_MAX_OUTPUT_TOKENS));+ assert!(request.tools.is_empty());}}-struct Shipped {- output: String,- instruction: String,- prompts: Vec<String>,- verified: Vec<String>,- model_calls: usize,-}--/// The rung that keeps detection from costing the user the answer: the leak is-/// caught, one corrective re-ask goes out naming it, and the clean second-/// candidate ships instead of a record dump.#[tokio::test]-async fn a_leaking_candidate_is_repaired_by_one_re_ask() {- let shipped = run(vec![leaking_reply(), CLEAN_REPLY.to_string()], vec![None]).await;+async fn terminal_failed_close_requests_are_counted_without_usage() {+ use tinyagents_harness::testkit::ScriptedModel;- assert_eq!(shipped.output, CLEAN_REPLY);- assert_eq!(shipped.prompts.len(), 2, "exactly one re-ask");- assert_eq!(- shipped.prompts[0], shipped.instruction,- "the first attempt gets the instruction unchanged"- );- assert!(- shipped.prompts[1].contains("repeated these directions"),- "the re-ask must name the violation: {}",- shipped.prompts[1]- );- assert!(- shipped.prompts[1].contains(&shipped.instruction),- "the re-ask must still carry the records: {}",- shipped.prompts[1]- );- assert_eq!(- shipped.verified,- vec![CLEAN_REPLY.to_string()],- "the deterministic guard runs first, so the leak never reaches the checker"- );- assert_eq!(- shipped.model_calls, 3,- "two closing calls and the one verification"- );+ let source = TurnModelSource::from_model(Arc::new(ScriptedModel::new(Vec::new())));+ let closed = close_if_needed(+ &source,+ "test-model",+ 0.0,+ None,+ &tinytools_agent::dialect::NativeDialect,+ &[],+ "Summarize the workspace.",+ &blank_outcome(false),+ None,+ )+ .await+ .expect("blank terminal reply needs a close");++ assert_eq!(closed.usage.model_calls, 2, "one failed ask and its repair");+ assert_eq!(closed.usage.input_tokens, 0);+ assert_eq!(closed.usage.output_tokens, 0);+ assert_eq!(closed.usage.last_call_input_tokens, 0);}-/// The budget is one. A model that quotes the directive twice is not going to-/// stop on a third ask, so the turn takes the deterministic summary.#[tokio::test]-async fn a_second_leak_falls_back_to_the_deterministic_summary() {- let shipped = run(vec![leaking_reply(), leaking_reply()], vec![]).await;+async fn required_output_repair_preserves_all_host_output_placements() {+ use tinyagents_harness::testkit::ScriptedModel;- assert_eq!(shipped.output, FALLBACK);- assert_eq!(shipped.prompts.len(), 2, "no third attempt");- assert!(- shipped.verified.is_empty(),- "neither leak is worth a verification call: {:?}",- shipped.verified- );- assert_eq!(shipped.model_calls, 2);-}+ async fn repair(candidate: &str, reply: &str, streamed: bool) -> String {+ let source = TurnModelSource::from_model(Arc::new(ScriptedModel::replies(vec![candidate])));+ let contract = tinyagents_harness::config::RequiredOutput {+ block_key: "result".into(),+ required_keys: vec!["status".into()],+ };+ let mut usage = RepairUsage::for_model("test-model");+ super::repair_required_output(+ &source,+ "test-model",+ 0.0,+ None,+ &tinytools_agent::dialect::NativeDialect,+ &contract,+ &[],+ reply,+ streamed,+ None,+ 1,+ &mut usage,+ )+ .await+ .expect("reply lacks the required block")+ }-/// A candidate the guard clears but the checker rejects takes the same single-/// rung — the repair is not reserved for quotations.-#[tokio::test]-async fn a_checker_rejection_also_gets_one_repair() {- let shipped = run(- vec!["I'll go and look.".to_string(), CLEAN_REPLY.to_string()],- vec![Some(CloseViolation::Unverified), None],- )- .await;+ let valid = r#"{"result":{"status":"ok"}}"#;+ let invalid = "not structured output";+ let reply = "Original reply.";+ let block = r#"{"result":{"status":""}}"#;- assert_eq!(shipped.output, CLEAN_REPLY);- assert!(- shipped.prompts[1].contains("did not pass the check"),- "{}",- shipped.prompts[1]- );- assert_eq!(shipped.verified.len(), 2);+ assert_eq!(repair(valid, reply, false).await, valid);assert_eq!(- shipped.model_calls, 4,- "two closing calls, two verifications"+ repair(valid, reply, true).await,+ format!("{reply}\n\n{valid}"));-}--/// An empty candidate is a violation like any other, and is worth the re-ask-/// rather than dropping straight to the fallback.-#[tokio::test]-async fn an_empty_candidate_is_re_asked_before_the_fallback() {- let shipped = run(vec![" ".to_string(), CLEAN_REPLY.to_string()], vec![None]).await;-- assert_eq!(shipped.output, CLEAN_REPLY);- assert!(- shipped.prompts[1].contains("empty or tried to call a tool"),- "{}",- shipped.prompts[1]+ assert_eq!(+ repair(invalid, reply, true).await,+ format!("{reply}\n\n{block}"));assert_eq!(- shipped.verified,- vec![CLEAN_REPLY.to_string()],- "an empty candidate is not sent to the checker"+ repair(invalid, reply, false).await,+ format!("{block}\n\n{reply}"));}@@ -254,48 +225,6 @@ fn a_capped_truncated_turn_gets_the_cap_checkpoint() {assert!(out.contains("<tool_records>"), "{out}");}-/// #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.-/// 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 stalled = std::future::pending::<String>();- let output = within_close_budget(Some(Duration::from_secs(20)), stalled, fallback).await;- assert_eq!(output, FALLBACK);-- for budget in [Some(Duration::from_secs(60)), None] {- 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");-}-/// The same for the required-output repair (#7721 review): its call answered,/// then streaming the correction outlived the turn budget. The caller-owned/// accumulator still holds the call.