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
feat(agent): hold a turn that never wrote the file its request named
killbille9ad8a8defc9
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsindex d7f392e287..de4c4d3c86 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs@@ -592,6 +592,15 @@ pub(super) fn assemble_turn_harness(tool_policy.as_ref().map(|p| p.agent_definition_id.as_str()),&wrap_up_fired,);+ // The rungs above all *tell* the turn to produce its deliverable; this one+ // looks. Same scope as the requirements check: a sub-agent answers to its+ // parent, and the parent's own request is the one that names a file.+ if verify_before_finish::applies(+ subagent_scope.is_some(),+ tool_policy.as_ref().map(|p| p.agent_definition_id.as_str()),+ ) {+ harness.push_middleware(Arc::new(middleware::UnmetDeliverableMiddleware::new()));+ }// Direct web lookup is bounded. Once enough search/fetch results have// returned, the web tools leave the request so the run works with what itdiff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rsindex a5448fcd15..04b85c3529 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs@@ -44,6 +44,7 @@ mod tool_output;mod tool_output_file_read;mod tool_policy;mod turn_context;+mod unmet_deliverable;pub(crate) use approval::ApprovalSecurityMiddleware;pub(crate) use cli_rpc_only::CliRpcOnlyMiddleware;@@ -62,6 +63,7 @@ pub(crate) use tool_policy::ToolPolicyMiddleware;pub(crate) use turn_context::{render_unanswered_steps, TranscriptSnapshot, TranscriptSnapshotSink, TurnContextMiddleware,};+pub(crate) use unmet_deliverable::UnmetDeliverableMiddleware;/// Render the canonical TinyTools content blocks at the OpenHuman boundary./// Middleware that used the retired string-shaped harness result must notdiff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rsnew file mode 100644index 0000000000..014f523b6d--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable.rs@@ -0,0 +1,292 @@+//! A named output file that was never written, caught before the turn ends.+//!+//! # Why this exists+//!+//! The turn already carries four rungs that *tell* the model to produce its+//! deliverable: the budget notice part-way through, the penultimate call's+//! narrowed writer belt, the concluding call's instruction, and the+//! requirements check. Every one of them is advice, and the orchestrator+//! prompt's rule ("when the request names an output file, that file is the+//! deliverable") is advice too. None of them observes whether anything was+//! written, so a turn that ignores all five ends with a careful account of+//! work nobody can use.+//!+//! That is not hypothetical. One run reconstructed a transcript, catalogued+//! eleven variants and resolved the domain it was asked for, listed the output+//! file in its own answer as "still outstanding", and ended the turn. Every+//! check that read the file failed on the file's absence rather than on+//! anything it contained; an earlier run of the same request, which wrote a+//! partly-filled file, was scored on its contents.+//!+//! # How a path is identified without parsing the request+//!+//! The obvious objection to reading paths out of a request is telling an+//! output from an input: a request routinely names both. Grammar ("write to"+//! versus "read from") would be the fragile way to decide.+//!+//! The existence check decides it instead, for free. A path the request names+//! as an input is already on disk, so it is never reported. A path that the+//! request names and that nothing has created is, by construction, either a+//! deliverable that was skipped or a path the request mentioned in passing —+//! and the cost of the second case is one advisory sentence.++use std::collections::{HashMap, HashSet};+use std::sync::Mutex;++use async_trait::async_trait;+use tinyagents_harness::context::RunContext;+use tinyagents_harness::error::{Result, TinyAgentsError};+use tinyagents_harness::middleware::Middleware;+use tinyagents_harness::tinyinference_llm::message::Message;+use tinyagents_harness::tinyinference_llm::model::{ModelRequest, ModelResponse};++use crate::agent::session_host::turn_checkpoint::wrap_harness_instruction;++/// Leave the model room to act on the notice. Below this the turn cannot both+/// write a file and answer, so the notice would only cost a call.+const MIN_REMAINING_MODEL_CALLS: usize = 3;++/// How many candidates one request may contribute. A request naming more+/// absolute paths than this is describing a tree, not a deliverable, and+/// statting an unbounded list on the concluding call is not worth it.+const MAX_CANDIDATES: usize = 8;++/// Longest plausible path. Anything longer is prose that happens to contain+/// slashes.+const MAX_PATH_CHARS: usize = 200;++/// Characters that continue a path token. Everything else — whitespace,+/// quotes, backticks, brackets, commas — ends it.+fn is_path_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-' | '+' | '@' | '%')+}++/// Whether `segment` ends in a file extension: a dot followed by 1-8+/// alphanumerics, and not the whole segment (so a dotfile is not an+/// extension).+fn has_extension(segment: &str) -> bool {+ match segment.rsplit_once('.') {+ Some((stem, ext)) => {+ !stem.is_empty()+ && (1..=8).contains(&ext.len())+ && ext.chars().all(|c| c.is_ascii_alphanumeric())+ }+ None => false,+ }+}++/// Absolute paths with a file extension that `text` names, in order, deduped+/// and capped at [`MAX_CANDIDATES`].+///+/// Absolute only: a relative token in prose ("see config/settings.yml") is far+/// more often a reference than a deliverable, and a relative path cannot be+/// resolved without assuming the turn's working directory. An extension is+/// required for the same reason — it is what separates a file the request asks+/// for from a directory or a sentence fragment. Both limits mean this reports+/// nothing rather than guessing when a request is written loosely.+pub(crate) fn candidate_paths(text: &str) -> Vec<String> {+ let mut seen = HashSet::new();+ let mut out = Vec::new();+ let bytes: Vec<char> = text.chars().collect();+ let mut index = 0;+ while index < bytes.len() {+ if bytes[index] != '/' {+ index += 1;+ continue;+ }+ // A path starts at a `/` that does not continue a token (so `a/b` in+ // prose is not read as rooted at `/b`).+ if index > 0 && is_path_char(bytes[index - 1]) {+ index += 1;+ continue;+ }+ let start = index;+ while index < bytes.len() && is_path_char(bytes[index]) {+ index += 1;+ }+ let token: String = bytes[start..index].iter().collect();+ let token = token.trim_end_matches(['.', '-', '_', '+']);+ if token.len() < 3 || token.len() > MAX_PATH_CHARS {+ continue;+ }+ // `..` is never statted: a request that needs traversal to name its+ // own output is not a case this should act on.+ if token.contains("..") {+ continue;+ }+ let mut segments = token.split('/').filter(|s| !s.is_empty());+ let Some(first) = segments.next() else {+ continue;+ };+ let Some(last) = token.rsplit('/').next() else {+ continue;+ };+ // At least two segments: `/report.json` at the filesystem root is far+ // more likely a stray token than a deliverable.+ if first == last || !has_extension(last) {+ continue;+ }+ if seen.insert(token.to_string()) {+ out.push(token.to_string());+ if out.len() >= MAX_CANDIDATES {+ break;+ }+ }+ }+ out+}++/// The notice, naming every candidate that does not exist.+pub(crate) fn notice(missing: &[String]) -> String {+ let list = missing+ .iter()+ .map(|path| format!("`{path}`"))+ .collect::<Vec<_>>()+ .join(", ");+ let (subject, verb) = if missing.len() == 1 {+ ("a file", "does not exist")+ } else {+ ("files", "do not exist")+ };+ wrap_harness_instruction(&format!(+ "The request names {subject} that {verb}: {list}. Nothing has been written there, so \+ none of this turn's work is available to whoever asked for it. Write it now with \+ whatever you have established, even where fields are incomplete or provisional, and \+ then answer. A file holding the parts you are sure of is worth more than a \+ description of what it would have contained; mark anything provisional inside it, or \+ say in your reply what is still missing."+ ))+}++/// Per-run state: the candidates read off the request, and whether the notice+/// has already been given.+#[derive(Default)]+struct RunState {+ candidates: Option<Vec<String>>,+ fired: bool,+}++/// Holds a turn's first final answer once, when the request named an output+/// file that nothing has created. See the module docs.+pub(crate) struct UnmetDeliverableMiddleware {+ runs: Mutex<HashMap<u64, RunState>>,+}++impl UnmetDeliverableMiddleware {+ pub(crate) fn new() -> Self {+ Self {+ runs: Mutex::default(),+ }+ }++ /// Which of `candidates` are absent. Existence only: nothing is opened or+ /// read, and the paths echoed back are the ones the request already+ /// carried.+ fn missing(candidates: &[String]) -> Vec<String> {+ candidates+ .iter()+ .filter(|path| !std::path::Path::new(path.as_str()).exists())+ .cloned()+ .collect()+ }++ /// Why this response must not be held, or `None` when it may be.+ fn skip_reason<C>(ctx: &RunContext<C>, response: &ModelResponse) -> Option<&'static str> {+ if !response.tool_calls().is_empty() {+ return Some("not_final");+ }+ if response.text().trim().is_empty() {+ return Some("empty_answer");+ }+ if response.finish_reason.as_deref() == Some("length") {+ return Some("truncated");+ }+ if response.continue_turn.is_some() {+ return Some("already_continued");+ }+ if ctx.limits.remaining_model_calls() < MIN_REMAINING_MODEL_CALLS {+ return Some("model_call_budget");+ }+ None+ }+}++#[async_trait]+impl<C: Send + Sync> Middleware<(), C> for UnmetDeliverableMiddleware {+ fn name(&self) -> &str {+ "unmet_deliverable"+ }++ async fn before_model(+ &self,+ ctx: &mut RunContext<C>,+ _state: &(),+ request: &mut ModelRequest,+ ) -> Result<()> {+ let Ok(mut runs) = self.runs.lock() else {+ return Ok(());+ };+ let run = runs.entry(ctx.instance_id()).or_default();+ if run.candidates.is_some() {+ return Ok(());+ }+ // The request is the turn's first user message; later user turns are+ // this harness's own injections and the model's follow-ups.+ let text = request+ .messages+ .iter()+ .find(|message| matches!(message, Message::User(_)))+ .map(Message::text)+ .unwrap_or_default();+ run.candidates = Some(candidate_paths(&text));+ Ok(())+ }++ async fn after_model(+ &self,+ ctx: &mut RunContext<C>,+ _state: &(),+ response: &mut ModelResponse,+ ) -> Result<()> {+ let candidates = {+ let Ok(runs) = self.runs.lock() else {+ return Ok(());+ };+ match runs.get(&ctx.instance_id()) {+ Some(run) if !run.fired => run.candidates.clone().unwrap_or_default(),+ _ => return Ok(()),+ }+ };+ if candidates.is_empty() {+ return Ok(());+ }+ if let Some(reason) = Self::skip_reason(ctx, response) {+ tracing::debug!(reason, "[unmet_deliverable] not holding this answer");+ return Ok(());+ }+ let missing = Self::missing(&candidates);+ if missing.is_empty() {+ return Ok(());+ }+ if let Ok(mut runs) = self.runs.lock() {+ runs.entry(ctx.instance_id()).or_default().fired = true;+ }+ tracing::info!(+ missing = missing.len(),+ "[unmet_deliverable] holding the answer: a named output file was never written"+ );+ response.continue_turn = Some(notice(&missing));+ Ok(())+ }++ async fn on_error(&self, ctx: &mut RunContext<C>, _error: &TinyAgentsError) -> Result<()> {+ if let Ok(mut runs) = self.runs.lock() {+ runs.remove(&ctx.instance_id());+ }+ Ok(())+ }+}++#[cfg(test)]+#[path = "unmet_deliverable_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rsnew file mode 100644index 0000000000..bfd2706352--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/unmet_deliverable_tests.rs@@ -0,0 +1,205 @@+use super::*;++use std::sync::Arc;++use tinyagents_harness::limits::RunLimits;+use tinyagents_harness::runtime::{AgentHarness, RunPolicy};+use tinyagents_harness::testkit::{FakeTool, ScriptedModel};+use tinyagents_harness::tinyinference_llm::tool::ToolCall;++/// The real request this middleware was built for names three inputs and one+/// output. Extraction deliberately cannot tell them apart -- that is the+/// existence check's job -- so it must return all four.+const ATRX_REQUEST: &str = "Catalogue all coding variants present in the mutated ATRX \+ transcripts at /app/data/mutated-transcripts.txt relative to the wild-type NM_000489.6 \+ reference (encoded by /app/data/genomic-locus.fa and the CDS information at \+ /app/data/CDS-information.txt). Write the final results to \+ /app/output/mutation.report.json as a single JSON object.";++#[test]+fn extraction_returns_every_named_file_input_and_output_alike() {+ assert_eq!(+ candidate_paths(ATRX_REQUEST),+ vec![+ "/app/data/mutated-transcripts.txt",+ "/app/data/genomic-locus.fa",+ "/app/data/CDS-information.txt",+ "/app/output/mutation.report.json",+ ]+ );+}++/// The design claim: separating a deliverable from an input needs no grammar,+/// because an input is on disk and a skipped deliverable is not.+#[test]+fn existence_alone_separates_a_skipped_deliverable_from_the_inputs() {+ let dir = std::env::temp_dir().join(format!("oh-unmet-{}", std::process::id()));+ std::fs::create_dir_all(&dir).expect("temp dir");+ let input = dir.join("given.txt");+ std::fs::write(&input, b"provided").expect("write input");+ let output = dir.join("report.json");+ let _ = std::fs::remove_file(&output);++ let candidates = vec![+ input.to_string_lossy().to_string(),+ output.to_string_lossy().to_string(),+ ];+ assert_eq!(+ UnmetDeliverableMiddleware::missing(&candidates),+ vec![output.to_string_lossy().to_string()],+ "the input must not be reported; only the path nothing created"+ );++ // Once written, even empty, it stops being reported: this middleware+ // checks existence, never contents.+ std::fs::write(&output, b"{}").expect("write output");+ assert!(UnmetDeliverableMiddleware::missing(&candidates).is_empty());+ let _ = std::fs::remove_dir_all(&dir);+}++#[test]+fn only_absolute_paths_carrying_a_file_extension_are_candidates() {+ for rejected in [+ "see config/settings.yml for the rest", // relative: a reference, not a deliverable+ "write it under /app/output/", // a directory, no extension+ "results go in /report.json", // single segment at the root+ "read /app/../etc/passwd", // traversal is never statted+ "the ratio is 3/4.5 overall", // arithmetic, not a path+ ] {+ assert!(+ candidate_paths(rejected).is_empty(),+ "must not treat {rejected:?} as a deliverable: {:?}",+ candidate_paths(rejected)+ );+ }+}++#[test]+fn a_path_is_recognised_through_the_punctuation_a_request_wraps_it_in() {+ for (text, expected) in [+ ("write to `/app/out/r.json`.", "/app/out/r.json"),+ ("write to \"/app/out/r.json\",", "/app/out/r.json"),+ ("write to (/app/out/r.json)", "/app/out/r.json"),+ ("write to /app/out/r.json.", "/app/out/r.json"),+ ("write to </app/out/r.json>", "/app/out/r.json"),+ ] {+ assert_eq!(candidate_paths(text), vec![expected], "for {text:?}");+ }+}++#[test]+fn a_repeated_path_is_reported_once_and_a_long_list_is_bounded() {+ let twice = "first /a/b/c.json then /a/b/c.json again";+ assert_eq!(candidate_paths(twice), vec!["/a/b/c.json"]);++ let many = (0..20)+ .map(|i| format!("/dir/file{i}.json"))+ .collect::<Vec<_>>()+ .join(" ");+ assert_eq!(candidate_paths(&many).len(), MAX_CANDIDATES);+}++#[test]+fn the_notice_names_the_paths_and_asks_for_a_partial_file() {+ let one = notice(&["/app/output/r.json".to_string()]);+ assert!(one.contains("<harness_instruction>"));+ assert!(one.contains("a file that does not exist"));+ assert!(one.contains("`/app/output/r.json`"));+ assert!(one.contains("even where fields are incomplete or provisional"));++ let two = notice(&["/a/x.json".to_string(), "/b/y.csv".to_string()]);+ assert!(two.contains("files that do not exist"));+ assert!(two.contains("`/a/x.json`, `/b/y.csv`"));+}++fn tool_round(id: &str, name: &str) -> tinyagents_harness::tinyinference_llm::model::ModelResponse {+ let mut response =+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(String::new());+ response.message.content = Vec::new();+ response.message.tool_calls = vec![ToolCall::new(id, name, serde_json::json!({}))];+ response.finish_reason = Some("tool_calls".to_string());+ response+}++/// Drive a run whose request names a path that does not exist. The notice has+/// to reach the model, leave it free to call tools, and let its second answer+/// stand -- and it must not be given twice.+#[tokio::test]+async fn an_unwritten_deliverable_holds_the_answer_once_and_permits_a_fix() {+ let missing = std::env::temp_dir().join(format!("oh-unmet-run-{}.json", std::process::id()));+ let _ = std::fs::remove_file(&missing);+ let request = format!("Do the work and write it to {}", missing.display());++ let mut harness: AgentHarness<()> = AgentHarness::new();+ harness.register_model(+ "mock",+ Arc::new(ScriptedModel::new(vec![+ tool_round("c0", "writer"),+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(+ "here is what I found".to_string(),+ ),+ tool_round("c1", "writer"),+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(+ "written and answered".to_string(),+ ),+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(+ "must not be reached".to_string(),+ ),+ ])),+ );+ harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));+ harness.with_policy(RunPolicy {+ limits: RunLimits::default()+ .with_max_model_calls(20)+ .with_max_tool_calls(20),+ ..RunPolicy::default()+ });+ harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new()));++ let run = harness+ .invoke_default(&(), vec![Message::user(request)])+ .await+ .expect("run succeeds");++ assert_eq!(run.text().as_deref(), Some("written and answered"));+ let notices = run+ .messages+ .iter()+ .filter(|m| matches!(m, Message::User(_)) && m.text().contains("does not exist"))+ .count();+ assert_eq!(+ notices, 1,+ "the notice must be given once, not every answer"+ );+}++/// A request that names nothing, or names only files that exist, must cost the+/// turn nothing: the first answer stands.+#[tokio::test]+async fn a_request_naming_no_missing_file_is_left_alone() {+ let mut harness: AgentHarness<()> = AgentHarness::new();+ harness.register_model(+ "mock",+ Arc::new(ScriptedModel::new(vec![+ tool_round("c0", "writer"),+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(+ "done".to_string(),+ ),+ tinyagents_harness::tinyinference_llm::model::ModelResponse::assistant(+ "must not be reached".to_string(),+ ),+ ])),+ );+ harness.register_tool(Arc::new(FakeTool::returning("writer", "ok")));+ harness.with_policy(RunPolicy {+ limits: RunLimits::default().with_max_model_calls(20),+ ..RunPolicy::default()+ });+ harness.push_middleware(Arc::new(UnmetDeliverableMiddleware::new()));++ let run = harness+ .invoke_default(&(), vec![Message::user("summarise the situation for me")])+ .await+ .expect("run succeeds");+ assert_eq!(run.text().as_deref(), Some("done"));+}