Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Merge upstream/main into ta-final-7605

Steven Enamakel533f223b29ce
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index 28b9669b5a,a35742c632..6416d7b1fb
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@@ -270,48 -293,60 +270,49 @@@ async fn run_turn_via_tinyagents_body
hosted_root.as_ref().map(|(base, _)| base.config.as_ref()),
max_output_tokens,
),
- has_thread,
- run_context.memory_turn.clone(),
run_context.tool_rules.clone(),
++ run_context.tool_call_limit,
);
- if let Some(scope) = run_context.response_shape.clone() {
- tinyagents_harness::middleware::install_response_shape(&mut harness, scope);
- }
- super::budget::install_depth(&mut harness, &run_context);
- super::deadline_wind_down::install(&mut harness, &handle, &run_context, &subagent_scope);
- // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
- // The projected `CapabilityRegistry` produced these diagnostics during
- // assembly; enforce them here, *before* the first model dispatch, so an
- // ambiguous/broken tool surface (duplicate name across native/MCP/Composio/
- // generated tools, dangling alias, etc.) aborts the turn instead of silently
- // resolving to an unintended component while a provider call is in flight.
- if !registry_diagnostics.is_empty() {
- let (errors, warnings): (
- Vec<&tinyagents_registry::RegistryDiagnostic>,
- Vec<&tinyagents_registry::RegistryDiagnostic>,
- ) = registry_diagnostics
- .iter()
- .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));
- for diag in &warnings {
- tracing::warn!(
- kind = diag.kind.as_str(),
- name = %diag.name,
- "[registry] non-fatal diagnostic: {}",
- diag.message
- );
- }
- if !errors.is_empty() {
- let messages: Vec<String> = errors
- .iter()
- .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))
- .collect();
- for msg in &messages {
- tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");
- }
- tracing::error!(
- error_count = messages.len(),
- warning_count = warnings.len(),
- "[registry] aborting turn before model dispatch: capability registry validation failed"
- );
- return Err(anyhow::Error::new(
- tinyagents_harness::agent_error::AgentError::RegistryValidationFailed {
- diagnostics: messages,
- },
- ));
- }
- tracing::debug!(
- warning_count = warnings.len(),
- "[registry] registry diagnostics present (warnings only); proceeding with turn"
- );
- }
+ // The turn's crate `ChatModel` set (`turn_models`) and the provider telemetry id are built by
+ // the caller via `build_turn_models`: the seam is crate-native and names no `Provider` (#4249,
+ // Phase 5). The telemetry id (`{provider_id}.{model}` in Langfuse) rides in as a param.
+ let TurnModels {
+ primary,
+ routes: tier_routes,
+ summarizer: summarizer_model,
+ error_slot,
+ ..
+ } = turn_models;
+ let plan_models = turn_models_for_plan(
+ model,
+ primary,
+ tier_routes,
+ &error_slot,
+ hosted_security_gate,
+ );
+ let planner = OpenHumanTurnPlanner {
+ models: plan_models.clone(),
+ policy,
+ tool_sets: tool_sets.clone(),
+ allowed: allowed.clone(),
+ has_thread,
+ session_deferred: Arc::clone(&run_context.deferred_tool_names),
+ };
+ let driver = TurnDriver::<(), OpenHumanRunContext>::new(Arc::new(planner), Arc::new(()));
+
+ // Shared slots the middleware writes and the event bridge / finalizer read.
+ // They are created here, not by the middleware installer, because the run
+ // context (built before the harness is prepared) carries two of them.
+ let cursor: tinyagents_harness::events::IterationCursor = Arc::default();
+ let tool_names: crate::agent::tinyagents::observability::ToolNameMap = Arc::default();
+ let failure_map: crate::agent::tinyagents::observability::ToolFailureMap = Arc::default();
+ let provider_usage_carry: crate::agent::tinyagents::observability::ProviderUsageCarry =
+ Arc::default();
+ let tool_outcome_sink: ToolOutcomeSink = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let tool_result_artifact_index = context_mw
+ .artifact_store
+ .as_ref()
+ .map(|_| Arc::new(ToolResultArtifactIndexStore::new()));
// The hosted graph is the execution boundary of the same root turn the
// runtime/session already created. Retain that root config id here instead
@@@ -324,9 -358,14 +325,9 @@@
"openhuman-agent-turn"
})
.with_max_model_calls(max_iterations)
- .with_max_tool_calls(crate::agent::stop_hooks::tool_call_limit(max_iterations))
+ .with_max_tool_calls(run_context.tool_call_limit_for(max_iterations))
.with_max_depth(super::budget::depth(&run_context))
.with_tag("openhuman")
- .with_tag(if subagent_scope.is_some() {
- "scope:subagent"
- } else {
- "scope:root"
- })
.with_tag(if on_progress.is_some() {
"observed"
} else {
@@@ -471,140 -552,71 +472,140 @@@
journal::register_request_journal_run(request_id, journal_run_id.as_str());
}
}
+ ctx = ctx.with_events(sink.clone());
- if let Some(events) = &events {
- ctx = ctx.with_events(events.clone());
- }
+ // Per-turn controls for the driver. Best-effort thread label for the
+ // delivery/requeue observability events and the metadata on any requeued
+ // steer: a sub-agent uses its task id; the interactive/channel parent turn
+ // reads the turn origin.
+ let steer_thread_label =
+ steering_forwarder::thread_label(subagent_scope.as_ref(), run_context.origin.as_ref());
+ let controls = TurnControls {
+ max_iterations: Some(max_iterations),
+ pause_at_cap,
+ early_exit_tools: early_exit_tools
+ .iter()
+ .map(|name| (*name).to_string())
+ .collect::<BTreeSet<_>>(),
+ // The host emits the terminal `TurnCompleted` itself (it carries the
+ // stop classification), so the driver never fires a completion sink.
+ defer_turn_completed: true,
+ scope: match &subagent_scope {
+ Some(scope) => TurnScope::Subagent(DriverSubagentScope {
+ agent_id: scope.agent_id.clone(),
+ task_id: scope.task_id.clone(),
+ }),
+ None => TurnScope::Root,
+ },
+ // Forwards mid-flight steers from the session's run queue, drains
+ // residual (delivered-but-unapplied) steers back into it when the turn
+ // ends — also on cancellation (issue #4456).
+ steering: run_queue.map(steering_forwarder::queue_feed),
+ registrar: is_subagent
+ .then(|| Arc::new(steering_forwarder::SharedSteeringRegistrar) as Arc<_>),
+ thread_label: Some(steer_thread_label),
+ // Only the top-level turn's cap pause is binding on dispatch; a
+ // delegated child reaching its own cap is routine and must not stop the
+ // parent's fan-out (it still gets its advisory `Pause`). `Pause` is
+ // advisory, so the pause is also recorded on the turn's dispatch guard
+ // to stop a racing sub-agent dispatch (#5804).
+ cap_pause_recorder: (!is_subagent)
+ .then(|| run_context.dispatch.clone())
+ .flatten()
+ .map(|guard| {
+ Arc::new(move |completed: u64, cap: u64| {
+ guard.record_pause_requested(completed, cap)
+ }) as tinyagents_harness::events::PauseRecorder
+ }),
+ ..TurnControls::default()
+ };
+ let request = DriverRequest {
+ history: input,
+ // A turn driven outside a `Session` has no frozen declaration set; the
+ // planner disables the snapshot comparison.
+ tools: ToolSnapshot::new(Vec::new()).map_err(|error| anyhow::anyhow!("{error}"))?,
+ run_context: ctx,
+ stream: streaming,
+ controls,
+ };
+ let mut prepared = driver.prepare(request).await.map_err(|failure| {
+ tracing::error!(error = %failure.error, "[tinyagents] turn driver could not prepare the turn");
+ anyhow::anyhow!("{}", failure.error)
+ })?;
+ let steering =
+ prepared.run_context.steering.clone().ok_or_else(|| {
+ anyhow::anyhow!("turn driver prepared a run without a steering handle")
+ })?;
+ let tool_count = prepared.tools().registered.len();
- // Steering: attach the shared handle (when present), drain any already-queued
- // steer messages into it (so a pre-run steer lands before the first model
- // call), and forward mid-flight steers via a poll loop. The same handle
- // carries the early-exit `Pause`.
- //
- // Best-effort thread label for the delivery/requeue observability events and
- // the metadata on any requeued steer: a sub-agent uses its task id; the
- // interactive/channel parent turn reads the task-local turn origin.
- let steer_thread_label = subagent_scope
- .as_ref()
- .map(|s| s.task_id.clone())
- .or_else(|| match run_context.origin.as_ref() {
- Some(crate::agent::turn_origin::AgentTurnOrigin::WebChat { thread_id, .. }) => {
- Some(thread_id.clone())
- }
- Some(crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {
- reply_target,
- ..
- }) => Some(reply_target.clone()),
- _ => None,
- })
- .unwrap_or_default();
+ let candidate_names = prepared.tools().plan.candidates.clone();
+ let TurnWiring {
+ halt_summary,
+ wrap_up_fired,
+ compression_mw,
+ prompt_cache_guard,
+ } = install_turn_middleware(
+ &mut prepared.harness,
+ &steering,
+ TurnMiddlewareInputs {
+ model: model.to_string(),
+ tool_sets,
+ allowed,
+ candidate_names,
+ subagent_scope: subagent_scope.clone(),
+ context_window,
+ context_mw,
- stop_hooks: run_context.stop_hooks.clone(),
++ host_policy: run_context.harness_host_policy(),
+ tool_policy: tool_policy.clone(),
+ required_capabilities: routes::turn_required_capabilities(model),
+ deterministic_cacheable,
+ has_route_fallback,
+ hosted_security_gate,
+ pause_at_cap,
+ run_mode: run_context
+ .thread_id
+ .as_deref()
+ .map(crate::agent::tinyagents::run_mode::handle_for_thread),
+ memory_turn: run_context.memory_turn.clone(),
+ summarizer_model,
+ failure_map: failure_map.clone(),
+ provider_usage_carry: provider_usage_carry.clone(),
+ tool_outcome_sink: tool_outcome_sink.clone(),
+ },
+ );
+ if let Some(scope) = run_context.response_shape.clone() {
+ tinyagents_harness::middleware::install_response_shape(&mut prepared.harness, scope);
+ }
+ super::budget::install_depth(&mut prepared.harness, &run_context);
+ super::deadline_wind_down::install(
+ &mut prepared.harness,
+ &Some(steering.clone()),
+ &run_context,
+ &subagent_scope,
+ );
+ turn_observer::install(&mut prepared.harness, &sink, hosted_security_gate);
- // The forwarder is wrapped in an abort-on-drop RAII guard (issue #4456): its
- // `Drop` aborts the poll task, deregisters the sub-agent steering handle, and
- // drains residual (delivered-but-unapplied) steers back into the session run
- // queue. Because the guard is held across the drive future, that cleanup runs
- // identically on normal return, error, AND drop-cancellation — the previous
- // manual `forwarder.abort()` after the drive future only ran on normal
- // return, so a cancelled turn (web interrupt / sub-agent abort, both
- // drop-based) leaked a forwarder task that looped forever and raced the next
- // turn for the shared run queue.
- let steering_forwarder_guard = if let Some(handle) = handle {
- let registry_task_id = if let Some(scope) = &subagent_scope {
- let task_id = TaskId::new(scope.task_id.clone());
- shared_steering_registry().register(task_id.clone(), handle.clone());
- tracing::debug!(
- task_id = scope.task_id.as_str(),
- "[tinyagents] registered subagent steering handle"
- );
- Some(task_id)
- } else {
- None
- };
- // Pre-run drain so a steer/collect queued before the turn started lands
- // ahead of the first model call.
- if let Some(queue) = run_queue.clone() {
- steering_forwarder::forward_steers(&queue, &handle, &steer_thread_label).await;
- steering_forwarder::forward_collects(&queue, &handle, &steer_thread_label).await;
- }
- ctx = ctx.with_steering(handle.clone());
- Some(steering_forwarder::arm_guard(
- handle,
- run_queue,
- registry_task_id,
- steer_thread_label.clone(),
- ))
- } else {
- None
- };
+ // Fail-closed registry validation gate (issue #4249, Workstream 10 — registry).
+ // The projected `CapabilityRegistry` produced these diagnostics while the
+ // turn was planned; enforce them here, *before* the first model dispatch, so
+ // an ambiguous/broken tool surface (duplicate name across native/MCP/Composio/
+ // generated tools, dangling alias, etc.) aborts the turn instead of silently
+ // resolving to an unintended component while a provider call is in flight.
+ let registry_diagnostics = capability_diagnostics(
+ &plan_models,
+ &bridge_tool_sets,
+ &prepared.tools().plan.admitted,
+ );
+ if let Err(error) = enforce_registry_diagnostics(&registry_diagnostics) {
+ // Settle the driver's steering registration before the turn aborts.
+ let _ = prepared.split().1.finish(None);
+ return Err(error);
+ }
+ tracing::debug!(
+ model,
+ tools = tool_count,
+ "[tinyagents] turn harness assembled"
+ );
// Heap-allocate the harness drive future. It is large (it owns the whole run
// context, middleware stack, and loop state), and a sub-agent turn runs
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index 3d48c6bcec,9ed15e596a..6098abe607
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@@ -34,110 -22,137 +34,116 @@@ use crate::agent::tinyagents::context_w
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::observability::{ProviderUsageCarry, SubagentScope, ToolFailureMap};
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 policies, scoped tool callbacks (registered after the runtime's
- // global ones) and the host's tool-call cap, from the explicit run context.
- host_policy: super::host::HarnessHostPolicy,
- 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 {
+
+/// What the middleware stack needs to know about the turn.
+pub(super) struct TurnMiddlewareInputs {
+ /// The turn's primary model name.
+ pub(super) model: String,
+ /// The shared tool sets the turn's tools resolve against.
+ pub(super) tool_sets: Vec<tinyagents_runtime::turn_driver::SharedToolSet>,
+ /// The allowlist the turn registered under (`None` = every visible tool).
+ pub(super) allowed: Option<HashSet<String>>,
+ /// The tool names the registration considered (before the allowlist).
+ pub(super) candidate_names: Vec<String>,
+ /// Set for a delegated child run.
+ pub(super) subagent_scope: Option<SubagentScope>,
+ pub(super) context_window: Option<u64>,
+ pub(super) context_mw: TurnContextMiddleware,
- pub(super) stop_hooks:
- Vec<Arc<dyn tinyagents_harness::middleware::StopHook<tinyagents_harness::cost::TurnCost>>>,
++ /// Stop policies and scoped tool callbacks (registered after the runtime's
++ /// global ones), from the explicit run context.
++ pub(super) host_policy: super::host::HarnessHostPolicy,
+ pub(super) tool_policy: Option<ToolPolicyEnforcement>,
+ pub(super) required_capabilities: Option<CapabilitySet>,
+ pub(super) deterministic_cacheable: bool,
+ /// Whether the run has a cross-route fallback chain.
+ pub(super) has_route_fallback: bool,
+ /// Hosted roots authorize tools through `OpenHumanSecurityGate`; installing
+ /// the legacy approval middleware as well would issue a second approval.
+ pub(super) 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.
+ pub(super) pause_at_cap: bool,
+ /// Live per-thread Plan/Build mode handle; `Some` installs
+ /// `PlanModeMiddleware`. `None` for a caller with no thread identity.
+ pub(super) run_mode: Option<RunModeHandle>,
+ /// This turn's memory binding: the compaction summarizer recalls under it.
+ pub(super) memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
+ /// The context-window summarizer's model.
+ pub(super) summarizer_model: TurnChatModel,
+ /// Shared `call_id -> (success, failure, elapsed_ms, output_chars)` side
+ /// channel: middleware records each outcome for the bridge's
+ /// `ToolCallCompleted`.
+ pub(super) 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(super) provider_usage_carry: ProviderUsageCarry,
+ /// Per-call tool success/content capture for honest `ToolCallRecord`s.
+ pub(super) tool_outcome_sink: ToolOutcomeSink,
+}
+
+/// The handles the run loop reads after the drive returns.
+pub(super) struct TurnWiring {
+ /// Root-cause summary recorded by the repeated-tool-failure breaker.
+ pub(super) halt_summary: HaltSummarySlot,
+ /// 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).
+ pub(super) wrap_up_fired:
+ Option<Arc<tinyagents_harness::middleware::FinalCallWrapUpMiddleware>>,
+ /// The installed compression middleware, drained after the run to surface
+ /// each compaction's provenance.
+ pub(super) compression_mw: Option<Arc<ContextCompressionMiddleware>>,
+ /// Records a `CacheLayoutEvent` whenever the cacheable prompt prefix changes
+ /// across model calls (issue #4249, 03.2).
+ pub(super) prompt_cache_guard: Arc<PromptCacheGuardMiddleware>,
+}
+
+/// Installs the host's middleware stack onto `harness`, whose models, run
+/// policy and tools the driver already registered. `steering` is the run's own
+/// handle (the breakers, stop hooks and nudges pause through it).
+pub(super) fn install_turn_middleware(
+ harness: &mut AgentHarness<(), OpenHumanRunContext>,
+ steering: &SteeringHandle,
+ inputs: TurnMiddlewareInputs,
+) -> TurnWiring {
+ let TurnMiddlewareInputs {
+ model,
+ tool_sets,
+ allowed,
+ candidate_names,
+ subagent_scope,
+ context_window,
+ context_mw,
- stop_hooks,
++ host_policy,
+ tool_policy,
+ required_capabilities,
+ deterministic_cacheable,
+ has_route_fallback,
+ hosted_security_gate,
+ pause_at_cap,
+ run_mode,
+ memory_turn,
+ summarizer_model,
+ failure_map,
+ provider_usage_carry,
+ tool_outcome_sink,
+ } = inputs;
+ let super::host::HarnessHostPolicy {
+ stop_hooks,
+ tool_hooks: scoped_tool_hooks,
- tool_call_cap,
++ ..
+ } = host_policy;
- 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(),
- tool_call_cap,
- );
- 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);
+ let model = model.as_str();
+ crate::tools::timeout::install_harness_tool_timeouts(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
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
index 938c68c129,0000000000..8df5717329
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
@@@ -1,183 -1,0 +1,188 @@@
+//! The host's [`TurnPlanner`]: what one OpenHuman turn plugs into a
+//! [`TurnDriver`](tinyagents_runtime::turn_driver::TurnDriver).
+//!
+//! The driver assembles the harness; this file decides the product-shaped
+//! inputs it assembles from: the provider models (primary first, then the
+//! workload-tier routes), the run policy (retry, cross-route fallback, tool
+//! discovery, dialect, reasoning, tool rules) and the tool registration (shared
+//! sets, fail-closed admission, session deferral, typed dispatches, turn-origin
+//! scope). The middleware stack that wraps model and tool calls is installed on
+//! the prepared harness by [`turn_middleware`](super::turn_middleware).
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use tinyagents_harness::runtime::RunPolicy;
+use tinyagents_registry::{DiagnosticSeverity, RegistryDiagnostic};
+use tinyagents_runtime::turn_driver::{SharedToolSet, TurnPlan, TurnPlanner};
+use tinyagents_runtime::{DriverRequest, RuntimeError};
+use tinyinference_llm::model::ErrorSlotModel;
+
+use crate::agent::tinyagents::host::OpenHumanRunContext;
+use crate::agent::tinyagents::model::TurnChatModel;
+use crate::agent::tinyagents::routes;
+use crate::agent::tinyagents::tool_registration::host_tool_set_builder;
+use crate::agent::tinyagents::turn_policy::run_policy_for_provider;
+
+/// The run policy for one turn, and whether it carries a cross-route fallback.
+///
+/// Cross-route fallback ownership (issue #4249, Workstream 02.2): the SDK
+/// `RunPolicy.fallback` holds the ordered same-family route chain for the
+/// turn's primary model, so the harness fails over to a sibling workload tier
+/// (e.g. `hint:chat` to `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.
+pub(super) fn turn_run_policy(
+ model: &str,
+ max_iterations: usize,
+ deterministic_cacheable: bool,
+ local_provider: bool,
+ tool_dialect: tinyagents_harness::config::ToolDispatcher,
+ reasoning: Option<tinyinference_llm::model::ReasoningConfig>,
+ tool_rules: Option<Arc<tinyagents_harness::tool::ToolRulePolicy>>,
++ tool_call_cap: Option<usize>,
+) -> (RunPolicy, bool) {
- let mut policy =
- run_policy_for_provider(max_iterations, deterministic_cacheable, local_provider);
++ let mut policy = run_policy_for_provider(
++ max_iterations,
++ deterministic_cacheable,
++ local_provider,
++ tool_call_cap,
++ );
+ 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,
+ fallback_chain = ?route_fallback.as_ref().map(|f| &f.models),
+ "[models] turn policy: dialect pinned from the session, SDK retry/fallback applied"
+ );
+ (policy, route_fallback.is_some())
+}
+
+/// The models a turn registers, primary first. 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.
+///
+/// Each workload route is an additive registry entry carrying its per-route
+/// capability profile; the primary stays the default and dispatch target.
+pub(super) fn turn_models_for_plan(
+ model: &str,
+ primary: TurnChatModel,
+ tier_routes: Vec<(String, TurnChatModel)>,
+ error_slot: &tinyinference_llm::model::ModelErrorSlot,
+ hosted_security_gate: bool,
+) -> Vec<(String, TurnChatModel)> {
+ let slotted = |model: TurnChatModel| -> TurnChatModel {
+ if hosted_security_gate {
+ model
+ } else {
+ Arc::new(ErrorSlotModel::new(model, error_slot.clone()))
+ }
+ };
+ std::iter::once((model.to_string(), primary))
+ .chain(tier_routes)
+ .map(|(name, route)| (name, slotted(route)))
+ .collect()
+}
+
+/// Everything the planner decides a turn from.
+pub(super) struct OpenHumanTurnPlanner {
+ pub(super) models: Vec<(String, TurnChatModel)>,
+ pub(super) policy: RunPolicy,
+ pub(super) tool_sets: Vec<SharedToolSet>,
+ pub(super) allowed: Option<HashSet<String>>,
+ pub(super) has_thread: bool,
+ pub(super) session_deferred: Arc<HashSet<String>>,
+}
+
+#[async_trait]
+impl TurnPlanner<(), OpenHumanRunContext> for OpenHumanTurnPlanner {
+ async fn plan(
+ &self,
+ _request: &DriverRequest<OpenHumanRunContext>,
+ ) -> Result<TurnPlan<(), OpenHumanRunContext>, RuntimeError> {
+ let mut plan = TurnPlan::new(self.models.clone());
+ plan.policy = self.policy.clone();
+ plan.tools = host_tool_set_builder(
+ &self.tool_sets,
+ &self.allowed,
+ self.has_thread,
+ &self.session_deferred,
+ );
+ // A turn driven outside a `Session` has no frozen tool declaration to
+ // compare against; the registration above is the authority.
+ plan.enforce_tool_snapshot = false;
+ Ok(plan)
+ }
+}
+
+/// Enforces the capability registry's diagnostics fail-closed (issue #4249,
+/// Workstream 10 — registry), *before* the first model dispatch: an ambiguous or
+/// broken tool surface (a name shared across native/MCP/Composio/generated
+/// tools, a dangling alias) aborts the turn instead of silently resolving to an
+/// unintended component while a provider call is in flight. Warnings are logged.
+pub(super) fn enforce_registry_diagnostics(
+ registry_diagnostics: &[RegistryDiagnostic],
+) -> anyhow::Result<()> {
+ if !registry_diagnostics.is_empty() {
+ let (errors, warnings): (
+ Vec<&tinyagents_registry::RegistryDiagnostic>,
+ Vec<&tinyagents_registry::RegistryDiagnostic>,
+ ) = registry_diagnostics
+ .iter()
+ .partition(|d| matches!(d.severity, DiagnosticSeverity::Error));
+ for diag in &warnings {
+ tracing::warn!(
+ kind = diag.kind.as_str(),
+ name = %diag.name,
+ "[registry] non-fatal diagnostic: {}",
+ diag.message
+ );
+ }
+ if !errors.is_empty() {
+ let messages: Vec<String> = errors
+ .iter()
+ .map(|d| format!("[{}] {}: {}", d.kind.as_str(), d.name, d.message))
+ .collect();
+ for msg in &messages {
+ tracing::error!("[registry] error-severity diagnostic aborting turn: {msg}");
+ }
+ tracing::error!(
+ error_count = messages.len(),
+ warning_count = warnings.len(),
+ "[registry] aborting turn before model dispatch: capability registry validation failed"
+ );
+ return Err(anyhow::Error::new(
+ tinyagents_harness::agent_error::AgentError::RegistryValidationFailed {
+ diagnostics: messages,
+ },
+ ));
+ }
+ tracing::debug!(
+ warning_count = warnings.len(),
+ "[registry] registry diagnostics present (warnings only); proceeding with turn"
+ );
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "turn_plan_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs
index eadbfede96,c10aa1deb7..1b74b304e3
--- a/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_plan_tests.rs
@@@ -68,73 -71,38 +68,74 @@@ async fn prepare_with
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,
+ let (policy, _) = turn_run_policy(
"assembly-test-model",
- vec![Arc::new(tools)],
- None,
3,
- None,
- None,
- None,
- &[],
- TurnContextMiddleware::default(),
- Default::default(),
- None,
- None,
- false,
- false,
false,
+ models.is_local(),
tinyagents_harness::config::ToolDispatcher::default(),
- Arc::new(HashSet::new()),
None,
+ tool_rules,
+ None,
+ );
+ let TurnModels {
+ primary,
+ routes,
+ error_slot,
+ ..
+ } = models;
+ let planner = OpenHumanTurnPlanner {
+ models: turn_models_for_plan("assembly-test-model", primary, routes, &error_slot, false),
+ policy,
+ tool_sets,
+ allowed: None,
+ has_thread,
+ session_deferred: Arc::new(HashSet::new()),
+ };
+ let request = DriverRequest {
+ history: vec![tinyinference_llm::message::Message::user("hi")],
+ tools: ToolSnapshot::new(Vec::new()).expect("empty snapshot"),
+ run_context: tinyagents_harness::context::RunContext::new(
+ tinyagents_harness::context::RunConfig::new("plan-test"),
+ OpenHumanRunContext::new(),
+ ),
+ stream: false,
+ controls: TurnControls::default(),
+ };
+ TurnDriver::new(Arc::new(planner), Arc::new(()))
+ .prepare(request)
+ .await
+ .map_err(|failure| failure.error)
+ .expect("turn prepares")
+}
+
+/// Prepare a turn over the real goal tools plus one ordinary tool.
+async fn prepared_with(
+ has_thread: bool,
+ tool_rules: Option<Arc<tinyagents_harness::tool::ToolRulePolicy>>,
+) -> tinyagents_runtime::turn_driver::PreparedTurn<(), OpenHumanRunContext> {
+ let workspace = tempfile::TempDir::new().expect("workspace");
+ let mut tools = crate::agent::goals::goal_tools(workspace.path());
+ tools.push(Box::new(PlainTool));
+ prepare_with(
+ Arc::new(IdleModel),
+ vec![Arc::new(tools)],
has_thread,
- None,
tool_rules,
)
+ .await
}
-#[test]
-fn turn_tool_rules_reach_the_harness_policy() {
+async fn registered_tool_names(has_thread: bool) -> Vec<String> {
+ prepared_with(has_thread, None)
+ .await
+ .harness
+ .tools()
+ .names()
+}
+
+#[tokio::test]
+async 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)),