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
feat(tinyagents): add deadline wind-down and budget-aware turn policy
Steven Enamakelb0fd53d46700
diff --git a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rsindex 48f65d43b4..2311589e80 100644--- a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs@@ -12,7 +12,7 @@ fn handle() -> SteeringHandle {fn the_default_harness_ceiling_is_clamped_below_the_backstop() {let backstop =Duration::from_secs(tinyagents_harness::turn_deadline::DEFAULT_TURN_BACKSTOP_SECS);- let default_ms = crate::agent::tinyagents::DEFAULT_AGENT_TURN_TIMEOUT_SECS * 1_000;+ let default_ms = tinyagents_harness::turn_policy::DEFAULT_AGENT_TURN_TIMEOUT_SECS * 1_000;assert!(default_ms > backstop.as_millis() as u64,"precondition: the unclamped ceiling is later than the backstop"diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rsindex b02c685ba0..f31aba546f 100644--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs@@ -2,7 +2,7 @@//! shared tools end up registered on the assembled harness.use super::*;-use crate::agent::tinyagents::turn_policy::{+use tinyagents_harness::turn_policy::{DEFAULT_MODEL_CALL_TIMEOUT_SECS, LOCAL_MODEL_CALL_TIMEOUT_SECS,};use crate::agent::tinyagents::TurnModelSource;diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex ba9d9c553c..c3c5aada5e 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -100,10 +100,7 @@ pub(crate) use turn_runner::{run_root_turn_via_hosted_agent, run_turn_via_tinyag#[cfg(test)]use tinyagents_harness::runtime::InvalidArgsPolicy;#[cfg(test)]-use turn_policy::{- model_call_wall_clock_ms, parse_agent_turn_wall_clock_ms, parse_model_call_wall_clock_ms,- run_policy_for, DEFAULT_AGENT_TURN_TIMEOUT_SECS, DEFAULT_MODEL_CALL_TIMEOUT_SECS,-};+use turn_policy::run_policy_for;#[cfg(test)]#[path = "nested_calls_tests.rs"]diff --git a/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs b/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rsindex 7c45531df1..95aea5e17c 100644--- a/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/tinyagents_tests.rs@@ -168,53 +168,24 @@ fn run_policy_retries_one_nontruncated_empty_completion() {assert_eq!(policy.empty_response_retries, 1);}-#[test]-fn parse_model_call_wall_clock_defaults_to_fifteen_minutes() {- // Absent and unparseable values both fall back to the 900s default.- assert_eq!(parse_model_call_wall_clock_ms(None), Some(900_000));- assert_eq!(- parse_model_call_wall_clock_ms(Some("garbage")),- Some(900_000)- );- assert_eq!(parse_model_call_wall_clock_ms(Some("")), Some(900_000));-}--#[test]-fn parse_model_call_wall_clock_honors_explicit_value_and_zero_opt_out() {- assert_eq!(parse_model_call_wall_clock_ms(Some("300")), Some(300_000));- assert_eq!(parse_model_call_wall_clock_ms(Some(" 300 ")), Some(300_000));- // `0` disables the per-call ceiling entirely (remainder-only, pre-#5766).- assert_eq!(parse_model_call_wall_clock_ms(Some("0")), None);-}-#[test]fn run_policy_wires_both_wall_clock_ceilings_from_their_resolvers() {- // Compare the policy against the same-process resolvers rather than- // hard-coded defaults, so a dev/CI environment exporting either- // `OPENHUMAN_MODEL_CALL_TIMEOUT_SECS` or `OPENHUMAN_AGENT_TURN_TIMEOUT_SECS`- // (including `0` = disabled, or a per-call value above the turn value)- // cannot fail the test while the wiring is correct. No env mutation —- // whatever the environment says, the policy must carry exactly what the- // resolvers produce.+ // Compare against the harness resolvers fed the same environment, so a+ // dev/CI environment exporting either override cannot fail the test while+ // the wiring is correct.let policy = run_policy_for(10, false);- assert_eq!(policy.limits.max_model_call_ms, model_call_wall_clock_ms());- assert_eq!(policy.limits.max_wall_clock_ms, agent_turn_wall_clock_ms());-}--#[test]-fn default_per_call_ceiling_sits_under_the_default_turn_ceiling() {- // Env-free: assert the *defaults* through the pure parsers, not through- // the env-reading policy path. A per-call ceiling at or above the turn- // deadline is dead code, because `min(ceiling, remainder)` would always- // pick the remainder.- let per_call =- parse_model_call_wall_clock_ms(None).expect("the per-call ceiling is armed by default");- let turn = parse_agent_turn_wall_clock_ms(None).expect("the turn ceiling is armed by default");- assert_eq!(per_call, DEFAULT_MODEL_CALL_TIMEOUT_SECS * 1_000);- assert_eq!(turn, DEFAULT_AGENT_TURN_TIMEOUT_SECS * 1_000);- assert!(- per_call < turn,- "per-call ceiling ({per_call} ms) must be under the turn ceiling ({turn} ms)"+ assert_eq!(+ policy.limits.max_model_call_ms,+ tinyagents_harness::turn_policy::model_call_wall_clock_ms(+ std::env::var("OPENHUMAN_MODEL_CALL_TIMEOUT_SECS")+ .ok()+ .as_deref(),+ false+ )+ );+ assert_eq!(+ policy.limits.max_wall_clock_ms,+ crate::agent::tinyagents::turn_policy::agent_turn_wall_clock_ms_for(false));}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rsindex 8a2a02f1ba..87d1e75df5 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_policy.rs@@ -1,9 +1,16 @@-//! Harness [`RunPolicy`] construction for an openhuman turn, plus the small-//! constants/helpers that shape it (wall-clock ceilings, the model-call cap-//! normalization, and the builder-configured tool-policy enforcement handle).--use tinyagents_harness::retry::RetryPolicy;-use tinyagents_harness::runtime::{InvalidArgsPolicy, RunPolicy, UnknownToolPolicy};+//! Harness [`RunPolicy`] construction for an openhuman turn.+//!+//! The policy itself (ceilings, retry schedule, unknown-tool and invalid-arg+//! recovery, cache and capture settings) is owned by+//! `tinyagents_harness::turn_policy`. This module keeps the host half: the+//! `OPENHUMAN_*` environment overrides, provider locality, the per-turn tool+//! budget and the spawn-depth cap.++use tinyagents_harness::runtime::RunPolicy;+use tinyagents_harness::turn_policy::{+ local_turn_backstop_secs, run_policy, turn_wall_clock_ms, TurnPolicyOptions,+ TurnPolicyOverrides,+};use crate::agent::tinyagents::budget::MAX_SPAWN_DEPTH;@@ -24,52 +31,6 @@ pub(crate) struct ToolPolicyEnforcement {pub agent_definition_id: String,}-/// Default per-turn wall-clock ceiling for an openhuman agent turn, in seconds-/// (issue #4746). Applied as the harness `RunLimits::max_wall_clock_ms` so the-/// loop interrupts a call instead of parking forever with no terminal event.-///-/// 60 minutes (#5766, was 10). With hang detection now owned by the per-call-/// ceiling below, this is a pure runaway guard over the whole turn — its old-/// 600s value doubled as the per-call bound (every call got the turn's-/// *remainder*), which killed long *productive* turns: a turn that had-/// legitimately spent ~543s across many successful calls handed its next model-/// call a 56s budget and died. A turn's real bounds are the model/tool call-/// caps times the per-call ceiling; this only catches what escapes those.-pub(super) const DEFAULT_AGENT_TURN_TIMEOUT_SECS: u64 = 3_600;--/// Default wall-clock ceiling for a **single model call** within a turn, in-/// seconds (#5766). Applied as the harness `RunLimits::max_model_call_ms`, so-/// every model call (and every retry attempt) gets a fresh-/// `min(this, turn remainder)` budget instead of only the shrinking remainder.-/// This is the hang detector the turn ceiling used to double as — scoped to-/// the one call that wedged, not the whole turn's history.-///-/// Deliberately generous — 15 minutes: a hidden-reasoning model call can be-/// legitimately app-silent for several minutes, so this is a backstop for-/// calls that will never return, not a latency target. Tool calls (including-/// sub-agent delegations, which wrap entire child turns) are exempt by design-/// in the harness and stay bounded by the turn remainder plus their own-/// per-tool timeouts.-pub(super) const DEFAULT_MODEL_CALL_TIMEOUT_SECS: u64 = 900;--/// Per-model-call ceiling for a **local / self-hosted** provider (Ollama,-/// LM Studio, MLX, llama.cpp...), in seconds (#6042). A local model prefills-/// the whole prompt before it emits its first token, and a ~57K-token prompt-/// takes many minutes on consumer hardware, so the hosted 900s ceiling killed-/// calls that were making progress. One hour; hang detection for hosted-/// providers keeps the tighter [`DEFAULT_MODEL_CALL_TIMEOUT_SECS`].-pub(super) const LOCAL_MODEL_CALL_TIMEOUT_SECS: u64 = 3_600;--/// Per-turn ceiling for a local / self-hosted provider, in seconds (#6042):-/// four hours, so a turn of several slow local calls still fits. Must stay-/// above [`LOCAL_MODEL_CALL_TIMEOUT_SECS`].-pub(super) const LOCAL_AGENT_TURN_TIMEOUT_SECS: u64 = 14_400;--/// Extra seconds the outer web-turn backstop allows a local turn beyond the-/// harness turn ceiling, so the harness's own (more informative) timeout fires-/// first.-pub(crate) const LOCAL_WEB_TURN_BACKSTOP_GRACE_SECS: u64 = 300;-/// Whether `provider` (a provider string such as `ollama:llama3`) with the/// resolved `endpoint` is a local / self-hosted runtime, which gets the longer/// ceilings (#6042).@@ -120,178 +81,38 @@ pub(crate) fn local_openai_endpoint(config: &crate::config::Config) -> Option<St})}-/// Resolve the per-turn wall-clock ceiling in milliseconds for the harness-/// policy. Reads `OPENHUMAN_AGENT_TURN_TIMEOUT_SECS` (falling back to-/// [`DEFAULT_AGENT_TURN_TIMEOUT_SECS`]); `0` means "no ceiling" → `None`, which-/// restores the previous unbounded behavior for callers that deliberately opt-/// out (e.g. very long autonomous runs).-#[cfg(test)]-pub(crate) fn agent_turn_wall_clock_ms() -> Option<u64> {- agent_turn_wall_clock_ms_for(false)-}--/// Resolve the wall-clock ceiling for a turn on a local provider when `local`:-/// the env override still wins, otherwise the default is-/// [`LOCAL_AGENT_TURN_TIMEOUT_SECS`].+/// Resolve the per-turn wall-clock ceiling in milliseconds for a turn on a+/// local provider when `local`. `OPENHUMAN_AGENT_TURN_TIMEOUT_SECS` still wins;+/// `0` means "no ceiling" and yields `None`.pub(crate) fn agent_turn_wall_clock_ms_for(local: bool) -> Option<u64> {- parse_turn_ms_with_default(- std::env::var("OPENHUMAN_AGENT_TURN_TIMEOUT_SECS")- .ok()- .as_deref(),- if local {- LOCAL_AGENT_TURN_TIMEOUT_SECS- } else {- DEFAULT_AGENT_TURN_TIMEOUT_SECS- },- )+ turn_wall_clock_ms(env_str("OPENHUMAN_AGENT_TURN_TIMEOUT_SECS").as_deref(), local)}-fn parse_turn_ms_with_default(env_value: Option<&str>, default_secs: u64) -> Option<u64> {- let secs = env_value- .and_then(|v| v.trim().parse::<u64>().ok())- .unwrap_or(default_secs);- (secs > 0).then(|| secs.saturating_mul(1_000))-}--/// Outer web-turn backstop for a turn on a local provider: the local turn-/// ceiling plus [`LOCAL_WEB_TURN_BACKSTOP_GRACE_SECS`], or `None` when the turn-/// ceiling is disabled. The backstop must sit above the harness ceiling or it-/// pre-empts it (#6042: it was 900s, under even the hosted 3600s ceiling).+/// Outer web-turn backstop for a turn on a local provider (#6042): the local+/// turn ceiling plus the harness grace, or `None` when the ceiling is disabled.pub(crate) fn local_web_turn_backstop_secs() -> Option<u64> {- agent_turn_wall_clock_ms_for(true).map(|ms| ms / 1_000 + LOCAL_WEB_TURN_BACKSTOP_GRACE_SECS)-}--/// Pure core of the per-turn wall-clock ceiling: map an optional-/// `OPENHUMAN_AGENT_TURN_TIMEOUT_SECS` value to a wall-clock ceiling in-/// milliseconds. An absent/unparseable value falls back to-/// [`DEFAULT_AGENT_TURN_TIMEOUT_SECS`]; `0` yields `None` (unbounded opt-out).-/// Kept env-free so it is deterministically unit-testable.-pub(super) fn parse_agent_turn_wall_clock_ms(env_value: Option<&str>) -> Option<u64> {- parse_turn_ms_with_default(env_value, DEFAULT_AGENT_TURN_TIMEOUT_SECS)-}--/// Resolve the per-model-call wall-clock ceiling in milliseconds for the-/// harness policy. Reads `OPENHUMAN_MODEL_CALL_TIMEOUT_SECS` (falling back to-/// [`DEFAULT_MODEL_CALL_TIMEOUT_SECS`]); `0` means "no per-call ceiling" →-/// `None`, leaving calls bounded only by the turn's remaining wall clock as-/// before #5766.-pub(super) fn model_call_wall_clock_ms() -> Option<u64> {- model_call_wall_clock_ms_for(false)-}--/// [`model_call_wall_clock_ms`] for a local provider when `local` (#6042): the-/// env override still wins, otherwise [`LOCAL_MODEL_CALL_TIMEOUT_SECS`].-pub(super) fn model_call_wall_clock_ms_for(local: bool) -> Option<u64> {- parse_turn_ms_with_default(- std::env::var("OPENHUMAN_MODEL_CALL_TIMEOUT_SECS")- .ok()- .as_deref(),- if local {- LOCAL_MODEL_CALL_TIMEOUT_SECS- } else {- DEFAULT_MODEL_CALL_TIMEOUT_SECS- },- )-}--/// Pure core of [`model_call_wall_clock_ms`]: map an optional-/// `OPENHUMAN_MODEL_CALL_TIMEOUT_SECS` value to a per-call ceiling in-/// milliseconds. An absent/unparseable value falls back to-/// [`DEFAULT_MODEL_CALL_TIMEOUT_SECS`]; `0` yields `None` (opt-out). Kept-/// env-free so it is deterministically unit-testable — the same shape as-/// [`parse_agent_turn_wall_clock_ms`].-pub(super) fn parse_model_call_wall_clock_ms(env_value: Option<&str>) -> Option<u64> {- parse_turn_ms_with_default(env_value, DEFAULT_MODEL_CALL_TIMEOUT_SECS)-}--/// Default silence allowed between output events of a streaming model call,-/// in seconds, once the first output has arrived. Matches the harness default-/// but is set explicitly so a harness bump cannot silently change it.-pub(super) const DEFAULT_STREAM_IDLE_TIMEOUT_SECS: u64 = 120;--/// Default circuit breaker: consecutive stream idle timeouts on one model-/// before retrying that model stops.-pub(super) const DEFAULT_MAX_CONSECUTIVE_STREAM_IDLE_TIMEOUTS: usize = 5;--/// Pure core of the stream idle ceiling: `OPENHUMAN_STREAM_IDLE_TIMEOUT_SECS`-/// in seconds, `0` disables, absent/unparseable falls back to the default.-pub(super) fn parse_stream_idle_timeout_ms(env_value: Option<&str>) -> Option<u64> {- let secs = env_value- .and_then(|v| v.trim().parse::<u64>().ok())- .unwrap_or(DEFAULT_STREAM_IDLE_TIMEOUT_SECS);- (secs > 0).then(|| secs.saturating_mul(1_000))-}--/// Pure core of the first-event ceiling: `OPENHUMAN_STREAM_FIRST_EVENT_TIMEOUT_SECS`.-/// Off (`None`) unless set to a positive value: reasoning-hidden providers and-/// local models legitimately stay silent for minutes before the first token.-pub(super) fn parse_stream_first_event_timeout_ms(env_value: Option<&str>) -> Option<u64> {- env_value- .and_then(|v| v.trim().parse::<u64>().ok())- .filter(|secs| *secs > 0)- .map(|secs| secs.saturating_mul(1_000))-}--/// Pure core of the idle-timeout breaker:-/// `OPENHUMAN_MAX_CONSECUTIVE_STREAM_IDLE_TIMEOUTS`, `0` disables.-pub(super) fn parse_max_consecutive_stream_idle_timeouts(env_value: Option<&str>) -> Option<usize> {- let n = env_value- .and_then(|v| v.trim().parse::<usize>().ok())- .unwrap_or(DEFAULT_MAX_CONSECUTIVE_STREAM_IDLE_TIMEOUTS);- (n > 0).then_some(n)-}--/// Writes the three stream-silence limits from raw override values. Taking the-/// values as arguments keeps the default-policy tests independent of the-/// process environment.-pub(super) fn apply_stream_limits(- limits: &mut tinyagents_harness::limits::RunLimits,- idle: Option<&str>,- first_event: Option<&str>,- breaker: Option<&str>,-) {- limits.stream_idle_timeout_ms = parse_stream_idle_timeout_ms(idle);- limits.stream_first_event_timeout_ms = parse_stream_first_event_timeout_ms(first_event);- limits.max_consecutive_stream_idle_timeouts =- parse_max_consecutive_stream_idle_timeouts(breaker);+ local_turn_backstop_secs(env_str("OPENHUMAN_AGENT_TURN_TIMEOUT_SECS").as_deref())}fn env_str(name: &str) -> Option<String> {std::env::var(name).ok()}-/// Build the harness [`RunPolicy`] for an openhuman turn.-///-/// The loop enforces limits from `self.policy.limits` (not the per-run-/// `RunConfig`), so the model-call cap **must** be set here or it falls back to-/// the tinyagents default of 25 — far more than openhuman's `max_iterations`.-/// The recursion depth cap is also set here so TinyAgents uses OpenHuman's-/// existing sub-agent spawn depth instead of the SDK default.-/// Retry is now owned by the crate [`RetryPolicy`] (issue #4249, Phase 3a): the-/// turn path no longer wraps its provider in `ReliableProvider` (removed in-/// `session/builder/factory.rs`), so the single retry layer is here, at the-/// harness model call. The schedule is **4 retries over ~45 s** (issue #6413);-/// it used to mirror the former `ReliableProvider` defaults — 2 retries with-/// 500 ms backoff, about 1.5 s in total — which was far too short to outlast a-/// throttled upstream. Retryability is decided by the crate-/// `is_retryable`, which the [`native model adapter`](super::model) adapter feeds-/// correctly: a permanent config/auth/quota/context error is mapped to a-/// non-retryable `TinyAgentsError::Validation`, a transient blip to a retryable-/// `Model` error. The crate caps `max_attempts` at-/// `RunLimits::max_retries_per_call + 1` (default 3 retries), so this stays-/// within the loop's own bound.-///-/// (Config parity note: the former `config.reliability.provider_retries` /-/// `provider_backoff_ms` / `model_fallbacks` no longer drive the turn path —-/// retry is the fixed schedule below and cross-route fallback is the crate-/// registry `FallbackPolicy` from [`routes::route_fallback_policy`](super::routes::route_fallback_policy).-/// Those config knobs still apply to the non-seam `ReliableProvider` paths.)-///-/// Cross-route **fallback** (`RunPolicy.fallback`) is orthogonal to retry and is-/// populated per-turn by the caller ([`assemble_turn_harness`](super::harness_assembly::assemble_turn_harness)-/// via [`routes::route_fallback_policy`](super::routes::route_fallback_policy)); it is safe to enable now because-/// `ReliableProvider` does *not* fail over across the registered workload-tier-/// routes (chat→burst, reasoning→agentic, …) the way the harness registry can.+/// The `OPENHUMAN_*` overrides for the harness ceilings, read from the process+/// environment.+fn env_overrides() -> TurnPolicyOverrides {+ TurnPolicyOverrides {+ turn_timeout_secs: env_str("OPENHUMAN_AGENT_TURN_TIMEOUT_SECS"),+ model_call_timeout_secs: env_str("OPENHUMAN_MODEL_CALL_TIMEOUT_SECS"),+ stream_idle_timeout_secs: env_str("OPENHUMAN_STREAM_IDLE_TIMEOUT_SECS"),+ stream_first_event_timeout_secs: env_str("OPENHUMAN_STREAM_FIRST_EVENT_TIMEOUT_SECS"),+ max_consecutive_stream_idle_timeouts: env_str(+ "OPENHUMAN_MAX_CONSECUTIVE_STREAM_IDLE_TIMEOUTS",+ ),+ }+}++/// Build the harness [`RunPolicy`] for an openhuman turn (hosted provider).pub(crate) fn run_policy_for(max_iterations: usize, response_cache_enabled: bool) -> RunPolicy {run_policy_for_provider(max_iterations, response_cache_enabled, false)}@@ -299,178 +120,22 @@ pub(crate) fn run_policy_for(max_iterations: usize, response_cache_enabled: bool/// [`run_policy_for`] with the turn's provider locality: a local / self-hosted/// provider gets the longer per-call and per-turn ceilings (#6042); hosted/// providers keep the tight defaults so a wedged call is still caught fast.+///+/// Cross-route fallback (`RunPolicy.fallback`) is orthogonal and populated+/// per-turn by [`assemble_turn_harness`](super::harness_assembly::assemble_turn_harness).pub(crate) fn run_policy_for_provider(max_iterations: usize,response_cache_enabled: bool,local_provider: bool,) -> RunPolicy {- let mut policy = RunPolicy::default();- // A managed streaming response can finish with reasoning but no visible- // answer. Reissue that unusable call once; the harness keeps the same- // output cap and drops the blank assistant row before retrying. If it- // repeats, the existing EmptyProviderResponse path remains actionable.- policy.empty_response_retries = 1;- policy.limits.max_model_calls = max_iterations;- policy.limits.max_tool_calls = crate::agent::stop_hooks::tool_call_limit(max_iterations);- policy.limits.max_depth = MAX_SPAWN_DEPTH;- // Wall-clock ceiling for the whole turn (issue #4746). The harness bounds- // every individual model AND tool call by the run's *remaining* wall-clock- // budget (`with_call_budget` → `tokio::time::timeout`), but ONLY when a- // deadline is configured — with `max_wall_clock_ms = None` (the default)- // `call_budget()` returns `None` and each call is awaited UNBOUNDED. That is- // exactly how a turn shipped an empty reply: a hung/slow model stream or a- // delegated sub-agent tool call that never returned left the loop parked- // inside an await, so the between-call deadline check never ran and no- // terminal event (loop `Timeout` → chat_error) ever fired. Setting the cap- // here arms the harness's per-call timeout so a wedged call is interrupted- // mid-flight and the turn degrades gracefully. It also bounds sub-agents:- // the parent's remaining-budget wraps the sub-agent tool call, and a child- // turn with no per-run timeout inherits this policy-level cap. Generous by- // design (a backstop, not a UX deadline); env-overridable, `0` disables.- policy.limits.max_wall_clock_ms = agent_turn_wall_clock_ms_for(local_provider);- // Per-model-call ceiling (#5766): each model call (and retry attempt) gets- // a fresh `min(ceiling, turn remainder)` budget, so hang detection is- // per-call instead of riding the turn deadline — which let the turn- // ceiling above grow from 10 to 60 minutes without a wedged call being- // able to hold a turn for more than this. Tool calls (incl. sub-agent- // delegations) are exempt in the harness and keep the remainder-only- // budget. Env-overridable, `0` disables.- policy.limits.max_model_call_ms = model_call_wall_clock_ms_for(local_provider);- // Stream silence bounds, explicit so a harness default change cannot- // alter them. The idle window applies only after the first output event;- // the first-event bound is OFF by default because local and hidden-- // reasoning models stay silent for minutes before the first token. The- // breaker stops retrying a model that keeps stalling.- apply_stream_limits(- &mut policy.limits,- env_str("OPENHUMAN_STREAM_IDLE_TIMEOUT_SECS").as_deref(),- env_str("OPENHUMAN_STREAM_FIRST_EVENT_TIMEOUT_SECS").as_deref(),- env_str("OPENHUMAN_MAX_CONSECUTIVE_STREAM_IDLE_TIMEOUTS").as_deref(),- );- // Each executed tool row ends with `[took 12.3s]` (#6953). Without it the- // model cannot tell a fifteen-minute command from a fast one, so it cannot- // budget the rest of the turn against the ceiling above.- policy.tool_result_durations = true;- // Crate-owned retry (Phase 3a), lengthened for #6413.- //- // The former schedule — 2 retries at 500 ms and 1 s — spent about 1.5 s in- // total, which is nothing against a throttled upstream: a managed 429 killed- // the turn while the provider was still rate-limiting. 4 retries at 3/6/12/24 s- // spend ~45 s, and ~33.75 s even on the worst jitter draw (`JITTER_FRACTION`- // is 0.25, so each delay lands in `[base * 0.75, base * 1.25]`) — the floor is- // what has to clear the issue's "at least 3 retries over >=30 s", not the- // nominal figure.- //- // `max_retries_per_call` is raised alongside it and that line is load-bearing:- // `RunLimits` defaults it to 3, and the harness applies- // `max_attempts_capped_at(max_retries_per_call)` at the model call- // (`agent_loop/model_call.rs`), so `max_attempts` above 4 is **silently- // clamped** without it. Raising `max_attempts` alone would have looked like a- // fix and changed nothing.- //- // The first retry moves 500 ms -> 3 s, which is the deliberate cost: one curve- // serves every retryable class, so a transient 5xx now waits 3 s too. Buying a- // fast first retry *and* a 30 s tail needs per-class backoff, which lives in- // the crate's `backoff_for_error` rather than here.- //- // Both ceilings stay bounded — `max_attempts` and `max_retry_after_ms` — so- // this adds no unbounded retry (cf. #6412, which is the opposite failure in- // `vendor/tinymcp`: a different crate and loop, untouched by this).- //- // `jitter` is now on: a fleet throttled together previously retried in- // lockstep on an identical curve, which is the shape that keeps an upstream- // saturated. Jitter only widens the band; it never removes the delay.- policy.limits.max_retries_per_call = 4;- policy.retry = RetryPolicy {- max_attempts: 5,- initial_backoff_ms: 3_000,- max_backoff_ms: 30_000,- multiplier: 2.0,- jitter: true,- backoff_sleep: true,- max_retry_after_ms: RetryPolicy::DEFAULT_MAX_RETRY_AFTER_MS,- retry_on: None,- };- // Unknown-tool recovery (01.2 / C3): the crate policy owns this end to end —- // the `__openhuman_unknown_tool__` sentinel tool + `UnknownToolRewriteMiddleware`- // were already deleted. We deliberately keep `ReturnToolError` rather than- // `Rewrite { tool_name }`: Rewrite requires a real catch-all target tool (the- // deleted sentinel was exactly that) and, when it hits, *silently* executes- // that tool and emits `AgentEvent::UnknownToolCall { recovery: "rewrite:.." }`- // WITHOUT injecting a tool message. `ReturnToolError` instead injects a- // recoverable `unknown tool `<name>`: ...` result naming the originally- // requested tool, a few close matches and (when discovery is on) a pointer- // to `tool_search` rather than a dump of every callable name. Two live consumers depend on- // that message: (1) the #4419 attempted-tool-name UX and (2) the failure- // classifier in `agent::hooks::sanitize_tool_output`, which labels the result- // `unknown_tool` by matching the "unknown tool" substring. Flipping to Rewrite- // would drop both. The original name + args are also preserved verbatim on- // `AgentEvent::UnknownToolCall` and projected by `OpenhumanEventBridge`.- policy.unknown_tool = UnknownToolPolicy::ReturnToolError;- // Registered tools with schema-invalid arguments should produce a tool- // error the model can correct, not abort the entire run. TinyAgents 2.1- // owns this admission behavior directly; the former host SchemaGuard had- // to manufacture valid stub arguments only because this policy was left at- // its historical fail-fast default.- //- // Normalize first: some providers (DeepSeek via OpenRouter) JSON-encode a- // nested object-typed argument, e.g. `mcp_registry_tool_call` with- // `"arguments": "{}"`. `ArgRecoveryMiddleware` only repairs a top-level- // string, so without the harness's schema-guided coercion every such call- // failed validation — and a parallel batch of them tripped the- // classified-failure breaker before the model could correct itself.- // Normalization keeps a rewrite only when it validates, so genuinely- // invalid arguments still come back as a corrective tool error.- policy.invalid_args = InvalidArgsPolicy::NormalizeThenReturnToolError;- // Prompt-prefix protection is always on (issue #4249, 03.2). Two things- // ride on it, and both were inert until the harness started stamping this- // effective policy onto the outgoing request (tinyagents `model_call`):- // * the `PromptCacheGuardMiddleware` records a `CacheLayoutEvent` whenever- // volatile content busts the provider KV-cache prefix (diagnostic), and- // * the loop injects a `prompt_cache_key` routing hint derived from the- // stable prefix into `provider_options`, and the provider adapters see- // `protect_prompt_prefix` and emit explicit `cache_control` breakpoints- // where the provider needs them (native Anthropic, OpenRouter relays).- // The stable prefix itself is declared per request by the vendor loop from- // the session's frozen system prefix (`RunContext::frozen_system_prefix_len`).- policy.cache.protect_prompt_prefix = true;- // Response caching is gated: it is enabled only for deterministic internal- // runs (which additionally attach a `ResponseCache`). Interactive chat turns- // pass `false` here AND attach no cache, so a live user turn can never be- // served a cached model response (double fail-safe).- policy.cache.response_cache_enabled = response_cache_enabled;- // Payload capture ON: the loop stamps request messages + completion onto- // `ModelCompleted` and tool arguments + result onto `ToolCompleted`, which- // the `OpenhumanEventBridge` projects into content-bearing `AgentProgress`- // events (generation/tool span input+output in trace exports). Privacy- // posture is unchanged off-device: the durable journal passes through a- // `RedactingSink` (on-device, same data class as the threads DB, which- // already persists full conversations + tool output), and the Langfuse- // exporter withholds all content unless- // `observability.agent_tracing.capture_content` is on.- policy.capture = tinyagents_harness::runtime::PayloadCapture::all();- policy-}--/// Consecutive identical tool failures that trip the repeated-failure circuit-/// breaker (see `middleware::RepeatedToolFailureMiddleware`). Three matches the-/// legacy progress-guard's tolerance before it halted a stuck loop.-pub(crate) const REPEATED_TOOL_FAILURE_THRESHOLD: usize = 3;--/// Legacy default model-call cap used when a caller passes `max_iterations == 0`-/// to request "unset" (native-bus / test callers relied on the old loop treating-/// `max_tool_iterations == 0` as the default of 10). Passing `0` straight through-/// would set the harness `max_model_calls` to zero and abort before the first-/// provider call, so the runners normalize `0` to this value.-const DEFAULT_MAX_ITERATIONS: usize = 10;--/// Normalize a caller-supplied iteration cap: `0` means "unset" → the default.-pub(crate) fn effective_max_iterations(max_iterations: usize) -> usize {- if max_iterations == 0 {- DEFAULT_MAX_ITERATIONS- } else {- max_iterations- }+ run_policy(&TurnPolicyOptions {+ max_model_calls: max_iterations,+ max_tool_calls: crate::agent::stop_hooks::tool_call_limit(max_iterations),+ max_depth: MAX_SPAWN_DEPTH,+ local_provider,+ response_cache_enabled,+ overrides: env_overrides(),+ })}/// True when `name` is a sub-agent spawn/delegation tool that a **child** rundiff --git a/crates/openhuman-core/src/agent/tinyagents/turn_policy_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/turn_policy_budget_tests.rsindex 1cd13fb392..135a62b24c 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_policy_budget_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_policy_budget_tests.rs@@ -18,33 +18,6 @@ fn tool_results_carry_their_duration() {assert!(run_policy_for(10, false).tool_result_durations);}-#[test]-fn stream_timeouts_are_set_explicitly_with_first_event_off() {- let mut limits = RunPolicy::default().limits;- apply_stream_limits(&mut limits, None, None, None);- assert_eq!(limits.stream_idle_timeout_ms, Some(120_000));- assert_eq!(limits.stream_first_event_timeout_ms, None);- assert_eq!(limits.max_consecutive_stream_idle_timeouts, Some(5));-}--#[test]-fn stream_timeout_env_overrides_parse() {- assert_eq!(parse_stream_idle_timeout_ms(Some("30")), Some(30_000));- assert_eq!(parse_stream_idle_timeout_ms(Some("0")), None);- assert_eq!(parse_stream_idle_timeout_ms(Some("junk")), Some(120_000));- assert_eq!(- parse_stream_first_event_timeout_ms(Some("45")),- Some(45_000)- );- assert_eq!(parse_stream_first_event_timeout_ms(Some("0")), None);- assert_eq!(parse_stream_first_event_timeout_ms(None), None);- assert_eq!(parse_max_consecutive_stream_idle_timeouts(Some("0")), None);- assert_eq!(- parse_max_consecutive_stream_idle_timeouts(Some("2")),- Some(2)- );-}-#[test]fn local_providers_get_longer_ceilings_than_hosted_ones() {let hosted = run_policy_for_provider(10, false, false);@@ -72,7 +45,7 @@ fn local_web_backstop_sits_above_the_local_turn_ceiling() {let backstop = local_web_turn_backstop_secs();assert_eq!(backstop,- turn_secs.map(|s| s + LOCAL_WEB_TURN_BACKSTOP_GRACE_SECS)+ turn_secs.map(|s| s + tinyagents_harness::turn_policy::LOCAL_WEB_TURN_BACKSTOP_GRACE_SECS));}diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rsindex a6e3e9d201..07abc6095a 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_runner.rs@@ -23,7 +23,7 @@ use crate::agent::tinyagents::middleware::TurnContextMiddleware;use crate::agent::tinyagents::observability::{OpenhumanEventBridge, SubagentScope};use crate::agent::tinyagents::turn_models::TurnModels;use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;-use crate::agent::tinyagents::turn_policy::effective_max_iterations;+use tinyagents_harness::turn_policy::effective_max_iterations;use crate::agent::tinyagents::turn_run_error::map_turn_run_error;use crate::agent::tinyagents::turn_run_finalize::finalize_turn_outcome;use crate::agent::tinyagents::{journal, routes, steering_forwarder};