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 harness close helper
Steven Enamakele5de9574cf42
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 5fef8854cb..318a84ed77 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@@ -6,10 +6,9 @@//! It deliberately uses the same explicit model source as the turn and keeps//! its usage in a sidecar; it never owns transcript history or persistence.-use futures::StreamExt;use tinyagents_runtime::transcript::message_to_native_transcript as message_to_native_chat_message;use tinyagents_session::transcript::TranscriptMessage;-use tinyinference_llm::model::{ModelRequest, ModelStreamItem};+use tinyinference_llm::model::ModelResponse;use tinytools_agent::dialect::ToolDialect;use tinyagents_harness::middleware::wrap_harness_instruction;@@ -18,13 +17,11 @@ use crate::agent::{session_host::turn_checkpoint::{self, build_deterministic_checkpoint, build_deterministic_final_summary,close_repair_instruction, close_verification_prompt, final_answer_instruction,- parse_close_verdict, quotes_harness_instruction, render_tool_results,- results_from_tool_outcomes, CloseVerdict, CloseViolation,+ harness_instruction_needles, render_tool_results, results_from_tool_outcomes,},tinyagents::{TinyagentsTurnOutcome, TurnModelSource},};-use crate::inference::provider::model::dialect_response_from_provider;-use crate::inference::provider::{BilledUsage, ChatResponse, AGENT_TURN_MAX_OUTPUT_TOKENS};+use crate::inference::provider::{BilledUsage, AGENT_TURN_MAX_OUTPUT_TOKENS};/// Accounting from model calls performed after the harness loop has ended.#[derive(Default)]@@ -219,42 +216,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 base: Vec<TranscriptMessage> = base_history- .iter()- .filter_map(message_to_native_chat_message)- .collect();+ 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 ask = |prompt: String| {- let mut messages = base.clone();- messages.push(TranscriptMessage::user(prompt));- async move { completion(source, model, temperature, thread_id, messages).await }- };- // A closing response is only user-visible after a separate, tool-less- // verifier accepts it. This prevents a fluent repair from contradicting a- // captured failure result or merely narrating intended work.- let verify = |candidate: String| {- let prompt = (!contains_tool_call(dispatcher, &candidate))- .then(|| close_verification_prompt(user_message, &rendered, &candidate));- async move {- let Some(prompt) = prompt else {- return (Some(CloseViolation::NoReply), None);- };- let (verdict, verdict_usage) = completion(- source,- model,- temperature,- thread_id,- vec![TranscriptMessage::user(prompt)],- )- .await;- let violation = match parse_close_verdict(&verdict) {- CloseVerdict::Accept => None,- CloseVerdict::Reject | CloseVerdict::Unclear => Some(CloseViolation::Unverified),- };- (violation, verdict_usage)- }- };let fallback = || {if needs_cap_close {build_deterministic_checkpoint(&records, outcome.model_calls)@@ -264,153 +228,65 @@ pub(super) async fn close_if_needed(};let mut usage = RepairUsage::for_model(model);- let output = within_close_budget(- budget,- close_with_one_repair(instruction, stop_reason, ask, verify, &fallback, &mut usage),- &fallback,- )- .await;- Some(GroundedClose { output, usage })-}--/// Run `close` within `budget`, else ship `fallback` (the deterministic summary-/// 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>,- close: impl std::future::Future<Output = String>,- fallback: impl FnOnce() -> String,-) -> String {- let Some(budget) = budget else {- return close.await;- };- match tokio::time::timeout(budget, close).await {- Ok(closed) => closed,- Err(_) => {- let budget_ms = budget.as_millis() as u64;- tracing::warn!(- budget_ms,- "[session-runtime] grounded close ran out of the turn budget; shipping the deterministic summary"- );- fallback()+ 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,+ });}- }-}--/// Ask for a closing message, screen it, and on a violation ask exactly once-/// more with that violation named, before giving up to `fallback`.-///-/// The rung exists because detection alone makes the user worse off: a-/// rejection otherwise drops straight to a raw dump of tool records, and a-/// reply rejected for leaking harness text usually carries a sound answer-/// underneath the leak. One re-ask is the whole budget — this path already runs-/// after the turn's own model calls, and a model that ignores a named directive-/// twice will not comply on a third try.-///-/// `ask` and `verify` are supplied by the caller so the sequence can be-/// 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>(- instruction: String,- stop_reason: Option<&str>,- ask: A,- verify: V,- fallback: impl FnOnce() -> String,- usage: &mut RepairUsage,-) -> String-where- A: 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 prompt = instruction.clone();- for attempt in 0..2 {- let (candidate, candidate_usage) = ask(prompt).await;- usage.record(candidate_usage, true);- let candidate = candidate.trim().to_owned();- let violation = if candidate.is_empty() {- Some(CloseViolation::NoReply)- } else if quotes_harness_instruction(&candidate, stop_reason) {- Some(CloseViolation::QuotedHarnessText)- } else {- let (violation, verify_usage) = verify(candidate.clone()).await;- // The verifier sees one synthetic prompt, not the conversation- // context that will be resumed, so it must not replace the gauge.- usage.record(verify_usage, false);- violation- };- let Some(violation) = violation else {- return candidate;- };- if attempt > 0 {- break;- }- tracing::debug!(- ?violation,- "[session-runtime] grounded close rejected, re-asking once"+ };+ let mut on_call_completed = |kind, response: Option<&ModelResponse>| {+ let billed = response.and_then(crate::inference::provider::model::usage_info_from_response);+ usage.record(+ billed,+ kind != tinyagents_harness::close::CloseRequestKind::Verification,);- prompt = close_repair_instruction(&instruction, violation);- }- fallback()-}--async fn completion(- source: &TurnModelSource,- model: &str,- temperature: f64,- thread_id: Option<&str>,- messages: Vec<TranscriptMessage>,-) -> (String, Option<BilledUsage>) {- let Ok(model_client) = source.build_summarizer(model, temperature, thread_id) else {- return (String::new(), None);};- let request = ModelRequest::new(- messages- .iter()- .map(crate::agent::tinyagents::chat_message_to_message)- .collect(),- )- .with_model(model)- .with_temperature(temperature)- .with_max_tokens(AGENT_TURN_MAX_OUTPUT_TOKENS);- let Ok(mut stream) = model_client.stream(&(), request).await else {- return (String::new(), None);+ let close_options = tinyagents_harness::close::CloseRequestOptions {+ model: Some(model),+ temperature: Some(temperature),+ max_output_tokens: Some(AGENT_TURN_MAX_OUTPUT_TOKENS),+ minimum_harness_phrase_chars: 1,+ on_call_completed: Some(&mut on_call_completed),};- let mut buffered = String::new();- while let Some(item) = stream.next().await {- match item {- ModelStreamItem::MessageDelta(delta) => buffered.push_str(&delta.text),- ModelStreamItem::Completed(response) => {- let text = response.text();- let selected = if !text.trim().is_empty() {- text- } else {- buffered+ let output = tinyagents_harness::close::grounded_close_with_options(+ model_client.as_ref(),+ &(),+ dispatcher,+ tinyagents_harness::close::GroundedCloseConfig {+ history: base_history,+ initial_prompt: &instruction,+ verification_prompt: |candidate| {+ close_verification_prompt(user_message, &rendered, candidate)+ },+ repair_instruction: |violation| {+ let violation = match violation {+ tinyagents_harness::close::CloseViolation::NoReply+ | tinyagents_harness::close::CloseViolation::QuotedInstruction => {+ crate::agent::session_host::turn_checkpoint::CloseViolation::QuotedHarnessText+ }+ tinyagents_harness::close::CloseViolation::Unverified => {+ crate::agent::session_host::turn_checkpoint::CloseViolation::Unverified+ }};- return (- selected,- crate::inference::provider::model::usage_info_from_response(&response),- );- }- ModelStreamItem::Failed(_) | ModelStreamItem::ProviderFailed(_) => {- return (String::new(), None);- }- _ => {}- }- }- (String::new(), None)-}--fn contains_tool_call(dispatcher: &dyn ToolDialect, text: &str) -> bool {- !dispatcher- .parse_response(&dialect_response_from_provider(&ChatResponse {- text: Some(text.to_owned()),- ..ChatResponse::default()- }))- .1- .is_empty()+ crate::agent::session_host::turn_checkpoint::close_repair_instruction(+ &instruction,+ violation,+ )+ },+ harness_phrases: &harness_phrases,+ budget,+ deterministic_fallback: fallback,+ },+ close_options,+ )+ .await+ .text;+ Some(GroundedClose { output, usage })}#[cfg(test)]