Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge remote-tracking branch 'fork/tinyagents-refactor' into epic-7929-7953-session-host

Steven Enamakel6c308caa77c3
diff --cc crates/openhuman-core/src/agent/session_host/driver.rs
index e457fefac9,c36532f903..e1019733ed
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@@ -257,7 -249,9 +259,9 @@@ impl SessionDriver<OpenHumanRunContext
&& (outcome.model_calls >= self.max_iterations
|| outcome.tool_calls >= self.max_iterations
|| outcome.tool_outcomes.len() >= self.max_iterations);
- // Normalize the exhausted-loop fallback when older hosted paths hide raw counters.
+ // Older hosted-harness fallbacks leave the raw counters unavailable.
- // It is only produced when the loop exhausted a tool round without a
- // model conclusion, so normalize it to the same resumable cap state.
++ // They only occur when the loop exhausted a tool round without a model
++ // conclusion, so normalize them to the same resumable cap state.
let exhausted_fallback = outcome
.text
.starts_with("I finished this turn without writing up a result.");
diff --cc crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
index 04a52036e5,9c1c5ac3a5..86f2fe9e0d
--- 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,21 -6,25 +6,24 @@@
//! 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 std::sync::Arc;
use tinyagents_runtime::transcript::message_to_native_transcript as message_to_native_chat_message;
- use tinyinference_llm::model::{ChatModel, ModelRequest, ModelResponse, ModelStream};
-use tinyagents_session::transcript::TranscriptMessage;
-use tinyinference_llm::model::{ModelCallCorrelation, ModelRequest, ModelStreamItem};
++use tinyinference_llm::model::{
++ ChatModel, ModelCallCorrelation, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
++};
use tinytools_agent::dialect::ToolDialect;
+use tinyagents_harness::middleware::wrap_harness_instruction;
+
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,
+ close_verification_prompt, final_answer_instruction, harness_instruction_needles,
+ render_tool_results, results_from_tool_outcomes,
},
- tinyagents::{TinyagentsTurnOutcome, TurnModelSource},
+ tinyagents::{SupplementalTrace, TinyagentsTurnOutcome, TurnModelSource},
};
-use crate::inference::provider::model::dialect_response_from_provider;
-use crate::inference::provider::{BilledUsage, ChatResponse, AGENT_TURN_MAX_OUTPUT_TOKENS};
-use tinyagents_harness::middleware::wrap_harness_instruction;
+use crate::inference::provider::{BilledUsage, AGENT_TURN_MAX_OUTPUT_TOKENS};
/// Accounting from model calls performed after the harness loop has ended.
#[derive(Default)]
@@@ -58,57 -70,14 +69,139 @@@ impl RepairUsage
self.input_tokens += usage.input_tokens;
self.output_tokens += usage.output_tokens;
self.cached_input_tokens += usage.cached_input_tokens();
- self.cost
- .add(crate::agent::cost::call_cost(&self.pricing_model, &usage));
+ if trace.is_some_and(SupplementalTrace::is_cache_hit) {
+ self.cost.add(tinyagents_harness::cost::CallCost::Unknown);
+ } else {
+ self.cost
+ .add(crate::agent::cost::call_cost(&self.pricing_model, &usage));
+ }
}
}
+
+ fn record_close_call(
+ &mut self,
+ kind: tinyagents_harness::close::CloseRequestKind,
+ response: Option<&ModelResponse>,
++ trace: Option<&SupplementalTrace>,
+ ) {
+ self.record(
+ response.and_then(crate::inference::provider::model::usage_info_from_response),
+ kind != tinyagents_harness::close::CloseRequestKind::Verification,
++ trace,
+ );
+ }
+}
+
+/// 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>,
++ trace: Option<&'a Arc<SupplementalTrace>>,
++}
++
++struct SupplementalCall {
++ trace: Arc<SupplementalTrace>,
++ call_id: tinyagents_harness::ids::CallId,
++ started_at_ms: u64,
++ model: String,
++ input: serde_json::Value,
++ completed: bool,
++}
++
++impl SupplementalCall {
++ fn start(trace: &Arc<SupplementalTrace>, model: &str, request: &mut ModelRequest) -> Self {
++ let (call_id, started_at_ms) = trace.begin(model);
++ request.correlation = Some(ModelCallCorrelation::new(
++ trace.run_id().as_str(),
++ call_id.as_str(),
++ ));
++ Self {
++ trace: Arc::clone(trace),
++ call_id,
++ started_at_ms,
++ model: model.to_owned(),
++ input: serde_json::to_value(&request.messages).unwrap_or(serde_json::Value::Null),
++ completed: false,
++ }
++ }
++
++ fn complete(&mut self, response: &ModelResponse) {
++ self.trace.completed(
++ self.call_id.clone(),
++ &self.model,
++ self.started_at_ms,
++ self.input.clone(),
++ response,
++ );
++ self.completed = true;
++ }
++}
++
++impl Drop for SupplementalCall {
++ fn drop(&mut self) {
++ if !self.completed {
++ self.trace
++ .failed(self.call_id.clone(), &self.model, self.started_at_ms);
++ }
++ }
+}
+
+#[async_trait::async_trait]
+impl ChatModel<()> for SummarizerSourceModel<'_> {
+ async fn invoke(
+ &self,
+ state: &(),
- request: ModelRequest,
++ mut 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
++ let mut call = self
++ .trace
++ .map(|trace| SupplementalCall::start(trace, self.model, &mut request));
++ match model.invoke(state, request).await {
++ Ok(response) => {
++ if let Some(call) = &mut call {
++ call.complete(&response);
++ }
++ Ok(response)
++ }
++ Err(error) => Err(error),
++ }
+ }
+
+ async fn stream(
+ &self,
+ state: &(),
- request: ModelRequest,
++ mut 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
++ let mut call = self
++ .trace
++ .map(|trace| SupplementalCall::start(trace, self.model, &mut request));
++ let stream = model.stream(state, request).await?;
++ Ok(stream.map_items(move |item| {
++ match &item {
++ ModelStreamItem::Completed(response) => {
++ if let Some(call) = &mut call {
++ call.complete(response);
++ }
++ }
++ ModelStreamItem::Failed(_) | ModelStreamItem::ProviderFailed(_) => {
++ call.take();
++ }
++ _ => {}
++ }
++ item
++ }))
+ }
}
/// A repaired terminal reply and the extra provider usage it incurred.
@@@ -154,66 -124,64 +248,67 @@@ pub(super) async fn repair_required_out
) -> Option<String> {
use tinyagents_harness::config as required;
- if required::output_satisfies_contract(reply, contract) {
- return None;
- }
-
- let mut prompt_history: Vec<TranscriptMessage> = history
+ let prompt_history: Vec<tinyinference_llm::message::Message> = history
.iter()
.filter_map(message_to_native_chat_message)
+ .map(|message| crate::agent::tinyagents::chat_message_to_message(&message))
.collect();
- prompt_history.push(TranscriptMessage::user(wrap_harness_instruction(
- &required::repair_instruction(contract),
- )));
- let (candidate, candidate_usage) = completion(
+ let repair_instruction = wrap_harness_instruction(&required::repair_instruction(contract));
+ let mut on_call_completed = |kind, response: Option<&ModelResponse>| {
- usage.record_close_call(kind, response);
++ usage.record_close_call(kind, response, trace.map(Arc::as_ref));
+ };
+ let options = tinyagents_harness::close::RequiredOutputRepairOptions {
+ request: 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),
+ },
+ fallback_placement: tinyagents_harness::close::RequiredOutputFallbackPlacement::Prepend,
+ };
+ let model_client = SummarizerSourceModel {
source,
model,
temperature,
thread_id,
- prompt_history,
- trace.map(Arc::as_ref),
- )
- .await;
- usage.record(candidate_usage, true, trace.map(Arc::as_ref));
- let candidate = candidate.trim().to_owned();
- let candidate_is_usable = !candidate.is_empty()
- && !contains_tool_call(dispatcher, &candidate)
- && required::output_satisfies_contract(&candidate, contract);
-
- if !reply_already_streamed {
- let output = if candidate_is_usable {
- candidate
- } else {
- format!("{}\n\n{reply}", required::synthesize_block(contract))
- };
- return Some(output);
- }
-
- // The main loop may have already emitted the original reply. Never
- // replace what the user saw: append the recovered block (or a deterministic
- // one) and stream that exact continuation before returning it for commit.
- let correction = if candidate_is_usable {
- required::find_required_block(&candidate, contract)
- .and_then(|block| serde_json::to_string(&block).ok())
- .unwrap_or_else(|| required::synthesize_block(contract))
- } else {
- required::synthesize_block(contract)
++ trace,
};
- let continuation = format!("\n\n{correction}");
- if let Some(progress) = progress {
- if let Err(error) = progress
- .send(crate::progress::AgentProgress::TextDelta {
- delta: continuation.clone(),
- iteration,
- })
- .await
- {
- tracing::debug!(%error, "[session-runtime] required-output repair progress receiver closed");
+ let repaired = tinyagents_harness::close::repair_required_output_with_repair_options(
+ &model_client,
+ &(),
+ dispatcher,
+ tinyagents_harness::close::RequiredOutputRepairConfig {
+ history: &prompt_history,
+ reply,
+ contract,
+ repair_instruction: &repair_instruction,
+ reply_already_streamed,
+ },
+ options,
+ )
+ .await?;
+ // The main loop may already have emitted the reply. In that case send only
+ // TinyAgents' returned continuation, then commit the same full text.
+ if reply_already_streamed {
+ let continuation = repaired
+ .text
+ .strip_prefix(reply)
+ .unwrap_or(&repaired.text)
+ .to_owned();
+ if let Some(progress) = progress {
+ if let Err(error) = progress
+ .send(crate::progress::AgentProgress::TextDelta {
+ delta: continuation,
+ iteration,
+ })
+ .await
+ {
+ tracing::debug!(%error, "[session-runtime] required-output repair progress receiver closed");
+ }
}
}
- Some(format!("{reply}{continuation}"))
+ Some(repaired.text)
}
/// The tool-less closing instruction for `outcome`: the cap checkpoint when the
@@@ -288,60 -296,192 +384,61 @@@ 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,
- trace.map(Arc::as_ref),
- ),
- &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;
+ let model_client = SummarizerSourceModel {
+ source,
+ model,
+ temperature,
+ thread_id,
++ trace,
};
- 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()
- }
- }
-}
-
-/// 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,
- trace: Option<&SupplementalTrace>,
-) -> 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, trace);
- 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, trace);
- violation
- };
- let Some(violation) = violation else {
- return candidate;
- };
- if attempt > 0 {
- break;
- }
- tracing::debug!(
- ?violation,
- "[session-runtime] grounded close rejected, re-asking once"
- );
- prompt = close_repair_instruction(&instruction, violation);
- }
- fallback()
-}
-
-async fn completion(
- source: &TurnModelSource,
- model: &str,
- temperature: f64,
- thread_id: Option<&str>,
- messages: Vec<TranscriptMessage>,
- trace: Option<&SupplementalTrace>,
-) -> (String, Option<BilledUsage>) {
- let Ok(model_client) = source.build_summarizer(model, temperature, thread_id) else {
- return (String::new(), None);
+ let mut on_call_completed = |kind, response: Option<&ModelResponse>| {
- usage.record_close_call(kind, response);
++ usage.record_close_call(kind, response, trace.map(Arc::as_ref));
};
- let (call_id, started_at_ms) = trace
- .map(|trace| trace.begin(model))
- .map_or((None, None), |(call_id, started_at)| {
- (Some(call_id), Some(started_at))
- });
- 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 request = match (trace, call_id.as_ref()) {
- (Some(trace), Some(call_id)) => request.with_correlation(ModelCallCorrelation::new(
- trace.run_id().as_str(),
- call_id.as_str(),
- )),
- _ => request,
+ 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 input = serde_json::to_value(&request.messages).unwrap_or(serde_json::Value::Null);
- let Ok(mut stream) = model_client.stream(&(), request).await else {
- if let (Some(trace), Some(call_id), Some(started_at_ms)) = (trace, call_id, started_at_ms) {
- trace.failed(call_id, model, started_at_ms);
- }
- return (String::new(), None);
+ let verification_prompt = |candidate: &str| -> String {
+ close_verification_prompt(user_message, &rendered, candidate)
};
- 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
- };
- if let (Some(trace), Some(call_id), Some(started_at_ms)) =
- (trace, call_id, started_at_ms)
- {
- trace.completed(call_id, model, started_at_ms, input, &response);
- }
- return (
- selected,
- crate::inference::provider::model::usage_info_from_response(&response),
- );
+ let repair_instruction = |violation: tinyagents_harness::close::CloseViolation| -> String {
+ let violation = match violation {
+ tinyagents_harness::close::CloseViolation::NoReply => {
+ crate::agent::session_host::turn_checkpoint::CloseViolation::NoReply
}
- ModelStreamItem::Failed(_) | ModelStreamItem::ProviderFailed(_) => {
- if let (Some(trace), Some(call_id), Some(started_at_ms)) =
- (trace, call_id, started_at_ms)
- {
- trace.failed(call_id, model, started_at_ms);
- }
- return (String::new(), None);
+ tinyagents_harness::close::CloseViolation::QuotedInstruction => {
+ crate::agent::session_host::turn_checkpoint::CloseViolation::QuotedHarnessText
}
- _ => {}
- }
- }
- if let (Some(trace), Some(call_id), Some(started_at_ms)) = (trace, call_id, started_at_ms) {
- trace.failed(call_id, model, started_at_ms);
- }
- (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()
+ tinyagents_harness::close::CloseViolation::Unverified => {
+ crate::agent::session_host::turn_checkpoint::CloseViolation::Unverified
+ }
+ };
+ crate::agent::session_host::turn_checkpoint::close_repair_instruction(
+ &instruction,
+ violation,
+ )
+ };
+ let output = tinyagents_harness::close::grounded_close_with_options(
+ &model_client,
+ &(),
+ dispatcher,
+ tinyagents_harness::close::GroundedCloseConfig {
+ history: &history,
+ initial_prompt: &instruction,
+ verification_prompt,
+ repair_instruction,
+ harness_phrases: &harness_phrases,
+ budget,
+ deterministic_fallback: fallback,
+ },
+ close_options,
+ )
+ .await
+ .text;
+ Some(GroundedClose { output, usage })
}
#[cfg(test)]
diff --cc crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs
index 0ddc6d49d7,fa863685e8..f9de522431
--- 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
@@@ -45,184 -54,158 +51,403 @@@ fn classified_halt_returns_partial_work
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.")
-}
-
-/// 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 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) }
+/// 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::message::{
+ AssistantMessage, ContentBlock, ImageRef, Message, ToolMessage, UserMessage,
};
-
- let mut usage = RepairUsage::for_model("test-model");
- let output = close_with_one_repair(
- instruction.clone(),
+ use tinyinference_llm::tool::ToolCall;
+ use tinyinference_llm::usage::Usage;
+
+ 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 history = vec![
+ Message::User(UserMessage {
+ content: vec![
+ ContentBlock::Text("inspect ".into()),
+ ContentBlock::Image(ImageRef {
+ url: "data:image/png;base64,AAAA".into(),
+ mime_type: Some("image/png".into()),
+ }),
+ ],
+ }),
+ Message::Assistant(AssistantMessage {
+ id: Some("assistant-1".into()),
+ content: vec![
+ ContentBlock::thinking("reasoning context"),
+ ContentBlock::Text("calling the tool".into()),
+ ],
+ tool_calls: vec![ToolCall {
+ id: "tool-call-1".into(),
+ name: "list_directory".into(),
+ arguments: serde_json::json!({"path": "."}),
+ invalid: None,
+ }],
+ usage: None,
+ origin: None,
+ }),
+ Message::Tool(ToolMessage {
+ tool_call_id: "tool-call-1".into(),
+ content: vec![ContentBlock::Text("three crates".into())],
+ trusted_verbatim: false,
+ artifact: None,
+ }),
+ ];
+ 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 closed = close_if_needed(
+ &source,
+ "host-selected-model",
+ 0.37,
+ None,
+ &tinytools_agent::dialect::NativeDialect,
+ &history,
+ "Summarize the workspace.",
+ &outcome,
None,
- ask,
- verify,
- || FALLBACK.to_string(),
- &mut usage,
+ None,
)
- .await;
-
- Shipped {
- output,
- instruction,
- prompts: prompts.into_inner(),
- verified: verified.into_inner(),
- model_calls: usage.model_calls,
+ .await
+ .expect("blank terminal reply needs a close");
+
+ 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;
-
- 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"
- );
+ let expected_history: Vec<_> = history
+ .iter()
+ .filter_map(tinyagents_runtime::transcript::message_to_native_transcript)
+ .map(|message| crate::agent::tinyagents::chat_message_to_message(&message))
+ .collect();
assert_eq!(
- shipped.model_calls, 3,
- "two closing calls and the one verification"
+ &requests[0].messages[..expected_history.len()],
+ expected_history,
+ "close requests preserve the transcript roundtrip for attachments, reasoning and tool rows"
);
}
-/// 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 terminal_failed_close_requests_are_counted_without_usage() {
+ 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);
+ 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,
++ 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);
}
-/// 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],
++async fn close_state_machine_calls_emit_correlated_native_model_events() {
++ use std::sync::Mutex;
++ use tinyagents_harness::events::{AgentEvent, EventListener, EventSink};
++ use tinyagents_harness::ids::RunId;
++ use tinyagents_harness::testkit::ScriptedModel;
++ use tinyinference_llm::model::ModelResponse;
++
++ #[derive(Default)]
++ struct Recorder(Mutex<Vec<AgentEvent>>);
++ impl EventListener for Recorder {
++ fn on_event(&self, record: &tinyagents_harness::events::EventRecord) {
++ self.0.lock().unwrap().push(record.event.clone());
++ }
++ }
++
++ async fn run(replies: Vec<ModelResponse>, expected_calls: usize, expect_failure: bool) {
++ let run_id = RunId::new("close-state-machine-trace");
++ let sink = EventSink::with_stream_id(run_id.as_str());
++ let recorder = Arc::new(Recorder::default());
++ sink.subscribe(recorder.clone());
++ let trace = SupplementalTrace::new(sink, run_id.clone());
++ let scripted = Arc::new(ScriptedModel::new(replies));
++ let source = TurnModelSource::from_model(scripted.clone());
++
++ close_if_needed(
++ &source,
++ "host-selected-model",
++ 0.25,
++ None,
++ &tinytools_agent::dialect::NativeDialect,
++ &[],
++ "Summarize the workspace.",
++ &blank_outcome(false),
++ None,
++ Some(&trace),
++ )
++ .await
++ .expect("blank terminal reply needs a close");
++
++ let requests = scripted.requests();
++ assert_eq!(requests.len(), expected_calls);
++ let records = recorder.0.lock().unwrap();
++ let started: Vec<_> = records
++ .iter()
++ .filter_map(|event| match event {
++ AgentEvent::ModelStarted { call_id, model } => {
++ assert_eq!(model, "host-selected-model");
++ Some(call_id.as_str())
++ }
++ _ => None,
++ })
++ .collect();
++ let completed: Vec<_> = records
++ .iter()
++ .filter_map(|event| match event {
++ AgentEvent::ModelCompleted { call_id, .. } => Some(call_id.as_str()),
++ _ => None,
++ })
++ .collect();
++ let failed: Vec<_> = records
++ .iter()
++ .filter_map(|event| match event {
++ AgentEvent::ModelFailed { call_id, .. } => Some(call_id.as_str()),
++ _ => None,
++ })
++ .collect();
++ assert_eq!(started.len(), expected_calls);
++ if expect_failure {
++ assert!(completed.is_empty());
++ assert_eq!(
++ failed, started,
++ "each failed request has one terminal event"
++ );
++ } else {
++ assert_eq!(
++ completed, started,
++ "each completed request has one terminal event"
++ );
++ assert!(failed.is_empty());
++ }
++ for (request, call_id) in requests.iter().zip(started) {
++ let correlation = request
++ .correlation
++ .as_ref()
++ .expect("host model forwards native call correlation");
++ assert_eq!(correlation.run_id, run_id.as_str());
++ assert_eq!(correlation.call_id, call_id);
++ }
++ }
++
++ run(
++ vec![
++ ModelResponse::assistant(CLEAN_REPLY),
++ ModelResponse::assistant("ACCEPT"),
++ ],
++ 2,
++ false,
++ )
++ .await;
++ run(
++ vec![
++ ModelResponse::assistant(CLEAN_REPLY),
++ ModelResponse::assistant("REJECT"),
++ ModelResponse::assistant(CLEAN_REPLY),
++ ModelResponse::assistant("ACCEPT"),
++ ],
++ 4,
++ false,
+ )
+ .await;
++ run(Vec::new(), 2, true).await;
++}
+
- 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!(
- shipped.model_calls, 4,
- "two closing calls, two verifications"
- );
++#[tokio::test(start_paused = true)]
++async fn close_stream_eof_and_timeout_emit_terminal_traces_without_timeout_usage() {
++ use std::sync::Mutex;
++ use tinyagents_harness::events::{AgentEvent, EventListener, EventSink};
++ use tinyagents_harness::ids::RunId;
++ use tinyinference_llm::model::{
++ ChatModel, ModelRequest, ModelResponse, ModelStream, ModelStreamItem,
++ };
++
++ struct EmptyOrPendingModel(bool);
++ #[async_trait::async_trait]
++ impl ChatModel<()> for EmptyOrPendingModel {
++ async fn invoke(
++ &self,
++ _state: &(),
++ _request: ModelRequest,
++ ) -> tinyinference_llm::Result<ModelResponse> {
++ Err(tinyinference_llm::Error::Model("stream only".into()))
++ }
++
++ async fn stream(
++ &self,
++ _state: &(),
++ _request: ModelRequest,
++ ) -> tinyinference_llm::Result<ModelStream> {
++ let items: std::pin::Pin<Box<dyn futures::Stream<Item = ModelStreamItem> + Send>> =
++ if self.0 {
++ Box::pin(futures::stream::pending())
++ } else {
++ Box::pin(futures::stream::empty())
++ };
++ Ok(ModelStream::new(items))
++ }
++ }
++
++ #[derive(Default)]
++ struct Recorder(Mutex<Vec<AgentEvent>>);
++ impl EventListener for Recorder {
++ fn on_event(&self, record: &tinyagents_harness::events::EventRecord) {
++ self.0.lock().unwrap().push(record.event.clone());
++ }
++ }
++
++ async fn run(pending: bool) -> (usize, usize, usize) {
++ let run_id = RunId::new(if pending {
++ "close-timeout"
++ } else {
++ "close-eof"
++ });
++ let sink = EventSink::with_stream_id(run_id.as_str());
++ let recorder = Arc::new(Recorder::default());
++ sink.subscribe(recorder.clone());
++ let trace = SupplementalTrace::new(sink, run_id);
++ let source = TurnModelSource::from_model(Arc::new(EmptyOrPendingModel(pending)));
++ let close = close_if_needed(
++ &source,
++ "host-selected-model",
++ 0.0,
++ None,
++ &tinytools_agent::dialect::NativeDialect,
++ &[],
++ "Summarize the workspace.",
++ &blank_outcome(false),
++ pending.then_some(std::time::Duration::from_secs(1)),
++ Some(&trace),
++ )
++ .await
++ .expect("blank terminal reply needs a close");
++ let records = recorder.0.lock().unwrap();
++ let started = records
++ .iter()
++ .filter(|event| matches!(event, AgentEvent::ModelStarted { .. }))
++ .count();
++ let completed = records
++ .iter()
++ .filter(|event| matches!(event, AgentEvent::ModelCompleted { .. }))
++ .count();
++ let failed = records
++ .iter()
++ .filter(|event| matches!(event, AgentEvent::ModelFailed { .. }))
++ .count();
++ if pending {
++ assert!(!close.output.is_empty(), "timeout ships a fallback");
++ assert_eq!(
++ close.usage.model_calls, 0,
++ "timeout has no completion callback"
++ );
++ assert_eq!((started, completed, failed), (1, 0, 1));
++ } else {
++ assert_eq!(
++ close.usage.model_calls, 2,
++ "each EOF retry is observed once"
++ );
++ assert_eq!((started, completed, failed), (2, 0, 2));
++ }
++ (started, completed, failed)
++ }
++
++ run(false).await;
++ run(true).await;
+ }
+
-/// 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;
+async fn required_output_repair_preserves_all_host_output_placements() {
+ use tinyagents_harness::testkit::ScriptedModel;
+
+ async fn repair(candidate: &str, reply: &str, streamed: bool) -> (String, Vec<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");
+ let (progress, mut receiver) = tokio::sync::mpsc::channel(2);
+ let output = super::repair_required_output(
+ &source,
+ "test-model",
+ 0.0,
+ None,
+ &tinytools_agent::dialect::NativeDialect,
+ &contract,
+ &[],
+ reply,
+ streamed,
+ Some(&progress),
+ 1,
+ &mut usage,
++ None,
+ )
+ .await
+ .expect("reply lacks the required block");
+ let mut deltas = Vec::new();
+ while let Ok(event) = receiver.try_recv() {
+ if let crate::progress::AgentProgress::TextDelta { delta, .. } = event {
+ deltas.push(delta);
+ }
+ }
+ (output, deltas)
+ }
- assert_eq!(shipped.output, CLEAN_REPLY);
- assert!(
- shipped.prompts[1].contains("empty or tried to call a tool"),
- "{}",
- shipped.prompts[1]
- );
- assert_eq!(
- shipped.verified,
- vec![CLEAN_REPLY.to_string()],
- "an empty candidate is not sent to the checker"
- );
+ let valid = r#"{"result":"ok","status":"ok"}"#;
+ let invalid = "not structured output";
+ let reply = "Original reply.";
+ let block = r#"{"result":"","status":""}"#;
+
+ let (valid_unstreamed, valid_unstreamed_deltas) = repair(valid, reply, false).await;
+ assert_eq!(valid_unstreamed, valid);
+ assert!(valid_unstreamed_deltas.is_empty());
+ let (valid_streamed, valid_streamed_deltas) = repair(valid, reply, true).await;
+ assert_eq!(valid_streamed, format!("{reply}\n\n{valid}"));
+ assert_eq!(valid_streamed_deltas, vec![format!("\n\n{valid}")]);
+ let (invalid_streamed, invalid_streamed_deltas) = repair(invalid, reply, true).await;
+ assert_eq!(invalid_streamed, format!("{reply}\n\n{block}"));
+ assert_eq!(invalid_streamed_deltas, vec![format!("\n\n{block}")]);
+ let (invalid_unstreamed, invalid_unstreamed_deltas) = repair(invalid, reply, false).await;
+ assert_eq!(invalid_unstreamed, format!("{block}\n\n{reply}"));
+ assert!(invalid_unstreamed_deltas.is_empty());
}
fn blank_outcome(truncated: bool) -> TinyagentsTurnOutcome {
@@@ -247,79 -232,287 +474,178 @@@
}
}
-#[tokio::test]
-async fn supplemental_close_call_emits_native_start_and_actual_completion() {
- use std::sync::{Arc, Mutex};
- use tinyagents_harness::events::{AgentEvent, EventListener, EventSink};
- use tinyagents_harness::ids::RunId;
- use tinyagents_session::transcript::TranscriptMessage;
+/// #6951: a turn that ended because the model ran out of output tokens while
+/// reasoning is closed with that cause named, not with "you have finished
+/// using tools" — which told the model its unfinished work was done.
+#[test]
+fn a_truncated_turn_is_closed_with_the_output_budget_named() {
+ let truncated = close_instruction(&blank_outcome(true), false, RECORDS);
+ assert!(
+ truncated.contains("ran out of output tokens"),
+ "{truncated}"
+ );
+ assert!(
+ !truncated.contains("You have finished using tools"),
+ "{truncated}"
+ );
+ assert!(truncated.contains("<tool_records>"), "{truncated}");
- #[derive(Default)]
- struct Recorder(Mutex<Vec<AgentEvent>>);
- impl EventListener for Recorder {
- fn on_event(&self, record: &tinyagents_harness::events::EventRecord) {
- self.0.lock().unwrap().push(record.event.clone());
- }
- }
+ let finished = close_instruction(&blank_outcome(false), false, RECORDS);
+ assert!(
+ finished.contains("You have finished using tools"),
+ "{finished}"
+ );
+}
- let run_id = RunId::new("host-supplemental-fixture");
- let sink = EventSink::with_stream_id(run_id.as_str());
- let recorder = Arc::new(Recorder::default());
- sink.subscribe(recorder.clone());
- let trace = SupplementalTrace::new(sink, run_id.clone());
- let source = TurnModelSource::from_model(Arc::new(
- tinyagents_harness::testkit::ScriptedModel::replies(vec!["supplemental answer"]),
+/// The cap checkpoint still wins when the run also hit its call cap.
+#[test]
+fn a_capped_truncated_turn_gets_the_cap_checkpoint() {
+ let out = close_instruction(&blank_outcome(true), true, RECORDS);
+ assert!(!out.contains("ran out of output tokens"), "{out}");
+ assert!(out.contains("<tool_records>"), "{out}");
+}
+
+/// 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.
+#[tokio::test(start_paused = true)]
+async fn timed_out_repair_keeps_the_usage_of_its_answered_call() {
+ use crate::progress::AgentProgress;
+ let source = crate::agent::tinyagents::TurnModelSource::from_model(std::sync::Arc::new(
+ tinyagents_harness::testkit::ScriptedModel::replies(vec!["no block"]),
));
+ let contract = tinyagents_harness::config::RequiredOutput {
+ block_key: "result".into(),
+ required_keys: vec!["status".into()],
+ };
+ // A full channel whose receiver is alive: the correction's send blocks.
+ let (progress, _receiver) = tokio::sync::mpsc::channel(1);
+ assert!(progress
+ .try_send(AgentProgress::TextDelta {
+ delta: "earlier".into(),
+ iteration: 1,
+ })
+ .is_ok());
+ let mut usage = RepairUsage::for_model("test-model");
- let (text, usage) = completion(
- &source,
- "gpt-4.1",
- 0.0,
- None,
- vec![TranscriptMessage::user("supplemental prompt")],
- Some(trace.as_ref()),
+ let repaired = tokio::time::timeout(
+ std::time::Duration::from_secs(20),
+ repair_required_output(
+ &source,
+ "test-model",
+ 0.0,
+ None,
+ &tinytools_agent::dialect::NativeDialect,
+ &contract,
+ &[],
+ "Done.",
+ true,
+ Some(&progress),
+ 2,
+ &mut usage,
++ None,
+ ),
)
.await;
- assert_eq!(text, "supplemental answer");
- assert!(usage.is_none());
- let records = recorder.0.lock().unwrap();
- let started = records
- .iter()
- .find_map(|event| match event {
- AgentEvent::ModelStarted { call_id, model } => {
- assert_eq!(model, "gpt-4.1");
- Some(call_id)
- }
- _ => None,
- })
- .expect("supplemental source emits a typed start");
- assert_eq!(
- started.as_str(),
- "host-supplemental-fixture-host-supplemental-1"
- );
- assert!(
- records.iter().any(|event| matches!(
- event,
- AgentEvent::ModelCompleted {
- call_id,
- input: Some(input),
- output: Some(output),
- ..
- } if call_id == started
- && input.to_string().contains("supplemental prompt")
- && output.to_string().contains("supplemental answer")
- )),
- "the source response is journaled with its actual IO"
- );
+ assert!(repaired.is_err(), "the blocked send outlives the budget");
+ assert_eq!(usage.model_calls, 1, "the answered repair call is recorded");
}
+
+ #[test]
+ fn supplemental_cached_response_is_marked_before_usage_without_provider_charge() {
+ use std::sync::{Arc, Mutex};
+ use tinyagents_harness::events::{AgentEvent, EventListener, EventSink};
+ use tinyagents_harness::ids::RunId;
+
+ #[derive(Default)]
+ struct Recorder(Mutex<Vec<AgentEvent>>);
+ impl EventListener for Recorder {
+ fn on_event(&self, record: &tinyagents_harness::events::EventRecord) {
+ self.0.lock().unwrap().push(record.event.clone());
+ }
+ }
+
+ let run_id = RunId::new("host-supplemental-cache-fixture");
+ let sink = EventSink::with_stream_id(run_id.as_str());
+ let recorder = Arc::new(Recorder::default());
+ sink.subscribe(recorder.clone());
+ let trace = SupplementalTrace::new(sink, run_id);
+ let (call_id, started_at_ms) = trace.begin("gpt-4.1");
+ let usage = tinyinference_llm::usage::Usage {
+ input_tokens: 14,
+ output_tokens: 3,
+ total_tokens: 17,
+ charged_amount: Some(tinyinference_llm::usage::ChargedAmount::usd_micros(900)),
+ ..Default::default()
+ };
+ let mut response = tinyinference_llm::model::ModelResponse::assistant("cached answer");
+ response.served_from_cache = true;
+ response.usage = Some(usage);
+ response.message.usage = Some(usage);
+ trace.completed(
+ call_id,
+ "gpt-4.1",
+ started_at_ms,
+ serde_json::json!(["cached prompt"]),
+ &response,
+ );
+
+ let records = recorder.0.lock().unwrap();
+ assert!(matches!(records.as_slice(), [
+ AgentEvent::ModelStarted { .. },
+ AgentEvent::ModelResponseCached { .. },
+ AgentEvent::UsageRecorded { usage },
+ AgentEvent::ModelCompleted { usage: Some(completed), .. },
+ AgentEvent::GenerationEnriched { enrichment, .. },
+ ] if usage.charged_amount.is_none()
+ && completed.charged_amount.is_none()
+ && enrichment.estimated_cost_usd.is_none()));
+ }
+
+ #[test]
+ fn supplemental_free_route_uses_zero_catalog_rates() {
+ use std::sync::{Arc, Mutex};
+ use tinyagents_harness::events::{AgentEvent, EventListener, EventSink};
+ use tinyagents_harness::ids::RunId;
+
+ #[derive(Default)]
+ struct Recorder(Mutex<Vec<AgentEvent>>);
+ impl EventListener for Recorder {
+ fn on_event(&self, record: &tinyagents_harness::events::EventRecord) {
+ self.0.lock().unwrap().push(record.event.clone());
+ }
+ }
+
+ let run_id = RunId::new("host-supplemental-free-fixture");
+ let sink = EventSink::with_stream_id(run_id.as_str());
+ let recorder = Arc::new(Recorder::default());
+ sink.subscribe(recorder.clone());
+ let trace = SupplementalTrace::new(sink, run_id);
+ let (call_id, started_at_ms) = trace.begin("openrouter/test-model:free");
+ let response = tinyinference_llm::model::ModelResponse::assistant("free answer");
+ trace.completed(
+ call_id,
+ "openrouter/test-model:free",
+ started_at_ms,
+ serde_json::json!(["free prompt"]),
+ &response,
+ );
+
+ let records = recorder.0.lock().unwrap();
+ let enrichment = records
+ .iter()
+ .find_map(|event| match event {
+ AgentEvent::GenerationEnriched { enrichment, .. } => Some(enrichment),
+ _ => None,
+ })
+ .expect("supplemental generation carries catalog enrichment");
+ let pricing = enrichment
+ .pricing
+ .as_ref()
+ .expect("free routes have known zero rates");
+ assert_eq!(pricing.input_per_mtok_usd, Some(0.0));
+ assert_eq!(pricing.cached_input_per_mtok_usd, Some(0.0));
+ assert_eq!(pricing.output_per_mtok_usd, Some(0.0));
+ assert_eq!(enrichment.estimated_cost_usd, None);
+ }
-
-/// #6951: a turn that ended because the model ran out of output tokens while
-/// reasoning is closed with that cause named, not with "you have finished
-/// using tools" — which told the model its unfinished work was done.
-#[test]
-fn a_truncated_turn_is_closed_with_the_output_budget_named() {
- let truncated = close_instruction(&blank_outcome(true), false, RECORDS);
- assert!(
- truncated.contains("ran out of output tokens"),
- "{truncated}"
- );
- assert!(
- !truncated.contains("You have finished using tools"),
- "{truncated}"
- );
- assert!(truncated.contains("<tool_records>"), "{truncated}");
-
- let finished = close_instruction(&blank_outcome(false), false, RECORDS);
- assert!(
- finished.contains("You have finished using tools"),
- "{finished}"
- );
-}
-
-/// The cap checkpoint still wins when the run also hit its call cap.
-#[test]
-fn a_capped_truncated_turn_gets_the_cap_checkpoint() {
- let out = close_instruction(&blank_outcome(true), true, RECORDS);
- assert!(!out.contains("ran out of output tokens"), "{out}");
- 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, None),
- 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.
-#[tokio::test(start_paused = true)]
-async fn timed_out_repair_keeps_the_usage_of_its_answered_call() {
- use crate::progress::AgentProgress;
- let source = crate::agent::tinyagents::TurnModelSource::from_model(std::sync::Arc::new(
- tinyagents_harness::testkit::ScriptedModel::replies(vec!["no block"]),
- ));
- let contract = tinyagents_harness::config::RequiredOutput {
- block_key: "result".into(),
- required_keys: vec!["status".into()],
- };
- // A full channel whose receiver is alive: the correction's send blocks.
- let (progress, _receiver) = tokio::sync::mpsc::channel(1);
- assert!(progress
- .try_send(AgentProgress::TextDelta {
- delta: "earlier".into(),
- iteration: 1,
- })
- .is_ok());
- let mut usage = RepairUsage::for_model("test-model");
-
- let repaired = tokio::time::timeout(
- std::time::Duration::from_secs(20),
- repair_required_output(
- &source,
- "test-model",
- 0.0,
- None,
- &tinytools_agent::dialect::NativeDialect,
- &contract,
- &[],
- "Done.",
- true,
- Some(&progress),
- 2,
- &mut usage,
- None,
- ),
- )
- .await;
-
- assert!(repaired.is_err(), "the blocked send outlives the budget");
- assert_eq!(usage.model_calls, 1, "the answered repair call is recorded");
-}
diff --cc crates/openhuman-core/src/agent/session_host/mod.rs
index 6726b46397,19fff0b244..80e7431c90
--- a/crates/openhuman-core/src/agent/session_host/mod.rs
+++ b/crates/openhuman-core/src/agent/session_host/mod.rs
@@@ -74,8 -73,8 +74,10 @@@ mod runtime_adapter_session_state_tests
#[cfg(test)]
mod runtime_adapter_tests;
#[cfg(test)]
+ mod runtime_adapter_trace_tests;
+ #[cfg(test)]
+mod runtime_adapter_usage_tests;
+#[cfg(test)]
mod transcript_compat_tests;
#[cfg(test)]
#[path = "transcript_resume_stable_tests.rs"]
diff --cc crates/openhuman-core/src/agent/tinyagents/mod.rs
index 0baed439dc,026b363c52..ae3192428c
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@@ -67,8 -69,13 +69,12 @@@ pub(crate) use crate::agent::message_co
pub(crate) use crate::inference::reasoning::{apply_requested_effort, parse_reasoning_effort};
pub use crate::inference::turn_models::TurnModelSource;
-pub(crate) use crate::inference::turn_models::TurnModels;
pub(crate) use observability::SubagentScope;
+ pub(crate) use supplemental_trace::SupplementalTrace;
pub(crate) use turn_exec::TurnSpec;
+ pub(crate) use turn_exec_native::NativeSubagentRunContext;
+ #[cfg(test)]
+ pub(crate) use turn_outcome::DeferredTurnTerminal;
pub(crate) use turn_outcome::TinyagentsTurnOutcome;
#[cfg(test)]
pub(crate) use turn_policy::is_subagent_spawn_or_delegate_tool;
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index 27b2585084,b4c6a7fc94..059f2b230f
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -31,10 -32,10 +31,10 @@@ const LEGACY_LIMIT_ENTRIES =
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 964],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 921],
["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 754],
- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 925],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1117],
+ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 922],
+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1089],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its