Skip to content

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

feat(agent): add required output validation for harness

Steven Enamakel6da31b647a86
diff --git a/crates/openhuman-core/src/agent/harness/mod.rs b/crates/openhuman-core/src/agent/harness/mod.rs
index 8872ce0f0f..8af44d5238 100644
--- a/crates/openhuman-core/src/agent/harness/mod.rs
+++ b/crates/openhuman-core/src/agent/harness/mod.rs
@@ -32,7 +32,6 @@ pub(crate) mod graph;
pub(crate) mod memory_context;
pub(crate) mod memory_context_safety;
pub(crate) mod memory_protocol;
-pub(crate) mod required_output;
pub mod sandbox_context;
pub(crate) mod spawn_depth_context;
pub mod task_recency_context;
diff --git a/crates/openhuman-core/src/agent/harness/required_output.rs b/crates/openhuman-core/src/agent/harness/required_output.rs
deleted file mode 100644
index d3f1e933f4..0000000000
--- a/crates/openhuman-core/src/agent/harness/required_output.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! Required structured-output validation & repair (issue #4117).
-//!
-//! Some agent contracts mandate a JSON block — e.g. a `thoughts` block like
-//! `{"thoughts": "…", "next_action": "…"}` — on **every** turn, because
-//! downstream parsing/routing depends on it. Models frequently omit the block
-//! entirely, leaving those consumers with nothing.
-//!
-//! This module supplies the pure primitives the turn engine uses to guarantee a
-//! well-formed block on every accepted turn:
-//!
-//! * [`output_satisfies_contract`] — validate presence + shape of the block,
-//! * [`repair_instruction`] — the corrective re-prompt that asks the model to
-//! re-emit its reply with the block, and
-//! * [`synthesize_block`] — a minimal, schema-valid block used as a deterministic
-//! fallback when the re-prompt also omits it.
-//!
-//! The orchestration that ties these together (validate → re-prompt → synthesize)
-//! lives on the session in `session::turn::session_io` so it can drive the extra
-//! provider call and reconcile with streaming; keeping the logic here pure keeps
-//! it unit-testable without a provider.
-
-use tinyagents_harness::config::RequiredOutput;
-
-/// Whether `text` satisfies `contract`: it contains a JSON object carrying every
-/// required key with a non-null value, in the expected leading position. An
-/// inert contract (no non-blank keys) is treated as always satisfied so
-/// enforcement is a no-op.
-pub(crate) fn output_satisfies_contract(text: &str, contract: &RequiredOutput) -> bool {
- if !contract.is_active() {
- return true;
- }
- find_required_block(text, contract).is_some()
-}
-
-/// The required block when it appears in the expected **leading position** —
-/// the *first* JSON value in `text` must be an object carrying every required
-/// key with a non-null value — else `None`.
-///
-/// Issue #4117 mandates the block in a predictable position so downstream
-/// parsing/routing can rely on it. Prose before the block is fine (prose is not
-/// JSON, so the block is still the first extracted value), but a block buried
-/// after *another* JSON object is rejected and gets repaired rather than
-/// silently accepted. Reuses the harness JSON extractor so fenced, inline, and
-/// whole-object replies are all recognised.
-pub(crate) fn find_required_block(
- text: &str,
- contract: &RequiredOutput,
-) -> Option<serde_json::Value> {
- let keys = contract.all_keys();
- if keys.is_empty() {
- return None;
- }
- let first = tinytools_agent::extract_json_values(text)
- .into_iter()
- .next()?;
- let obj = first.as_object()?;
- let has_all = keys
- .iter()
- .all(|key| obj.get(key).is_some_and(|v| !v.is_null()));
- if has_all {
- Some(first)
- } else {
- None
- }
-}
-
-/// A minimal, schema-valid block synthesised when the model omits the block and
-/// a corrective re-prompt fails to recover it. Every required key maps to an
-/// empty string so downstream parsing always has a well-formed object to
-/// consume. Returns `"{}"` only for an inert contract (which enforcement never
-/// reaches).
-pub(crate) fn synthesize_block(contract: &RequiredOutput) -> String {
- let mut obj = serde_json::Map::new();
- for key in contract.all_keys() {
- obj.insert(key, serde_json::Value::String(String::new()));
- }
- serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_else(|_| "{}".to_string())
-}
-
-/// The corrective instruction that re-prompts the model to re-emit its reply
-/// with the required block. Mirrors the iteration-cap checkpoint re-prompt: a
-/// self-contained user turn appended after the omitting reply.
-///
-/// The model is asked to lead with the JSON object so the repaired reply
-/// satisfies the leading-position rule directly, whether the caller keeps the
-/// re-prompt as the whole reply (the non-streamed *replace* path) or appends it
-/// after prose that was already streamed (the *append* path); see
-/// `OpenHumanSessionHost::enforce_required_output`.
-pub(crate) fn repair_instruction(contract: &RequiredOutput) -> String {
- let keys = contract.all_keys().join("\", \"");
- format!(
- "Your previous reply omitted the required JSON `{}` block that every turn must include. \
-Reply again, leading with a single valid JSON object containing the keys \"{}\" — all present \
-and non-null — then continue with your answer. Do not call any tools.",
- contract.block_key, keys
- )
-}
-
-#[cfg(test)]
-#[path = "required_output_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/harness/required_output_tests.rs b/crates/openhuman-core/src/agent/harness/required_output_tests.rs
deleted file mode 100644
index c9c42b9aeb..0000000000
--- a/crates/openhuman-core/src/agent/harness/required_output_tests.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-use super::*;
-
-fn thoughts_contract() -> RequiredOutput {
- RequiredOutput {
- block_key: "thoughts".into(),
- required_keys: vec!["next_action".into()],
- }
-}
-
-#[test]
-fn present_well_formed_block_satisfies_contract() {
- let contract = thoughts_contract();
- let text = "Sure! {\"thoughts\": \"planning\", \"next_action\": \"call tool\"}";
- assert!(output_satisfies_contract(text, &contract));
- assert!(find_required_block(text, &contract).is_some());
-}
-
-#[test]
-fn prose_only_reply_fails_validation() {
- let contract = thoughts_contract();
- assert!(!output_satisfies_contract(
- "Sure, I'll handle that.",
- &contract
- ));
-}
-
-#[test]
-fn block_missing_a_required_sibling_key_fails() {
- let contract = thoughts_contract();
- // Has `thoughts` but not `next_action`.
- let text = "{\"thoughts\": \"planning\"}";
- assert!(!output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn null_valued_required_key_fails() {
- let contract = RequiredOutput::new("thoughts");
- assert!(!output_satisfies_contract(
- "{\"thoughts\": null}",
- &contract
- ));
-}
-
-#[test]
-fn synthesized_block_satisfies_its_own_contract() {
- let contract = thoughts_contract();
- let synthesized = synthesize_block(&contract);
- assert!(
- output_satisfies_contract(&synthesized, &contract),
- "synthesized fallback must satisfy the contract it was built from: {synthesized}"
- );
-}
-
-#[test]
-fn leading_block_after_prose_is_accepted() {
- let contract = thoughts_contract();
- // Prose before the block is fine — prose is not JSON, so the block is
- // still the first extracted value.
- let text = "Here is my plan.\n{\"thoughts\": \"x\", \"next_action\": \"y\"}";
- assert!(output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn synthesized_block_prepended_to_prose_leads_correctly() {
- // The non-streamed *replace* fallback prepends a synthesized block to the
- // original prose; the block must be the first JSON value so the reply
- // validates.
- let contract = thoughts_contract();
- let repaired = format!("{}\n\n{}", synthesize_block(&contract), "Working on it.");
- assert!(output_satisfies_contract(&repaired, &contract));
-}
-
-#[test]
-fn block_buried_after_another_json_object_is_rejected() {
- let contract = thoughts_contract();
- // A different JSON object leads; the required block is second → rejected
- // so it gets repaired rather than silently accepted (issue #4117).
- let text = "{\"foo\": 1}\n{\"thoughts\": \"x\", \"next_action\": \"y\"}";
- assert!(!output_satisfies_contract(text, &contract));
-}
-
-#[test]
-fn blank_block_key_makes_contract_inert() {
- // A blank block key is inert even when sibling keys are listed — the
- // contract's defining key can never be enforced, so enforcement is
- // skipped instead of accepting a block missing that key.
- let contract = RequiredOutput {
- block_key: " ".into(),
- required_keys: vec!["next_action".into()],
- };
- assert!(!contract.is_active());
- assert!(output_satisfies_contract(
- "{\"next_action\": \"y\"}",
- &contract
- ));
-}
-
-#[test]
-fn inert_contract_is_always_satisfied() {
- let contract = RequiredOutput::default();
- assert!(!contract.is_active());
- assert!(output_satisfies_contract("no block here", &contract));
- assert!(find_required_block("no block here", &contract).is_none());
-}
-
-#[test]
-fn all_keys_trims_and_dedupes() {
- let contract = RequiredOutput {
- block_key: " thoughts ".into(),
- required_keys: vec![
- "thoughts".into(),
- " next_action ".into(),
- "next_action".into(),
- ],
- };
- // block_key trimmed; duplicate `thoughts` and repeated `next_action`
- // collapse to a single occurrence each, order-preserving.
- assert_eq!(contract.all_keys(), vec!["thoughts", "next_action"]);
-}
-
-#[test]
-fn repair_instruction_names_every_required_key() {
- let contract = thoughts_contract();
- let instruction = repair_instruction(&contract);
- assert!(instruction.contains("thoughts"));
- assert!(instruction.contains("next_action"));
-}
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rs
index d5222132c7..6bfaa65a71 100644
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@ -312,11 +312,11 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
.is_some_and(|reason| reason.starts_with("Stopping after "));
let required_repair = match required_output.as_ref() {
Some(contract) if classified_halt => {
- if !crate::agent::harness::required_output::output_satisfies_contract(
+ if !tinyagents_harness::config::output_satisfies_contract(
&output, contract,
) {
output.push_str("\n\n");
- output.push_str(&crate::agent::harness::required_output::synthesize_block(
+ output.push_str(&tinyagents_harness::config::synthesize_block(
contract,
));
if history
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.rs
index acfbf9ed7f..95821c5a8b 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
@@ -83,7 +83,7 @@ pub(super) async fn repair_required_output(
progress: Option<&tokio::sync::mpsc::Sender<crate::agent::progress::AgentProgress>>,
iteration: u32,
) -> Option<GroundedClose> {
- use crate::agent::harness::required_output as required;
+ use tinyagents_harness::config as required;
if required::output_satisfies_contract(reply, contract) {
return None;
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
index b2b39a987c..635789ed4f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -28,7 +28,7 @@ use crate::agent::tinyagents::observability::{
};
use crate::agent::tinyagents::routes;
use crate::agent::tinyagents::stop_hooks;
-use crate::agent::tinyagents::tools::EarlyExitHook;
+use tinyagents_harness::tool::EarlyExitHook;
use crate::agent::tinyagents::turn_models::TurnModels;
use crate::agent::tinyagents::turn_outcome::{HaltSummarySlot, ToolOutcomeSink};
use crate::agent::tinyagents::turn_policy::{run_policy_for, REPEATED_TOOL_FAILURE_THRESHOLD};
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
index 3fe222b86e..2ad1df1f93 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_tool_registration.rs
@@ -18,7 +18,7 @@ use crate::agent::orchestration::tools::{
SpawnSubagentDispatch, SpawnWorkerThreadDispatch, SteerSubagentDispatch, WaitSubagentDispatch,
};
use crate::agent::tinyagents::host::OpenHumanRunContext;
-use crate::agent::tinyagents::tools::{CanonicalSharedToolAdapter, EarlyExitHook};
+use tinyagents_harness::tool::{CanonicalSharedToolAdapter, EarlyExitHook};
use crate::agent::tinyagents::turn_policy::is_subagent_spawn_or_delegate_tool;
use crate::agent::tinyagents::use_skill_dispatch::UseSkillDispatch;
use crate::agent::tools::{DelegateToolDispatch, TodoToolDispatch};
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index c69686b1bd..7e1c5e2a6f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -53,7 +53,6 @@ mod steering_forwarder;
pub(crate) mod stop_hooks;
mod summarize;
pub mod todos;
-pub(crate) mod tools;
mod topology;
mod turn_models;
mod turn_outcome;
diff --git a/crates/openhuman-core/src/agent/tinyagents/tools.rs b/crates/openhuman-core/src/agent/tinyagents/tools.rs
deleted file mode 100644
index ace45b55bb..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/tools.rs
+++ /dev/null
@@ -1,198 +0,0 @@
-//! `tinyagents` [`Tool`] adapter over an openhuman [`Tool`] (issue #4249).
-//!
-//! It resolves a tool from the session's shared registry and delegates through
-//! the canonical `tinytools::Tool` contract without creating a second tool
-//! result vocabulary.
-
-use std::sync::{Arc, Mutex, PoisonError};
-
-use async_trait::async_trait;
-use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};
-use tinytools::{Tool, ToolCallOptions, ToolResult, ToolRunContext};
-
-/// A captured early-exit: a sub-agent invoked an early-exit tool (e.g.
-/// `ask_user_clarification`), so the loop should pause and surface `question`
-/// to the user. Mirrors the legacy `run_turn_engine` `early_exit_tool` seam.
-#[derive(Debug, Clone)]
-pub(crate) struct EarlyExit {
- pub(crate) tool: String,
- pub(crate) question: String,
-}
-
-/// Shared early-exit hook handed to the adapters for the early-exit tool names.
-/// On a successful call to one of those tools it records the [`EarlyExit`] and
-/// sends a [`SteeringCommand::Pause`] so the harness loop short-circuits at the
-/// next checkpoint (before the next model call) — the tinyagents analogue of the
-/// legacy loop's "break on early-exit tool" behavior.
-#[derive(Clone)]
-pub(crate) struct EarlyExitHook {
- handle: SteeringHandle,
- slot: Arc<Mutex<Option<EarlyExit>>>,
-}
-
-impl EarlyExitHook {
- /// Build a hook that pauses `handle` and records into a fresh slot.
- pub(crate) fn new(handle: SteeringHandle) -> Self {
- Self {
- handle,
- slot: Arc::new(Mutex::new(None)),
- }
- }
-
- /// The captured early-exit, if one fired during the run.
- pub(crate) fn take(&self) -> Option<EarlyExit> {
- // #4469 item 3: recover a poisoned slot rather than panic — a panic while
- // some other tool held this lock must not swallow the early-exit.
- self.slot
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .take()
- }
-
- /// Record an early-exit and request a cooperative pause. Only the first
- /// early-exit in a run is kept (matching the legacy "halt on first").
- fn trigger(&self, tool: &str, question: String) {
- {
- // #4469 item 3: `into_inner` keeps early-exit recording working even
- // if the slot mutex was poisoned by an unrelated panic.
- let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner);
- if slot.is_none() {
- *slot = Some(EarlyExit {
- tool: tool.to_string(),
- question,
- });
- }
- }
- tracing::info!(tool, "[tinyagents] early-exit tool — requesting pause");
- self.handle.send(SteeringCommand::Pause);
- }
-}
-
-/// Canonical TinyTools adapter over the shared session tool sets.
-///
-/// The runtime now executes the canonical `tinytools::Tool` contract directly;
-/// this wrapper only resolves a non-cloneable tool from the shared registry and
-/// preserves the early-exit control hook.
-pub(crate) struct CanonicalSharedToolAdapter {
- sets: Vec<Arc<Vec<Box<dyn Tool>>>>,
- name: String,
- description: String,
- parameters_schema: serde_json::Value,
- early_exit: Option<EarlyExitHook>,
-}
-
-impl CanonicalSharedToolAdapter {
- pub(crate) fn for_name(sets: Vec<Arc<Vec<Box<dyn Tool>>>>, name: &str) -> Option<Self> {
- let spec = sets
- .iter()
- .flat_map(|set| set.iter())
- .find(|tool| tool.name() == name)
- .map(|tool| tool.spec())?;
- Some(Self {
- sets,
- name: spec.name,
- description: spec.description,
- parameters_schema: spec.parameters,
- early_exit: None,
- })
- }
-
- pub(crate) fn with_early_exit(mut self, hook: EarlyExitHook) -> Self {
- self.early_exit = Some(hook);
- self
- }
-
- fn resolved_tool(&self) -> Option<&dyn Tool> {
- self.sets
- .iter()
- .flat_map(|set| set.iter())
- .find(|tool| tool.name() == self.name)
- .map(|tool| tool.as_ref())
- }
-}
-
-#[async_trait]
-impl Tool for CanonicalSharedToolAdapter {
- fn name(&self) -> &str {
- &self.name
- }
-
- fn description(&self) -> &str {
- &self.description
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- self.parameters_schema.clone()
- }
-
- fn policy(&self) -> tinytools::ToolPolicy {
- self.resolved_tool().map(Tool::policy).unwrap_or_default()
- }
-
- /// Forwarded so the harness indexes `Deferred` registrations for its
- /// `tool_search` bridge instead of advertising them. Without this every
- /// registered tool reported `Direct` and the bridge stayed inert.
- ///
- /// `Hidden` is **not** forwarded. The host is the exposure policy owner:
- /// the session builder already drops every `Hidden` registration from a
- /// wildcard belt, so a `Hidden` tool that reaches harness registration was
- /// named by hand in a `[tools] named` belt (`memory_recall` on the
- /// orchestrator, the `memory_*` readers on `flow_memory_agent`) or is a
- /// synthesised specialist route the belt admitted. Forwarding `Hidden`
- /// made the harness advertise 14 of the orchestrator's 25 visible tools
- /// while the prompt described all 25 (#6370): every `research` / `plan` /
- /// `memory_*` call the model was told about was unreachable.
- fn exposure(&self) -> tinytools::ToolExposure {
- match self.resolved_tool().map(Tool::exposure) {
- Some(tinytools::ToolExposure::Deferred) => tinytools::ToolExposure::Deferred,
- _ => tinytools::ToolExposure::Direct,
- }
- }
-
- fn family(&self) -> Option<&str> {
- self.resolved_tool().and_then(Tool::family)
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(
- args,
- ToolCallOptions {
- prefer_markdown: true,
- },
- None,
- )
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let Some(tool) = self.resolved_tool() else {
- tracing::warn!(tool = %self.name, "[tinyagents] shared tool not found");
- return Ok(ToolResult::error(format!("unknown tool '{}'", self.name)));
- };
- // A callable tool's operational failure is input to the agent loop, not
- // a failure of the harness itself. Preserve it as an error result so
- // the model can recover (or explain the failure) on its next round.
- let result = match tool.execute_with_context(args, options, context).await {
- Ok(result) => result,
- Err(error) => {
- tracing::warn!(tool = %self.name, %error, "[tinyagents] shared tool execution failed");
- ToolResult::error(format!("{} failed: {error}", self.name))
- }
- };
- if !result.is_error {
- if let Some(hook) = &self.early_exit {
- hook.trigger(&self.name, result.output_for_llm(true));
- }
- }
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "tools_canonical_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs
deleted file mode 100644
index a44a11c47f..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/tools_canonical_tests.rs
+++ /dev/null
@@ -1,244 +0,0 @@
-use super::*;
-
-use std::sync::atomic::{AtomicBool, Ordering};
-
-use tinytools::{ToolContent, ToolPolicy};
-
-struct RecordingTool {
- saw_context: AtomicBool,
-}
-
-#[async_trait]
-impl Tool for RecordingTool {
- fn name(&self) -> &str {
- "recording"
- }
-
- fn description(&self) -> &str {
- "Preserves the canonical TinyTools contract."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object", "properties": {"fail": {"type": "boolean"}}})
- }
-
- fn policy(&self) -> ToolPolicy {
- ToolPolicy::read_only().requiring_approval()
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- self.saw_context.store(
- context.is_some() && options.prefer_markdown,
- Ordering::SeqCst,
- );
- Ok(ToolResult {
- content: vec![
- ToolContent::Text {
- text: "plain content".to_string(),
- },
- ToolContent::Json {
- data: serde_json::json!({"preserved": true}),
- },
- ],
- is_error: args["fail"].as_bool().unwrap_or(false),
- markdown_formatted: Some("markdown content".to_string()),
- ..ToolResult::default()
- })
- }
-}
-
-struct TestToolRunContext;
-impl ToolRunContext for TestToolRunContext {}
-
-#[tokio::test]
-async fn canonical_adapter_preserves_spec_policy_context_and_result() {
- let seen_context = Arc::new(AtomicBool::new(false));
- struct SharedRecordingTool(Arc<AtomicBool>);
- #[async_trait]
- impl Tool for SharedRecordingTool {
- fn name(&self) -> &str {
- "recording"
- }
- fn description(&self) -> &str {
- "Preserves the canonical TinyTools contract."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
- fn policy(&self) -> ToolPolicy {
- ToolPolicy::read_only().requiring_approval()
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- self.0.store(
- context.is_some() && options.prefer_markdown,
- Ordering::SeqCst,
- );
- Ok(ToolResult {
- content: vec![
- ToolContent::Text {
- text: "plain content".into(),
- },
- ToolContent::Json {
- data: serde_json::json!({"preserved": true}),
- },
- ],
- is_error: args["fail"].as_bool().unwrap_or(false),
- markdown_formatted: Some("markdown content".into()),
- ..ToolResult::default()
- })
- }
- }
- let sets: Vec<Arc<Vec<Box<dyn Tool>>>> = vec![Arc::new(vec![Box::new(SharedRecordingTool(
- seen_context.clone(),
- ))])];
- let adapter = CanonicalSharedToolAdapter::for_name(sets, "recording").expect("registered tool");
-
- assert_eq!(adapter.name(), "recording");
- assert_eq!(
- adapter.description(),
- "Preserves the canonical TinyTools contract."
- );
- assert_eq!(
- adapter.parameters_schema(),
- serde_json::json!({"type": "object"})
- );
- assert_eq!(
- adapter.policy(),
- ToolPolicy::read_only().requiring_approval()
- );
-
- let result = adapter
- .execute_with_context(
- serde_json::json!({"fail": true}),
- ToolCallOptions::prefer_markdown(),
- Some(&TestToolRunContext),
- )
- .await
- .expect("canonical result");
- assert!(seen_context.load(Ordering::SeqCst));
- assert!(result.is_error);
- assert_eq!(
- result.markdown_formatted.as_deref(),
- Some("markdown content")
- );
- assert_eq!(result.content.len(), 2);
- assert!(matches!(result.content[0], ToolContent::Text { ref text } if text == "plain content"));
- assert!(
- matches!(result.content[1], ToolContent::Json { ref data } if data == &serde_json::json!({"preserved": true}))
- );
-}
-
-#[tokio::test]
-async fn canonical_adapter_fails_closed_when_the_registered_tool_is_gone() {
- let adapter = CanonicalSharedToolAdapter {
- sets: Vec::new(),
- name: "missing".to_string(),
- description: "missing".to_string(),
- parameters_schema: serde_json::json!({"type": "object"}),
- early_exit: None,
- };
-
- let result = adapter
- .execute(serde_json::json!({}))
- .await
- .expect("reported failure");
- assert!(result.is_error);
- assert_eq!(result.output(), "unknown tool 'missing'");
-}
-
-#[tokio::test]
-async fn early_exit_only_fires_after_a_successful_canonical_result() {
- let sets: Vec<Arc<Vec<Box<dyn Tool>>>> = vec![Arc::new(vec![Box::new(RecordingTool {
- saw_context: AtomicBool::new(false),
- })])];
- let hook = EarlyExitHook::new(SteeringHandle::allow_all());
- let adapter = CanonicalSharedToolAdapter::for_name(sets, "recording")
- .expect("registered tool")
- .with_early_exit(hook.clone());
-
- let failed = adapter
- .execute(serde_json::json!({"fail": true}))
- .await
- .expect("reported failure");
- assert!(failed.is_error);
- assert!(
- hook.take().is_none(),
- "reported tool errors must not pause the run"
- );
-
- let successful = adapter
- .execute(serde_json::json!({"fail": false}))
- .await
- .expect("success");
- assert!(!successful.is_error);
- let early_exit = hook
- .take()
- .expect("successful early-exit tool pauses the run");
- assert_eq!(early_exit.tool, "recording");
- assert_eq!(early_exit.question, "markdown content");
-}
-
-struct ExposedTool(&'static str, tinytools::ToolExposure);
-
-#[async_trait]
-impl Tool for ExposedTool {
- fn name(&self) -> &str {
- self.0
- }
-
- fn description(&self) -> &str {
- "exposure probe"
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- serde_json::json!({"type": "object"})
- }
-
- fn exposure(&self) -> tinytools::ToolExposure {
- self.1
- }
-
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::default())
- }
-}
-
-/// The host decides what a belt advertises; the harness only needs to know
-/// which admitted registrations are searchable rather than advertised. A
-/// `Hidden` tool that reached registration was named by the belt, so it is
-/// advertised; `Deferred` stays deferred (#6370).
-#[test]
-fn adapter_advertises_admitted_hidden_tools_and_keeps_deferred_ones_deferred() {
- let set: Arc<Vec<Box<dyn Tool>>> = Arc::new(vec![
- Box::new(ExposedTool("direct", tinytools::ToolExposure::Direct)),
- Box::new(ExposedTool("hidden", tinytools::ToolExposure::Hidden)),
- Box::new(ExposedTool("deferred", tinytools::ToolExposure::Deferred)),
- ]);
- let exposure = |name: &str| {
- CanonicalSharedToolAdapter::for_name(vec![set.clone()], name)
- .expect("registered")
- .exposure()
- };
- assert_eq!(exposure("direct"), tinytools::ToolExposure::Direct);
- assert_eq!(exposure("hidden"), tinytools::ToolExposure::Direct);
- assert_eq!(exposure("deferred"), tinytools::ToolExposure::Deferred);
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
index 7b5c8de994..64c03bf7dd 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs
@@ -15,7 +15,7 @@ use tokio::sync::mpsc::Sender;
use crate::agent::progress::AgentProgress;
use crate::agent::tinyagents::journal::TurnJournal;
use crate::agent::tinyagents::observability::{self, OpenhumanEventBridge, SubagentScope};
-use crate::agent::tinyagents::tools::EarlyExitHook;
+use tinyagents_harness::tool::EarlyExitHook;
use crate::agent::tinyagents::turn_outcome::{
HaltSummarySlot, TinyagentsTurnOutcome, ToolOutcomeSink,
};
diff --git a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch.rs b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch.rs
index ec70e4acb2..7fdfb9eb17 100644
--- a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch.rs
@@ -104,7 +104,7 @@ impl ToolDispatch<(), OpenHumanRunContext> for UseSkillDispatch {
// had the model reached `name` directly instead of through
// `use_skill`.
let Some(inner_adapter) =
- super::tools::CanonicalSharedToolAdapter::for_name(vec![tools], &name)
+ tinyagents_harness::tool::CanonicalSharedToolAdapter::for_name(vec![tools], &name)
.map(|adapter| Arc::new(adapter) as Arc<dyn Tool>)
else {
return self
diff --git a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs
index 5a5c76a8b2..f69fc168ef 100644
--- a/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/use_skill_dispatch_tests.rs
@@ -17,7 +17,7 @@ use super::*;
use crate::agent::harness::definition::AgentDefinitionRegistry;
use crate::agent::harness::ParentExecutionContext;
use crate::agent::prompts::ToolCallFormat;
-use crate::agent::tinyagents::tools::CanonicalSharedToolAdapter;
+use tinyagents_harness::tool::CanonicalSharedToolAdapter;
use crate::memory::{Memory, MemoryCategory, MemoryEntry, NamespaceSummary, RecallOpts};
use crate::tools::toolpacks::tools::{PackRegistryHandle, UseSkillTool};
use async_trait::async_trait;