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 harness assembly and turn middleware
Steven Enamakel48b1fb2bae62
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rsdeleted file mode 100644index 7955b7ea4b..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs+++ /dev/null@@ -1,676 +0,0 @@-//! [`assemble_turn_harness`] — register the provider model, every shared-//! tool, and the full middleware stack in the intended order for one turn.--use std::collections::HashSet;-use std::sync::Arc;--use tinyagents_harness::cache::InMemoryResponseCache;-use tinyagents_harness::middleware::{- plan_mode_middleware, ApprovalGateMiddleware, ArgRecoveryMiddleware, BudgetLimits,- BudgetMiddleware, BudgetParityObserver, ContextCompressionMiddleware,- PromptCacheGuardMiddleware, RepeatProgressMiddleware, RunModeHandle,- ToolPolicyMiddleware as TaToolPolicyMiddleware,-};-use tinyagents_harness::runtime::AgentHarness;-use tinyagents_harness::steering::SteeringHandle;-use tinyagents_registry::{CapabilityRegistry, RegistryDiagnostic, RegistrySnapshot};-use tinyinference_llm::model::CapabilitySet;-use tokio::sync::mpsc::Sender;--use crate::agent::progress::AgentProgress;-use crate::agent::tinyagents::context_wiring::install_context_ladder;-use crate::agent::tinyagents::harness_tool_registration::register_turn_tools_and_agents;-use crate::agent::tinyagents::host::steering;-use crate::agent::tinyagents::host::OpenHumanRunContext;-use crate::agent::tinyagents::middleware::{self, TurnContextMiddleware};-use crate::agent::tinyagents::model::TurnChatModel;-use crate::agent::tinyagents::observability::{- ProviderUsageCarry, SubagentScope, ToolFailureMap, ToolNameMap,-};-use crate::agent::tinyagents::routes;-use crate::agent::tinyagents::stop_hooks;-use crate::agent::tinyagents::tools::EarlyExitHook;-use crate::agent::tinyagents::turn_models::TurnModels;-use crate::agent::tinyagents::turn_policy::run_policy_for_provider;-use crate::agent::tinyagents::verify_before_finish;-use tinyagents_harness::middleware::{- install_unmet_deliverable, is_repeat_call_exempt, tool_sets_lookup, ResearchBudgetMiddleware,- ShellTurnBudget, TurnClockMiddleware, DIRECT_WEB_READ_LIMIT,-};-use tinyagents_harness::store::InMemoryStore as ToolResultArtifactIndexStore;-use tinyagents_harness::turn_outcome::{HaltSummarySlot, ToolOutcomeSink};-use tinyagents_harness::turn_policy::REPEATED_TOOL_FAILURE_THRESHOLD;-use tinyinference_llm::model::ErrorSlotModel;--use super::ToolPolicyEnforcement;-mod assembled;-pub(super) use assembled::AssembledTurnHarness;--/// Assemble the turn harness for [`run_turn_via_tinyagents_shared`](super::run_turn_via_tinyagents_shared):-/// register the provider model, every shared tool, and the full middleware-/// stack in the intended order. Split out of the runner so the adapter-/// inventory is directly testable (issue #4249, Phase 11) — the returned-/// [`AssembledTurnHarness`] exposes the harness registries without driving a-/// run.-#[allow(clippy::too_many_arguments)]-pub(super) fn assemble_turn_harness(- turn_models: TurnModels,- model: &str,- tool_sets: Vec<Arc<Vec<Box<dyn tinytools::Tool>>>>,- allowed: Option<HashSet<String>>,- max_iterations: usize,- _on_progress: Option<Sender<AgentProgress>>,- subagent_scope: Option<SubagentScope>,- context_window: Option<u64>,- early_exit_tools: &[&str],- context_mw: TurnContextMiddleware,- stop_hooks: Vec<- Arc<dyn tinyagents_harness::middleware::StopHook<tinyagents_harness::cost::TurnCost>>,- >,- tool_policy: Option<ToolPolicyEnforcement>,- required_capabilities: Option<CapabilitySet>,- deterministic_cacheable: bool,- // Hosted roots authorize tools through `OpenHumanSecurityGate`; installing- // the legacy approval middleware as well would issue a second approval.- hosted_security_gate: bool,- // Whether this run pauses gracefully at its model-call cap (issue #6014).- // Only such a run gets the in-loop conclusion: a run that errors at its cap- // instead (the channel/CLI path, which maps the stop to- // `MaxIterationsExceeded`) must keep doing that, and handing it a wrap-up- // would silently convert a documented error into an answer.- pause_at_cap: bool,- // The dialect the session composed its prompt for; see- // `OpenHumanRunContext::tool_dialect`.- tool_dialect: tinyagents_harness::config::ToolDispatcher,- // Session-deferred tools (`OpenHumanRunContext::deferred_tool_names`):- // registered as `Deferred` whatever their own exposure says.- session_deferred: Arc<HashSet<String>>,- // Live per-thread Plan/Build mode handle (`agent::tinyagents::run_mode`).- // `Some` installs `PlanModeMiddleware`, which hides/denies side-effecting- // tools while the thread is in `RunMode::Plan` — flipped without- // restarting the run by `plan_exit` or the `agent.set_run_mode` RPC.- // `None` for a caller with no thread identity (a sub-agent child, most- // notably), which never runs in plan mode.- run_mode: Option<RunModeHandle>,- // The turn's reasoning choice (`reasoning::turn_reasoning_for`), attached- // to every model request this harness builds.- reasoning: Option<tinyinference_llm::model::ReasoningConfig>,- // Whether this turn runs on a chat thread (`OpenHumanRunContext::thread_id`- // is `Some`). The per-thread `goal_*` tools resolve their target from the- // run's thread, so a thread-less turn (a headless `inference_agent_chat`- // without a `thread_id`) is not offered them at all (issue #6956).- has_thread: bool,- // This turn's memory binding (`OpenHumanRunContext::memory_turn`): the- // compaction summarizer recalls under it. `None` leaves compaction- // memory-free.- memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,- tool_rules: Option<Arc<tinyagents_harness::tool::ToolRulePolicy>>, // `OpenHumanRunContext::tool_rules`-) -> AssembledTurnHarness {- let mut harness: AgentHarness<(), OpenHumanRunContext> = AgentHarness::new();- // Cross-route fallback ownership (issue #4249, Workstream 02.2): populate the- // SDK `RunPolicy.fallback` with the ordered same-family route chain for this- // turn's primary model so the harness fails over to a sibling workload tier- // (e.g. hint:chat → hint:burst) when the primary route errors. Retry stays pinned- // to a single attempt (see `run_policy_for`) — fallback and retry are- // independent knobs, and only fallback is enabled here because `ReliableProvider`- // (still wrapped) does not fail over across the registered tier routes.- let mut policy = run_policy_for_provider(- max_iterations,- deterministic_cacheable,- turn_models.is_local(),- );- let route_fallback = routes::route_fallback_policy(model);- policy.fallback = route_fallback.clone();- // Tool discovery: the harness advertises its `tool_search` bridge over the- // `Deferred` registrations the allowlist admits, ranked by whatever the- // process installed (`agent::tinyagents::discovery`).- policy.discovery = super::discovery::discovery_policy();-- policy.tool_dialect = tool_dialect;- policy.default_reasoning = reasoning;- // The session composes its prompt for this same dialect: `ToolsSection`- // renders the protocol block and the catalogue of the visible tools into- // the system prompt (inside the cacheable prefix, counted by- // `prompt-size`). Without this the harness appended a second copy of- // both on every text-dialect call.- policy.host_renders_tool_catalogue = true;- crate::tools::rules::install_turn_rules(&mut policy, tool_rules);- tracing::debug!(- model,- ?tool_dialect,- "[models] turn harness tool dialect pinned from the session"- );- tracing::debug!(- model,- fallback_chain = ?route_fallback.as_ref().map(|f| &f.models),- "[models] assembling turn harness with SDK retry/fallback policy"- );- harness.with_policy(policy);- crate::tools::timeout::install_harness_tool_timeouts(&mut harness);- // Deterministic internal runs (summarizer/triage/memory-scoring style) may- // reuse a prior identical model response; attach an in-memory response cache- // so the agent loop can short-circuit a recurring provider call and emit- // `CacheHit`/`CacheMiss` (issue #4249, 03.2). NEVER attached for interactive- // chat turns — a live user turn must never be served a cached response.- if deterministic_cacheable {- harness.with_response_cache(Arc::new(InMemoryResponseCache::new()));- tracing::debug!(- model,- "[cache] response cache attached (deterministic internal run)"- );- }- let mut capability_registry: CapabilityRegistry<()> = CapabilityRegistry::new();-- let cursor: tinyagents_harness::events::IterationCursor = Arc::default();- // Shared `call_id → tool_name` map: the forwarder records the name on- // tool-call start (the crate `ToolDelta` carries none), the bridge reads it- // to label the argument fragments now streamed via `MessageDelta.tool_call`.- let tool_names: ToolNameMap = Arc::default();- // Shared FIFO carry of per-call provider `BilledUsage`: `UsageCarryMiddleware`- // pushes each response's usage (charged USD + context window +- // cache-creation/reasoning tokens, read off the response via G1), the event- // bridge pops it when recording that call's usage (#4467, item 1). The carry- // is produced by a wrap-model middleware now, not the adapter, so route models- // carry no usage side-channel (Phase 5).- let provider_usage_carry: ProviderUsageCarry = Arc::default();- // The turn's models are pre-built by `build_turn_models` (the single- // `native model adapter` construction site) and handed in as crate `ChatModel`s —- // the assembly no longer touches the raw provider (issue #4249, Phase 5).- let TurnModels {- primary,- routes,- summarizer: summarizer_model,- error_slot,- // Provider metadata (id/context-window/caps) is consumed by the turn-path- // caller before dispatch, not by harness assembly.- ..- } = turn_models;- // A non-hosted run owns its registry, so its models record into the run's- // error slot (#6724). A hosted root shares its runtime registry with its- // sub-agents; there only the resolver's lead model records.- let slotted = |model: TurnChatModel| -> TurnChatModel {- if hosted_security_gate {- model- } else {- Arc::new(ErrorSlotModel::new(model, error_slot.clone()))- }- };- let primary = slotted(primary);- capability_registry.replace_model(model, primary.clone());- harness- .register_model(model, primary)- .set_default_model(model);-- // Project the full workload-route set into the registry (issue #4249,- // Workstream 02.1). Each route is an additive registry entry carrying its- // per-route capability profile; `set_default_model` above keeps the turn's- // effective model as the dispatch target, so behavior is preserved until- // fallback/selection (02.2) chooses among the routes. `build_turn_models`- // already skipped the turn's own model, so we don't shadow the default.- for (name, route_model) in routes {- let route_model = slotted(route_model);- capability_registry.replace_model(name.as_str(), route_model.clone());- harness.register_model(name, route_model);- }-- // Cost usage capture (issue #4249, Phase 5): feed the event bridge's usage- // carry from a wrap-model middleware that reads the full `BilledUsage` off each- // response, instead of every `native model adapter` pushing it. Installed- // unconditionally — usage flows on every turn — and shares the same carry the- // bridge drains on `UsageRecorded`.- harness.push_model_middleware(Arc::new(routes::UsageCarryMiddleware::new(- provider_usage_carry.clone(),- )));-- // Route audit capture is a typed run-context concern. The canonical- // TinyInference decorator attached in `turn_models` stamps the successful- // unary response and the streamed terminal response, and this middleware- // moves that metadata into the explicit OpenHuman carrier.- harness.push_model_middleware(Arc::new(routes::ResolvedRouteMiddleware));-- // Per-call capability gate (issue #4249, Workstream 02.1): when the turn has- // derivable capability needs (today: vision for a `hint:vision` turn), stamp- // them onto every `ModelRequest` via `with_required_capabilities` so an unfit- // model is rejected pre-dispatch (and, once 02.2 lands, a capable fallback is- // selected) instead of failing at the provider.- if let Some(required) = required_capabilities {- harness.push_model_middleware(Arc::new(routes::RequiredCapabilitiesMiddleware::new(- required,- )));- }-- // Fallback event parity (issue #4249, Workstream 02.2): the crate's- // registry-backed `RunPolicy.fallback` traversal (wired above) performs the- // cross-route swap silently — it emits no `AgentEvent::FallbackSelected`. Wrap- // the model-resolving core with an observer that surfaces the parity event- // whenever the resolved model differs from the primary, so a fallback is- // visible on the OpenHuman progress/observability bridge (and grep-logged under- // `[fallback]`). Installed only when a fallback chain exists; it never re-issues- // the call, so it adds no provider dispatch (no double-fallback).- if route_fallback.is_some() {- harness.push_model_middleware(Arc::new(routes::FallbackObserverMiddleware::new(model)));- }-- // Capture context settings before `install` consumes `context_mw`.- let autocompact_enabled = context_mw.autocompact_enabled;- let compaction = context_mw.compaction;- // Captured for the same reason `autocompact_enabled` is — `install` consumes- // `context_mw` — and used to site microcompact below, after compression.- let microcompact_keep_recent = context_mw.microcompact_keep_recent;- let tool_result_artifact_index = context_mw- .artifact_store- .as_ref()- .map(|_| Arc::new(ToolResultArtifactIndexStore::new()));-- // A steering handle is always created now: besides run-queue steering, the- // early-exit / cap / stop-hook pauses, the repeated-tool-failure breaker- // (below) also pauses through it, and it wants to fire on every path- // (including plain channel turns that set none of the other flags). An idle- // handle is a no-op — the loop just drains an empty steering channel.- // Tighten the steering allowlist by run class: a live interactive chat turn- // keeps the InjectMessage/Pause allowlist exactly, while a detached- // sub-agent run (identified by its `subagent_scope`) additionally accepts- // graceful control-flow steering (Resume/Cancel/Redirect). `subagent_scope`- // is the only run-class signal available at this steer site.- let steering_run_class = if subagent_scope.is_some() {- steering::SteeringRunClass::Background- } else {- steering::SteeringRunClass::Interactive- };- let handle = Some(steering::openhuman_steering_handle(steering_run_class));-- // Shared by the two breakers below: whichever halts writes the root cause here.- let halt_summary: HaltSummarySlot = std::sync::Arc::new(std::sync::Mutex::new(None));-- // Repeat-progress breaker (#4463, restoring #4088/#4095): the failure- // breaker resets on success, so it misses successful no-op loops and repeated- // narration+call batches. This guard catches identical successful calls or- // outputs, including repeats with other calls between them (#6275). Polling- // tools (`wait_subagent`) stay exempt.- //- // Pushed first / outermost: `after_tool` runs in reverse registration order,- // so this guard fingerprints a result only after every other middleware- // (byte cap, summarizer, memory-protocol note) has finished rewriting it,- // i.e. exactly what the model sees. Registered any later, a result whose- // visible note changed between calls would count as identical.- // Classified read-only tools are the guard's read-only set.- let read_only_tools: HashSet<String> = tool_sets- .iter()- .flat_map(|set| set.iter())- .filter(|t| t.policy().classified && t.policy().side_effects.read_only)- .map(|t| t.name().to_string())- .collect();- let repeat_progress = handle.as_ref().map(|handle| {- Arc::new(- RepeatProgressMiddleware::new(- handle.clone(),- halt_summary.clone(),- Arc::new(is_repeat_call_exempt),- )- .with_read_only(Arc::new(move |name: &str| read_only_tools.contains(name)))- .with_cleared_placeholder(crate::agent::context::CLEARED_PLACEHOLDER),- )- });- // Time awareness (#6953); before the repeat guard so its notes land last.- let turn_budget = harness- .policy()- .limits- .max_wall_clock_ms- .map(std::time::Duration::from_millis);- harness.push_middleware(Arc::new(TurnClockMiddleware::new(turn_budget)));- let shell_turn_budget =- ShellTurnBudget::with_max_timeout(turn_budget, tinytools_std::timeout::MAX_TIMEOUT_SECS);- harness.push_middleware(Arc::new(shell_turn_budget.notes()));- if let Some(mw) = &repeat_progress {- harness.push_middleware(mw.clone());- }-- // Repeated failures stop the run using each tool's declared side effects.- let repeated_failure = handle.as_ref().map(|handle| {- let (t, halt) = (REPEATED_TOOL_FAILURE_THRESHOLD, halt_summary.clone());- let mw = middleware::RepeatedToolFailureMiddleware::new(handle.clone(), t, halt);- Arc::new(mw.with_tool_facts(tool_sets_lookup(tool_sets.clone())))- });- if let Some(mw) = &repeated_failure {- harness.push_middleware(mw.clone());- }-- stop_hooks::install(- &mut harness,- handle.as_ref(),- model,- stop_hooks,- halt_summary.clone(),- );- let early_exit_set: HashSet<&str> = early_exit_tools.iter().copied().collect();- // One hook per run, shared by every early-exit adapter (records the first- // early-exit and pauses). Requires the steering handle.- let early_exit_hook = handle- .as_ref()- .filter(|_| !early_exit_set.is_empty())- .map(|h| EarlyExitHook::new(h.clone()));-- let is_subagent_run = subagent_scope.is_some();- let (tool_count, candidate_names, registry_diagnostics, registry_snapshot) =- register_turn_tools_and_agents(- &mut harness,- &mut capability_registry,- &tool_sets,- &allowed,- &early_exit_set,- early_exit_hook.as_ref(),- is_subagent_run,- has_thread,- &session_deferred,- );-- // SHADOW tool-exposure layer (issue #4249, 01.3 — dynamic exposure). Compose- // the OpenHuman exposure policy as a crate-native selection layer- // (ToolAllowlistMiddleware + a ContextualToolSelectionMiddleware built via- // `inheriting`) and run it in shadow: it emits the exposure decision- // event-native (`AgentEvent::ToolsFiltered`) and logs any divergence between- // the crate layer's decision and the set OpenHuman actually registered as- // callable — WITHOUT changing the callable set (byte-identical to today).- // Folding the remaining host selection policy in `tool_prep.rs` into the- // middleware is gated on `[tool-exposure]` divergence logs showing parity. Tags encode- // the OpenHuman run context (agent id / channel / scope) for the flip; the- // name-based `inheriting` predicate does not consult them yet.- let exposure_tags: Vec<String> = {- let mut tags = vec![if subagent_scope.is_some() {- "scope:subagent".to_string()- } else {- "scope:root".to_string()- }];- if let Some(scope) = &subagent_scope {- tags.push(format!("agent:{}", scope.agent_id));- tags.push(format!("task:{}", scope.task_id));- }- if let Some(enforcement) = &tool_policy {- tags.push(format!("channel:{}", enforcement.channel));- tags.push(format!("agent_def:{}", enforcement.agent_definition_id));- }- tags- };- harness.push_middleware(Arc::new(- middleware::OpenHumanToolExposureShadowMiddleware::new(- &candidate_names,- allowed.as_ref(),- exposure_tags,- ),- ));-- // Prompt-cache prefix protection (issue #4249, 03.2). The vendor loop owns- // the stable-prefix layout (`PromptSegment`s built from the session's frozen- // system prefix, `frozen_system_prefix_len`); the crate- // `PromptCacheGuardMiddleware` diffs the cacheable prefix across model calls- // and records a `CacheLayoutEvent` when volatile content busts it. The guard- // is returned so the run loop can drain its events into the observability- // bridge.- let prompt_cache_guard = Arc::new(PromptCacheGuardMiddleware::new());- harness.push_middleware(prompt_cache_guard.clone());-- // openhuman context concerns as graph middlewares (issue #4249): microcompact- // tool-body clearing and the after-tool byte cap / payload summarizer.- // Installed before the summarization/trim block below so `before_model` hooks- // run microcompact → compress → trim. (KV-cache-prefix drift is handled above- // by the crate `PromptCacheGuardMiddleware`; the warn-only CacheAlign shadow- // was deleted in C3.) Tool-result caps read the SDK registry policy snapshot,- // not the OpenHuman-side tool lookup.- // Capture each tool call's real success + content before the harness folds the- // result into a `Message::tool` that drops the failure flag, so the turn can- // build honest per-call `ToolCallRecord`s (post-turn hooks + cap checkpoint).- //- // REVERSE-ORDER RULE (issue #4464): the crate runs `after_tool` in REVERSE- // registration order, so the LATER a middleware is pushed the EARLIER its- // `after_tool` runs. This capture must observe the FINAL (summarized/capped)- // content, so it is pushed BEFORE `context_mw.install` (which registers the- // handoff + tool-output budget/caps) — that way its `after_tool` runs AFTER- // those caps, not before. Registering it after `install` (the pre-#4464 bug)- // made its `after_tool` run first and record the full raw payload of every- // call, bloating the per-turn sink and feeding failure classification /- // `ToolCallRecord.output_summary` pre-cap content.- let tool_outcome_sink: ToolOutcomeSink = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));- let failure_map: ToolFailureMap = Arc::default();- harness.push_middleware(Arc::new(middleware::ToolOutcomeCaptureMiddleware::new(- tool_outcome_sink.clone(),- failure_map.clone(),- )));-- let tool_policies = harness.tools().policies();- let summary_focus_tools = harness- .tools()- .schemas()- .into_iter()- .chain(harness.tools().deferred_schemas())- .filter(|schema| {- crate::inference::tokenjuice::focus::declares_summary_focus(&schema.parameters)- })- .map(|schema| schema.name)- .collect();- context_mw.install(&mut harness, tool_policies, summary_focus_tools);-- // Plan mode (issue: plan-mode approvals). `run_mode` is `Some` only for a- // turn with a thread identity (chat, not a sub-agent child); the- // middleware itself is a no-op whenever the live handle reads- // `RunMode::Build`, so pushing it unconditionally for those turns is- // cheap and lets a mid-run `plan_exit`/`agent.set_run_mode` flip take- // effect on the very next tool exposure or execution check. `.allow(..)`- // keeps plan-mode-specific and session-bookkeeping tools reachable while- // planning even though they are not (or should not be gated as)- // side-effect-free: `plan_exit` (the hand-off signal itself),- // `request_plan_review` (the review gate IS the consent surface), the- // session `todo` list, and the per-thread `goal_*` tools.- if let Some(mode) = run_mode {- harness.push_middleware(Arc::new(- plan_mode_middleware(mode, harness.tools().policies()).allow([- "plan_exit",- "request_plan_review",- "todo",- "goal_set",- "goal_get",- "goal_complete",- ]),- ));- }-- // Observe-only crate `BudgetMiddleware`, installed with empty limits so it- // never enforces: it only folds each call's usage into a shared tracker.- // The spend cap is gone; `BudgetParityObserver` below compares that tracker- // against the authoritative `AgentRun.usage` at end of run and logs- // `[budget_parity]` parity or divergence.- let shadow_budget = Arc::new(BudgetMiddleware::new(BudgetLimits::default()));- let shadow_budget_tracker = shadow_budget.tracker();- harness.push_middleware(shadow_budget);-- harness.push_middleware(Arc::new(BudgetParityObserver::new(shadow_budget_tracker)));- // The context ladder (compression, microcompact, final-call wrap-up,- // artifact contents list, trim), registered here so each step keeps its- // place in the middleware order. See `context_wiring.rs`.- let (compression_mw, wrap_up_fired) = install_context_ladder(- &mut harness,- model,- context_window,- autocompact_enabled,- compaction.trigger_tokens,- compaction.strategy,- microcompact_keep_recent,- summarizer_model,- pause_at_cap && subagent_scope.is_none(),- &tool_outcome_sink,- memory_turn,- );- let is_subagent = subagent_scope.is_some();- let agent_id = tool_policy.as_ref().map(|p| p.agent_definition_id.as_str());- let turn_wall_clock_ms = harness.policy().limits.max_wall_clock_ms;- verify_before_finish::install(- &mut harness,- is_subagent,- agent_id,- &wrap_up_fired,- turn_wall_clock_ms,- );- // The rungs above all *tell* the turn to produce its deliverable; this one- // looks, on the same scope as the requirements check.- if verify_before_finish::applies(is_subagent, agent_id) {- install_unmet_deliverable(&mut harness);- } else {- tracing::debug!(- is_subagent,- agent = agent_id.unwrap_or("<none>"),- "[unmet_deliverable] not installed for this turn"- );- }-- // Direct web lookup is bounded. Once enough search/fetch results have- // returned, the web tools leave the request so the run works with what it- // has; a run with nothing but web tools answers instead. Sub-agent runs- // keep their own budgets and are not narrowed here.- if subagent_scope.is_none() {- harness.push_middleware(Arc::new(ResearchBudgetMiddleware::with_limit(- DIRECT_WEB_READ_LIMIT,- )));- }- // SDK-owned tool-policy projection (issue #4249 / tinyagents-full-migration- // 01.1). Keep this narrow for now: enforce sandbox requirements declared by- // adapter policies without enabling classification/approval/result-byte- // gates yet. `require_classification(true)` would currently reject an- // unregistered hallucinated tool in `before_tool` before- // `RunPolicy::unknown_tool` can return a recoverable tool error, while- // OpenHuman's existing wrappers still own HITL approval and output caps.- harness.push_middleware(Arc::new(- TaToolPolicyMiddleware::new(harness.tools().policies()).require_sandbox(true),- ));-- // Human-in-the-loop approval as a named tool middleware (issue #4249,- // Phase 1): an external-effect tool intercepts through the global- // `ApprovalGate`, a denial short-circuits with a model-consumable result, and- // an approved call records a terminal audit row. Replaces the inline approval- // block that used to live in the legacy tool adapter.- if !hosted_security_gate {- harness.push_tool_middleware(Arc::new(ApprovalGateMiddleware::new(- "approval_security",- Arc::new(middleware::ApprovalSecurityMiddleware::new(- tool_sets.clone(),- )),- )));- }-- // CLI/RPC-only scope gate — a tool restricted to explicit CLI/RPC invocation- // must not run from the model loop. Intrinsic to the tool, so installed on- // every path (channel/session/sub-agent).- harness.push_tool_middleware(Arc::new(middleware::CliRpcOnlyMiddleware::new(- tool_sets.clone(),- )));-- // Builder-configured tool policy (`.tool_policy()`), enforced at the tool- // boundary. The in-house engine ran this in `agent_tool_exec`; the tinyagents- // path bypassed it, so a deny/require-approval silently no-opped (security- // regression). Installed only when the caller threads an enforcement context- // (the session chat path); channel/CLI + sub-agent paths pass `None`.- // The packed-tool router below gates on the same session, and `None`- // disables it, so take a copy before the enforcement is moved.- let route_session = tool_policy- .as_ref()- .map(|enforcement| enforcement.session.clone());- if let Some(enforcement) = tool_policy {- harness.push_tool_middleware(Arc::new(middleware::ToolPolicyMiddleware::new(- enforcement.policy,- enforcement.session,- tool_sets.clone(),- enforcement.channel,- )));- }-- // Credential scrubbing (issue #4453): redact credential-shaped secrets out of- // every tool result. The legacy engine ran `scrub_credentials` over every- // tool output before it entered model context; the tinyagents path dropped- // that call site. Installed as the **innermost** tool wrap (pushed last) so- // it scrubs the RAW tool result before any outer wrap, the `after_tool`- // chain (summarization/caps), the transcript push, or the tool-outcome- // capture sink can observe the unredacted content — covering the parent,- // sub-agent, persisted-transcript, and `ToolCallOutcome` surfaces by- // construction since every path shares this seam.- harness.push_tool_middleware(Arc::new(middleware::credential_scrub_middleware()));-- // Malformed-argument recovery (`before_tool`): repair a call's non-object- // arguments before the crate's schema gate — decode JSON-encoded-string args- // (optionally markdown-fenced) to an object, or coerce to `{}` only when the- // tool schema has no required fields (engine parity). A non-object against a- // required-field schema is left untouched so the crate's- // `InvalidArgsPolicy::ReturnToolError` admission path reports the original- // validation error. It never reaches approval/policy wrappers or the tool.- harness.push_middleware(Arc::new(ArgRecoveryMiddleware::new(tool_sets.clone())));-- // Clamp shell `timeout_secs` to the turn remainder (#6953), on recovered args.- harness.push_middleware(Arc::new(shell_turn_budget.clamp()));-- // Bare packed-tool routing (`before_tool`, #6276): a call that names a- // withheld packed tool directly becomes the `use_skill` call that reaches- // it, ahead of admission, so every gate above still applies. Only when the- // session lets that tool run, and never without a session. After- // `ArgRecoveryMiddleware` so it wraps recovered arguments; before the- // embedder hooks so they observe the call that actually runs.- let registered_tools = harness.tools().names();- harness.push_middleware(Arc::new(middleware::packed_tool_route_middleware(- registered_tools,- route_session,- )));-- // Embedder tool lifecycle hooks. Registered AFTER `ArgRecoveryMiddleware`:- // `before_tool` runs in registration order, so a hook installed earlier would- // observe the provider's raw (possibly JSON-encoded-string / non-object)- // arguments instead of the recovered object that `ToolHookContext` documents.- // The middleware caches the normalized pre-call arguments by `call_id` and- // replays them into the `PostToolUse` context. Its `after_tool` is- // observation-only (never mutates the result), so running first in the- // reverse-order `after_tool` chain is safe — it cannot perturb the- // summarization/cap or tool-outcome capture layers.- let embedder_tool_hooks = crate::agent::hooks::turn_tool_hooks();- if !embedder_tool_hooks.is_empty() {- harness.push_middleware(Arc::new(middleware::EmbedderToolHooksMiddleware::new(- embedder_tool_hooks,- )));- }-- // Registered last so its `before_model` sees the request after every- // reduction step above (compression, microcompact, trim) has run. A tool- // result they evicted is no longer a repeat the model can see, so the- // repeat-progress recurrence ledger restarts (#6275).- if let Some(mw) = &repeat_progress {- harness.push_middleware(Arc::new(mw.eviction_observer()));- }- // Registered after it: the breaker's corrective nudges ride the next- // request only. Anything earlier (notably the transcript snapshot a failed- // turn persists) must not see them, or they become durable history (#6725).- if let Some(mw) = &repeated_failure {- harness.push_middleware(Arc::new(mw.nudge_injector()));- }- // The turn's memory pack rides every request of the turn, after every- // reduction step and after the transcript snapshot, so it is never- // compacted, trimmed or persisted (`memory::lifecycle::hooks::pre_turn`).- harness.push_middleware(Arc::new(middleware::memory_pack_middleware()));-- AssembledTurnHarness {- harness,- cursor,- tool_names,- failure_map,- provider_usage_carry,- error_slot,- halt_summary,- tool_outcome_sink,- handle,- early_exit_hook,- wrap_up_fired,- tool_count,- registry_snapshot,- registry_diagnostics,- tool_result_artifact_index,- compression_mw,- prompt_cache_guard,- }-}--#[cfg(test)]-#[path = "harness_assembly_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly/assembled.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly/assembled.rsdeleted file mode 100644index e29ae37bed..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly/assembled.rs+++ /dev/null@@ -1,65 +0,0 @@-use super::*;--/// Everything [`assemble_turn_harness`](super::assemble_turn_harness) wires up-/// for one turn: the configured harness plus the shared slots and handles the-/// run loop reads after the drive future returns.-pub(in crate::agent::tinyagents) struct AssembledTurnHarness {- /// The fully assembled harness: model, tools, and middleware registered in- /// the intended order.- pub(in crate::agent::tinyagents) harness: AgentHarness<(), OpenHumanRunContext>,- /// Shared 1-based model-call cursor (event bridge advances, model adapter- /// reads for out-of-band thinking attribution).- pub(in crate::agent::tinyagents) cursor: tinyagents_harness::events::IterationCursor,- /// Shared `call_id → tool_name` map used by the event bridge to label- /// tool-argument fragments projected off the crate stream.- pub(in crate::agent::tinyagents) tool_names: ToolNameMap,- /// Shared `call_id → (success, failure, elapsed_ms, output_chars)` side-channel:- /// middleware records each outcome for the event bridge's `ToolCallCompleted`.- pub(in crate::agent::tinyagents) failure_map: ToolFailureMap,- /// Shared FIFO carry of per-call provider `BilledUsage`; the event bridge- /// reads it when recording usage to preserve charged-USD precedence (#4467).- pub(in crate::agent::tinyagents) provider_usage_carry: ProviderUsageCarry,- /// Recovers the original (downcastable) provider error on run failure.- pub(in crate::agent::tinyagents) error_slot: tinyinference_llm::model::ModelErrorSlot,- /// Root-cause summary recorded by the repeated-tool-failure breaker.- pub(in crate::agent::tinyagents) halt_summary: HaltSummarySlot,- /// Per-call tool success/content capture for honest `ToolCallRecord`s.- pub(in crate::agent::tinyagents) tool_outcome_sink: ToolOutcomeSink,- /// The shared steering handle (mid-flight steer, early-exit, cap, stop-hook- /// pauses).- pub(in crate::agent::tinyagents) handle: Option<SteeringHandle>,- /// Records the first early-exit tool round, when early-exit tools exist.- pub(in crate::agent::tinyagents) early_exit_hook: Option<EarlyExitHook>,- /// Set by [`FinalCallWrapUpMiddleware`] when it turned the last permitted- /// model call into the turn's conclusion (issue #6014). `None` when the- /// middleware is not installed (a run that does not pause at its cap).- ///- /// A flag rather than an inference off the run, because this turn now ends- /// the way a finished one does — the model returns text and requests no- /// tools — so `final_response.is_none()` no longer tells the two apart.- pub(in crate::agent::tinyagents) wrap_up_fired:- Option<Arc<tinyagents_harness::middleware::FinalCallWrapUpMiddleware>>,- /// Number of callable tools registered.- pub(in crate::agent::tinyagents) tool_count: usize,- /// TinyAgents named-capability projection for this turn. The live run still- /// uses the harness registries above; this snapshot makes the projected- /// model/tool/graph inventory inspectable without changing dispatch.- pub(in crate::agent::tinyagents) registry_snapshot: RegistrySnapshot,- /// Health diagnostics from the projected registry.- pub(in crate::agent::tinyagents) registry_diagnostics: Vec<RegistryDiagnostic>,- /// TinyAgents store index for OpenHuman action-dir tool-result artifacts.- pub(in crate::agent::tinyagents) tool_result_artifact_index:- Option<Arc<ToolResultArtifactIndexStore>>,- /// Concrete handle to the installed [`ContextCompressionMiddleware`], when- /// summarization is active. Drained after the run to surface each compaction's- /// [`CompressionProvenance`][tinyagents_harness::summarization::CompressionProvenance]- /// via the observability path.- pub(in crate::agent::tinyagents) compression_mw: Option<Arc<ContextCompressionMiddleware>>,- /// Crate prompt-cache guard (issue #4249, 03.2). Records a `CacheLayoutEvent`- /// whenever the cacheable prompt prefix (system prompt + tool set) changes- /// across model calls. Drained after the run and surfaced via- /// [`observability::surface_cache_layout_events`](crate::agent::tinyagents::observability::surface_cache_layout_events) —- /// the crate-native replacement for the deleted `CacheAlignMiddleware`- /// warn-log (C3).- pub(in crate::agent::tinyagents) prompt_cache_guard: Arc<PromptCacheGuardMiddleware>,-}diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rsdeleted file mode 100644index a2f156cfdb..0000000000--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly_tests.rs+++ /dev/null@@ -1,253 +0,0 @@-//! Tool-inventory coverage for [`assemble_turn_harness`]: which of the turn's-//! shared tools end up registered on the assembled harness.--use super::*;-use crate::agent::tinyagents::TurnModelSource;-use async_trait::async_trait;-use tinyagents_harness::turn_policy::{- DEFAULT_MODEL_CALL_TIMEOUT_SECS, LOCAL_MODEL_CALL_TIMEOUT_SECS,-};-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};-use tinytools::{Tool, ToolResult};--const GOAL_TOOLS: [&str; 3] = ["goal_get", "goal_set", "goal_complete"];--struct PlainTool;--#[async_trait]-impl Tool for PlainTool {- fn name(&self) -> &str {- "plain_tool"- }-- fn description(&self) -> &str {- "thread-independent test tool"- }-- fn parameters_schema(&self) -> serde_json::Value {- serde_json::json!({"type": "object"})- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- Ok(ToolResult::success("ok"))- }-}--struct IdleModel;--#[async_trait]-impl ChatModel<()> for IdleModel {- fn profile(&self) -> Option<&ModelProfile> {- static PROFILE: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();- Some(PROFILE.get_or_init(|| {- let mut profile = ModelProfile::default();- profile.tool_calling = true;- profile- }))- }-- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- Ok(ModelResponse::assistant("done"))- }-}--/// Assemble a harness over the real goal tools plus one ordinary tool and-/// return the names it registered.-fn registered_tool_names(has_thread: bool) -> Vec<String> {- assembled_with(has_thread, None).harness.tools().names()-}--/// Assemble the same harness, optionally carrying turn tool rules.-fn assembled_with(- has_thread: bool,- tool_rules: Option<Arc<tinyagents_harness::tool::ToolRulePolicy>>,-) -> AssembledTurnHarness {- let workspace = tempfile::TempDir::new().expect("workspace");- let model: Arc<dyn ChatModel<()>> = Arc::new(IdleModel);- let models = TurnModelSource::from_model(model)- .build("assembly-test-model", 0.0, None, None)- .expect("scripted turn models build");- let mut tools = crate::agent::goals::goal_tools(workspace.path());- tools.push(Box::new(PlainTool));-- assemble_turn_harness(- models,- "assembly-test-model",- vec![Arc::new(tools)],- None,- 3,- None,- None,- None,- &[],- TurnContextMiddleware::default(),- Vec::new(),- None,- None,- false,- false,- false,- tinyagents_harness::config::ToolDispatcher::default(),- Arc::new(HashSet::new()),- None,- None,- has_thread,- None,- tool_rules,- )-}--#[test]-fn turn_tool_rules_reach_the_harness_policy() {- let rules = tinytools::ToolRules::from_allow_deny(Vec::<String>::new(), ["plain_*"]);- let policy = crate::tools::rules::turn_rule_policy(- Arc::new(tinytools::ToolRuleSet::single(rules)),- crate::tools::rules::rule_context(Some("web"), Some("orchestrator"), None),- );- let assembled = assembled_with(true, Some(Arc::new(policy.clone())));- assert_eq!(assembled.harness.policy().tool_rules, policy);-}--#[test]-fn a_turn_without_rules_leaves_the_harness_policy_permissive() {- let assembled = assembled_with(true, None);- assert!(assembled.harness.policy().tool_rules.is_permissive());-}--#[test]-fn goal_tools_are_not_registered_on_a_turn_without_a_thread() {- let names = registered_tool_names(false);-- for goal_tool in GOAL_TOOLS {- assert!(- !names.iter().any(|name| name == goal_tool),- "{goal_tool} must not be offered to a thread-less turn: {names:?}"- );- }- assert!(- names.iter().any(|name| name == "plain_tool"),- "thread-independent tools still register: {names:?}"- );-}--#[test]-fn goal_tools_are_registered_on_a_threaded_turn() {- let names = registered_tool_names(true);-- for goal_tool in GOAL_TOOLS.iter().chain(["plain_tool"].iter()) {- assert!(- names.iter().any(|name| name == goal_tool),- "{goal_tool} must be offered to a threaded turn: {names:?}"- );- }-}--/// A model whose first (and only) byte arrives `delay` after the call starts,-/// like a local model prefilling a huge prompt (#6042).-struct SlowFirstByteModel {- delay: std::time::Duration,- provider: &'static str,-}--#[async_trait]-impl ChatModel<()> for SlowFirstByteModel {- fn profile(&self) -> Option<&ModelProfile> {- static LOCAL: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();- static HOSTED: std::sync::OnceLock<ModelProfile> = std::sync::OnceLock::new();- let (cell, provider) = if self.provider == "ollama" {- (&LOCAL, "ollama")- } else {- (&HOSTED, "openrouter")- };- Some(cell.get_or_init(|| {- let mut profile = ModelProfile::default();- profile.provider = Some(provider.to_string());- profile- }))- }-- async fn invoke(- &self,- _state: &(),- _request: ModelRequest,- ) -> tinyinference_llm::Result<ModelResponse> {- tokio::time::sleep(self.delay).await;- Ok(ModelResponse::assistant("done"))- }-}--/// Assemble over a [`SlowFirstByteModel`] and run one turn on the virtual clock.-async fn run_slow_first_byte_turn(- provider: &'static str,- delay_secs: u64,-) -> Result<String, String> {- let model: Arc<dyn ChatModel<()>> = Arc::new(SlowFirstByteModel {- delay: std::time::Duration::from_secs(delay_secs),- provider,- });- let models = TurnModelSource::from_model(model)- .build("slow-model", 0.0, None, None)- .expect("turn models build");- let assembled = assemble_turn_harness(- models,- "slow-model",- Vec::new(),- None,- 3,- None,- None,- None,- &[],- TurnContextMiddleware::default(),- Vec::new(),- None,- None,- false,- false,- false,- tinyagents_harness::config::ToolDispatcher::default(),- Arc::new(HashSet::new()),- None,- None,- false,- None,- None,- );- assembled- .harness- .invoke_default(&(), vec![tinyinference_llm::message::Message::user("hi")])- .await- .map(|run| run.text().unwrap_or_default())- .map_err(|err| err.to_string())-}--/// #6042: a ~57K-token prefill on a local model can take longer than the hosted-/// 900s per-call ceiling before its first byte. A local provider must survive-/// it; a hosted provider with the identical silence must still be cut off.-#[tokio::test(start_paused = true)]-async fn local_provider_survives_a_slow_first_byte_that_a_hosted_one_does_not() {- let delay_secs = DEFAULT_MODEL_CALL_TIMEOUT_SECS + 100;-- let hosted = run_slow_first_byte_turn("openrouter", delay_secs).await;- let err = hosted.expect_err("hosted provider must hit the per-call ceiling");- assert!(err.contains("timed out"), "unexpected error: {err}");-- let local = run_slow_first_byte_turn("ollama", delay_secs).await;- assert_eq!(- local.expect("local provider must wait out the prefill"),- "done"- );-}--/// The local ceiling is still a ceiling: a call that outlasts it times out.-#[tokio::test(start_paused = true)]-async fn local_provider_is_still_bounded_by_the_local_ceiling() {- let err = run_slow_first_byte_turn("ollama", LOCAL_MODEL_CALL_TIMEOUT_SECS + 100)- .await- .expect_err("a call past the local ceiling must time out");- assert!(err.contains("timed out"), "unexpected error: {err}");-}diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rsindex 023e61fd0d..a44f94e4d2 100644--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs@@ -24,8 +24,6 @@ mod context_wiring;mod deadline_wind_down;pub mod discovery;mod embeddings;-mod harness_assembly;-pub(crate) mod harness_tool_registration;pub mod host;pub(crate) mod hosted_error;pub(crate) mod journal;@@ -58,14 +56,15 @@ mod routes;mod steering_forwarder;pub(crate) mod stop_hooks;pub mod todos;-pub(crate) mod tools;+pub(crate) mod tool_registration;mod turn_models;mod turn_outcome;mod turn_policy;mod turn_run_error;mod turn_run_finalize;-mod turn_runner;-mod turn_runner_boxed;+mod turn_exec;+mod turn_middleware;+mod turn_plan;mod use_skill_dispatch;mod verify_before_finish;@@ -89,7 +88,7 @@ pub(crate) use turn_policy::{agent_turn_wall_clock_ms_for, chat_provider_is_local, local_web_turn_backstop_secs,ToolPolicyEnforcement,};-pub(crate) use turn_runner::{run_root_turn_via_hosted_agent, run_turn_via_tinyagents_shared};+pub(crate) use turn_exec::{run_root_turn_via_hosted_agent, run_turn_via_tinyagents_shared};// Test-only glue so `tinyagents_tests.rs`'s `use super::*;` sees the// lower-level policy helpers it exercises directly (they otherwise staydiff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rsindex 46711a37a1..fbf8e82da7 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs@@ -635,7 +635,6 @@ async fn run_turn_via_tinyagents_body(failure_map: failure_map.clone(),provider_usage_carry: provider_usage_carry.clone(),tool_outcome_sink: tool_outcome_sink.clone(),- tool_result_artifact_index,},);if let Some(scope) = run_context.response_shape.clone() {diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rsindex 1b11d0d75d..a3fa26a7ac 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs@@ -26,7 +26,6 @@ use tinyagents_harness::middleware::{};use tinyagents_harness::runtime::AgentHarness;use tinyagents_harness::steering::SteeringHandle;-use tinyagents_harness::store::InMemoryStore as ToolResultArtifactIndexStore;use tinyagents_harness::turn_outcome::{HaltSummarySlot, ToolOutcomeSink};use tinyagents_harness::turn_policy::REPEATED_TOOL_FAILURE_THRESHOLD;use tinyinference_llm::model::CapabilitySet;@@ -97,9 +96,6 @@ pub(super) struct TurnMiddlewareInputs {pub(super) provider_usage_carry: ProviderUsageCarry,/// Per-call tool success/content capture for honest `ToolCallRecord`s.pub(super) tool_outcome_sink: ToolOutcomeSink,- /// Store index for action-dir tool-result artifacts (`Some` exactly when the- /// context middleware has an artifact store).- pub(super) tool_result_artifact_index: Option<Arc<ToolResultArtifactIndexStore>>,}/// The handles the run loop reads after the drive returns.@@ -149,7 +145,6 @@ pub(super) fn install_turn_middleware(failure_map,provider_usage_carry,tool_outcome_sink,- tool_result_artifact_index,} = inputs;let model = model.as_str();crate::tools::timeout::install_harness_tool_timeouts(harness);diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rsindex 9a0c2f3fa0..6515a461ca 100644--- a/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs+++ b/crates/openhuman-core/src/agent/tinyagents/turn_run_finalize.rs@@ -1,5 +1,5 @@//! Turn a completed `tinyagents` harness run into a-//! [`TinyagentsTurnOutcome`], for [`run_turn_via_tinyagents_shared`](super::run_turn_via_tinyagents_shared).+//! [`TinyagentsTurnOutcome`], for [`run_turn_via_tinyagents_shared`](super::turn_exec::run_turn_via_tinyagents_shared).//!//! Split out of the runner: everything here executes only on the success path//! (after the drive future returns `Ok`), covering journal completion,@@ -15,7 +15,6 @@ use tokio::sync::mpsc::Sender;use crate::agent::progress::AgentProgress;use crate::agent::tinyagents::journal::TurnJournal;use crate::agent::tinyagents::observability::{self, OpenhumanEventBridge, SubagentScope};-use crate::agent::tinyagents::tools::EarlyExitHook;use crate::agent::tinyagents::turn_outcome::TinyagentsTurnOutcome;use tinyagents_harness::turn_outcome::{HaltSummarySlot, ToolOutcomeSink};use tinyagents_harness::turn_run_finalize::{@@ -40,7 +39,7 @@ pub(super) async fn finalize_turn_outcome(prompt_cache_guard: &PromptCacheGuardMiddleware,turn_completed_sink: Option<Sender<AgentProgress>>,bridge: Option<Arc<OpenhumanEventBridge>>,- early_exit_hook: Option<EarlyExitHook>,+ early_exit: Option<tinyagents_runtime::turn_driver::EarlyExit>,halt_summary: &HaltSummarySlot,wrap_up_fired: &Option<Arc<tinyagents_harness::middleware::FinalCallWrapUpMiddleware>>,run_instance_id: u64,@@ -132,7 +131,6 @@ pub(super) async fn finalize_turn_outcome(// name and use its captured question as the turn text (the paused assistant// turn carries the tool call, not a final answer) so the caller can// checkpoint and prompt the user — matching the legacy `early_exit_tool`.- let early_exit = early_exit_hook.and_then(|hook| hook.take());// The repeated-failure breaker halts the run with a root-cause summary// instead of a final model turn; surface it as the turn's text so the