Skip to content

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

refactor(inference): adopt native workload routing

Steven Enamakel857e827af50e
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index 721ed571d2..b3695f0a71 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -36,7 +36,6 @@ The adapter seam between OpenHuman and the vendored [`tinyagents`](../../../../.
| [`middleware/research_budget.rs`](./middleware/research_budget.rs) | Withdraws the web tools from a top-level turn after eight successful search or fetch calls (forcing an answer only when no other tool remains), and notes once when consecutive web calls fail. |
| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. |
| [`tools.rs`](./tools.rs) | `CanonicalSharedToolAdapter`: resolves an OpenHuman shared tool registry and forwards the canonical `tinytools::Tool` contract; `EarlyExitHook` pauses successful `ask_user_clarification`-style calls. |
-| `routes.rs` | the workload router projected from the upstream `WORKLOAD_ROUTES` table, `RequiredCapabilitiesMiddleware`, `FallbackObserverMiddleware`, `UsageCarryMiddleware`, and the per-model fallback policy. |
| [`observability.rs`](./observability.rs) + `observability/` | `event_bridge.rs`: `OpenhumanEventBridge`, translating crate `AgentEvent`s into `AgentProgress` and feeding per-call usage into `crate::platform::cost`. `event_projection.rs`: its `EventListener` impl. `bridge_types.rs`: `SubagentScope` and the shared bridge carries (the cap pauser itself is `tinyagents_harness::events::CapPauser`). |
| [`host/steering.rs`](./host/steering.rs) | OpenHuman's steering allowlist and the shared `SteeringRegistry` for detached sub-agents. Task primitives are imported directly from `tinyagents_graph::orchestration`. |
| [`host/delegation.rs`](./host/delegation.rs) | Explicit tracing-bound execution helpers over `tinyagents_graph::delegation`'s plan, execute, review, finalize graph. |
@@ -72,7 +71,7 @@ Most of the module is `pub(crate)` or private. The `pub` items, per `mod.rs`:
- `config::*`: the host half of the generic-harness config seam.
- `payload_summarizer::*`: `pub` since issue #6014 so an embedder can pass its own `Arc<dyn PayloadSummarizer>` to `AgentBuilder::payload_summarizer` (the default dispatches a sub-agent, which some embedders cannot do).
-- `routes::ResolvedRouteMiddleware`: records canonical response metadata in the explicit run context; `TinyagentsTurnOutcome` carries it to the bus.
+- Native workload middleware: `turn_middleware.rs` installs the upstream `ResolvedRouteMiddleware` with OpenHuman's cost estimator, pricing lookup, and explicit route sink. `turn_plan.rs` and `turn_exec.rs` read fallback and capability policy directly from `WorkloadRouter`.
- `host::*` (the `OpenHuman*` adapter structs) and `TurnModelSource`.
Within the crate the entry point is `TurnSpec::run` (`pub(crate)`); `run_turn_via_tinyagents` is `#[cfg(test)]` only.
diff --git a/crates/openhuman-core/src/agent/tinyagents/mod.rs b/crates/openhuman-core/src/agent/tinyagents/mod.rs
index e3ea115de8..a74eade563 100644
--- a/crates/openhuman-core/src/agent/tinyagents/mod.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/mod.rs
@@ -47,7 +47,6 @@ pub mod budget;
pub mod payload_summarizer;
mod policy_denial;
pub(crate) mod reaper;
-mod routes;
mod steering_forwarder;
mod supplemental_trace;
pub(crate) mod thread_reasoning;
diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
index 25c6d9be3e..88d5a303e7 100644
--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs
@@ -674,7 +674,7 @@ impl EventListener for OpenhumanEventBridge {
// attempt (`RunPolicy.retry.max_attempts = 1`, pending `ReliableProvider`
// removal) it will not fire on the live path yet, but the bridge is wired
// for when it does. `FallbackSelected` is emitted by
- // [`FallbackObserverMiddleware`](super::routes::FallbackObserverMiddleware)
+ // `tinyagents_harness::middleware::library::FallbackObserverMiddleware`
// whenever the harness fails over to a sibling workload-tier route.
AgentEvent::RetryScheduled { call_id, attempt } => {
tracing::info!(
diff --git a/crates/openhuman-core/src/agent/tinyagents/routes.rs b/crates/openhuman-core/src/agent/tinyagents/routes.rs
deleted file mode 100644
index e280983908..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/routes.rs
+++ /dev/null
@@ -1,197 +0,0 @@
-//! Workload routing and model-call middleware for native TinyAgents models.
-
-use std::sync::LazyLock;
-
-use async_trait::async_trait;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::events::{AgentEvent, GenerationEnrichment, GenerationPricing};
-use tinyagents_harness::middleware::{MiddlewareModelOutcome, ModelHandler, ModelMiddleware};
-use tinyagents_harness::retry::FallbackPolicy;
-use tinyagents_registry::WorkloadRouter;
-use tinyinference_llm::model::{CapabilitySet, ModelRequest};
-
-/// The workload routing table (fallback chains and the vision `image_in` gate)
-/// projected into the crate [`WorkloadRouter`] from the upstream declarative
-/// [`WORKLOAD_ROUTES`](tinyinference_llm::model::workload::WORKLOAD_ROUTES) table,
-/// which owns the policy.
-static OH_WORKLOAD_ROUTER: LazyLock<WorkloadRouter> =
- LazyLock::new(|| WorkloadRouter::from_workload_routes("hint:vision"));
-
-/// The capability needs a turn imposes on every model call, derived from what is
-/// cheaply available at harness-assembly time.
-///
-/// Today the only reliably-derivable, safe-to-require signal is **vision**: when
-/// the turn's effective model is the dedicated `hint:vision` tier the turn was
-/// routed there because it carries image input (this is exactly what the
-/// `model_vision` selection in `subagent_host/ops/graph.rs` encodes), so we
-/// require `image_in` — which keeps the primary vision model selectable while
-/// filtering any non-vision fallback pre-dispatch.
-///
-/// Returns `None` (install no gate) when no requirement is derivable, so the
-/// common text turn is unaffected. Signals still to thread (see module note and
-/// the migration spec): per-call tool-calling and reasoning needs, BYOK vision
-/// (needs `Config` + `model_registry.vision`), and true per-message image
-/// presence rather than the tier proxy.
-pub(super) fn turn_required_capabilities(model: &str) -> Option<CapabilitySet> {
- OH_WORKLOAD_ROUTER.required_capabilities(model)
-}
-
-/// Build the [`FallbackPolicy`] for a turn whose effective/primary model is
-/// `model` (issue #4249, Workstream 02.2). The returned chain is `[primary,
-/// alternate…]` — the crate's [`FallbackPolicy::next_after`] traversal expects the
-/// current (primary) name as the first entry and yields each subsequent alternate.
-///
-/// The chain now comes straight from the declarative [`OH_WORKLOAD_ROUTER`]
-/// (`fallback_policy` leads with the primary, then the tier's same-family
-/// alternates). Returns `None` when no same-family alternate exists (vision, or
-/// a raw non-tier model string), leaving the turn primary-only.
-pub(super) fn route_fallback_policy(model: &str) -> Option<FallbackPolicy> {
- let policy = OH_WORKLOAD_ROUTER.fallback_policy(model);
- match &policy {
- Some(p) => tracing::debug!(
- route = model,
- chain = ?p.models,
- "[fallback] configured SDK-owned cross-route fallback chain"
- ),
- None => tracing::debug!(
- route = model,
- "[fallback] no same-family fallback route; turn is primary-only"
- ),
- }
- policy
-}
-
-/// Captures the concrete provider/model/host-route selected for a successful
-/// call from TinyInference's canonical response metadata.
-///
-/// `tinyinference_llm::model::RouteRecordingModel` decorates both unary
-/// responses and stream terminal metadata. The harness folds a stream into its
-/// terminal `ModelResponse` before middleware regains control, so this one
-/// typed boundary records primary and fallback routes identically without an
-/// OpenHuman model wrapper or task-local propagation.
-pub(super) struct ResolvedRouteMiddleware {
- /// Explicit configured fallback when a provider cannot return route metadata.
- provider_id: String,
- model: String,
-}
-
-impl ResolvedRouteMiddleware {
- pub(super) fn new(provider_id: impl Into<String>, model: impl Into<String>) -> Self {
- Self {
- provider_id: provider_id.into(),
- model: model.into(),
- }
- }
-}
-
-#[async_trait]
-impl ModelMiddleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for ResolvedRouteMiddleware
-{
- fn name(&self) -> &str {
- "openhuman.resolved_route"
- }
-
- async fn wrap_model(
- &self,
- ctx: &mut RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- state: &(),
- request: ModelRequest,
- next: ModelHandler<'_, (), crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> tinyagents_harness::Result<MiddlewareModelOutcome> {
- let call_id = request
- .correlation
- .as_ref()
- .map(|correlation| correlation.call_id.clone())
- .or_else(|| {
- ctx.active_model_call
- .as_ref()
- .map(|call_id| call_id.as_str().to_owned())
- });
- if let Some(call_id) = &call_id {
- let provider_id =
- valid_trace_provider_id(&self.provider_id).then(|| self.provider_id.clone());
- if let Some(provider_id) = provider_id {
- ctx.events.emit(AgentEvent::GenerationEnriched {
- call_id: call_id.clone().into(),
- enrichment: GenerationEnrichment {
- provider_id: Some(provider_id),
- ..Default::default()
- },
- });
- }
- }
- let outcome = next.run(ctx, state, request).await?;
- let response = outcome.into_response();
- if let Some(route) = response.resolved_route.clone() {
- *ctx.data
- .resolved_route
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(route);
- }
- if let Some(call_id) = call_id {
- let route = response.resolved_route.as_ref();
- let model = route
- .map(|route| route.model.as_str())
- .or_else(|| {
- response
- .resolved_model
- .as_ref()
- .map(|resolved| resolved.name.as_str())
- })
- .unwrap_or(&self.model);
- let provider_id = route
- .map(|route| route.provider.as_str())
- .unwrap_or(&self.provider_id);
- let provider_id = valid_trace_provider_id(provider_id).then(|| provider_id.to_owned());
- let pricing = if model.trim().to_ascii_lowercase().ends_with(":free") {
- Some(GenerationPricing {
- input_per_mtok_usd: Some(0.0),
- cached_input_per_mtok_usd: Some(0.0),
- output_per_mtok_usd: Some(0.0),
- })
- } else {
- tinyagents_registry::pricing::lookup(model).map(|price| GenerationPricing {
- input_per_mtok_usd: Some(price.input_per_mtok_usd),
- cached_input_per_mtok_usd: Some(price.cached_input_per_mtok_usd),
- output_per_mtok_usd: Some(price.output_per_mtok_usd),
- })
- };
- let billed = tinyinference_llm::usage::usage_info_from_response(&response);
- let estimated_cost_usd = if response.served_from_cache
- || billed.is_some_and(|usage| usage.charge_reported && !usage.cost_is_estimate)
- {
- None
- } else {
- billed.and_then(|usage| crate::agent::cost::estimate_call_cost_usd(model, &usage))
- };
- let enrichment = GenerationEnrichment {
- provider_id,
- pricing,
- estimated_cost_usd,
- };
- if enrichment.provider_id.is_some()
- || enrichment.pricing.is_some()
- || enrichment.estimated_cost_usd.is_some()
- {
- ctx.events.emit(AgentEvent::GenerationEnriched {
- call_id: call_id.into(),
- enrichment,
- });
- }
- }
- Ok(MiddlewareModelOutcome::from(response))
- }
-}
-
-fn valid_trace_provider_id(value: &str) -> bool {
- !value.is_empty()
- && value.len() <= 64
- && value.chars().all(|character| {
- character.is_ascii_alphanumeric() || matches!(character, '_' | '.' | ':' | '-')
- })
-}
-
-#[cfg(test)]
-#[path = "routes_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs b/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs
deleted file mode 100644
index 26d79cc6d1..0000000000
--- a/crates/openhuman-core/src/agent/tinyagents/routes_tests.rs
+++ /dev/null
@@ -1,345 +0,0 @@
-use super::*;
-use std::sync::Arc;
-use tinyinference_llm::model::workload::{
- ROUTE_AGENTIC, ROUTE_BURST, ROUTE_CHAT, ROUTE_CODING, ROUTE_REASONING, ROUTE_SUMMARIZATION,
- ROUTE_VISION, WORKLOAD_ROUTE_TIERS,
-};
-
-use async_trait::async_trait;
-use futures::StreamExt;
-use tinyagents_harness::agent_loop::AgentStreamItem;
-use tinyagents_harness::context::RunConfig;
-use tinyagents_harness::events::{AgentEvent, EventListener, EventRecord};
-use tinyagents_harness::runtime::{AgentHarness, RunPolicy};
-use tinyagents_harness::testkit::ScriptedModel;
-use tinyinference_llm::message::Message;
-use tinyinference_llm::model::{
- ChatModel, ModelRequest, ModelResponse, ResolvedModelRoute, RouteRecordingModel,
-};
-use tokio::sync::Barrier;
-
-struct FailingModel;
-
-/// A deterministic two-run gate. Each invocation waits until the test has
-/// observed both contexts at the same model-call boundary, then waits again
-/// for the test to release them together.
-struct GatedModel {
- entered: Arc<Barrier>,
- release: Arc<Barrier>,
-}
-
-#[async_trait]
-impl ChatModel<()> for FailingModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- Err(tinyinference_llm::Error::Model(
- "primary unavailable".to_string(),
- ))
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for GatedModel {
- async fn invoke(
- &self,
- _state: &(),
- _request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.entered.wait().await;
- self.release.wait().await;
- Ok(ModelResponse::assistant("done"))
- }
-}
-
-async fn run_recorded_route(
- streaming: bool,
- fallback: bool,
- route: ResolvedModelRoute,
- successful_model: Arc<dyn ChatModel<()>>,
-) -> (ResolvedModelRoute, Vec<AgentEvent>) {
- let mut harness: AgentHarness<(), crate::agent::tinyagents::host::OpenHumanRunContext> =
- AgentHarness::new();
- let served_route = if fallback {
- let primary = Arc::new(RouteRecordingModel::new(
- Arc::new(FailingModel),
- ResolvedModelRoute::new("primary", "unavailable", "primary"),
- ));
- harness
- .register_model("primary", primary)
- .set_default_model("primary");
- route.clone()
- } else {
- route.clone()
- };
- let successful = Arc::new(RouteRecordingModel::new(
- successful_model,
- served_route.clone(),
- ));
- if fallback {
- harness
- .register_model("backup", successful)
- .with_policy(RunPolicy {
- retry: tinyagents_harness::retry::RetryPolicy::default().with_max_attempts(1),
- fallback: Some(tinyagents_harness::retry::FallbackPolicy::new([
- "primary", "backup",
- ])),
- ..RunPolicy::default()
- });
- } else {
- harness
- .register_model("primary", successful)
- .set_default_model("primary");
- }
- harness.push_model_middleware(Arc::new(ResolvedRouteMiddleware::new(
- "configured-provider",
- "gpt-4o-mini",
- )));
-
- let host = crate::agent::tinyagents::host::OpenHumanRunContext::new();
- let slot = host.resolved_route.clone();
- let ctx = host.into_tinyagents(RunConfig::new("route-recording"));
- let recorder = Arc::new(RouteEventRecorder::default());
- ctx.events.subscribe(recorder.clone());
- if streaming {
- let mut stream =
- Box::pin(harness.invoke_stream_in_context(&(), ctx, vec![Message::user("route")]));
- while let Some(item) = stream.next().await {
- match item {
- AgentStreamItem::Completed(_) => break,
- AgentStreamItem::Failed { error, .. } => panic!("stream failed: {error}"),
- AgentStreamItem::Event(_) => {}
- }
- }
- } else {
- harness
- .invoke_in_context(&(), ctx, vec![Message::user("route")])
- .await
- .expect("unary route run succeeds");
- }
- let resolved = slot
- .lock()
- .expect("route slot")
- .clone()
- .expect("middleware records canonical response route");
- let events = recorder.0.lock().unwrap().clone();
- (resolved, events)
-}
-
-fn scripted_success() -> Arc<dyn ChatModel<()>> {
- Arc::new(ScriptedModel::replies(vec!["done"]))
-}
-
-#[derive(Default)]
-struct RouteEventRecorder(std::sync::Mutex<Vec<AgentEvent>>);
-
-impl EventListener for RouteEventRecorder {
- fn on_event(&self, record: &EventRecord) {
- self.0.lock().unwrap().push(record.event.clone());
- }
-}
-
-#[tokio::test]
-async fn resolved_route_enrichment_uses_actual_provider_model_and_call_identity() {
- let route = ResolvedModelRoute::new("anthropic", "claude-opus-4-8", "backup");
- let mut harness: AgentHarness<(), crate::agent::tinyagents::host::OpenHumanRunContext> =
- AgentHarness::new();
- let model = Arc::new(RouteRecordingModel::new(scripted_success(), route));
- harness
- .register_model("primary", model)
- .set_default_model("primary");
- harness.push_model_middleware(Arc::new(ResolvedRouteMiddleware::new(
- "configured-provider",
- "gpt-4.1",
- )));
-
- let host = crate::agent::tinyagents::host::OpenHumanRunContext::new();
- let ctx = host.into_tinyagents(RunConfig::new("route-enrichment"));
- let recorder = Arc::new(RouteEventRecorder::default());
- ctx.events.subscribe(recorder.clone());
- harness
- .invoke_in_context(&(), ctx, vec![Message::user("route")])
- .await
- .expect("routed invocation succeeds");
-
- let events = recorder.0.lock().unwrap();
- let call_id = events
- .iter()
- .find_map(|event| match event {
- AgentEvent::ModelStarted { call_id, .. } => Some(call_id.clone()),
- _ => None,
- })
- .expect("model attempt has a native call id");
- assert!(events.iter().any(|event| matches!(
- event,
- AgentEvent::GenerationEnriched { call_id: enriched, enrichment }
- if enriched == &call_id
- && enrichment.provider_id.as_deref() == Some("anthropic")
- && enrichment.pricing.as_ref().is_some_and(|pricing| {
- pricing.input_per_mtok_usd == Some(5.0)
- && pricing.cached_input_per_mtok_usd == Some(0.5)
- && pricing.output_per_mtok_usd == Some(25.0)
- })
- )), "pricing and provider metadata use the actual response route, not configured fallback values; events={events:#?}");
-}
-
-#[tokio::test]
-async fn resolved_route_middleware_records_primary_routes_for_unary_and_streaming_runs() {
- for streaming in [false, true] {
- let route = ResolvedModelRoute::new("openhuman", "chat-concrete", "chat-v1");
- let (observed, events) =
- run_recorded_route(streaming, false, route.clone(), scripted_success()).await;
- assert_eq!(observed, route, "streaming={streaming}");
- assert_actual_provider_enrichment(&events, &route, streaming);
- }
-}
-
-#[tokio::test]
-async fn resolved_route_middleware_records_successful_fallback_for_unary_and_streaming_runs() {
- for streaming in [false, true] {
- let route = ResolvedModelRoute::new("anthropic", "claude-concrete", "backup");
- let (observed, events) =
- run_recorded_route(streaming, true, route.clone(), scripted_success()).await;
- assert_eq!(observed, route, "streaming={streaming}");
- assert_actual_provider_enrichment(&events, &route, streaming);
- }
-}
-
-fn assert_actual_provider_enrichment(
- events: &[AgentEvent],
- route: &ResolvedModelRoute,
- streaming: bool,
-) {
- let call_ids = events
- .iter()
- .filter_map(|event| match event {
- AgentEvent::ModelStarted { call_id, .. } => Some(call_id),
- _ => None,
- })
- .collect::<Vec<_>>();
- assert!(!call_ids.is_empty(), "native model start is recorded");
- assert!(
- events.iter().any(|event| matches!(
- event,
- AgentEvent::GenerationEnriched { call_id, enrichment }
- if call_ids.contains(&call_id)
- && enrichment.provider_id.as_deref() == Some(route.provider.as_str())
- )),
- "resolved provider enriches the actual call; streaming={streaming}; events={events:#?}"
- );
-}
-
-#[tokio::test]
-async fn resolved_route_middleware_isolates_concurrent_run_contexts() {
- let first = ResolvedModelRoute::new("openai", "first", "chat-v1");
- let second = ResolvedModelRoute::new("anthropic", "second", "reasoning-v1");
- // The test is the third barrier participant. Both invoked model calls have
- // reached the first barrier before it can advance to the release barrier;
- // neither can return its response (and write its own route) until then.
- let entered = Arc::new(Barrier::new(3));
- let release = Arc::new(Barrier::new(3));
- let first_task = tokio::spawn(run_recorded_route(
- false,
- false,
- first.clone(),
- Arc::new(GatedModel {
- entered: entered.clone(),
- release: release.clone(),
- }),
- ));
- let second_task = tokio::spawn(run_recorded_route(
- true,
- false,
- second.clone(),
- Arc::new(GatedModel {
- entered: entered.clone(),
- release: release.clone(),
- }),
- ));
- entered.wait().await;
- release.wait().await;
- let (first_observed, first_events) = first_task.await.expect("first route task joins");
- let (second_observed, second_events) = second_task.await.expect("second route task joins");
- assert_eq!(first_observed, first);
- assert_eq!(second_observed, second);
- for (events, route) in [(&first_events, first), (&second_events, second)] {
- let call_id = events
- .iter()
- .find_map(|event| match event {
- AgentEvent::ModelStarted { call_id, .. } => Some(call_id),
- _ => None,
- })
- .expect("model attempt has a native call id");
- assert!(events.iter().any(|event| matches!(
- event,
- AgentEvent::GenerationEnriched { call_id: enriched, enrichment }
- if enriched == call_id
- && enrichment.provider_id.as_deref() == Some(route.provider.as_str())
- )));
- }
-}
-
-/// The fallback chain for every tier must lead with the primary and carry the
-/// single same-family alternate the legacy static table encoded — the crate
-/// `ModelRouter` projection is exactly behavior-neutral.
-#[test]
-fn route_fallback_policy_matches_legacy_chains() {
- let cases: &[(&str, Option<&[&str]>)] = &[
- (ROUTE_CHAT, Some(&[ROUTE_CHAT, ROUTE_BURST])),
- (ROUTE_BURST, Some(&[ROUTE_BURST, ROUTE_CHAT])),
- (ROUTE_REASONING, Some(&[ROUTE_REASONING, ROUTE_AGENTIC])),
- (ROUTE_AGENTIC, Some(&[ROUTE_AGENTIC, ROUTE_REASONING])),
- (ROUTE_CODING, Some(&[ROUTE_CODING, ROUTE_AGENTIC])),
- (
- ROUTE_SUMMARIZATION,
- Some(&[ROUTE_SUMMARIZATION, ROUTE_CHAT]),
- ),
- // Vision is primary-only (an image_in gate no text route can satisfy).
- (ROUTE_VISION, None),
- // A concrete model id installs no chain — including the managed
- // default, which is the model every managed route resolves to.
- ("gpt-4o", None),
- ("openrouter/deepseek/deepseek-v4-flash", None),
- ];
- for (model, expected) in cases {
- let got = route_fallback_policy(model).map(|p| p.models);
- let want = expected.map(|chain| chain.iter().map(|s| s.to_string()).collect::<Vec<_>>());
- assert_eq!(got, want, "fallback chain mismatch for {model}");
- }
-}
-
-/// Only the vision route imposes an `image_in` gate; the
-/// common text turn stays ungated.
-#[test]
-fn turn_required_capabilities_gates_only_vision() {
- let vision = turn_required_capabilities(ROUTE_VISION).expect("vision is gated");
- assert!(vision.image_in);
- for model in [
- ROUTE_CHAT,
- ROUTE_REASONING,
- ROUTE_AGENTIC,
- ROUTE_CODING,
- ROUTE_BURST,
- ROUTE_SUMMARIZATION,
- "gpt-4o",
- ] {
- assert!(
- turn_required_capabilities(model).is_none(),
- "{model} must not be capability-gated"
- );
- }
-}
-
-/// The router covers exactly the projected route inventory, so the fallback/capability source of truth stays aligned with
-/// `WORKLOAD_ROUTE_TIERS`.
-#[test]
-fn router_covers_the_workload_tier_inventory() {
- for tier in WORKLOAD_ROUTE_TIERS {
- assert!(
- OH_WORKLOAD_ROUTER.route(tier).is_some(),
- "router missing tier {tier}"
- );
- }
-}
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
index 62fff5b07a..6d01c20aab 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_exec.rs
@@ -35,7 +35,7 @@ use crate::agent::tinyagents::turn_plan::{
use crate::agent::tinyagents::turn_run_error::map_turn_run_error;
use crate::agent::tinyagents::turn_run_finalize::finalize_turn_outcome;
use crate::agent::tinyagents::NativeSubagentRunContext;
-use crate::agent::tinyagents::{journal, routes, steering_forwarder};
+use crate::agent::tinyagents::{journal, steering_forwarder};
use crate::inference::turn_models::TurnModels;
use tinyagents_harness::events::EventSink;
use tinyagents_harness::observability::turn_observer;
@@ -553,7 +553,10 @@ async fn drive_turn(
context_mw,
host_policy: run_context.harness_host_policy(),
tool_policy: tool_policy.clone(),
- required_capabilities: routes::turn_required_capabilities(model),
+ required_capabilities: tinyagents_registry::WorkloadRouter::from_workload_routes(
+ "hint:vision",
+ )
+ .required_capabilities(model),
deterministic_cacheable,
has_route_fallback,
dispatch: run_context.dispatch_ctx(),
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
index 0c07bc884b..a7009349f3 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_middleware.rs
@@ -35,11 +35,18 @@ use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::middleware;
use crate::agent::tinyagents::middleware::turn_context::TurnContextMiddleware;
use crate::agent::tinyagents::observability::{ProviderUsageCarry, SubagentScope, ToolFailureMap};
-use crate::agent::tinyagents::routes;
use crate::agent::tinyagents::verify_before_finish;
use super::ToolPolicyEnforcement;
+struct OpenHumanCostEstimator;
+
+impl tinyagents_harness::middleware::library::CostEstimator for OpenHumanCostEstimator {
+ fn estimate(&self, model: &str, usage: &tinyinference_llm::usage::BilledUsage) -> Option<f64> {
+ crate::agent::cost::estimate_call_cost_usd(model, usage)
+ }
+}
+
/// What the middleware stack needs to know about the turn.
pub(super) struct TurnMiddlewareInputs {
/// Configured provider id used only when the response has no resolved route.
@@ -188,14 +195,38 @@ pub(super) fn install_turn_middleware(
}),
));
- // 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::new(
- provider_id,
- model,
- )));
+ // Native route enrichment records the canonical resolved route in this
+ // run's explicit host carrier; pricing and cost remain host-owned.
+ harness.push_model_middleware(Arc::new(
+ tinyagents_harness::middleware::library::ResolvedRouteMiddleware::new(
+ provider_id,
+ model,
+ OpenHumanCostEstimator,
+ |data: &OpenHumanRunContext, route| {
+ *data
+ .resolved_route
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(route);
+ },
+ )
+ .with_pricing_lookup(|model| {
+ if crate::agent::cost::is_free_model(model) {
+ Some(tinyagents_harness::events::GenerationPricing {
+ input_per_mtok_usd: Some(0.0),
+ cached_input_per_mtok_usd: Some(0.0),
+ output_per_mtok_usd: Some(0.0),
+ })
+ } else {
+ tinyagents_registry::pricing::lookup(model).map(|price| {
+ tinyagents_harness::events::GenerationPricing {
+ input_per_mtok_usd: Some(price.input_per_mtok_usd),
+ cached_input_per_mtok_usd: Some(price.cached_input_per_mtok_usd),
+ output_per_mtok_usd: Some(price.output_per_mtok_usd),
+ }
+ })
+ }
+ }),
+ ));
// Per-call capability gate (issue #4249, Workstream 02.1): when the turn has
// derivable capability needs (today: vision for a `hint:vision` turn), stamp
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs b/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
index 9a97b4959c..eaeef1a818 100644
--- a/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/turn_plan.rs
@@ -20,7 +20,6 @@ use tinyagents_runtime::{DriverRequest, RuntimeError};
use tinyinference_llm::model::ErrorSlotModel;
use crate::agent::tinyagents::host::OpenHumanRunContext;
-use crate::agent::tinyagents::routes;
use crate::agent::tinyagents::tool_registration::host_tool_set_builder_for_turn;
use crate::agent::tinyagents::turn_policy::run_policy_for_provider;
@@ -50,7 +49,8 @@ pub(super) fn turn_run_policy(
local_provider,
tool_call_cap,
);
- let route_fallback = routes::route_fallback_policy(model);
+ let route_fallback = tinyagents_registry::WorkloadRouter::from_workload_routes("hint:vision")
+ .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
diff --git a/crates/openhuman-core/src/inference/README.md b/crates/openhuman-core/src/inference/README.md
index 92264e93c2..68cee9f506 100644
--- a/crates/openhuman-core/src/inference/README.md
+++ b/crates/openhuman-core/src/inference/README.md
@@ -68,9 +68,8 @@ lands on a provider with no credentials, the error says it was a background role
instead of naming a slug the user never configured.
Provider model aliases, defaults, and capabilities come from the registered provider-model hooks
-in `registry.rs`. The generic `provider_model.rs` adapter maps workload-role hints and preserves
-concrete ids without carrying a hosted catalog. The TinyAgents workload router that consumes this
-for agent turns is in [`agent/tinyagents/routes.rs`](../agent/tinyagents/routes.rs).
+in `registry.rs`. The `provider_model.rs` adapter uses TinyAgents' `WorkloadRouter` for workload
+role and hint resolution while preserving provider-owned aliases and concrete ids.
One-shot callers use `create_chat_model*` in `factory/chat_model.rs`. Agent turns use the
TinyAgents `TurnModelSet` through `TurnModelSource`, which builds the primary, workload routes,
@@ -199,7 +198,7 @@ picks the provider the same way a provider string does.
| `auth_error_registry.rs` | Process singleton and user-facing copy over `tinyinference_providers::auth_registry::ProviderAuthErrorRegistry` (the once-per-episode latch). |
| `failure_copy/` | `table.rs` maps a failure class to the wire `error_type`, source, retry verdict and user copy. `halt.rs` has loop-guard halt summaries. |
| `provider/` | Model construction and provider policy. See [`provider/README.md`](provider/README.md). |
-| `provider/factory.rs`, [`provider/factory/`](./provider/factory/) | Provider-string grammar and model construction: `routing`, `primary_cloud`, `access_gates`, `credentials`, `managed_backend`, `local_runtime`, `cloud_slug`, `cloud_spec`, `subprocess_providers`, `discovery`, `chat_model`, `turn_model`. |
+| `provider/factory.rs`, [`provider/factory/`](./provider/factory/) | Provider-string grammar and model construction: the `RouteSource` adapter for TinyAgents' `WorkloadRouter`, `primary_cloud`, `access_gates`, `credentials`, `managed_backend`, `local_runtime`, `cloud_slug`, `cloud_spec`, `subprocess_providers`, `discovery`, `chat_model`, `turn_model`. |
| `provider_model.rs`, `registry.rs` | Provider-neutral model hooks and caller adapters; hosted aliases, model defaults, pricing, and request metadata are registered by `openhuman-tinyhumans`. |
| `registry.rs` | Registered provider ownership metadata; provider-neutral retry classification is supplied by TinyInference. |
| `provider/fallback_diagnostics.rs` | Explains background-role fallback when it hits a provider with no credentials. |
diff --git a/crates/openhuman-core/src/inference/provider/README.md b/crates/openhuman-core/src/inference/provider/README.md
index 59fd7675d6..120ab5c633 100644
--- a/crates/openhuman-core/src/inference/provider/README.md
+++ b/crates/openhuman-core/src/inference/provider/README.md
@@ -10,7 +10,7 @@ previously `providers/` (pre-consolidation single-crate layout); see
## Public surface
-- **Factory** ([`factory.rs`](./factory.rs) + `factory/`: `routing.rs`, `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`), `create_chat_model`,
+- **Factory** ([`factory.rs`](./factory.rs) + `factory/`: `routing.rs` (`RouteSource` host adapter), `subprocess_providers.rs`, `access_gates.rs`, `chat_model.rs`, `cloud_slug.rs`, `credentials.rs`, `local_runtime.rs`, `managed_backend.rs`), `create_chat_model`,
`create_chat_model_from_string[_with_model_id]`,
`create_chat_model_with_model_id`, `provider_for_role`,
`probe_inference_readiness`, `BYOK_INCOMPLETE_SENTINEL`. Parses the
@@ -51,7 +51,7 @@ previously `providers/` (pre-consolidation single-crate layout); see
`Config::claude_agent_sdk`, abstract tier model constants.
- `crate::security::credentials`: auth-profile store for BYOK keys and OAuth
tokens.
-- `crate::agent::tinyagents::{routes, host}`: workload routing and explicit run
+- `crate::agent::tinyagents::host`: explicit run
explicit run-thread plumbing consumed while building a managed model.
- `crate::security::live_policy` + `crate::security::egress`: Privacy-Mode
`LocalOnly` refusal and `EgressDescriptor` emission at the factory chokepoint
diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rs
index 83e463c9aa..e13f5f5691 100644
--- a/crates/openhuman-core/src/inference/provider/factory.rs
+++ b/crates/openhuman-core/src/inference/provider/factory.rs
@@ -34,8 +34,9 @@ pub(crate) use credentials::{
openai_bearer_is_oauth, redact_endpoint_origin, resolve_codex_routing,
};
pub(crate) use local_runtime::create_local_chat_model_from_string;
-pub(crate) use routing::role_uses_implicit_cloud_fallback;
+pub(crate) use routing::{fallback_diagnostics_for_role, role_uses_implicit_cloud_fallback};
pub use routing::{provider_for_role, role_bypasses_managed_credits};
+pub(crate) use routing::{workload_router, ConfigRouteSource};
// Factory-internal helpers shared across the implementation modules.
use access_gates::{emit_inference_egress, enforce_local_only_inference};
diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
index ab8f0c503b..fdab3a56ae 100644
--- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs
@@ -133,7 +133,8 @@ pub(crate) fn resolve_cloud_slug_for<'a>(
// Only an *implicit* fallback is explained as one. A role with its own
// explicit cloud route can fail key lookup here too, and telling that user
// their local chat model caused it would be a lie.
- let implicit_fallback = role_uses_implicit_cloud_fallback(role, config);
+ let fallback_diagnostic = super::fallback_diagnostics_for_role(role, config);
+ let implicit_fallback = fallback_diagnostic.is_some();
let local_chat = if implicit_fallback {
config
.chat_provider
@@ -152,7 +153,14 @@ pub(crate) fn resolve_cloud_slug_for<'a>(
entry.auth_style.as_str(),
implicit_fallback
);
- fallback_diagnostics::missing_provider_credentials_message(role, slug, local_chat)
+ fallback_diagnostic.as_ref().map_or_else(
+ || format!("No usable credentials for '{slug}'. Add a key in Connections → LLM."),
+ |diagnostic| {
+ fallback_diagnostics::missing_provider_credentials_message(
+ diagnostic, slug, local_chat,
+ )
+ },
+ )
};
let key = lookup_key_for_slug(slug, config)
diff --git a/crates/openhuman-core/src/inference/provider/factory/routing.rs b/crates/openhuman-core/src/inference/provider/factory/routing.rs
index 83dd7845a2..371905cc9c 100644
--- a/crates/openhuman-core/src/inference/provider/factory/routing.rs
+++ b/crates/openhuman-core/src/inference/provider/factory/routing.rs
@@ -1,204 +1,144 @@
-//! Role → configured provider-string resolution (`provider_for_role`) plus the
-//! managed-credits bypass check and the `<model>[@<temp>]` suffix parser.
+//! Host facts supplied to TinyAgents' generic workload router.
use super::*;
-use crate::config::ops::resolve_primary_cloud_provider_string;
-use crate::inference::provider::fallback_diagnostics;
+use tinyagents_registry::router::{
+ DefaultModelRoute, FallbackDiagnostics, RouteSource, WorkloadRouter,
+};
-/// The provider route a role has **explicitly** configured, before any
-/// fallback.
-///
-/// Split out of [`provider_for_role`] so the fallback machinery can ask the
-/// same question the router asks — "did the user route this role anywhere?" —
-/// without re-deriving the role→config-field mapping and drifting from it.
+static WORKLOAD_ROUTER: std::sync::LazyLock<WorkloadRouter> =
+ std::sync::LazyLock::new(|| WorkloadRouter::from_workload_routes("hint:vision"));
+
+/// Config-backed facts that the generic router needs from the host.
+pub(crate) struct ConfigRouteSource<'a> {
+ config: &'a Config,
+ provider_id: &'a str,
+ extensions: Option<Option<&'a crate::core::slots::Extensions>>,
+ primary_cloud_route: String,
+ managed_default_model: Option<String>,
+}
+
+impl<'a> ConfigRouteSource<'a> {
+ pub(crate) fn new(config: &'a Config, provider_id: &'a str) -> Self {
+ Self::with_extension_selection(config, provider_id, None)
+ }
+
+ pub(crate) fn with_extension_selection(
+ config: &'a Config,
+ provider_id: &'a str,
+ extensions: Option<Option<&'a crate::core::slots::Extensions>>,
+ ) -> Self {
+ Self {
+ config,
+ provider_id,
+ extensions,
+ primary_cloud_route: crate::config::ops::resolve_primary_cloud_provider_string(config),
+ managed_default_model: None,
+ }
+ }
+
+ pub(crate) fn with_managed_default_model(mut self, model: Option<String>) -> Self {
+ self.managed_default_model = model;
+ self
+ }
+}
+
+impl RouteSource for ConfigRouteSource<'_> {
+ fn configured_route_for_role(&self, role: &str) -> Option<&str> {
+ configured_route_for_role(role, self.config)
+ }
+
+ fn primary_cloud_route(&self) -> &str {
+ &self.primary_cloud_route
+ }
+
+ fn default_model(&self) -> Option<&str> {
+ self.config.default_model.as_deref()
+ }
+
+ fn classify_default_model_route(&self, model: &str) -> DefaultModelRoute {
+ if is_explicit_provider_default(model, self.config) {
+ DefaultModelRoute::ExplicitProvider
+ } else if model.trim().starts_with("openrouter/") {
+ DefaultModelRoute::ManagedCatalog
+ } else {
+ DefaultModelRoute::Other
+ }
+ }
+
+ fn is_managed_route(&self, route: &str) -> bool {
+ let route = route.trim();
+ route.is_empty()
+ || route == "cloud"
+ || route == PROVIDER_OPENHUMAN
+ || route == BYOK_INCOMPLETE_SENTINEL
+ || route == self.provider_id
+ }
+
+ fn managed_default_model(&self) -> Option<&str> {
+ self.managed_default_model.as_deref()
+ }
+
+ fn legacy_tier_role(&self, tier: &str) -> Option<&str> {
+ let role = match self.extensions {
+ None => crate::inference::registry::provider_model_role(self.provider_id, tier),
+ Some(extensions) => crate::inference::registry::provider_model_role_for(
+ extensions,
+ self.provider_id,
+ tier,
+ ),
+ };
+ role.and_then(|role| {
+ crate::config::WORKLOAD_ROLES
+ .iter()
+ .copied()
+ .find(|known| *known == role)
+ })
+ }
+}
+
+/// Explicit route configured for a workload role, before fallback resolution.
pub(super) fn configured_route_for_role<'a>(role: &str, config: &'a Config) -> Option<&'a str> {
match role {
"chat" => config.chat_provider.as_deref(),
"reasoning" => config.reasoning_provider.as_deref(),
- "agentic" => config.agentic_provider.as_deref(),
+ "agentic" | "burst" => config.agentic_provider.as_deref(),
"coding" => config.coding_provider.as_deref(),
- // Burst uses the existing Agentic workload route for BYOK/local parity.
- // If unset, it falls through to the managed backend and is pinned to
- // `hint:burst` by `managed_tier_for_role`.
- "burst" => config.agentic_provider.as_deref(),
- // Tier-specific multimodal model; when unset it falls through to
- // `primary_cloud` (→ managed `hint:vision`), as every unset route now does.
"vision" => config.vision_provider.as_deref(),
- // `memory_provider` routes the summarizer sub-agent (whose definition
- // declares `hint = "summarization"`): "produce a condensed
- // representation of input text".
"memory" | "summarization" => config.memory_provider.as_deref(),
"embeddings" => config.embeddings_provider.as_deref(),
_ => None,
}
}
-/// Whether `role` reached a cloud slug by *implicit fallback* rather than by an
-/// explicit route.
-///
-/// True only when the role is one of the cloud-fallback background roles **and**
-/// its own route is unset (or the literal `"cloud"`). An explicitly configured
-/// cloud route — say `vision_provider = "anthropic:claude-…"` — is not a
-/// fallback, so a credential failure there must not be explained as "your local
-/// chat model cannot do this".
-pub(crate) fn role_uses_implicit_cloud_fallback(role: &str, config: &Config) -> bool {
- if !fallback_diagnostics::role_falls_back_to_cloud(role) {
- return false;
- }
- let route = configured_route_for_role(role, config).unwrap_or("").trim();
- route.is_empty() || route == "cloud"
+/// Shared workload routing policy, with product-specific facts supplied here.
+pub(crate) fn workload_router() -> &'static WorkloadRouter {
+ &WORKLOAD_ROUTER
}
-/// Return the configured provider string for a named workload role.
-///
-/// Empty / `"cloud"` resolves through `primary_cloud`. **Every** role behaves
-/// this way, and no role uses a sibling's BYOK provider as a fallback.
-///
-/// "Resolves through `primary_cloud`" is not the same as "goes to the managed
-/// backend": [`resolve_primary_cloud_provider_string`] may yield a legacy
-/// external `inference_url` (see below), or the fail-closed sentinel for a
-/// half-migrated BYOK config. The guarantee here is narrower and exact — an
-/// unset route does not borrow a *sibling's* configured provider.
-///
-/// The deliberate *aliases* in [`configured_route_for_role`] are unaffected and
-/// remain: `burst` reads `agentic_provider` and `summarization` reads
-/// `memory_provider`. Those are two names for one configured route, which is a
-/// different thing from an unset route borrowing a set one.
-///
-/// Until #6109 the three chat-tier roles (`chat`, `reasoning`, `coding`) took a
-/// configured BYOK provider from *any* sibling first, so setting one route moved
-/// the other two onto that key — a user who pointed only `coding_provider` at
-/// their own OpenRouter account found ordinary chat billed there too, with no
-/// setting saying so. Each route now stands alone.
-///
-/// For backwards compatibility, a legacy external `inference_url` takes
-/// precedence when `primary_cloud` still points at OpenHuman because
-/// migration 1→2 preserved the URL as a custom provider entry but older
-/// configs did not explicitly set per-workload routes.
-// keep until v0.66 (review after 2027-01-11): inference_url remains a supported
-// config.update input, and unfinished BYOK upgrades must not change billing route.
+/// Route a role through the native workload router.
pub fn provider_for_role(role: &str, config: &Config) -> String {
- let opt = configured_route_for_role(role, config);
- let s = opt.unwrap_or("").trim();
- if s.is_empty() || s == "cloud" {
- // #6109: an unset chat-tier route no longer inherits a sibling's BYOK
- // provider. Setting only `coding_provider` used to move `chat` and
- // `reasoning` onto that key too — ordinary conversations silently billed
- // to the user's own account, with no settings field saying so. Each
- // route now stands alone and an unset one falls through to the managed
- // backend, the same as every other workload.
-
- // #6938: the Chat UI model picker records its selection in
- // `config.default_model` (the web-chat turn path stores the per-turn
- // `model_override` there — see `build_session_agent`), but role
- // resolution never consulted it, so a picked BYOK/local model still
- // fell through to the managed backend and 401'd as "session expired".
- // When the default names an explicit provider route, honour it here
- // instead of the managed fallback.
- if let Some(route) = default_model_route_for_role(role, config) {
+ let source = ConfigRouteSource::new(config, PROVIDER_OPENHUMAN);
+ let resolved = WORKLOAD_ROUTER.provider_for_role(role, &source);
+ if let Some(diagnostic) = WORKLOAD_ROUTER.fallback_diagnostics(role, &source) {
+ if let Some(chat) = config
+ .chat_provider
+ .as_deref()
+ .filter(|chat| tinyinference_local::profile::is_local_provider_string(chat))
+ {
log::info!(
- "[providers][default-model-route] role={} route={}",
+ "[providers][local-fallback] role={} {}",
role,
- route
+ crate::inference::provider::fallback_diagnostics::cloud_fallback_notice(
+ &diagnostic,
+ chat,
+ )
);
- return route;
- }
-
- let resolved = resolve_primary_cloud_provider_string(config);
-
- // #5146 §2.1: the fallback itself is correct and stays — background
- // workloads run tier-specific models that local runtimes don't serve,
- // and a local-chat + managed-subscription user genuinely wants them on
- // the cloud. What was missing is the *explanation*: when this route
- // later fails for want of a key, the user saw a bare slug-level auth
- // error naming a provider they never configured. Emit the same
- // user-facing sentence the error path uses, so the routing decision is
- // visible in logs and support transcripts before anything goes wrong.
- if fallback_diagnostics::role_falls_back_to_cloud(role) {
- if let Some(chat) = config.chat_provider.as_deref() {
- if tinyinference_local::profile::is_local_provider_string(chat) {
- log::info!(
- "[providers][local-fallback] role={} {}",
- role,
- fallback_diagnostics::cloud_fallback_notice(role, chat, &resolved)
- );
- }
- }
}
-
- resolved
- } else {
- s.to_string()
}
+ resolved
}
-/// #6938: the provider route named by `config.default_model`, if it names an
-/// explicit provider rather than a model for the managed backend.
-///
-/// The Chat UI model picker (both the composer's per-turn pick, stored in
-/// `default_model` by `build_session_agent`, and a hand-set `default_model`
-/// in `config.toml`) records selections like `my-openai:gpt-4o` there, but
-/// role resolution never consulted it — the turn fell through to the managed
-/// backend regardless. Only the chat-tier roles consult the default: a
-/// chat-model pick says nothing about which model should do vision or
-/// summarization, so the background specialist roles keep their managed
-/// fallback.
-///
-/// Returns `None` (managed fallback unchanged) for everything that is not an
-/// explicit route: tier hints (`hint:chat`), the AI settings row's managed
-/// catalog pin (`openrouter/<author>/<slug>[:tag]` — a model name for the
-/// managed backend, see `DefaultModelRow.tsx`), bare model ids, and slugs
-/// that name no configured provider. The one bare provider name that is
-/// honoured is `claude_agent_sdk`: unlike local runtimes and cloud slugs,
-/// which need a `:model` part to construct, the SDK falls back to
-/// `config.claude_agent_sdk.default_model` (see
-/// `claude_agent_sdk_model_from_string`).
-fn default_model_route_for_role(role: &str, config: &Config) -> Option<String> {
- match role {
- "chat" | "reasoning" | "agentic" | "coding" | "burst" => {}
- _ => return None,
- }
- let dm = config.default_model.as_deref()?.trim();
- if dm.is_empty() || dm.starts_with("hint:") || dm.starts_with("openrouter/") {
- return None;
- }
- // Bare `claude_agent_sdk` is the only bare provider name honoured here:
- // the SDK resolves its model from `config.claude_agent_sdk.default_model`
- // (see `claude_agent_sdk_model_from_string`), while bare local runtimes
- // (`ollama`, ...) and bare cloud slugs carry no `:model` part and fail
- // at construction — they keep the managed fallback rather than erroring
- // (tinysweeper review on #6996; CodeRabbit review on #6996).
- if !dm.contains(':') {
- return (dm == CLAUDE_AGENT_SDK_PROVIDER).then(|| dm.to_string());
- }
- let (slug, rest) = dm.split_once(':')?;
- let slug = slug.trim();
- if slug.is_empty() || slug == PROVIDER_OPENHUMAN || rest.trim().is_empty() {
- return None;
- }
- let known = config.cloud_providers.iter().any(|e| e.slug == slug)
- || tinyinference_local::profile::is_local_provider_string(dm)
- || dm.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)
- || dm.starts_with(CLAUDE_AGENT_SDK_PREFIX);
- known.then(|| dm.to_string())
-}
-
-/// #3767: Whether the OpenHuman managed-credits gate should be bypassed for a
-/// single workload role.
-///
-/// Returns true when `role` resolves (via [`provider_for_role`]) to a non-managed
-/// provider the user funds themselves — a BYO cloud key (incl. OpenAI OAuth), a
-/// local runtime, or claude-code — with usable credentials. When the role is on
-/// the OpenHuman managed backend, or a BYO route has no usable key, it returns
-/// false (the gate stays on; #3767: "BYO key present but invalid/unverified →
-/// still gated").
-///
-/// The gate is evaluated per-tier so the UI can check the tier the user actually
-/// selected: the chat header's "Quick" mode runs on the `chat` tier and
-/// "Reasoning" mode on the `reasoning` tier, so each is checked respectively.
-/// These per-role results are surfaced under `credits_bypass` in the
-/// client-config snapshot. Tiers that stay managed and run anyway surface the
-/// per-call `USER_INSUFFICIENT_CREDITS` (402) error reactively.
+/// Whether the role's selected provider can be funded directly by the user.
pub fn role_bypasses_managed_credits(role: &str, config: &Config) -> bool {
let resolved = provider_for_role(role, config);
let r = resolved.trim();
@@ -212,14 +152,51 @@ pub fn role_bypasses_managed_credits(role: &str, config: &Config) -> bool {
usable_byo
}
+/// Native route metadata drives the branded explanation; this helper only
+/// determines whether the host should attach that explanation to an error.
+pub(crate) fn fallback_diagnostics_for_role(
+ role: &str,
+ config: &Config,
+) -> Option<FallbackDiagnostics> {
+ let source = ConfigRouteSource::new(config, PROVIDER_OPENHUMAN);
+ WORKLOAD_ROUTER.fallback_diagnostics(role, &source)
+}
+
+pub(crate) fn role_uses_implicit_cloud_fallback(role: &str, config: &Config) -> bool {
+ fallback_diagnostics_for_role(role, config).is_some()
+}
+
+/// Kept until v0.66; review after 2027-01-11 before removing legacy
+/// `inference_url` route compatibility from the host's route source.
+fn is_explicit_provider_default(model: &str, config: &Config) -> bool {
+ let model = model.trim();
+ if model.is_empty() || model.starts_with("hint:") || model.starts_with("openrouter/") {
+ return false;
+ }
+ if !model.contains(':') {
+ return model == CLAUDE_AGENT_SDK_PROVIDER;
+ }
+ let Some((slug, rest)) = model.split_once(':') else {
+ return false;
+ };
+ let slug = slug.trim();
+ !slug.is_empty()
+ && slug != PROVIDER_OPENHUMAN
+ && !rest.trim().is_empty()
+ && (config
+ .cloud_providers
+ .iter()
+ .any(|entry| entry.slug == slug)
+ || tinyinference_local::profile::is_local_provider_string(model)
+ || model.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)
+ || model.starts_with(CLAUDE_AGENT_SDK_PREFIX))
+}
+
/// True when a resolved chat-tier provider string can actually run on the
/// user's own funding: local runtimes / claude-code carry their own creds; a
-/// concrete cloud slug requires a non-empty stored key. Managed/sentinel
-/// strings are filtered by the caller and never reach here as "usable".
+/// concrete cloud slug requires a non-empty stored key.
pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> bool {
let r = resolved.trim();
- // Local runtimes (ollama/lmstudio/mlx/local-openai) and the local CLI
- // delegates carry their own credentials / run on-device.
if tinyinference_local::profile::is_local_provider_string(r)
|| r.starts_with(tinyagents_harness::providers::claude_code::PROVIDER_PREFIX)
|| r == CLAUDE_AGENT_SDK_PROVIDER
@@ -227,13 +204,9 @@ pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> b
{
return true;
}
- // Concrete cloud slug "<slug>:<model>" — require a usable stored key.
if let Some((slug, _)) = r.split_once(':') {
let slug = slug.trim();
if !slug.is_empty() {
- // Don't silently swallow auth-store / OAuth lookup failures — a
- // transient Err would otherwise keep the credits gate on for a
- // valid BYO setup with no diagnostics. Log and treat as not-usable.
match lookup_key_for_slug(slug, config) {
Ok(key) => {
let usable = !key.trim().is_empty();
@@ -242,9 +215,9 @@ pub(super) fn route_has_usable_credentials(resolved: &str, config: &Config) -> b
);
return usable;
}
- Err(e) => {
+ Err(error) => {
log::debug!(
- "[billing] route_has_usable_credentials slug={slug} lookup_error={e}"
+ "[billing] route_has_usable_credentials slug={slug} lookup_error={error}"
);
return false;
}
diff --git a/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs b/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs
index 44955574e5..e69a872f53 100644
--- a/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/factory_egress_fallback_tests.rs
@@ -243,14 +243,10 @@ fn implicit_cloud_fallback_is_claimed_only_when_the_role_has_no_route_of_its_own
#[test]
fn cloud_fallback_roles_match_the_roles_provider_for_role_actually_falls_back() {
- // `factory_tests` is a child module of `factory`, so `super` is `factory`,
- // not `provider` — reach the sibling module by its crate path.
- use crate::inference::provider::fallback_diagnostics::role_falls_back_to_cloud;
- let mut config = Config::default();
- config.chat_provider = Some("ollama:gemma3:1b".to_string());
+ let router = crate::inference::provider::factory::workload_router();
- // The diagnostics module carries its own role list; if the two drift, users
- // get either a missing explanation or one that names the wrong knob.
+ // The native router's metadata is the source of truth for roles that may
+ // fall back to the primary cloud provider.
for role in [
"vision",
"embeddings",
@@ -260,13 +256,13 @@ fn cloud_fallback_roles_match_the_roles_provider_for_role_actually_falls_back()
"burst",
] {
assert!(
- role_falls_back_to_cloud(role),
- "'{role}' falls back in provider_for_role but is missing from CLOUD_FALLBACK_ROLES"
+ router.cloud_fallback_role(role).is_some(),
+ "'{role}' falls back in provider_for_role but is missing native fallback metadata"
);
}
for role in ["chat", "reasoning", "coding"] {
assert!(
- !role_falls_back_to_cloud(role),
+ router.cloud_fallback_role(role).is_none(),
"'{role}' is a chat-tier role and must not be described as a cloud fallback"
);
}
diff --git a/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs b/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs
index 255d5d75fe..5be2a1612a 100644
--- a/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs
+++ b/crates/openhuman-core/src/inference/provider/fallback_diagnostics.rs
@@ -1,66 +1,8 @@
-//! Actionable diagnostics for background-workload provider fallback (#5146 §2.1).
-//!
-//! ## The user-visible bug
-//!
-//! A user configures a local Ollama model for chat, attaches an image, and gets
-//! `failed to read API key for slug 'anthropic'` — naming a provider they never
-//! configured. The same shape appears for embeddings, memory and the other
-//! background workloads.
-//!
-//! ## Why it happens, and why the routing itself is correct
-//!
-//! [`super::factory::provider_for_role`] deliberately routes the background
-//! roles (`vision`, `embeddings`, `memory`, `agentic`, `burst`)
-//! to the primary cloud provider when their
-//! own route is unset: they run tier-specific models (`hint:vision`,
-//! `hint:summarization`, …) that local runtimes and BYOK slugs do not serve. A
-//! user on a local chat model with a managed subscription genuinely wants those
-//! workloads on the cloud, so the fallback must stay.
-//!
-//! What was wrong is that the fallback was **unexplained**. When it landed on a
-//! provider with no usable credentials, the failure surfaced as a raw slug-level
-//! auth error with no hint that (a) this was a background role, (b) it fell back
-//! because the local model cannot serve that capability, or (c) what to do about
-//! it. That is the whole of the fix here: the routing decision is unchanged, the
-//! *explanation* is not.
-//!
-//! Everything in this module is a pure string/predicate function so the wording
-//! and the routing rules can be unit-tested without a live provider.
-//!
-//! Users who want no cloud egress at all already have
-//! [`crate::config::schema::PrivacyMode::LocalOnly`], enforced at the
-//! inference chokepoint by `factory::enforce_local_only_inference`. This module
-//! deliberately does not duplicate that gate.
+//! OpenHuman wording for native workload-router fallback diagnostics.
-/// Workload roles that inherit the primary cloud provider when their own route
-/// is unset — the set [`super::factory::provider_for_role`] does **not** include
-/// in chat-tier BYOK inheritance.
-///
-/// `chat`, `reasoning` and `coding` are absent on purpose: they inherit a
-/// configured BYOK slug instead, so they never produce the confusion this
-/// module exists to explain.
-const CLOUD_FALLBACK_ROLES: &[&str] = &[
- "vision",
- "embeddings",
- "memory",
- "summarization",
- "agentic",
- "burst",
-];
+use tinyagents_registry::router::FallbackDiagnostics;
-/// Whether `role` falls through to the primary cloud provider when its own
-/// route is unset.
-pub(crate) fn role_falls_back_to_cloud(role: &str) -> bool {
- CLOUD_FALLBACK_ROLES.contains(&role.trim())
-}
-
-/// The capability a background role provides, phrased for a user-facing
-/// sentence ("… does not support **vision**").
-///
-/// `None` for roles whose name is not a capability the user would recognise as
-/// a model feature (`burst`, …); callers fall back to the role
-/// name itself.
-pub(crate) fn role_capability_label(role: &str) -> Option<&'static str> {
+fn role_capability_label(role: &str) -> Option<&'static str> {
match role.trim() {
"vision" => Some("vision (image input)"),
"embeddings" => Some("embeddings"),
@@ -70,86 +12,57 @@ pub(crate) fn role_capability_label(role: &str) -> Option<&'static str> {
}
}
-/// How a role is described in a sentence — the capability when it maps to one,
-/// otherwise the bare role name.
fn role_phrase(role: &str) -> String {
- match role_capability_label(role) {
- Some(capability) => capability.to_string(),
- None => role.trim().to_string(),
- }
+ role_capability_label(role)
+ .map(str::to_owned)
+ .unwrap_or_else(|| role.trim().to_owned())
}
-/// Explanation logged when a background role runs on the cloud because the
-/// user's chat model is local and cannot serve that capability.
-///
-/// This is the informational, everything-is-working case: the user has a cloud
-/// route available and the workload will succeed. It exists so the routing
-/// decision is visible in logs and support transcripts rather than silent.
+/// OpenHuman's branded notice for the native router's implicit cloud fallback.
pub(crate) fn cloud_fallback_notice(
- role: &str,
+ diagnostic: &FallbackDiagnostics,
local_chat_provider: &str,
- resolved_provider: &str,
) -> String {
format!(
"{} is running via your managed/cloud provider ('{}') because your local chat model \
('{}') does not serve this workload. Set {}_provider explicitly in Connections to \
override.",
- capitalize_first(&role_phrase(role)),
- resolved_provider.trim(),
+ capitalize_first(&role_phrase(&diagnostic.role)),
+ diagnostic.fallback_route.trim(),
local_chat_provider.trim(),
- override_knob_for_role(role),
+ diagnostic.override_role,
)
}
-/// The config knob a user sets to override a role's route.
-///
-/// `burst` has no knob of its own — it rides the agentic route — so it points
-/// the user at `agentic_provider` rather than a setting that does not exist.
-pub(crate) fn override_knob_for_role(role: &str) -> &str {
- match role.trim() {
- "burst" => "agentic",
- "summarization" => "memory",
- other => other,
- }
-}
-
-/// Actionable error for the failing case: a background role fell back to a
-/// cloud slug whose credentials cannot be read.
-///
-/// Replaces the bare `failed to read API key for slug 'anthropic'` that named a
-/// provider the user never chose. Mentions the local chat model when there is
-/// one, because that is the missing half of the story.
+/// Branded missing-credentials copy for a fallback selected by the native router.
pub(crate) fn missing_provider_credentials_message(
- role: &str,
+ diagnostic: &FallbackDiagnostics,
slug: &str,
local_chat_provider: Option<&str>,
) -> String {
- let role = role.trim();
let slug = slug.trim();
- match local_chat_provider {
- Some(local) if !local.trim().is_empty() => format!(
- "No usable credentials for '{slug}', which OpenHuman selected for the {} workload. \
+ let role = role_phrase(&diagnostic.role);
+ match local_chat_provider.filter(|local| !local.trim().is_empty()) {
+ Some(local) => format!(
+ "No usable credentials for '{slug}', which OpenHuman selected for the {role} workload. \
Your chat model is local ('{}') and does not serve this workload, so it fell back \
to your cloud provider — but '{slug}' has no API key configured. Add a key for \
'{slug}' in Connections → LLM, set {}_provider to a provider that is configured, \
or enable the managed OpenHuman backend.",
- role_phrase(role),
local.trim(),
- override_knob_for_role(role),
+ diagnostic.override_role,
),
- _ => format!(
- "No usable credentials for '{slug}', which OpenHuman selected for the {} workload. \
+ None => format!(
+ "No usable credentials for '{slug}', which OpenHuman selected for the {role} workload. \
Add a key for '{slug}' in Connections → LLM, set {}_provider to a provider that is \
configured, or enable the managed OpenHuman backend.",
- role_phrase(role),
- override_knob_for_role(role),
+ diagnostic.override_role,
),
}
}
-/// Actionable message for the vision pre-flight: the active model cannot accept
-/// images, so the caller should say so instead of stripping the image and
-/// producing a confusing blind answer.
+/// Actionable message for the vision pre-flight when a selected local model
+/// cannot accept image input.
pub(crate) fn local_vision_unsupported_message(model: &str) -> String {
format!(
"The selected local model ('{}') does not support vision (image input). Switch to a \
diff --git a/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs b/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs
index 82b04a8eef..89aa262638 100644
--- a/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs
+++ b/crates/openhuman-core/src/inference/provider/fallback_diagnostics_tests.rs
@@ -1,107 +1,57 @@
use super::*;
-
-#[test]
-fn chat_tier_roles_do_not_fall_back_to_cloud() {
- // These inherit a BYOK slug instead; including them would attach the
- // "your local model can't serve this" explanation to the very roles the
- // user did configure locally.
- for role in ["chat", "reasoning", "coding"] {
- assert!(
- !role_falls_back_to_cloud(role),
- "{role} must not be treated as a cloud-fallback role"
- );
- }
-}
-
-#[test]
-fn background_roles_fall_back_to_cloud() {
- for role in [
- "vision",
- "embeddings",
- "memory",
- "summarization",
- "agentic",
- "burst",
- ] {
- assert!(
- role_falls_back_to_cloud(role),
- "{role} must be treated as a cloud-fallback role"
- );
+use tinyagents_registry::router::{FallbackDiagnostics, FallbackReason};
+
+fn vision_fallback() -> FallbackDiagnostics {
+ FallbackDiagnostics {
+ role: "vision".into(),
+ requested_route: None,
+ fallback_route: "anthropic:claude-sonnet-4".into(),
+ reason: FallbackReason::ImplicitCloudFallback,
+ override_role: "vision".into(),
}
}
#[test]
-fn unknown_role_does_not_fall_back() {
- assert!(!role_falls_back_to_cloud("not-a-role"));
- assert!(!role_falls_back_to_cloud(""));
-}
-
-#[test]
-fn role_falls_back_to_cloud_ignores_surrounding_whitespace() {
- assert!(role_falls_back_to_cloud(" vision "));
-}
-
-#[test]
-fn burst_points_at_the_agentic_knob_that_actually_exists() {
- // There is no `burst_provider`; telling the user to set one would be a
- // dead end.
- assert_eq!(override_knob_for_role("burst"), "agentic");
- assert_eq!(override_knob_for_role("summarization"), "memory");
- assert_eq!(override_knob_for_role("vision"), "vision");
-}
-
-#[test]
-fn fallback_notice_names_capability_local_model_and_override() {
- let msg = cloud_fallback_notice("vision", "ollama:gemma3:1b", "anthropic:claude-sonnet-4");
- assert!(msg.contains("Vision (image input)"), "got: {msg}");
- assert!(msg.contains("ollama:gemma3:1b"), "got: {msg}");
- assert!(msg.contains("anthropic:claude-sonnet-4"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
-}
-
-#[test]
-fn fallback_notice_for_role_without_capability_label_uses_role_name() {
- let msg = cloud_fallback_notice("scratch", "ollama:gemma3:1b", "openhuman");
- assert!(msg.contains("Scratch"), "got: {msg}");
- assert!(msg.contains("scratch_provider"), "got: {msg}");
-}
-
-#[test]
-fn missing_credentials_message_explains_the_local_fallback() {
- let msg = missing_provider_credentials_message("vision", "anthropic", Some("ollama:gemma3:1b"));
- // The whole point of #5146 §2.1: the user must learn *why* a provider
- // they never configured is being asked for a key.
- assert!(msg.contains("anthropic"), "got: {msg}");
- assert!(msg.contains("ollama:gemma3:1b"), "got: {msg}");
- assert!(msg.contains("vision (image input)"), "got: {msg}");
- assert!(msg.contains("Connections"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
+fn fallback_notice_renders_native_route_as_branded_actionable_copy() {
+ let message = cloud_fallback_notice(&vision_fallback(), "ollama:gemma3:1b");
+ assert!(message.contains("Vision (image input)"), "got: {message}");
+ assert!(message.contains("ollama:gemma3:1b"), "got: {message}");
+ assert!(
+ message.contains("anthropic:claude-sonnet-4"),
+ "got: {message}"
+ );
+ assert!(message.contains("vision_provider"), "got: {message}");
}
#[test]
-fn missing_credentials_message_without_local_chat_omits_the_local_clause() {
- let msg = missing_provider_credentials_message("embeddings", "openai", None);
- assert!(msg.contains("openai"), "got: {msg}");
- assert!(msg.contains("embeddings"), "got: {msg}");
- assert!(
- !msg.contains("Your chat model is local"),
- "must not claim a local chat model when there is none: {msg}"
+fn missing_credentials_copy_uses_native_role_and_override_metadata() {
+ let message = missing_provider_credentials_message(
+ &vision_fallback(),
+ "anthropic",
+ Some("ollama:gemma3:1b"),
);
+ assert!(message.contains("anthropic"), "got: {message}");
+ assert!(message.contains("ollama:gemma3:1b"), "got: {message}");
+ assert!(message.contains("vision (image input)"), "got: {message}");
+ assert!(message.contains("Connections"), "got: {message}");
+ assert!(message.contains("vision_provider"), "got: {message}");
}
#[test]
-fn missing_credentials_message_treats_blank_local_provider_as_absent() {
- let msg = missing_provider_credentials_message("embeddings", "openai", Some(" "));
+fn missing_credentials_without_local_chat_does_not_claim_a_local_model() {
+ let message = missing_provider_credentials_message(&vision_fallback(), "anthropic", None);
+ assert!(message.contains("anthropic"), "got: {message}");
+ assert!(message.contains("vision (image input)"), "got: {message}");
assert!(
- !msg.contains("Your chat model is local"),
- "blank provider string is not a local model: {msg}"
+ !message.contains("Your chat model is local"),
+ "got: {message}"
);
}
#[test]
fn vision_unsupported_message_names_model_and_a_concrete_remedy() {
- let msg = local_vision_unsupported_message("gemma3:1b");
- assert!(msg.contains("gemma3:1b"), "got: {msg}");
- assert!(msg.contains("llava:7b"), "got: {msg}");
- assert!(msg.contains("vision_provider"), "got: {msg}");
+ let message = local_vision_unsupported_message("gemma3:1b");
+ assert!(message.contains("gemma3:1b"), "got: {message}");
+ assert!(message.contains("llava:7b"), "got: {message}");
+ assert!(message.contains("vision_provider"), "got: {message}");
}
diff --git a/crates/openhuman-core/src/inference/provider_model.rs b/crates/openhuman-core/src/inference/provider_model.rs
index 28c91db5e2..c74771218f 100644
--- a/crates/openhuman-core/src/inference/provider_model.rs
+++ b/crates/openhuman-core/src/inference/provider_model.rs
@@ -1,7 +1,8 @@
//! Provider-neutral helpers for resolving model ids against registered model
//! vocabularies.
-use crate::config::{Config, WORKLOAD_ROLES};
+use crate::config::Config;
+use tinyagents_registry::router::RouteSource;
/// The workload role represented by a provider-specific model alias, defaulting
/// to the generic `chat` role for concrete and unknown ids.
@@ -28,18 +29,18 @@ fn role_for_provider_model_with(
model: &str,
extensions: Option<Option<&crate::core::slots::Extensions>>,
) -> &'static str {
- let role = model
- .strip_prefix("hint:")
- .filter(|role| WORKLOAD_ROLES.contains(role))
- .map(str::to_string)
- .or_else(|| match extensions {
- Some(extensions) => {
- crate::inference::registry::provider_model_role_for(extensions, provider_id, model)
- }
- None => crate::inference::registry::provider_model_role(provider_id, model),
- });
- role.as_deref()
- .and_then(|role| WORKLOAD_ROLES.iter().copied().find(|known| *known == role))
+ let config = Config::default();
+ let source = crate::inference::provider::factory::ConfigRouteSource::with_extension_selection(
+ &config,
+ provider_id,
+ extensions,
+ );
+ let role =
+ crate::inference::provider::factory::workload_router().role_for_model_tier(model, &source);
+ crate::config::WORKLOAD_ROLES
+ .iter()
+ .copied()
+ .find(|known| *known == role)
.unwrap_or("chat")
}
@@ -91,30 +92,17 @@ fn resolve_provider_model_hint_with(
if trimmed.is_empty() {
return trimmed.to_string();
}
- let role = trimmed
- .strip_prefix("hint:")
- .filter(|role| WORKLOAD_ROLES.contains(role))
- .map(str::to_string)
- .or_else(|| match extensions {
- Some(extensions) => crate::inference::registry::provider_model_role_for(
- extensions,
- provider_id,
- trimmed,
- ),
- None => crate::inference::registry::provider_model_role(provider_id, trimmed),
- });
- let Some(role) = role else {
- return trimmed.to_string();
- };
-
- let route = crate::inference::provider::factory::provider_for_role(&role, config);
- let route = route.trim();
- if route.is_empty()
- || route == "cloud"
- || route == provider_id
- || route == crate::inference::provider::factory::BYOK_INCOMPLETE_SENTINEL
- {
- let resolved = match extensions {
+ let router = crate::inference::provider::factory::workload_router();
+ let base_source =
+ crate::inference::provider::factory::ConfigRouteSource::with_extension_selection(
+ config,
+ provider_id,
+ extensions,
+ );
+ let role = router.role_for_model_tier(trimmed, &base_source);
+ let route = router.provider_for_role(&role, &base_source);
+ let managed_default_model = if base_source.is_managed_route(&route) {
+ match extensions {
Some(extensions) => crate::inference::registry::resolve_provider_model_for(
extensions,
provider_id,
@@ -128,13 +116,14 @@ fn resolve_provider_model_hint_with(
config,
Some(trimmed),
),
- };
- return resolved.unwrap_or_else(|| trimmed.to_string());
- }
- if let Some((_, model)) = route.split_once(':') {
- return tinyinference_providers::route::split_model_and_temperature(model).0;
- }
- route.to_string()
+ }
+ } else {
+ None
+ };
+ let source = base_source.with_managed_default_model(managed_default_model);
+ router
+ .resolve_model_for_hint(trimmed, &source)
+ .unwrap_or_else(|| trimmed.to_string())
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/inference/provider_model_tests.rs b/crates/openhuman-core/src/inference/provider_model_tests.rs
index 04fb2c9b3a..9de2c8380c 100644
--- a/crates/openhuman-core/src/inference/provider_model_tests.rs
+++ b/crates/openhuman-core/src/inference/provider_model_tests.rs
@@ -51,7 +51,9 @@ fn registered_model_defaults_and_aliases_are_context_scoped() {
is_alias: Arc::new(|model| model == "scoped-alias"),
is_raw_model: Arc::new(|model| model == "scoped/model"),
supports_vision: Arc::new(|_| false),
- resolve_model: Arc::new(|_, _, _| None),
+ resolve_model: Arc::new(|role, _, override_model| {
+ (override_model == Some("scoped-alias")).then(|| format!("scoped-{role}"))
+ }),
context_window: Arc::new(|model| match model {
"" => Some(99_999),
"scoped/model" => Some(77_777),
@@ -153,6 +155,61 @@ fn registered_model_defaults_and_aliases_are_context_scoped() {
.as_deref(),
Some("reasoning")
);
+ assert_eq!(
+ role_for_provider_model(
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias"
+ ),
+ "reasoning",
+ "the public resolver must use the ambient context registration"
+ );
+ assert_eq!(
+ role_for_provider_model_for(
+ Some(&extensions),
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias",
+ ),
+ "reasoning",
+ "an explicit context must use that context's provider hooks"
+ );
+ assert_eq!(
+ role_for_provider_model_for(
+ None,
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias",
+ ),
+ "chat",
+ "explicit process-only lookup must not borrow the ambient provider hook"
+ );
+ assert_eq!(
+ resolve_provider_model_hint(
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias",
+ &Config::default(),
+ ),
+ "scoped-reasoning",
+ "the public hint resolver must preserve ambient route and model hooks"
+ );
+ assert_eq!(
+ resolve_provider_model_hint_for(
+ None,
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias",
+ &Config::default(),
+ ),
+ "scoped-alias",
+ "explicit process-only hint resolution must not borrow ambient hooks"
+ );
+ assert_eq!(
+ resolve_provider_model_hint_for(
+ Some(&extensions),
+ crate::inference::provider::factory::PROVIDER_OPENHUMAN,
+ "scoped-alias",
+ &Config::default(),
+ ),
+ "scoped-reasoning",
+ "explicit context hint resolution must use that context's hooks"
+ );
});
assert_eq!(
crate::inference::registry::provider_default_model(