Skip to content

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

feat(agent): add turn progress tracking for agent turns

Steven Enamakel12fb12c7dc3b
diff --git a/crates/openhuman-core/src/agent/turn_progress.rs b/crates/openhuman-core/src/agent/turn_progress.rs
new file mode 100644
index 0000000000..5948abf39a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/turn_progress.rs
@@ -0,0 +1,381 @@
+//! `AgentProgress` -> canonical `ChannelOutputEvent`.
+//!
+//! The one place a turn's progress becomes the shared output vocabulary. The
+//! web adapter (`tinychannels-runtime`) projects it onto the web wire, so this
+//! file builds no `WebChannelEvent`. Payload caps are applied here, before the
+//! projection, so a multi-megabyte tool result never reaches the socket.
+
+use serde::Serialize;
+use serde_json::Value;
+use tinychannels_bus::module_progressive::{
+ ChannelOutputEvent, SubagentOutput, SubagentUsage, ToolFailureSummary,
+};
+use tinychannels_bus::web::{cap_web_args, cap_web_output};
+
+use tinyagents_harness::progress::AgentProgress;
+
+type Failure = tinytools::status::ClassifiedFailure;
+
+/// Wire spelling of a unit-variant enum (`ClassifiedFailure` serializes its
+/// class and category as the bare variant name).
+fn variant_name<T: Serialize>(value: &T) -> String {
+ serde_json::to_value(value)
+ .ok()
+ .and_then(|json| json.as_str().map(str::to_owned))
+ .unwrap_or_default()
+}
+
+fn failure_summary(failure: &Failure) -> ToolFailureSummary {
+ ToolFailureSummary {
+ class: variant_name(&failure.class),
+ category: variant_name(&failure.category),
+ cause_plain: failure.cause_plain.clone(),
+ next_action: failure.next_action.clone(),
+ recoverable: failure.recoverable,
+ }
+}
+
+/// The skeleton of a sub-agent output in `state`; callers fill what the state
+/// carries.
+fn subagent(agent_id: &str, task_id: &str, state: &str) -> SubagentOutput {
+ SubagentOutput {
+ agent_id: agent_id.to_owned(),
+ task_id: task_id.to_owned(),
+ state: state.to_owned(),
+ mode: None,
+ dedicated_thread: None,
+ parent_call_id: None,
+ call_id: None,
+ iteration: None,
+ max_iterations: None,
+ prompt_chars: None,
+ message: None,
+ display_name: None,
+ tool_name: None,
+ arguments: None,
+ success: None,
+ elapsed_ms: None,
+ output_chars: None,
+ output: None,
+ structured: None,
+ usage: None,
+ failure: None,
+ display_label: None,
+ display_detail: None,
+ worker_thread_id: None,
+ worktree_path: None,
+ changed_files: Vec::new(),
+ dirty_status: None,
+ stop: None,
+ extended_policy: None,
+ }
+}
+
+fn lifecycle(
+ stage: &str,
+ message: Option<String>,
+ iteration: Option<u32>,
+ max: Option<u32>,
+) -> ChannelOutputEvent {
+ ChannelOutputEvent::Lifecycle {
+ stage: stage.to_owned(),
+ message,
+ iteration,
+ max_iterations: max,
+ stop: None,
+ }
+}
+
+pub(crate) fn inference_start() -> ChannelOutputEvent {
+ lifecycle("inference_start", None, None, None)
+}
+
+pub(crate) fn inference_heartbeat() -> ChannelOutputEvent {
+ lifecycle("inference_heartbeat", None, None, None)
+}
+
+pub(crate) fn iteration_start(iteration: u32, max_iterations: u32) -> ChannelOutputEvent {
+ lifecycle(
+ "iteration_start",
+ Some(format!("Iteration {iteration}/{max_iterations}")),
+ Some(iteration),
+ Some(max_iterations),
+ )
+}
+
+/// A tool call of the parent turn, as it started.
+pub(crate) fn tool_started(
+ call_id: String,
+ tool_name: String,
+ arguments: Value,
+ iteration: u32,
+ display_label: Option<String>,
+ display_detail: Option<String>,
+) -> ChannelOutputEvent {
+ ChannelOutputEvent::ToolCallStarted {
+ call_id,
+ tool_name,
+ arguments: cap_web_args(Some(arguments)).unwrap_or(Value::Null),
+ iteration,
+ display_label,
+ display_detail,
+ }
+}
+
+/// A finished tool call of the parent turn, with its size-capped result.
+pub(crate) fn tool_completed(event: AgentProgress) -> Option<ChannelOutputEvent> {
+ let AgentProgress::ToolCallCompleted {
+ call_id,
+ tool_name,
+ success,
+ output_chars,
+ output,
+ arguments,
+ elapsed_ms,
+ iteration,
+ failure,
+ display_label,
+ display_detail,
+ structured,
+ } = event
+ else {
+ return None;
+ };
+ Some(ChannelOutputEvent::ToolCallCompleted {
+ call_id,
+ tool_name,
+ success,
+ output_chars,
+ output: cap_web_output(output),
+ arguments: cap_web_args(arguments),
+ elapsed_ms,
+ iteration,
+ failure: failure.as_ref().map(failure_summary),
+ display_label,
+ display_detail,
+ structured,
+ })
+}
+
+/// The parent's cumulative spend so far, as a live cost readout.
+pub(crate) fn cost_update(
+ model: String,
+ iteration: u32,
+ input_tokens: u64,
+ output_tokens: u64,
+ cached_input_tokens: u64,
+ total_usd: f64,
+) -> ChannelOutputEvent {
+ ChannelOutputEvent::Usage {
+ model: Some(model),
+ iteration: Some(iteration),
+ input_tokens,
+ output_tokens,
+ cached_input_tokens,
+ total_usd: Some(total_usd),
+ }
+}
+
+pub(crate) fn sub_spawned(
+ agent_id: &str,
+ task_id: &str,
+ round: u32,
+ mode: String,
+ dedicated_thread: bool,
+ prompt_chars: usize,
+ worker_thread_id: Option<String>,
+ display_name: Option<String>,
+ parent_call_id: Option<String>,
+) -> ChannelOutputEvent {
+ let label = display_name.as_deref().unwrap_or(agent_id).to_owned();
+ let mut out = subagent(agent_id, task_id, "spawned");
+ out.message = Some(format!("Sub-agent '{label}' spawned"));
+ out.tool_name = Some(agent_id.to_owned());
+ out.iteration = Some(round);
+ out.mode = Some(mode);
+ out.dedicated_thread = Some(dedicated_thread);
+ out.prompt_chars = Some(prompt_chars);
+ out.worker_thread_id = worker_thread_id;
+ out.display_name = display_name;
+ out.parent_call_id = parent_call_id;
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+/// A finished sub-agent. `iterations` is the child's own total, carried as the
+/// output's iteration, which the projection reports as the detail's
+/// `iterations`.
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn sub_completed(
+ agent_id: &str,
+ task_id: &str,
+ elapsed_ms: u64,
+ iterations: u32,
+ output_chars: usize,
+ output: String,
+ usage: Option<&tinyagents_harness::progress::SubagentUsage>,
+ worktree_path: Option<String>,
+ changed_files: Vec<String>,
+ dirty_status: Option<bool>,
+ parent_call_id: Option<String>,
+) -> ChannelOutputEvent {
+ let mut out = subagent(agent_id, task_id, "completed");
+ out.message = Some(format!(
+ "Sub-agent '{agent_id}' completed in {elapsed_ms}ms"
+ ));
+ out.tool_name = Some(agent_id.to_owned());
+ out.success = Some(true);
+ out.iteration = Some(iterations);
+ out.elapsed_ms = Some(elapsed_ms);
+ out.output_chars = Some(output_chars);
+ out.output = Some(cap_web_output(output));
+ // Present only when this child's spend is not already inside the parent
+ // turn's totals; the consumer adds it unconditionally, and reads an
+ // unknown cost as zero.
+ out.usage = usage.map(|usage| SubagentUsage {
+ input_tokens: usage.input_tokens,
+ output_tokens: usage.output_tokens,
+ cached_input_tokens: usage.cached_input_tokens,
+ charged_amount_usd: usage.cost().usd().unwrap_or_default(),
+ cost_source: Default::default(),
+ });
+ out.worktree_path = worktree_path;
+ out.changed_files = changed_files;
+ out.dirty_status = dirty_status;
+ out.parent_call_id = parent_call_id;
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+pub(crate) fn sub_failed(
+ agent_id: &str,
+ task_id: &str,
+ round: u32,
+ error: String,
+ parent_call_id: Option<String>,
+) -> ChannelOutputEvent {
+ let mut out = subagent(agent_id, task_id, "failed");
+ out.message = Some(error);
+ out.tool_name = Some(agent_id.to_owned());
+ out.success = Some(false);
+ out.iteration = Some(round);
+ out.parent_call_id = parent_call_id;
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+pub(crate) fn sub_awaiting_user(
+ agent_id: &str,
+ task_id: &str,
+ round: u32,
+ question: String,
+ worker_thread_id: Option<String>,
+ parent_call_id: Option<String>,
+) -> ChannelOutputEvent {
+ let mut out = subagent(agent_id, task_id, "awaiting_user");
+ out.message = Some(question);
+ out.tool_name = Some(agent_id.to_owned());
+ out.success = Some(true);
+ out.iteration = Some(round);
+ out.worker_thread_id = worker_thread_id;
+ out.parent_call_id = parent_call_id;
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+pub(crate) fn sub_iteration(
+ agent_id: &str,
+ task_id: &str,
+ iteration: u32,
+ max_iterations: u32,
+ extended_policy: bool,
+) -> ChannelOutputEvent {
+ let mut out = subagent(agent_id, task_id, "iteration_start");
+ out.message = Some(if extended_policy {
+ format!("Sub-agent '{agent_id}' step {iteration}")
+ } else {
+ format!("Sub-agent '{agent_id}' iteration {iteration}/{max_iterations}")
+ });
+ out.tool_name = Some(agent_id.to_owned());
+ out.iteration = Some(iteration);
+ out.max_iterations = (!extended_policy).then_some(max_iterations);
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn sub_tool_started(
+ agent_id: &str,
+ task_id: &str,
+ call_id: String,
+ tool_name: String,
+ arguments: Value,
+ iteration: u32,
+ display_label: Option<String>,
+ display_detail: Option<String>,
+) -> ChannelOutputEvent {
+ let mut out = subagent(agent_id, task_id, "tool_call");
+ out.call_id = Some(call_id);
+ out.tool_name = Some(tool_name);
+ out.arguments = Some(arguments);
+ out.iteration = Some(iteration);
+ out.display_label = display_label;
+ out.display_detail = display_detail;
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+pub(crate) fn sub_tool_completed(event: AgentProgress) -> Option<ChannelOutputEvent> {
+ let AgentProgress::SubagentToolCallCompleted {
+ agent_id,
+ task_id,
+ call_id,
+ tool_name,
+ success,
+ output_chars,
+ output,
+ arguments,
+ elapsed_ms,
+ iteration,
+ failure,
+ display_label,
+ display_detail,
+ structured,
+ } = event
+ else {
+ return None;
+ };
+ let mut out = subagent(&agent_id, &task_id, "tool_result");
+ out.call_id = Some(call_id);
+ out.tool_name = Some(tool_name);
+ out.success = Some(success);
+ out.iteration = Some(iteration);
+ out.elapsed_ms = Some(elapsed_ms);
+ out.output_chars = Some(output_chars);
+ out.output = Some(cap_web_output(output));
+ out.arguments = cap_web_args(arguments);
+ out.structured = structured;
+ out.failure = failure.as_ref().map(failure_summary);
+ out.display_label = display_label;
+ out.display_detail = display_detail;
+ Some(ChannelOutputEvent::Subagent(Box::new(out)))
+}
+
+pub(crate) fn sub_delta(
+ agent_id: &str,
+ task_id: &str,
+ thinking: bool,
+ delta: String,
+ iteration: u32,
+) -> ChannelOutputEvent {
+ let mut out = subagent(
+ agent_id,
+ task_id,
+ if thinking {
+ "thinking_delta"
+ } else {
+ "text_delta"
+ },
+ );
+ out.message = Some(delta);
+ out.iteration = Some(iteration);
+ ChannelOutputEvent::Subagent(Box::new(out))
+}
+
+#[cfg(test)]
+#[path = "turn_progress_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/turn_progress_tests.rs b/crates/openhuman-core/src/agent/turn_progress_tests.rs
new file mode 100644
index 0000000000..5ad986f0d7
--- /dev/null
+++ b/crates/openhuman-core/src/agent/turn_progress_tests.rs
@@ -0,0 +1,322 @@
+use super::*;
+use serde_json::json;
+use tinychannels_bus::web::MAX_WEB_TOOL_PAYLOAD_BYTES;
+
+fn expect_subagent(event: ChannelOutputEvent) -> SubagentOutput {
+ match event {
+ ChannelOutputEvent::Subagent(out) => *out,
+ other => panic!("expected a sub-agent output, got {other:?}"),
+ }
+}
+
+#[test]
+fn lifecycle_events_name_the_stage_and_the_round() {
+ let ChannelOutputEvent::Lifecycle {
+ stage, iteration, ..
+ } = inference_start()
+ else {
+ panic!("lifecycle")
+ };
+ assert_eq!((stage.as_str(), iteration), ("inference_start", None));
+ let ChannelOutputEvent::Lifecycle { stage, .. } = inference_heartbeat() else {
+ panic!("lifecycle")
+ };
+ assert_eq!(stage, "inference_heartbeat");
+ let ChannelOutputEvent::Lifecycle {
+ stage,
+ message,
+ iteration,
+ max_iterations,
+ ..
+ } = iteration_start(2, 9)
+ else {
+ panic!("lifecycle")
+ };
+ assert_eq!(stage, "iteration_start");
+ assert_eq!(message.as_deref(), Some("Iteration 2/9"));
+ assert_eq!((iteration, max_iterations), (Some(2), Some(9)));
+}
+
+#[test]
+fn a_started_tool_call_keeps_small_arguments_and_nulls_empty_ones() {
+ let ChannelOutputEvent::ToolCallStarted { arguments, .. } = tool_started(
+ "c".into(),
+ "shell".into(),
+ json!({ "cmd": "ls" }),
+ 1,
+ Some("Listing".into()),
+ None,
+ ) else {
+ panic!("tool call")
+ };
+ assert_eq!(arguments, json!({ "cmd": "ls" }));
+ let ChannelOutputEvent::ToolCallStarted { arguments, .. } =
+ tool_started("c".into(), "shell".into(), Value::Null, 1, None, None)
+ else {
+ panic!("tool call")
+ };
+ assert_eq!(arguments, Value::Null);
+}
+
+#[test]
+fn a_finished_tool_call_caps_output_and_arguments_and_names_its_failure() {
+ let failure = tinytools::status::classify("[not-found] no such file", false);
+ let event = AgentProgress::ToolCallCompleted {
+ call_id: "c".into(),
+ tool_name: "file_read".into(),
+ success: false,
+ output_chars: 3,
+ output: "x".repeat(MAX_WEB_TOOL_PAYLOAD_BYTES + 10),
+ arguments: Some(json!({ "body": "y".repeat(MAX_WEB_TOOL_PAYLOAD_BYTES) })),
+ elapsed_ms: 7,
+ iteration: 2,
+ failure: Some(failure.clone()),
+ display_label: None,
+ display_detail: Some("a.txt".into()),
+ structured: Some(json!({ "kind": "probe" })),
+ };
+ let ChannelOutputEvent::ToolCallCompleted {
+ output,
+ arguments,
+ failure: summary,
+ elapsed_ms,
+ iteration,
+ structured,
+ display_detail,
+ success,
+ ..
+ } = tool_completed(event).expect("a completed call")
+ else {
+ panic!("tool result")
+ };
+ assert!(output.len() <= MAX_WEB_TOOL_PAYLOAD_BYTES && output.contains("truncated"));
+ assert!(
+ arguments
+ .expect("arguments")
+ .as_str()
+ .is_some_and(|marker| marker.contains("truncated"))
+ );
+ let summary = summary.expect("failure summary");
+ assert_eq!(summary.cause_plain, failure.cause_plain);
+ assert_eq!(summary.recoverable, failure.recoverable);
+ assert!(!summary.class.is_empty() && !summary.category.is_empty());
+ assert_eq!((elapsed_ms, iteration, success), (7, 2, false));
+ assert_eq!(structured, Some(json!({ "kind": "probe" })));
+ assert_eq!(display_detail.as_deref(), Some("a.txt"));
+
+ assert!(tool_completed(AgentProgress::TurnStarted).is_none());
+}
+
+#[test]
+fn a_cost_update_is_a_charged_usage_readout() {
+ let ChannelOutputEvent::Usage {
+ model,
+ iteration,
+ input_tokens,
+ total_usd,
+ ..
+ } = cost_update("m".into(), 3, 10, 20, 5, 0.25)
+ else {
+ panic!("usage")
+ };
+ assert_eq!(model.as_deref(), Some("m"));
+ assert_eq!(
+ (iteration, input_tokens, total_usd),
+ (Some(3), 10, Some(0.25))
+ );
+}
+
+#[test]
+fn a_spawned_subagent_is_attributed_to_the_parents_round_and_call() {
+ let out = expect_subagent(sub_spawned(
+ "researcher",
+ "task-1",
+ 4,
+ "typed".into(),
+ true,
+ 120,
+ Some("worker".into()),
+ Some("Researcher".into()),
+ Some("call-9".into()),
+ ));
+ assert_eq!(out.state, "spawned");
+ assert_eq!(
+ out.message.as_deref(),
+ Some("Sub-agent 'Researcher' spawned")
+ );
+ assert_eq!(out.tool_name.as_deref(), Some("researcher"));
+ assert_eq!((out.iteration, out.prompt_chars), (Some(4), Some(120)));
+ assert_eq!(out.parent_call_id.as_deref(), Some("call-9"));
+ assert_eq!(out.worker_thread_id.as_deref(), Some("worker"));
+ assert_eq!(out.dedicated_thread, Some(true));
+}
+
+#[test]
+fn a_finished_subagent_carries_its_iterations_result_spend_and_worktree() {
+ let usage = tinyagents_harness::progress::SubagentUsage {
+ input_tokens: 5,
+ output_tokens: 6,
+ cached_input_tokens: 1,
+ charged_amount_usd: 0.5,
+ cost_source: tinyagents_harness::cost::CostSource::Charged,
+ };
+ let out = expect_subagent(sub_completed(
+ "researcher",
+ "task-1",
+ 1_500,
+ 3,
+ 4,
+ "done".into(),
+ Some(&usage),
+ Some("/w".into()),
+ vec!["a.rs".into()],
+ Some(true),
+ Some("call-9".into()),
+ ));
+ assert_eq!(out.state, "completed");
+ assert_eq!(out.iteration, Some(3), "the child's own iteration total");
+ assert_eq!(
+ out.message.as_deref(),
+ Some("Sub-agent 'researcher' completed in 1500ms")
+ );
+ assert_eq!(out.output.as_deref(), Some("done"));
+ assert_eq!(out.success, Some(true));
+ let spend = out.usage.expect("spend");
+ assert_eq!((spend.input_tokens, spend.charged_amount_usd), (5, 0.5));
+ assert_eq!(out.worktree_path.as_deref(), Some("/w"));
+ assert_eq!(
+ (out.changed_files, out.dirty_status),
+ (vec!["a.rs".to_string()], Some(true))
+ );
+
+ let none = expect_subagent(sub_completed(
+ "r",
+ "t",
+ 1,
+ 1,
+ 0,
+ String::new(),
+ None,
+ None,
+ Vec::new(),
+ None,
+ None,
+ ));
+ assert!(none.usage.is_none());
+}
+
+#[test]
+fn an_unknown_cost_reads_as_zero_spend_not_missing_tokens() {
+ let usage = tinyagents_harness::progress::SubagentUsage {
+ input_tokens: 9,
+ ..Default::default()
+ };
+ let out = expect_subagent(sub_completed(
+ "r",
+ "t",
+ 1,
+ 1,
+ 0,
+ String::new(),
+ Some(&usage),
+ None,
+ Vec::new(),
+ None,
+ None,
+ ));
+ let spend = out.usage.expect("tokens survive an unknown cost");
+ assert_eq!((spend.input_tokens, spend.charged_amount_usd), (9, 0.0));
+}
+
+#[test]
+fn failed_and_waiting_subagents_say_why() {
+ let failed = expect_subagent(sub_failed("r", "t", 2, "boom".into(), Some("p".into())));
+ assert_eq!(failed.state, "failed");
+ assert_eq!(
+ (failed.success, failed.message.as_deref()),
+ (Some(false), Some("boom"))
+ );
+ assert_eq!(failed.parent_call_id.as_deref(), Some("p"));
+
+ let waiting = expect_subagent(sub_awaiting_user(
+ "r",
+ "t",
+ 2,
+ "which one?".into(),
+ Some("w".into()),
+ None,
+ ));
+ assert_eq!(waiting.state, "awaiting_user");
+ assert_eq!(waiting.message.as_deref(), Some("which one?"));
+ assert_eq!(waiting.worker_thread_id.as_deref(), Some("w"));
+}
+
+#[test]
+fn a_subagent_iteration_hides_its_cap_under_the_extended_policy() {
+ let capped = expect_subagent(sub_iteration("r", "t", 2, 8, false));
+ assert_eq!(
+ capped.message.as_deref(),
+ Some("Sub-agent 'r' iteration 2/8")
+ );
+ assert_eq!(capped.max_iterations, Some(8));
+ let extended = expect_subagent(sub_iteration("r", "t", 2, 8, true));
+ assert_eq!(extended.message.as_deref(), Some("Sub-agent 'r' step 2"));
+ assert_eq!(extended.max_iterations, None);
+}
+
+#[test]
+fn subagent_tool_calls_carry_their_arguments_and_capped_results() {
+ let started = expect_subagent(sub_tool_started(
+ "r",
+ "t",
+ "call".into(),
+ "web_search".into(),
+ json!({ "q": 1 }),
+ 2,
+ Some("Search".into()),
+ None,
+ ));
+ assert_eq!(started.state, "tool_call");
+ assert_eq!(started.arguments, Some(json!({ "q": 1 })));
+ assert_eq!(started.call_id.as_deref(), Some("call"));
+
+ let completed = expect_subagent(
+ sub_tool_completed(AgentProgress::SubagentToolCallCompleted {
+ agent_id: "r".into(),
+ task_id: "t".into(),
+ call_id: "call".into(),
+ tool_name: "web_search".into(),
+ success: true,
+ output_chars: 4,
+ output: "z".repeat(MAX_WEB_TOOL_PAYLOAD_BYTES + 1),
+ arguments: Some(json!({ "q": 1 })),
+ elapsed_ms: 3,
+ iteration: 2,
+ failure: None,
+ display_label: None,
+ display_detail: None,
+ structured: Some(json!({ "kind": "web_search" })),
+ })
+ .expect("a completed sub-agent call"),
+ );
+ assert_eq!(completed.state, "tool_result");
+ assert!(
+ completed
+ .output
+ .is_some_and(|out| out.contains("truncated"))
+ );
+ assert_eq!(completed.structured, Some(json!({ "kind": "web_search" })));
+ assert!(sub_tool_completed(AgentProgress::TurnStarted).is_none());
+}
+
+#[test]
+fn subagent_deltas_are_text_or_thinking() {
+ let text = expect_subagent(sub_delta("r", "t", false, "hi".into(), 2));
+ assert_eq!(
+ (text.state.as_str(), text.message.as_deref()),
+ ("text_delta", Some("hi"))
+ );
+ let thinking = expect_subagent(sub_delta("r", "t", true, "hm".into(), 2));
+ assert_eq!(thinking.state, "thinking_delta");
+ assert_eq!(thinking.iteration, Some(2));
+}