Skip to content

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

fix(agent): correct tool execution order in orchestration

Steven Enamakele8d7b1cb3dae
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait.rs
deleted file mode 100644
index 2519b9238e..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/wait.rs
+++ /dev/null
@@ -1,300 +0,0 @@
-//! Tool: `wait` / `wait_loop` - delayed callback ticks for the orchestrator.
-//!
-//! These tools intentionally do not own scheduling state. They sleep for a
-//! bounded duration, then return the caller-provided message as a tool result so
-//! the orchestrator can decide whether to act, poll async sub-agents, or call the
-//! loop variant again.
-
-use std::time::Duration;
-
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{PermissionLevel, Tool, ToolResult, ToolTimeout};
-
-const DEFAULT_DURATION_SECS: u64 = 5;
-const MAX_DURATION_SECS: u64 = 600;
-const MILLIS_PER_SEC: u64 = 1_000;
-
-/// One-shot delayed callback tool for the orchestrator.
-pub struct WaitTool;
-/// Repeatable delayed callback tool for orchestrator-controlled polling loops.
-pub struct WaitLoopTool;
-
-impl WaitTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for WaitTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WaitLoopTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for WaitLoopTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for WaitTool {
- fn name(&self) -> &str {
- "wait"
- }
-
- fn description(&self) -> &str {
- "Wait for a bounded duration, then return the provided callback message \
- to the orchestrator. Use this to create a delayed tick before checking \
- async work or retrying a condition."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- wait_schema(false)
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {
- timeout_policy_for_wait(args)
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- execute_wait(args, false).await
- }
-}
-
-#[async_trait]
-impl Tool for WaitLoopTool {
- fn name(&self) -> &str {
- "wait_loop"
- }
-
- fn description(&self) -> &str {
- "Wait for a bounded duration, then return the same callback message plus \
- a ready-to-call wait_loop instruction. Use this for deliberate polling \
- loops where the orchestrator decides after each tick whether to repeat."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- wait_schema(true)
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {
- timeout_policy_for_wait(args)
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- execute_wait(args, true).await
- }
-}
-
-/// Sleep for the requested duration, then return the callback tick payload.
-async fn execute_wait(args: serde_json::Value, loop_mode: bool) -> anyhow::Result<ToolResult> {
- let request = match parse_wait_request(&args) {
- Ok(request) => request,
- Err(message) => return Ok(ToolResult::error(message)),
- };
- let tool_name = if loop_mode { "wait_loop" } else { "wait" };
- log::info!(
- "[wait] tool={} duration_ms={} iteration={} loop_key={} message_chars={}",
- tool_name,
- request.duration_ms,
- request.iteration,
- request.loop_key.as_deref().unwrap_or("none"),
- request.message.chars().count()
- );
-
- tokio::time::sleep(Duration::from_millis(request.duration_ms)).await;
-
- log::debug!(
- "[wait] elapsed tool={} duration_ms={} iteration={} loop_key={}",
- tool_name,
- request.duration_ms,
- request.iteration,
- request.loop_key.as_deref().unwrap_or("none")
- );
-
- Ok(ToolResult::success(format_wait_tick(&request, loop_mode)))
-}
-
-/// Build the JSON schema shared by `wait` and `wait_loop`.
-fn wait_schema(loop_mode: bool) -> serde_json::Value {
- let mut properties = serde_json::Map::new();
- properties.insert(
- "message".to_string(),
- json!({
- "type": "string",
- "description": "Callback message to return to the orchestrator after the wait elapses."
- }),
- );
- properties.insert(
- "duration_secs".to_string(),
- json!({
- "type": "integer",
- "minimum": 1,
- "maximum": MAX_DURATION_SECS,
- "description": "Seconds to wait before returning the callback. Default 5. Ignored when duration_ms is supplied."
- }),
- );
- properties.insert(
- "duration_ms".to_string(),
- json!({
- "type": "integer",
- "minimum": 1,
- "maximum": MAX_DURATION_SECS * MILLIS_PER_SEC,
- "description": "Milliseconds to wait before returning the callback. Use only for short test-sized waits."
- }),
- );
-
- if loop_mode {
- properties.insert(
- "loop_key".to_string(),
- json!({
- "type": "string",
- "description": "Optional caller-defined key for the polling loop."
- }),
- );
- properties.insert(
- "iteration".to_string(),
- json!({
- "type": "integer",
- "minimum": 1,
- "description": "Current loop iteration. Defaults to 1; the returned instruction increments it."
- }),
- );
- }
-
- json!({
- "type": "object",
- "required": ["message"],
- "properties": serde_json::Value::Object(properties)
- })
-}
-
-/// Give the harness a deadline that covers the requested wait plus grace.
-fn timeout_policy_for_wait(args: &serde_json::Value) -> ToolTimeout {
- let duration_ms = duration_ms_from_args(args).unwrap_or(DEFAULT_DURATION_SECS * MILLIS_PER_SEC);
- let rounded_secs = duration_ms.saturating_add(MILLIS_PER_SEC - 1) / MILLIS_PER_SEC;
- ToolTimeout::Millis(
- rounded_secs
- .saturating_add(1)
- .saturating_mul(MILLIS_PER_SEC),
- )
-}
-
-/// Extract and clamp the caller's requested wait duration in milliseconds.
-fn duration_ms_from_args(args: &serde_json::Value) -> Option<u64> {
- if let Some(duration_ms) = args.get("duration_ms").and_then(|v| v.as_u64()) {
- return Some(duration_ms.clamp(1, MAX_DURATION_SECS * MILLIS_PER_SEC));
- }
- args.get("duration_secs")
- .and_then(|v| v.as_u64())
- .map(|secs| secs.clamp(1, MAX_DURATION_SECS) * MILLIS_PER_SEC)
-}
-
-/// Validate tool arguments and normalize them into an internal request.
-fn parse_wait_request(args: &serde_json::Value) -> Result<WaitRequest, String> {
- let message = args
- .get("message")
- .and_then(|v| v.as_str())
- .unwrap_or("")
- .trim()
- .to_string();
- if message.is_empty() {
- return Err("wait: `message` is required".to_string());
- }
-
- let duration_ms = duration_ms_from_args(args).unwrap_or(DEFAULT_DURATION_SECS * MILLIS_PER_SEC);
- let iteration = args
- .get("iteration")
- .and_then(|v| v.as_u64())
- .unwrap_or(1)
- .max(1);
- let loop_key = args
- .get("loop_key")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
-
- Ok(WaitRequest {
- message,
- duration_ms,
- iteration,
- loop_key,
- })
-}
-
-/// Render the delayed callback as prose plus a machine-readable `[wait_tick]`.
-fn format_wait_tick(request: &WaitRequest, loop_mode: bool) -> String {
- let seconds = request.duration_ms as f64 / MILLIS_PER_SEC as f64;
- let loop_instruction = loop_mode.then(|| {
- json!({
- "tool": "wait_loop",
- "arguments": {
- "message": request.message,
- "duration_ms": request.duration_ms,
- "loop_key": request.loop_key,
- "iteration": request.iteration + 1
- }
- })
- });
- let payload = json!({
- "status": "elapsed",
- "message": request.message,
- "duration_ms": request.duration_ms,
- "durationMs": request.duration_ms,
- "duration_secs": seconds,
- "durationSecs": seconds,
- "loop": loop_mode,
- "loop_key": request.loop_key,
- "loopKey": request.loop_key,
- "iteration": request.iteration,
- "instructions": {
- "callback_message": request.message,
- "repeat": loop_instruction
- }
- });
-
- let prefix = if loop_mode {
- format!(
- "Loop tick {} elapsed after {}ms.",
- request.iteration, request.duration_ms
- )
- } else {
- format!("Wait elapsed after {}ms.", request.duration_ms)
- };
-
- format!(
- "{prefix}\n\n[wait_tick]\n{}\n[/wait_tick]\n\n{}",
- serde_json::to_string(&payload).unwrap_or_else(|_| "{}".to_string()),
- request.message
- )
-}
-
-#[derive(Debug)]
-/// Normalized wait arguments used by both wait tools.
-struct WaitRequest {
- message: String,
- duration_ms: u64,
- iteration: u64,
- loop_key: Option<String>,
-}
-
-#[cfg(test)]
-#[path = "wait_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/wait_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/wait_tests.rs
deleted file mode 100644
index 2182450065..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/wait_tests.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-use super::*;
-
-#[test]
-fn wait_schema_requires_message() {
- let schema = WaitTool::new().parameters_schema();
- let required = schema
- .get("required")
- .and_then(|v| v.as_array())
- .expect("required list");
- assert!(required.iter().any(|v| v.as_str() == Some("message")));
- assert!(schema["properties"].get("duration_secs").is_some());
- assert!(schema["properties"].get("duration_ms").is_some());
-}
-
-#[test]
-fn wait_loop_schema_includes_loop_controls() {
- let schema = WaitLoopTool::new().parameters_schema();
- assert!(schema["properties"].get("loop_key").is_some());
- assert!(schema["properties"].get("iteration").is_some());
-}
-
-#[test]
-fn parse_wait_request_clamps_duration_and_iteration() {
- let request = parse_wait_request(&json!({
- "message": "check subagents",
- "duration_secs": 9999,
- "iteration": 0
- }))
- .unwrap();
- assert_eq!(request.duration_ms, MAX_DURATION_SECS * MILLIS_PER_SEC);
- assert_eq!(request.iteration, 1);
-}
-
-#[test]
-fn missing_message_is_rejected() {
- let err = parse_wait_request(&json!({ "duration_secs": 1 })).unwrap_err();
- assert!(err.contains("message"));
-}
-
-#[test]
-fn wait_loop_tick_repeats_same_message() {
- let request = parse_wait_request(&json!({
- "message": "poll async workers",
- "duration_ms": 10,
- "loop_key": "workers",
- "iteration": 2
- }))
- .unwrap();
- let output = format_wait_tick(&request, true);
-
- assert!(output.contains("Loop tick 2 elapsed"));
- assert!(output.contains("\"tool\":\"wait_loop\""));
- assert!(output.contains("\"message\":\"poll async workers\""));
- assert!(output.contains("\"iteration\":3"));
-}
-
-#[tokio::test]
-async fn wait_execute_returns_callback_message() {
- let res = WaitTool::new()
- .execute(json!({
- "message": "time to check",
- "duration_ms": 1
- }))
- .await
- .unwrap();
- assert!(!res.is_error);
- assert!(res.output().contains("[wait_tick]"));
- assert!(res.output().contains("time to check"));
-}
diff --git a/crates/openhuman-core/src/agent/tools/ask_clarification.rs b/crates/openhuman-core/src/agent/tools/ask_clarification.rs
deleted file mode 100644
index 3f91d477cc..0000000000
--- a/crates/openhuman-core/src/agent/tools/ask_clarification.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-//! Tool: ask_user_clarification — pause execution and ask the user a question.
-
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// Pauses the current execution to ask the user for clarification.
-///
-/// The pause is NOT implemented here — this tool only returns the question as
-/// its output. The turn stops because `ask_user_clarification` is registered as
-/// an *early-exit tool* on the harness seam
-/// (`tinyagents::run_turn_via_tinyagents_shared`'s `early_exit_tools`): on a
-/// successful call the hook records the output as the pause question and steers
-/// the loop to `Pause`, so the caller ends the turn with that question as its
-/// text instead of feeding this result back to the model.
-///
-/// Every caller that exposes this tool MUST name it in `early_exit_tools`.
-/// A caller that does not gets a tool that answers its own question: the model
-/// reads this output as a successful result and carries on without ever asking
-/// (the chat and channel paths did exactly that until this was wired up).
-pub struct AskClarificationTool;
-
-impl Default for AskClarificationTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl AskClarificationTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for AskClarificationTool {
- fn name(&self) -> &str {
- "ask_user_clarification"
- }
-
- fn description(&self) -> &str {
- "Ask the user a clarifying question when the task is ambiguous or requires \
- a decision. The question will be shown to the user and their response returned. \
- Use sparingly — only when the answer cannot be inferred from context."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "question": {
- "type": "string",
- "description": "The clarifying question to ask the user. \
- If omitted, a generic clarification prompt is used."
- },
- "options": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Optional list of choices to present to the user."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- // Blank counts as absent. The schema has no `minLength`, so
- // `{"question":""}` is a legal call, and `as_str()` answers `Some("")` —
- // which slipped past the missing-argument fallback below. That was
- // survivable only while the `[CLARIFICATION NEEDED]` prefix kept the
- // output non-empty; now that this output *is* the message the user
- // reads, an empty one would park the turn on a blank prompt: a blank
- // assistant reply on the channel path, and an `AwaitingUser` sub-agent
- // card with nothing in it. Trimmed for the same reason — a whitespace
- // question is a blank one (#6213 review).
- let question = args
- .get("question")
- .and_then(|v| v.as_str())
- .map(str::trim)
- .filter(|q| !q.is_empty())
- .unwrap_or("Could you clarify?");
-
- let options = args.get("options").and_then(|v| v.as_array()).map(|arr| {
- arr.iter()
- .filter_map(|v| v.as_str())
- .collect::<Vec<_>>()
- .join(", ")
- });
-
- // Plain question text, no marker: this output IS the message the user
- // reads. The early-exit hook captures it verbatim as the pause question,
- // which the chat path returns as the turn's reply and the sub-agent path
- // carries on `SubagentRunStatus::AwaitingUser`. Nothing anywhere parsed
- // the old `[CLARIFICATION NEEDED]` prefix — it only ever leaked into the
- // user's face.
- let mut output = question.to_string();
- if let Some(opts) = options {
- output.push_str(&format!("\n\nOptions: {opts}"));
- }
-
- tracing::info!("[ask_clarification] question: {question}");
-
- Ok(ToolResult::success(output))
- }
-}
-
-#[cfg(test)]
-#[path = "ask_clarification_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tools/ask_clarification_tests.rs b/crates/openhuman-core/src/agent/tools/ask_clarification_tests.rs
deleted file mode 100644
index 0ccecae671..0000000000
--- a/crates/openhuman-core/src/agent/tools/ask_clarification_tests.rs
+++ /dev/null
@@ -1,121 +0,0 @@
-use super::*;
-use serde_json::json;
-
-#[test]
-fn name_is_correct() {
- assert_eq!(AskClarificationTool::new().name(), "ask_user_clarification");
-}
-
-#[test]
-fn description_is_non_empty() {
- assert!(!AskClarificationTool::new().description().is_empty());
-}
-
-#[test]
-fn schema_is_object_type() {
- let schema = AskClarificationTool::new().parameters_schema();
- assert_eq!(schema["type"], "object");
-}
-
-#[test]
-fn permission_level_is_none() {
- assert_eq!(
- AskClarificationTool::new().permission_level(),
- PermissionLevel::None
- );
-}
-
-#[test]
-fn default_and_new_are_equivalent() {
- let a = AskClarificationTool::new();
- let b = AskClarificationTool::default();
- assert_eq!(a.name(), b.name());
-}
-
-#[tokio::test]
-async fn execute_with_question_includes_question_in_output() {
- let tool = AskClarificationTool::new();
- let result = tool
- .execute(json!({ "question": "Which branch should I target?" }))
- .await
- .unwrap();
- assert!(!result.is_error);
- assert!(result.output().contains("Which branch should I target?"));
-}
-
-#[tokio::test]
-async fn execute_with_options_lists_choices() {
- let tool = AskClarificationTool::new();
- let result = tool
- .execute(json!({
- "question": "Which env?",
- "options": ["staging", "production"]
- }))
- .await
- .unwrap();
- assert!(!result.is_error);
- let out = result.output();
- assert!(out.contains("staging"));
- assert!(out.contains("production"));
-}
-
-#[tokio::test]
-async fn execute_without_question_uses_fallback() {
- let tool = AskClarificationTool::new();
- let result = tool.execute(json!({})).await.unwrap();
- assert!(!result.is_error);
- assert!(result.output().contains("clarify"));
-}
-
-/// The output is the message the user reads (the early-exit hook captures it
-/// verbatim as the pause question), so it must not carry a machine marker no
-/// reader parses.
-#[tokio::test]
-async fn output_is_the_bare_question_with_no_marker() {
- let tool = AskClarificationTool::new();
- let result = tool
- .execute(json!({ "question": "Which branch should I target?" }))
- .await
- .unwrap();
- assert_eq!(result.output(), "Which branch should I target?");
-}
-
-/// A blank question must fall back to the generic prompt, not park the turn on
-/// an empty one (#6213 review).
-///
-/// The schema has no `minLength`, so `{"question":""}` is a legal call. The
-/// early-exit hook captures this output verbatim as the pause question, so an
-/// empty one reaches the user as a blank assistant reply on the channel path
-/// and an empty answer box on a delegated sub-agent's card. The old
-/// `[CLARIFICATION NEEDED]` prefix masked this by keeping the string non-empty.
-#[tokio::test]
-async fn a_blank_question_falls_back_to_the_generic_prompt() {
- let tool = AskClarificationTool::new();
- for blank in ["", " ", "\n\t "] {
- let result = tool
- .execute(serde_json::json!({ "question": blank }))
- .await
- .expect("execute");
- assert!(
- !result.output().trim().is_empty(),
- "a blank question must never produce an empty pause prompt, got {:?}",
- result.output()
- );
- assert_eq!(
- result.output(),
- "Could you clarify?",
- "a blank question must use the same fallback as a missing one"
- );
- }
-}
-
-/// The fallback must not swallow a real question that merely has padding.
-#[tokio::test]
-async fn a_padded_question_is_trimmed_but_kept() {
- let tool = AskClarificationTool::new();
- let result = tool
- .execute(serde_json::json!({ "question": " Which three sources? " }))
- .await
- .expect("execute");
- assert_eq!(result.output(), "Which three sources?");
-}
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 725f5127e8..b61fefa9a7 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 725f5127e88c4f641072ff96383ff36fa0c08839
+Subproject commit b61fefa9a7061bba7d22a818150e433fc631d8c7