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
refactor(steering-forwarder): delegate poll-loop and cleanup logic to upstream crate
Steven Enamakel5ea2fd96ffab
diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rsindex 4a8205db1d..6a457b363d 100644--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder.rs@@ -1,354 +1,125 @@-//! Abort-on-drop steering forwarder guard (issue #4456).+//! Host adapter over the upstream abort-on-drop steering forwarder+//! (`tinyagents_harness::run_queue::SteeringForwarderGuard`, issue #4456).//!//! `run_turn_via_tinyagents_shared` bridges OpenHuman's session-owned-//! [`RunQueue`] into a running TinyAgents turn by spawning a 50 ms poll loop-//! that drains queued **steer**/**collect** messages and forwards them into the-//! run's [`SteeringHandle`]. The harness applies them at the next iteration-//! checkpoint.+//! [`RunQueue`] into a running TinyAgents turn by spawning a poll loop that+//! drains queued **steer**/**collect** messages into the run's+//! `SteeringHandle`. The loop, the drop-safe cleanup, and the residual-steer+//! requeue are upstream; this module supplies the host seams://!-//! The historical cleanup — `forwarder.abort()` + steering-registry-//! `deregister(...)` — only ran when the drive future returned *normally*. But-//! cancellation in this codebase is **drop-based** (the web channel drops the-//! turn future via a `tokio::select!` cancel token; detached sub-agents are-//! hard-aborted through an `AbortHandle`). On those paths the spawned task-//! *detached* and looped `sleep(50 ms) → drain` forever, pinning the-//! `Arc<RunQueue>` + `SteeringHandle` and — because the `RunQueue` is-//! session-owned and reused — **racing the next turn's forwarder**, stealing its-//! steer/collect messages into a dead handle. Registry entries for aborted-//! sub-agent tasks were likewise never removed.-//!-//! [`SteeringForwarderGuard`] fixes this with RAII: its [`Drop`] aborts the poll-//! task, deregisters from the shared steering registry, and drains any residual-//! (delivered-but-unapplied) steers back into the session `RunQueue` so a late-//! steer becomes the *next* turn's input instead of vanishing. Because the guard-//! is held across the drive future, cleanup happens identically on normal-//! return, error, and drop-cancellation.+//! - [`QueuedMessage`] for [`QueuedTurn`] (text/id accessors and how a recovered+//! steer is re-created),+//! - an event sink that publishes [`DomainEvent::RunQueueMessageDelivered`] /+//! [`DomainEvent::RunQueueSteerRequeued`] on the event bus,+//! - the cleanup hook that deregisters a sub-agent's handle from the shared+//! steering registry.-use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::Arc;-use std::time::Duration;use tinyagents_harness::ids::TaskId;-use tinyagents_harness::run_queue::{QueueLane, RunQueue};-use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};-use tinyinference_llm::message::Message as TaMessage;+use tinyagents_harness::run_queue::{+ self, ForwardEvent, ForwardEventSink, QueuedMessage, RunQueue, SteeringForwarderGuard,+};+use tinyagents_harness::steering::SteeringHandle;+use crate::agent::queued_turn::{text_preview, QueuedTurn};use crate::core::bus::BUS;use crate::core::events::DomainEvent;use super::host::steering::shared_steering_registry;-/// Framing prepended to a queued **steer** message when it is injected as a user-/// turn. Kept as a shared const so the residual-requeue path can strip it and-/// avoid double-prefixing when the next turn re-forwards the recovered text.-pub(super) const STEER_PREFIX: &str = "[User steering message]: ";--/// Framing prepended to a queued **collect** message (orchestrator/monitor-/// context lines). See [`STEER_PREFIX`].-pub(super) const COLLECT_PREFIX: &str = "[Additional context from user]: ";+impl QueuedMessage for QueuedTurn {+ fn id(&self) -> &str {+ &self.id+ }-/// Live steering-forwarder poll tasks, incremented when-/// [`SteeringForwarderGuard::new`] spawns a poll loop and decremented on its-/// `Drop`. Exposed for tests asserting the leak fix: after a cancelled/aborted-/// turn this must return to its pre-turn value (zero live forwarders for that-/// turn).-static ACTIVE_FORWARDERS: AtomicUsize = AtomicUsize::new(0);+ fn text(&self) -> &str {+ &self.text+ }-/// Number of steering-forwarder poll tasks currently live process-wide.-pub(crate) fn active_steering_forwarders() -> usize {- ACTIVE_FORWARDERS.load(Ordering::SeqCst)+ fn requeued(id: String, text: String, thread_label: &str, queued_at_ms: u64) -> Self {+ QueuedTurn {+ id,+ text,+ client_id: String::new(),+ thread_id: thread_label.to_string(),+ queued_at_ms,+ model_override: None,+ temperature: None,+ locale: None,+ }+ }}-/// Milliseconds since the Unix epoch (best-effort; `0` on a pre-epoch clock).-fn now_ms() -> u64 {- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as u64)- .unwrap_or(0)+/// Publish forwarder notifications as `RunQueue*` domain events.+fn event_bus_sink() -> ForwardEventSink {+ Arc::new(|event| match event {+ ForwardEvent::Delivered {+ thread_label,+ mode,+ delivered,+ item_id,+ text,+ } => BUS.publish(DomainEvent::RunQueueMessageDelivered {+ thread_id: thread_label,+ mode: mode.to_string(),+ delivered,+ item_id,+ text_preview: text.as_deref().map(text_preview),+ }),+ ForwardEvent::Requeued {+ thread_label,+ requeued,+ item_id,+ text,+ } => BUS.publish(DomainEvent::RunQueueSteerRequeued {+ thread_id: thread_label,+ requeued,+ item_id,+ text_preview: text.as_deref().map(text_preview),+ }),+ })}-/// Drain the run queue's pending **steer** messages and forward them to the-/// tinyagents [`SteeringHandle`] as injected user turns (the harness applies-/// them to the working transcript at the next iteration checkpoint). This is the-/// bridge behind the `steer_subagent` / mid-flight-steering feature. Emits a-/// [`DomainEvent::RunQueueMessageDelivered`] when at least one message is-/// delivered so the delivery is visible in the event stream (issue #4456).+/// Drain the queue's pending **steer** messages into `handle` (pre-run drain+/// and poll-loop body). See `tinyagents_harness::run_queue::forward_steers`.pub(super) async fn forward_steers(- queue: &RunQueue<crate::agent::queued_turn::QueuedTurn>,+ queue: &RunQueue<QueuedTurn>,handle: &SteeringHandle,thread_label: &str,) {- let drained = queue.drain(QueueLane::Steer).await;- if drained.is_empty() {- return;- }- let delivered = drained.len();- let (item_id, text_preview) = drained- .first()- .map(|msg| {- (- Some(msg.id.clone()),- Some(crate::agent::queued_turn::text_preview(&msg.text)),- )- })- .unwrap_or((None, None));- for msg in drained {- handle.send(SteeringCommand::InjectMessage(TaMessage::user(format!(- "{STEER_PREFIX}{}",- msg.text- ))));- }- tracing::debug!(- thread_id = thread_label,- delivered,- "[run_queue] delivered steer message(s) into running steering handle"- );- BUS.publish(DomainEvent::RunQueueMessageDelivered {- thread_id: thread_label.to_string(),- mode: "steer".to_string(),- delivered,- item_id,- text_preview,- });+ run_queue::forward_steers(queue, handle, thread_label, &event_bus_sink()).await;}-/// Forward any queued **collect** messages (orchestrator/monitor lines enqueued-/// via the collect queue lane into the run as injected user turns so they reach-/// the next LLM call as additional context. Mirrors the legacy-/// `[Additional context from user]:` framing the model was taught to read. Emits-/// a [`DomainEvent::RunQueueMessageDelivered`] on delivery (issue #4456).+/// Drain the queue's pending **collect** messages into `handle`. See+/// `tinyagents_harness::run_queue::forward_collects`.pub(super) async fn forward_collects(- queue: &RunQueue<crate::agent::queued_turn::QueuedTurn>,+ queue: &RunQueue<QueuedTurn>,handle: &SteeringHandle,thread_label: &str,) {- let drained = queue.drain(QueueLane::Collect).await;- if drained.is_empty() {- return;- }- let delivered = drained.len();- let (item_id, text_preview) = drained- .first()- .map(|msg| {- (- Some(msg.id.clone()),- Some(crate::agent::queued_turn::text_preview(&msg.text)),- )- })- .unwrap_or((None, None));- for msg in drained {- handle.send(SteeringCommand::InjectMessage(TaMessage::user(format!(- "{COLLECT_PREFIX}{}",- msg.text- ))));- }- tracing::debug!(- thread_id = thread_label,- delivered,- "[run_queue] delivered collect message(s) into running steering handle"- );- BUS.publish(DomainEvent::RunQueueMessageDelivered {- thread_id: thread_label.to_string(),- mode: "collect".to_string(),- delivered,- item_id,- text_preview,- });+ run_queue::forward_collects(queue, handle, thread_label, &event_bus_sink()).await;}-/// Abort-on-drop guard around the 50 ms steering-forwarder poll task.-///-/// Held across the harness drive future so its [`Drop`] runs on **every** exit-/// path (normal return, error, and drop-cancellation), aborting the poll task,-/// deregistering the sub-agent steering handle, and requeuing residual steers.-pub(super) struct SteeringForwarderGuard {- /// The spawned poll task; `abort()`-ed on drop. `None` after the abort so a- /// double-drop is a no-op.- forwarder: Option<tokio::task::JoinHandle<()>>,- /// A clone of the run's steering handle, drained on drop to recover- /// delivered-but-unapplied steers.+/// Arm the abort-on-drop guard. `registry_task_id` is `Some` for sub-agent runs+/// (whose handle is registered in the shared steering registry and deregistered+/// on every exit path) and `None` for the interactive parent turn.+pub(super) fn arm_guard(handle: SteeringHandle,- /// The session-owned run queue, used to requeue residual steers on drop.- /// `None` after the requeue so a double-drop is a no-op.- run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,- /// The steering-registry key to deregister on drop (sub-agent runs only).+ run_queue: Option<Arc<RunQueue<QueuedTurn>>>,registry_task_id: Option<TaskId>,- /// Best-effort thread label for observability + requeued-message metadata.thread_label: String,-}--impl SteeringForwarderGuard {- /// Arm the guard: spawn the 50 ms poll loop when a `run_queue` is present and- /// wrap all cleanup in an abort-on-drop scope.- ///- /// `run_queue` is `None` for a steering-only run (a sub-agent whose handle is- /// controlled purely through the steering registry, with no queue lane): no- /// poll task is spawned, but the guard still deregisters the handle on every- /// exit path so an aborted run cannot leak a registry entry. `registry_task_id`- /// is `Some` for sub-agent runs (whose handle is registered in the shared- /// steering registry) and `None` for the interactive parent turn.- pub(super) fn new(- handle: SteeringHandle,- run_queue: Option<Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>>,- registry_task_id: Option<TaskId>,- thread_label: String,- ) -> Self {- let forwarder = run_queue.as_ref().map(|queue| {- ACTIVE_FORWARDERS.fetch_add(1, Ordering::SeqCst);- let loop_queue = queue.clone();- let loop_handle = handle.clone();- let loop_label = thread_label.clone();- tokio::spawn(async move {- loop {- tokio::time::sleep(Duration::from_millis(50)).await;- forward_steers(&loop_queue, &loop_handle, &loop_label).await;- forward_collects(&loop_queue, &loop_handle, &loop_label).await;- }- })- });- tracing::debug!(- thread_id = thread_label.as_str(),- has_queue = run_queue.is_some(),- "[run_queue] steering forwarder guard armed (abort-on-drop)"- );- Self {- forwarder,- handle,- run_queue,- registry_task_id,- thread_label,- }- }-}--impl Drop for SteeringForwarderGuard {- fn drop(&mut self) {- // 1. Stop the poll loop so it can no longer race the next turn's- // forwarder for the shared, session-owned run queue.- if let Some(forwarder) = self.forwarder.take() {- forwarder.abort();- ACTIVE_FORWARDERS.fetch_sub(1, Ordering::SeqCst);- tracing::debug!(- thread_id = self.thread_label.as_str(),- "[run_queue] aborted steering forwarder (guard drop)"- );- }-- // 2. Deregister the sub-agent steering handle so an aborted run does not- // leak a registry entry keyed by a dead handle.- if let Some(task_id) = self.registry_task_id.take() {+) -> SteeringForwarderGuard<QueuedTurn> {+ let cleanup: Option<run_queue::ForwarderCleanup> = registry_task_id.map(|task_id| {+ Box::new(move || {shared_steering_registry().deregister(&task_id);tracing::debug!(task_id = task_id.as_str(),"[tinyagents] deregistered subagent steering handle (guard drop)");- }-- // 3. Recover residual steers: messages the poll loop already delivered- // into the handle but that the harness ended/cancelled before- // applying at a checkpoint. Strip the delivery prefix so the next- // turn's forwarder re-frames them cleanly (no double prefix).- // Control-flow-only commands (Pause/Resume/Cancel/…) are meaningless- // once the run is gone and are intentionally dropped.- let residual = self.handle.drain();- // Each residual steer gets its requeued id minted here (Drop is- // synchronous) so the `RunQueueSteerRequeued` event below and the- // `QueuedTurn` actually pushed onto the queue in the spawned task- // agree on the same id.- let requeue_items: Vec<(String, QueueLane, String)> = residual- .into_iter()- .filter_map(|cmd| match cmd {- SteeringCommand::InjectMessage(msg) => {- let text = msg.text();- // The prefix that matched tells us the lane — preserve it so- // a delivered-but-unapplied collect line re-enters as Collect- // (framed `[Additional context from user]:`) rather than being- // re-labeled as user Steer. Default to Steer when neither- // prefix is present (a raw steer that was never framed).- let (text, lane) = if let Some(rest) = text.strip_prefix(STEER_PREFIX) {- (rest.to_string(), QueueLane::Steer)- } else if let Some(rest) = text.strip_prefix(COLLECT_PREFIX) {- (rest.to_string(), QueueLane::Collect)- } else {- (text.to_string(), QueueLane::Steer)- };- Some((text, lane, uuid::Uuid::new_v4().to_string()))- }- _ => None,- })- .collect();-- let Some(queue) = self.run_queue.take() else {- return;- };- if requeue_items.is_empty() {- return;- }- let requeued = requeue_items.len();- let thread_label = self.thread_label.clone();- let (item_id, text_preview) = requeue_items- .first()- .map(|(text, _lane, id)| {- (- Some(id.clone()),- Some(crate::agent::queued_turn::text_preview(text)),- )- })- .unwrap_or((None, None));-- // `RunQueue::push` is async (tokio `Mutex`); `Drop` is synchronous. Push- // the recovered steers back on a detached task so they land in the- // session queue and become the next turn's input. The forwarder poll- // loop keeps re-draining the queue, so even if the requeue completes- // after the next turn starts, its next 50 ms tick picks them up.- match tokio::runtime::Handle::try_current() {- Ok(rt) => {- let label = thread_label.clone();- rt.spawn(async move {- for (text, lane, id) in requeue_items {- queue- .push(- lane,- crate::agent::queued_turn::QueuedTurn {- id,- text,- client_id: String::new(),- thread_id: label.clone(),- queued_at_ms: now_ms(),- model_override: None,- temperature: None,- locale: None,- },- )- .await;- }- });- }- Err(_) => {- // No runtime to spawn on (should not happen on the live paths,- // which always drop inside a tokio task). The steers are lost- // rather than silently mis-handled — log loudly.- tracing::warn!(- thread_id = thread_label.as_str(),- requeued,- "[run_queue] could not requeue residual steers: no tokio runtime at guard drop"- );- return;- }- }-- tracing::debug!(- thread_id = thread_label.as_str(),- requeued,- "[run_queue] requeued residual steer(s) as next-turn input (guard drop)"- );- BUS.publish(DomainEvent::RunQueueSteerRequeued {- thread_id: thread_label,- requeued,- item_id,- text_preview,- });- }+ }) as run_queue::ForwarderCleanup+ });+ SteeringForwarderGuard::new(handle, run_queue, cleanup, thread_label, event_bus_sink())}#[cfg(test)]diff --git a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rsindex 4d64fd9603..e885becfa1 100644--- a/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/steering_forwarder_tests.rs@@ -1,85 +1,48 @@use super::*;-use tinyagents_harness::context::{RunConfig, RunContext};-use tinyagents_harness::runtime::AgentHarness;-use tinyagents_harness::testkit::ScriptedModel;+use tinyagents_harness::run_queue::QueueLane;-#[tokio::test]-async fn residual_collect_requeues_to_its_original_lane() {- let queue = Arc::new(RunQueue::new());- let handle = SteeringHandle::allow_all();- let guard = SteeringForwarderGuard::new(- handle.clone(),- Some(queue.clone()),- None,- "thread-test".to_string(),- );- handle.send(SteeringCommand::InjectMessage(TaMessage::user(format!(- "{COLLECT_PREFIX}recovered context"- ))));- drop(guard);- tokio::time::timeout(Duration::from_secs(1), async {- loop {- if queue.status().await.collects == 1 {- return;- }- tokio::task::yield_now().await;- }- })- .await- .expect("residual collect should be requeued before timeout");- assert!(queue.drain(QueueLane::Steer).await.is_empty());- let recovered = queue.drain(QueueLane::Collect).await;- assert_eq!(recovered.len(), 1);- assert_eq!(recovered[0].text, "recovered context");+#[test]+fn recovered_steer_becomes_a_queued_turn_on_the_forwarders_thread() {+ let turn = QueuedTurn::requeued("id-1".into(), "text".into(), "thread-9", 42);+ assert_eq!(turn.id(), "id-1");+ assert_eq!(turn.text(), "text");+ assert_eq!(turn.thread_id, "thread-9");+ assert_eq!(turn.queued_at_ms, 42);+ assert!(turn.client_id.is_empty());+ assert!(turn.model_override.is_none() && turn.temperature.is_none() && turn.locale.is_none());}#[tokio::test]-async fn collect_reaches_the_next_model_boundary_as_additional_context() {- let queue = Arc::new(RunQueue::new());+async fn forwarders_drain_their_lane_into_the_steering_handle() {+ let queue = RunQueue::<QueuedTurn>::new();+ queue+ .push(+ QueueLane::Steer,+ QueuedTurn::requeued("s".into(), "go left".into(), "t", 1),+ )+ .await;queue.push(QueueLane::Collect,- crate::agent::queued_turn::QueuedTurn {- id: "queued-test".to_string(),- text: "the deployment finished successfully".to_string(),- client_id: "client-test".to_string(),- thread_id: "thread-test".to_string(),- queued_at_ms: 1,- model_override: None,- temperature: None,- locale: None,- },+ QueuedTurn::requeued("c".into(), "fyi".into(), "t", 1),).await;let handle = SteeringHandle::allow_all();- forward_collects(&queue, &handle, "thread-test").await;- let model = Arc::new(ScriptedModel::replies(vec!["done"]));- let mut harness: AgentHarness<()> = AgentHarness::new();- harness- .register_model("scripted", model.clone())- .set_default_model("scripted");- harness- .invoke_in_context(- &(),- RunContext::new(RunConfig::new("collect-boundary"), ()).with_steering(handle),- vec![TaMessage::user("start")],- )- .await- .expect("collect-context run should complete");- let requests = model.requests();- assert_eq!(requests.len(), 1, "one model boundary should be crossed");- let collect = requests[0]- .messages- .iter()- .find(|message| message.text().contains("deployment finished successfully"))- .expect("the next model request should contain the collected context");- assert!(matches!(collect, TaMessage::User(_)));- assert_eq!(- collect.text(),- "[Additional context from user]: the deployment finished successfully"- );+ forward_steers(&queue, &handle, "t").await;+ forward_collects(&queue, &handle, "t").await;+ assert_eq!(handle.drain().len(), 2);+ assert_eq!(queue.status().await.total, 0);+}++#[tokio::test]+async fn arm_guard_deregisters_the_subagent_handle_on_drop() {+ let task_id = TaskId::new("guard-task");+ let handle = SteeringHandle::allow_all();+ shared_steering_registry().register(task_id.clone(), handle.clone());+ let guard = arm_guard(handle, None, Some(task_id.clone()), "t".into());+ drop(guard);assert!(- !collect.text().starts_with(STEER_PREFIX),- "collect must be context, not a steering instruction"+ shared_steering_registry().get(&task_id).is_none(),+ "the guard must deregister the sub-agent handle");}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex 480025b970..b6259690e8 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -595,7 +595,7 @@ async fn run_turn_via_tinyagents_inner(steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;}ctx = ctx.with_steering(handle.clone());- Some(steering_forwarder::SteeringForwarderGuard::new(+ Some(steering_forwarder::arm_guard(handle,run_queue,registry_task_id,diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 58b1b3393b..2a2675a5b5 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 58b1b3393bbd7d96f5e13c7642ae273742bc5102+Subproject commit 2a2675a5b52f3909a0aee31d5e160c9334efcc07