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
fix(agent): count only the capped run's own model calls toward the turn cap (#6280)
M3gA-Mindca7f4d1ac901
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rsindex 4fc945e0f4..1abaa10fab 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser.rs@@ -86,9 +86,23 @@ pub(crate) type ProviderUsageCarry =/// check, so a `Pause` sent here short-circuits the loop cleanly. The caller then/// inspects the run's finish reason to decide whether to summarize a checkpoint/// — the tinyagents analogue of the legacy cap checkpoint seam.+///+/// Only the capped run's **own** model calls count. The sink is shared with+/// every in-process nested run (the payload summarizer runs its child on it via+/// `SubAgent::invoke_with_events`), and those children emit `ModelCompleted`+/// too. Counting them paused the turn after `cap - N` of its own calls while+/// `hit_cap` — which reads `run.model_calls`, the run's own count — stayed+/// `false`, so the turn ended on the no-final-text path instead of the cap+/// checkpoint (#6280).pub(crate) struct CapPauser {handle: SteeringHandle,cap: u32,+ /// Id of the run being capped. The crate mints that run's model call ids as+ /// `{run_id}-model-{n}` (`agent_loop/run_loop.rs`), while a nested child+ /// runs under its own `{name}-d{depth}-{seq}` id, so the call id alone+ /// attributes a completion to its run at any nesting depth, with no+ /// dependence on start/finish events a failed child never emits.+ run_id: String,completed: AtomicU32,/// The current turn's dispatch guard, when this run is a turn (rather than/// a CLI/direct invocation). Recording the pause here is what makes it@@ -98,45 +112,70 @@ pub(crate) struct CapPauser {}impl CapPauser {- /// Pause `handle` once `cap` model calls complete, recording the pause on- /// `dispatch_guard` when the run is executing inside a turn scope.+ /// Pause `handle` once `cap` of run `run_id`'s own model calls complete,+ /// recording the pause on `dispatch_guard` when the run is executing inside+ /// a turn scope.pub(crate) fn new(handle: SteeringHandle,cap: usize,+ run_id: impl Into<String>,dispatch_guard: Option<Arc<TurnDispatchState>>,) -> Arc<Self> {Arc::new(Self {handle,cap: cap as u32,+ run_id: run_id.into(),completed: AtomicU32::new(0),dispatch_guard,})}++ /// `true` when `call_id` is one of the capped run's own model calls+ /// (`{run_id}-model-{n}`), not a nested run's.+ fn is_own_model_call(&self, call_id: &str) -> bool {+ call_id+ .strip_prefix(self.run_id.as_str())+ .and_then(|rest| rest.strip_prefix("-model-"))+ .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))+ }}impl EventListener for CapPauser {fn on_event(&self, record: &EventRecord) {- if matches!(record.event, AgentEvent::ModelCompleted { .. }) {- let n = self.completed.fetch_add(1, Ordering::SeqCst) + 1;- if n >= self.cap {- tracing::info!(- completed = n,- cap = self.cap,- "[tinyagents] model-call cap reached — requesting graceful pause"- );- // Record BEFORE sending the advisory command. The crate drains- // its event queue synchronously, notifying listeners in- // insertion order on the emitting task- // (`vendor/tinyagents/src/harness/events/mod.rs:163-195`), so- // this store happens-before any tool call the loop dispatches- // afterwards. That ordering is the whole fix: the pause stops- // being something a dispatch can race and becomes something a- // dispatch must observe.- if let Some(guard) = self.dispatch_guard.as_ref() {- guard.record_pause_requested(u64::from(n), u64::from(self.cap));- }- self.handle.send(SteeringCommand::Pause);+ let AgentEvent::ModelCompleted { call_id, .. } = &record.event else {+ return;+ };+ if !self.is_own_model_call(call_id.as_str()) {+ tracing::debug!(+ call_id = call_id.as_str(),+ run_id = %self.run_id,+ "[tinyagents] model-call cap: ignoring a nested run's model completion"+ );+ return;+ }+ let n = self.completed.fetch_add(1, Ordering::SeqCst) + 1;+ if n >= self.cap {+ tracing::info!(+ completed = n,+ cap = self.cap,+ "[tinyagents] model-call cap reached — requesting graceful pause"+ );+ // Record BEFORE sending the advisory command. The crate drains+ // its event queue synchronously, notifying listeners in+ // insertion order on the emitting task+ // (`vendor/tinyagents/src/harness/events/mod.rs:163-195`), so+ // this store happens-before any tool call the loop dispatches+ // afterwards. That ordering is the whole fix: the pause stops+ // being something a dispatch can race and becomes something a+ // dispatch must observe.+ if let Some(guard) = self.dispatch_guard.as_ref() {+ guard.record_pause_requested(u64::from(n), u64::from(self.cap));}+ self.handle.send(SteeringCommand::Pause);}}}++#[cfg(test)]+#[path = "cap_pauser_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rsnew file mode 100644index 0000000000..00c268b715--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/observability/cap_pauser_tests.rs@@ -0,0 +1,100 @@+use super::*;++use async_trait::async_trait;+use tinyagents_harness::context::{RunConfig, RunContext};+use tinyagents_harness::error::Result as TaResult;+use tinyagents_harness::events::EventSink;+use tinyagents_harness::middleware::Middleware;+use tinyagents_harness::runtime::{AgentHarness, RunPolicy};+use tinyagents_harness::steering::SteeringPolicy;+use tinyagents_harness::subagent::SubAgent;+use tinyagents_harness::testkit::{FakeTool, ScriptedModel};+use tinyagents_harness::tool::ToolResult;+use tinyinference::message::{AssistantMessage, Message};+use tinyinference::model::ModelResponse;+use tinyinference::tool::ToolCall;++const CAP: usize = 3;++fn tool_call_response(id: &str) -> ModelResponse {+ ModelResponse {+ message: AssistantMessage {+ id: Some(format!("msg-{id}")),+ content: Vec::new(),+ tool_calls: vec![ToolCall::new(id, "lookup", serde_json::json!({}))],+ usage: None,+ },+ usage: None,+ finish_reason: Some("tool_calls".to_string()),+ raw: None,+ resolved_model: None,+ continue_turn: None,+ served_from_cache: false,+ }+}++/// Runs a one-call nested sub-agent on the parent's sink after every tool, the+/// way the payload summarizer does for an oversized result. The child is named+/// after the parent run so its run id (`agent_turn-d1-N`) shares the parent's+/// prefix — attribution must still tell the two apart.+struct NestedRunAfterEveryTool;++#[async_trait]+impl Middleware<()> for NestedRunAfterEveryTool {+ fn name(&self) -> &str {+ "nested_run_after_every_tool"+ }++ async fn after_tool(+ &self,+ ctx: &mut RunContext<()>,+ _state: &(),+ _result: &mut ToolResult,+ ) -> TaResult<()> {+ let mut child: AgentHarness<()> = AgentHarness::new();+ child+ .register_model("child", Arc::new(ScriptedModel::replies(vec!["summary"])))+ .set_default_model("child");+ SubAgent::new("agent_turn", "nested", Arc::new(child))+ .invoke_with_events(&(), (), ctx.depth(), "summarize", &ctx.events)+ .await?;+ Ok(())+ }+}++#[tokio::test]+async fn nested_runs_on_the_shared_sink_do_not_spend_the_parents_cap() {+ let mut harness: AgentHarness<()> = AgentHarness::new();+ let mut policy = RunPolicy::default();+ // Hard ceiling well above the cap, so only the pauser can stop the run.+ policy.limits.max_model_calls = 10 * CAP;+ policy.limits.max_tool_calls = 80 * CAP;+ harness.with_policy(policy);+ let replies = (1..=10 * CAP)+ .map(|i| tool_call_response(&format!("t{i}")))+ .collect();+ harness+ .register_model("parent", Arc::new(ScriptedModel::new(replies)))+ .set_default_model("parent");+ harness.register_tool(Arc::new(FakeTool::returning("lookup", "ok")));+ harness.push_middleware(Arc::new(NestedRunAfterEveryTool));++ let sink = EventSink::new();+ let handle = SteeringHandle::new(SteeringPolicy::allow_all());+ let ctx = RunContext::new(RunConfig::new("agent_turn"), ())+ .with_events(sink.clone())+ .with_steering(handle.clone());+ sink.subscribe(CapPauser::new(handle, CAP, ctx.run_id().as_str(), None));++ let run = harness+ .invoke_in_context(&(), ctx, vec![Message::user("go")])+ .await+ .expect("run completes");++ assert!(run.paused.is_some(), "the cap pauser must pause the run");+ assert_eq!(+ run.model_calls, CAP,+ "the pause must land after the run's OWN {CAP} model calls; a nested run's \+ completions on the shared sink must not count toward the parent's cap"+ );+}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex 1fc516c6db..dd0594db7c 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -478,6 +478,7 @@ pub(crate) async fn run_turn_via_tinyagents_shared(events.subscribe(CapPauser::new(handle.clone(),max_iterations,+ ctx.run_id().as_str(),dispatch_guard,));}