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
Merge upstream/main into fix/web-turn-inactivity-guard
killbille18fa4b3c547
diff --cc crates/openhuman-core/src/agent/session_host/turn_backstop.rsindex 9bea1fcbb0,8533bb611c..6a2dccd2ec--- a/crates/openhuman-core/src/agent/session_host/turn_backstop.rs+++ b/crates/openhuman-core/src/agent/session_host/turn_backstop.rs@@@ -10,9 -12,9 +12,9 @@@//!//! The deadline value (`tinyagents_harness::turn_deadline::TurnDeadline`)//! owns the two points the harness derives from the backstop; this module- //! keeps the host side (env override, task-local scope):+ //! keeps the host side (the env override)://!-//! * **wind-down** (`backstop - min(120s, backstop/5)`, 780s by default): the+//! * **wind-down** (`backstop - min(120s, backstop/5)`, 3480s by default): the//! harness pauses the run at the next safe point, after a model call or a//! tool result. The driver then writes the grounded close from the work//! already in hand. The margin before the backstop pays for that close.@@@ -22,82 -24,26 +24,48 @@@//! typed `Timeout` before the backstop drops the turn.//!//! For every positive backstop, `wind_down < hard_stop < backstop`- //! (see the harness `turn_deadline_tests.rs`).+ //! (see `turn_backstop_tests.rs`).//!+//! The web backstop defaults to [`DEFAULT_WEB_TURN_BACKSTOP_SECS`] (3600s, the+//! harness turn ceiling), not the harness default of 900s. It bounds a turn+//! that stays busy; it is not the hang detector. A turn that goes silent with+//! no model or tool call in flight is ended much earlier by the web-turn idle+//! guard (`web_chat::turn_activity`, 900s of inactivity by default). At 900s+//! the backstop did both jobs, so a turn that was working steadily was wound+//! down at 780s like a wedged one.+//!- //! The web-turn guard scopes the deadline on a task-local- //! ([`with_turn_deadline`]). The top-level session turn+ //! The web-turn guard builds the deadline and hands it to the session it runs+ //! (`HostTurnEnv::turn_deadline`). The top-level session turn//! (`OpenHumanSessionHost::turn_with_origin`) copies it onto its explicit run//! context. Turns with no backstop, such as other channels or the CLI, carry//! `None` and keep their previous behaviour.- use std::future::Future;use std::time::Duration;- use tinyagents_harness::turn_deadline::TurnDeadline;-use tinyagents_harness::turn_deadline::{parse_backstop, TurnDeadline};--/// Environment override for the backstop, in seconds; `0` disables it.pub const TURN_BACKSTOP_ENV: &str = "OPENHUMAN_WEB_TURN_TIMEOUT_SECS";- /// Time kept back from the post-loop grounded close so the turn can commit and- /// emit its reply before the backstop drops it.- const CLOSE_RESERVE: Duration = Duration::from_secs(10);-- /// How long the post-loop grounded close may run as of `now`: the backstop- /// remainder minus [`CLOSE_RESERVE`], zero once that has passed (#7716).- /// Host-side until the harness `TurnDeadline` grows the same accessor.- pub fn close_budget(deadline: &TurnDeadline, now: std::time::Instant) -> Duration {- deadline- .backstop()- .saturating_sub(deadline.elapsed_at(now))- .saturating_sub(CLOSE_RESERVE)- }-+/// Default web-turn backstop, in seconds: the harness's own default turn+/// ceiling (`DEFAULT_AGENT_TURN_TIMEOUT_SECS`). The harness default+/// (`tinyagents_harness::turn_deadline::DEFAULT_TURN_BACKSTOP_SECS`, 900s)+/// assumes the backstop is also the hang detector; on the web channel the idle+/// guard is.+pub const DEFAULT_WEB_TURN_BACKSTOP_SECS: u64 = 3_600;++/// Pure core of [`configured_backstop`]: an absent or unparseable value falls+/// back to [`DEFAULT_WEB_TURN_BACKSTOP_SECS`]; `0` disables the backstop.+pub fn parse_web_backstop(env_value: Option<&str>) -> Option<Duration> {+ let secs = env_value+ .and_then(|v| v.trim().parse::<u64>().ok())+ .unwrap_or(DEFAULT_WEB_TURN_BACKSTOP_SECS);+ (secs > 0).then(|| Duration::from_secs(secs))+}+/// The backstop in force for this process (env [`TURN_BACKSTOP_ENV`]).pub fn configured_backstop() -> Option<Duration> {- parse_backstop(std::env::var(TURN_BACKSTOP_ENV).ok().as_deref())+ parse_web_backstop(std::env::var(TURN_BACKSTOP_ENV).ok().as_deref())}- tokio::task_local! {- static CURRENT_TURN_DEADLINE: TurnDeadline;- }-- /// The deadline scoped on the current task, if any.- pub fn current() -> Option<TurnDeadline> {- CURRENT_TURN_DEADLINE.try_with(|deadline| *deadline).ok()- }-- /// Run `future` with `deadline` scoped on the task (a no-op scope for `None`).- pub async fn with_turn_deadline<F: Future>(deadline: Option<TurnDeadline>, future: F) -> F::Output {- match deadline {- Some(deadline) => CURRENT_TURN_DEADLINE.scope(deadline, future).await,- None => future.await,- }- }-#[cfg(test)]- #[path = "turn_deadline_tests.rs"]+ #[path = "turn_backstop_tests.rs"]mod tests;diff --cc crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rsindex 0000000000,9b79ddbc14..ec76bd6a6amode 000000,100644..100644--- a/crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/turn_backstop_tests.rs@@@ -1,0 -1,15 +1,34 @@@+ use super::*;++use tinyagents_harness::turn_deadline::{parse_backstop, TurnDeadline};++ #[test]+ fn parse_backstop_defaults_and_disables() {+ assert_eq!(parse_backstop(None), Some(Duration::from_secs(900)));+ assert_eq!(+ parse_backstop(Some("garbage")),+ Some(Duration::from_secs(900))+ );+ assert_eq!(+ parse_backstop(Some(" 120 ")),+ Some(Duration::from_secs(120))+ );+ assert_eq!(parse_backstop(Some("0")), None);+ }++++/// The web backstop defaults to the harness turn ceiling, not the harness's++/// 900s, and keeps the env override and the `0` opt-out.++#[test]++fn web_backstop_defaults_to_an_hour_and_keeps_the_override() {++ let hour = Some(Duration::from_secs(DEFAULT_WEB_TURN_BACKSTOP_SECS));++ assert_eq!(DEFAULT_WEB_TURN_BACKSTOP_SECS, 3_600);++ assert_eq!(parse_web_backstop(None), hour);++ assert_eq!(parse_web_backstop(Some("garbage")), hour);++ assert_eq!(++ parse_web_backstop(Some(" 120 ")),++ Some(Duration::from_secs(120))++ );++ assert_eq!(parse_web_backstop(Some("0")), None);++ let deadline = TurnDeadline::starting_now(hour.unwrap());++ assert_eq!(deadline.wind_down_after(), Duration::from_secs(3_480));++ assert_eq!(deadline.hard_stop_after(), Duration::from_secs(3_540));++}diff --cc crates/openhuman-core/src/agent/tinyagents/observability.rsindex 2430c4c0a5,32b645a3f6..07705eb3d3--- a/crates/openhuman-core/src/agent/tinyagents/observability.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability.rs@@@ -11,8 -11,6 +11,7 @@@mod bridge_types;mod event_bridge;mod event_projection;- mod graph_tracing;+mod tool_progress_projection;#[cfg(test)]use std::sync::Arc;diff --cc crates/openhuman-core/src/web_chat/ops/turn_guards.rsindex 3ca45de4b1,2cfa38bea8..94223a5c30--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs@@@ -6,35 -6,36 +6,36 @@@ use std::time::Durationuse tokio_util::sync::CancellationToken;+use super::super::turn_activity::{self, TurnActivity};+use super::super::turn_close::{StopCause, StoppedTurn};use super::super::types::WebChatTaskResult;+ use crate::agent::turn_env::HostTurnEnv;/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).///-/// This is the OUTER safety net (issue #4746), and the single source of truth-/// for the turn's deadlines (`agent::session_host::turn_backstop`, default 900s). The-/// harness derives two earlier points from it:+/// This is the turn's fixed total ceiling (issue #4746), and the single source- /// of truth for the turn's deadlines (`agent::turn_deadline`, default 3600s,++/// of truth for the turn's deadlines (`agent::session_host::turn_backstop`, default 3600s,+/// the harness's own turn ceiling). The harness derives two earlier points+/// from it:///-/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 780s by default.-/// The harness pauses the run at its next safe point, and the session driver-/// writes the grounded close from the work already done, so a long turn-/// still delivers an answer.-/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 840s by default.-/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,-/// 3600s on its own) is clamped to it, so a tool or sub-agent call that runs-/// across the wind-down point ends in the harness's own typed `Timeout` →-/// `chat_error`.+/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 3480s by+/// default. The harness pauses the run at its next safe point, and the+/// session driver writes the grounded close from the work already done, so a+/// long turn still delivers an answer.+/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 3540s by default.+/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`)+/// is clamped to it, so a tool or sub-agent call that runs across the+/// wind-down point ends in the harness's own typed `Timeout` → `chat_error`.///-/// So this backstop only fires if a turn wedges OUTSIDE the harness run, e.g.-/// in session assembly, the grounded close or the persistence plumbing. The-/// client then still gets a terminal `turn_timeout` event instead of an empty-/// reply or an endless `inference_heartbeat` stream. Before the derived-/// deadlines existed, the harness ceiling sat at 3600s, *after* this 900s-/// backstop. Long orchestrator turns were then dropped here, mid-work, with-/// nothing delivered. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to+/// It is not the hang detector. That is the idle guard+/// ([`turn_activity`](super::super::turn_activity)), which ends a turn that has+/// been silent with no model or tool call in flight. The backstop used to be+/// both, at 900s: a turn working steadily for 15 minutes was dropped exactly+/// like a wedged one. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to/// `0` to disable the backstop and the derived deadlines with it.fn web_turn_deadline() -> Option<Duration> {- crate::agent::turn_deadline::configured_backstop()+ crate::agent::session_host::turn_backstop::configured_backstop()}/// The backstop for a turn that has to be allowed to run long: one on a local /@@@ -102,93 -76,49 +103,107 @@@ async fn drive_turn_with_deadline<F>whereF: std::future::Future<Output = Result<WebChatTaskResult, String>>,{- match deadline {+ let activity = TurnActivity::new();+ // The turn future is boxed: it is very large, and the scope wrappers would+ // otherwise hold it inline again and overflow the worker stack.+ let turn = turn_activity::with_turn_activity(activity.clone(), Box::pin(fut));+ let bounded_turn = async move {+ let Some(d) = deadline else {+ return Ok(turn.await);+ };- // Scope the deadline on the task so the session turn hands it to the- // harness (`agent::turn_deadline`), which winds down before `d`.- let deadline = tinyagents_harness::turn_deadline::TurnDeadline::starting_now(d);- let scoped = crate::agent::turn_deadline::with_turn_deadline(Some(deadline), turn);- tokio::time::timeout(d, scoped)+ // The session turn carries the matching `TurnDeadline` on its explicit+ // host environment (`run_turn_under_cancel_and_deadline`), so the- // harness (`agent::session_host::turn_backstop`) winds down before `d`. The turn- // future is boxed: it is very large and would otherwise be held inline- // by the timeout wrapper and overflow the worker stack.- Some(d) => match tokio::time::timeout(d, Box::pin(fut)).await {- Ok(res) => res,- Err(_elapsed) => {- log::warn!(- "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \- (the harness wind-down did not close the turn in time); emitting graceful \- turn_timeout chat_error (issue #4746)",- d.as_secs()- );- Err(super::super::web_errors::turn_timeout_error_message(- d.as_secs(),- ))- }++ // harness (`agent::session_host::turn_backstop`) winds down before `d`.++ tokio::time::timeout(d, turn)+ .await+ .map_err(|_elapsed| Stop::Ceiling(d))+ };+ let watched = activity.clone();+ let watchdog = async move {+ match idle_window {+ Some(window) => turn_activity::idle_watchdog(watched, window).await,+ None => std::future::pending().await,+ }+ };+ let stop = tokio::select! {+ biased;+ res = bounded_turn => match res {+ Ok(res) => return res,+ Err(stop) => stop,},- None => fut.await,+ idle = watchdog => Stop::Idle(idle),+ };+ let stuck = activity.stuck_point();+ let (cause, fallback) = match stop {+ Stop::Ceiling(d) => {+ log::warn!(+ "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \+ (the harness wind-down did not close the turn in time); stuck={stuck:?} \+ (issue #4746)",+ d.as_secs()+ );+ (+ StopCause::Ceiling(d),+ super::super::web_errors::turn_timeout_error_message(d.as_secs()),+ )+ }+ Stop::Idle(idle) => {+ log::warn!(+ "[web-channel] turn idle guard fired: no progress for {}s with no model or tool \+ call in flight; stuck={stuck:?}",+ idle.as_secs()+ );+ (+ StopCause::Idle(idle),+ super::super::web_errors::turn_idle_error_message(idle.as_secs()),+ )+ }+ };+ let Some(ids) = ids else {+ return Err(fallback);+ };+ let (config, locale) = activity.turn_context();+ let stopped = StoppedTurn {+ thread_id: &ids.thread_id,+ request_id: &ids.request_id,+ cause,+ stuck,+ config,+ locale,+ };+ let close = super::super::turn_close::close_reply(stopped);+ match tokio::time::timeout(CLOSE_REPLY_BUDGET, close).await {+ Ok(Some(reply)) => Ok(reply),+ Ok(None) => Err(fallback),+ Err(_) => {+ log::warn!(+ "[web-channel] closing the stopped turn took over {}s; reporting turn_timeout",+ CLOSE_REPLY_BUDGET.as_secs()+ );+ Err(fallback)+ }}}+ /// The host environment a guarded turn runs with: its own session cancellation+ /// (returned too, so a Stop can fire it) and the `TurnDeadline` derived from the+ /// backstop, `None` when the backstop is disabled.+ fn turn_host_env(+ backstop: Option<Duration>,+ ) -> (HostTurnEnv, tinyagents_harness::cancel::CancellationToken) {+ let turn_cancellation = tinyagents_harness::cancel::CancellationToken::new();+ let env = HostTurnEnv {+ cancellation: Some(turn_cancellation.clone()),+ turn_deadline: backstop.map(tinyagents_harness::turn_deadline::TurnDeadline::starting_now),+ ..HostTurnEnv::default()+ };+ (env, turn_cancellation)+ }+-/// Run a chat-turn future under the two standard web-channel guards, inside the+/// Run a chat-turn future under the standard web-channel guards, inside the/// shared origin + approval-context scope: the cooperative cancel token-/// (interrupt/cancel paths tear the turn down at its next await point) and the-/// wall-clock backstop ([`drive_turn_with_deadline`]).+/// (interrupt/cancel paths tear the turn down at its next await point), the+/// idle guard and the wall-clock backstop ([`drive_turn_with_deadline`]).////// Returns `None` when the turn was cancelled cooperatively before producing a/// result — the cancelling side already emitted the user-facing `chat_error`,@@@ -201,22 -139,20 +224,26 @@@ pub(crate) async fn run_turn_under_canccancel_token: CancellationToken,origin: crate::agent::turn_origin::AgentTurnOrigin,approval_ctx: crate::security::approval::ApprovalChatContext,- fut: F,+ build_turn: B,) -> Option<Result<WebChatTaskResult, String>>where+ B: FnOnce(HostTurnEnv) -> F,F: std::future::Future<Output = Result<WebChatTaskResult, String>>,{+ let ids = approval_ctx.request_id.clone().map(|request_id| TurnIds {+ thread_id: approval_ctx.thread_id.clone(),+ request_id,+ });let deadline = resolve_web_turn_deadline().await;+ let (env, turn_cancellation) = turn_host_env(deadline);+ let fut = build_turn(env);run_until_stopped(cancel_token,+ turn_cancellation,drive_turn_with_deadline(deadline,+ turn_activity::configured_idle_window(),+ ids,crate::agent::turn_origin::with_origin(origin,crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),diff --cc crates/openhuman-core/src/web_chat/turn_activity.rsindex 958e098836,0000000000..65573441c3mode 100644,000000..100644--- a/crates/openhuman-core/src/web_chat/turn_activity.rs+++ b/crates/openhuman-core/src/web_chat/turn_activity.rs@@@ -1,294 -1,0 +1,294 @@@+//! Inactivity tracking for one web-chat turn.+//!+//! The web-turn guard (`ops::turn_guards`) used to drop a turn a fixed 900s+//! after it started, whether or not the turn was still working. A turn that+//! streamed a model reply or a tool result every few seconds died exactly as a+//! wedged one did. The guard exists to catch the wedged turn, so it now asks a+//! narrower question: has the turn been **silent with nothing in flight** for+//! the idle window?+//!+//! * Every [`AgentProgress`] event the turn emits restarts the idle clock.+//! * While a parent-scope model call (`IterationStarted` →+//! `ModelCallCompleted`) or a tool call (`ToolCallStarted` →+//! `ToolCallCompleted`) is open, the turn is never idle, however long the+//! call is silent. Those calls carry their own bounds: the harness per-model+//! call ceiling and the tool's own `timeout_secs`, both under the harness+//! turn ceiling. A silent provider retry (minutes) or a long shell build is+//! in flight, not idle.+//! * A tool approval parks before `ToolCallStarted`, so it counts as silence.+//! It is bounded by the approval TTL (600s by default), below the default+//! idle window.+//!+//! What remains idle is time no other bound covers: session checkout before+//! the run, the persistence plumbing after it, or a harness that went silent+//! with no call open. The fixed total ceiling still exists (the backstop in- //! `agent::turn_deadline`) and still anchors the harness wind-down; it no++//! `agent::session_host::turn_backstop`) and still anchors the harness wind-down; it no+//! longer doubles as the hang detector.+//!+//! The clock is [`tokio::time::Instant`], so time the machine spends asleep is+//! not counted as idle, and tests can drive it with a paused runtime.++use std::borrow::Cow;+use std::collections::HashSet;+use std::future::Future;+use std::sync::{Arc, Mutex};+use std::time::Duration;++use tokio::sync::mpsc;+use tokio::time::Instant;++use crate::agent::progress::AgentProgress;++/// Default idle window for a web-chat turn, in seconds.+pub(crate) const DEFAULT_TURN_IDLE_SECS: u64 = 900;++/// Environment override for the idle window, in seconds; `0` disables it.+pub(crate) const TURN_IDLE_ENV: &str = "OPENHUMAN_WEB_TURN_IDLE_SECS";++/// Longest the watchdog sleeps between checks while a call is in flight. A+/// call that closes is followed by a full idle window measured from its close,+/// so this only bounds how late the watchdog notices that.+const IN_FLIGHT_RECHECK: Duration = Duration::from_secs(15);++/// Pure core of [`configured_idle_window`]: an absent or unparseable value+/// falls back to [`DEFAULT_TURN_IDLE_SECS`]; `0` disables the idle guard.+pub(crate) fn parse_idle_window(env_value: Option<&str>) -> Option<Duration> {+ let secs = env_value+ .and_then(|v| v.trim().parse::<u64>().ok())+ .unwrap_or(DEFAULT_TURN_IDLE_SECS);+ (secs > 0).then(|| Duration::from_secs(secs))+}++/// The idle window in force for this process (env [`TURN_IDLE_ENV`]).+pub(crate) fn configured_idle_window() -> Option<Duration> {+ parse_idle_window(std::env::var(TURN_IDLE_ENV).ok().as_deref())+}++#[derive(Debug)]+struct State {+ last_event: Instant,+ open_tool_calls: HashSet<String>,+ model_call_open: bool,+ /// What the last event said the turn did, for the stop reply.+ last_step: Option<Cow<'static, str>>,+ turn_completed: bool,+ /// The config and reply locale the turn itself resolved, so a stop reply+ /// is written to the turn's own workspace and in its language.+ turn_config: Option<Arc<crate::config::Config>>,+ locale: Option<String>,+}++/// Where a turn was when it went silent, for the reply that closes it.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum StuckPoint {+ /// No progress event at all: the turn never got past session setup.+ BeforeRun,+ /// The agent loop was between steps; `after` names its last step.+ BetweenSteps { after: String },+ /// The agent loop had finished; the reply was being saved or delivered.+ AfterRun,+}++impl StuckPoint {+ /// One plain-language clause naming where the turn stopped.+ pub(crate) fn describe(&self) -> String {+ match self {+ Self::BeforeRun => {+ "before the agent started: the turn never got past setting up the chat \+ session"+ .to_string()+ }+ Self::BetweenSteps { after } => {+ format!("between steps: {after}, and the agent's next step never started")+ }+ Self::AfterRun => {+ "after the agent finished, while its reply was being saved".to_string()+ }+ }+ }+}++/// The step an event reports, as a clause for [`StuckPoint::BetweenSteps`].+/// `None` for bookkeeping (cost, usage, captured content) that says nothing+/// about what the turn was doing.+fn step_of(event: &AgentProgress) -> Option<Cow<'static, str>> {+ Some(match event {+ AgentProgress::TurnStarted => "the turn started".into(),+ AgentProgress::IterationStarted { .. } => "a model call started".into(),+ AgentProgress::ModelCallCompleted {+ subagent_task_id: None,+ ..+ } => "the model replied".into(),+ AgentProgress::ToolCallStarted { tool_name, .. } => {+ format!("the `{tool_name}` tool started").into()+ }+ AgentProgress::ToolCallCompleted {+ tool_name, success, ..+ } => {+ let outcome = if *success { "finished" } else { "failed" };+ format!("the `{tool_name}` tool {outcome}").into()+ }+ AgentProgress::TextDelta { .. } | AgentProgress::ThinkingDelta { .. } => {+ "the model was writing".into()+ }+ AgentProgress::ToolCallProgress { .. } => "a tool reported progress".into(),+ AgentProgress::SubagentSpawned { .. }+ | AgentProgress::SubagentCompleted { .. }+ | AgentProgress::SubagentFailed { .. }+ | AgentProgress::SubagentAwaitingUser { .. } => "a sub-agent reported progress".into(),+ _ => return None,+ })+}++/// Shared activity record for one turn. Cheap to clone; every clone sees the+/// same state.+#[derive(Clone, Debug)]+pub(crate) struct TurnActivity {+ state: Arc<Mutex<State>>,+}++impl TurnActivity {+ /// A record whose idle clock starts now, with nothing in flight. The turn+ /// emits no progress before its session is checked out, so that phase is+ /// measured from here.+ pub(crate) fn new() -> Self {+ Self {+ state: Arc::new(Mutex::new(State {+ last_event: Instant::now(),+ open_tool_calls: HashSet::new(),+ model_call_open: false,+ last_step: None,+ turn_completed: false,+ turn_config: None,+ locale: None,+ })),+ }+ }++ fn lock(&self) -> std::sync::MutexGuard<'_, State> {+ self.state.lock().unwrap_or_else(|p| p.into_inner())+ }++ /// Fold one progress event into the record.+ pub(crate) fn observe(&self, event: &AgentProgress) {+ let mut state = self.lock();+ state.last_event = Instant::now();+ if let Some(step) = step_of(event) {+ state.last_step = Some(step);+ }+ match event {+ AgentProgress::IterationStarted { .. } => state.model_call_open = true,+ AgentProgress::ModelCallCompleted {+ subagent_task_id: None,+ ..+ } => state.model_call_open = false,+ AgentProgress::ToolCallStarted { call_id, .. } => {+ state.open_tool_calls.insert(call_id.clone());+ }+ AgentProgress::ToolCallCompleted { call_id, .. } => {+ state.open_tool_calls.remove(call_id);+ }+ AgentProgress::TurnCompleted { .. } => {+ state.open_tool_calls.clear();+ state.model_call_open = false;+ state.turn_completed = true;+ }+ _ => {}+ }+ }++ /// How long the turn has been idle as of `now`, or `None` while a model or+ /// tool call is in flight.+ pub(crate) fn idle_for(&self, now: Instant) -> Option<Duration> {+ let state = self.lock();+ if state.model_call_open || !state.open_tool_calls.is_empty() {+ return None;+ }+ Some(now.saturating_duration_since(state.last_event))+ }+}++impl TurnActivity {+ /// Record the config and reply locale the turn resolved. A stop reply+ /// uses these rather than whatever profile is active when it fires.+ pub(crate) fn remember_turn(&self, config: Arc<crate::config::Config>, locale: Option<String>) {+ let mut state = self.lock();+ state.turn_config = Some(config);+ state.locale = locale;+ }++ /// The config and locale recorded by [`Self::remember_turn`], if the turn+ /// got that far.+ pub(crate) fn turn_context(&self) -> (Option<Arc<crate::config::Config>>, Option<String>) {+ let state = self.lock();+ (state.turn_config.clone(), state.locale.clone())+ }++ /// Where the turn was when its last event arrived.+ pub(crate) fn stuck_point(&self) -> StuckPoint {+ let state = self.lock();+ if state.turn_completed {+ return StuckPoint::AfterRun;+ }+ match &state.last_step {+ None => StuckPoint::BeforeRun,+ Some(step) => StuckPoint::BetweenSteps {+ after: step.to_string(),+ },+ }+ }+}++/// Resolve once the turn has been idle for `window`, returning the idle time+/// observed. Never resolves while the turn keeps emitting progress or keeps a+/// call in flight.+pub(crate) async fn idle_watchdog(activity: TurnActivity, window: Duration) -> Duration {+ loop {+ let wait = match activity.idle_for(Instant::now()) {+ Some(idle) if idle >= window => return idle,+ Some(idle) => window - idle,+ None => IN_FLIGHT_RECHECK.min(window),+ };+ tokio::time::sleep(wait).await;+ }+}++/// Interpose `activity` on a turn's progress stream: every event the agent+/// sends is folded into the record, then forwarded in order to the returned+/// receiver (the progress bridge). The forwarder only records and forwards, so+/// it drains the agent-side channel faster than the bridge, which publishes.+/// It ends when the agent's sender drops, closing the bridge's stream in turn.+pub(crate) fn tap(+ activity: TurnActivity,+ mut agent_rx: mpsc::Receiver<AgentProgress>,+ capacity: usize,+) -> mpsc::Receiver<AgentProgress> {+ let (bridge_tx, bridge_rx) = mpsc::channel(capacity);+ crate::core::runtime::spawn_scoped(async move {+ while let Some(event) = agent_rx.recv().await {+ activity.observe(&event);+ if bridge_tx.send(event).await.is_err() {+ break;+ }+ }+ });+ bridge_rx+}++tokio::task_local! {+ static CURRENT_TURN_ACTIVITY: TurnActivity;+}++/// The activity record scoped on the current task, if any.+pub(crate) fn current() -> Option<TurnActivity> {+ CURRENT_TURN_ACTIVITY.try_with(Clone::clone).ok()+}++/// Run `future` with `activity` scoped on the task.+pub(crate) async fn with_turn_activity<F: Future>(activity: TurnActivity, future: F) -> F::Output {+ CURRENT_TURN_ACTIVITY.scope(activity, future).await+}++#[cfg(test)]+#[path = "turn_activity_tests.rs"]+mod tests;diff --cc scripts/ci/check-openhuman-rust-layout.mjsindex dcc6e97d5f,6355e354c6..e7305a417d--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@@ -34,10 -34,10 +34,10 @@@ const LEGACY_LIMIT_ENTRIES =// provider, security, memory, tool and prompt policy. Generic session// state moved to tinyagents-runtime; this remaining composition is split in// a follow-up without reintroducing an old harness/session exception.- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 975],+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 974],["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1247],- ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1046],+ ["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1045],- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1261],+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1209],// These established external test modules grew with upstream coverage. Pin// their current sizes while follow-up work separates their test concerns.// `core/` was pruned from the line limit by name until these pins; its